| 1 | import { timingSafeEqual } from "crypto"; |
| 2 | import { eq } |
| 3 | import { NextResponse, type |
| 4 | import { getAuth } |
| 5 | import { db } |
| 6 | import { userGoogleDrives } |
| 7 | import { encrypt } |
| 8 | import { |
| 9 | exchangeAuthorizationCode, |
| 10 | fetchUserInfo, |
| 11 | getAppUrl, |
| 12 | getOperatorGDriveConfig, |
| 13 | } from "@struxa/api/services/google-drive"; |
| 14 | |
| 15 | function clearStateCookie(res: |
| 16 | res.cookies.set |
| 17 | httpOnly: true, |
| 18 | sameSite: "lax", |
| 19 | path: "/", |
| 20 | maxAge: 0, |
| 21 | }); |
| 22 | } |
| 23 | |
| 24 | export async function GET |
| 25 | const auth = |
| 26 | const session = |
| 27 | if (!session) |
| 28 | |
| 29 | const appUrl = |
| 30 | const url = |
| 31 | |
| 32 | const fail = |
| 33 | const res = |
| 34 | clearStateCookie(res); |
| 35 | return res; |
| 36 | }; |
| 37 | |
| 38 | if (url.searchParams |
| 39 | |
| 40 | const state = |
| 41 | const cookie = |
| 42 | const stateOk = |
| 43 | !!state && |
| 44 | !!cookie && |
| 45 | state.length === cookie |
| 46 | timingSafeEqual(Buffer.from |
| 47 | if (!stateOk) |
| 48 | const res = |
| 49 | clearStateCookie(res); |
| 50 | return res; |
| 51 | } |
| 52 | |
| 53 | const code = |
| 54 | if (!code) |
| 55 | |
| 56 | const config = |
| 57 | if (!config) |
| 58 | |
| 59 | try { |
| 60 | const tokens = |
| 61 | code, |
| 62 | `${appUrl}/api/account/google-drive/callback`, |
| 63 | ); |
| 64 | const userInfo = |
| 65 | const existing = |
| 66 | where: eq(userGoogleDrives |
| 67 | }); |
| 68 | if (existing && |
| 69 | return fail("mismatch |
| 70 | } |
| 71 | await db |
| 72 | .insert(userGoogleDrives) |
| 73 | .values({ |
| 74 | userId: session.user |
| 75 | accessToken: encrypt(tokens |
| 76 | refreshToken: encrypt(tokens |
| 77 | expiresAt: new Date |
| 78 | email: userInfo.email |
| 79 | }) |
| 80 | .onDuplicateKeyUpdate({ |
| 81 | set: { |
| 82 | accessToken: encrypt(tokens |
| 83 | refreshToken: encrypt(tokens |
| 84 | expiresAt: new Date |
| 85 | email: userInfo.email |
| 86 | }, |
| 87 | }); |
| 88 | return fail("connected |
| 89 | } catch { |
| 90 | return fail("error |
| 91 | } |
| 92 | } |