|
| 1 | +import { |
| 2 | + decodeIdToken, |
| 3 | + Google, |
| 4 | + generateCodeVerifier, |
| 5 | + generateState, |
| 6 | +} from "arctic"; |
| 7 | +import { and, eq } from "drizzle-orm"; |
| 8 | +import { Elysia, t } from "elysia"; |
| 9 | +import { db } from "../../db/index.ts"; |
| 10 | +import { accounts, users } from "../../db/schema.ts"; |
| 11 | +import { env } from "../../env.ts"; |
| 12 | +import { authMiddleware } from "../../middleware/auth.ts"; |
| 13 | + |
| 14 | +const google = new Google( |
| 15 | + env.GOOGLE_CLIENT_ID, |
| 16 | + env.GOOGLE_CLIENT_SECRET, |
| 17 | + `${env.CORS_ORIGIN}/auth/google/callback`, |
| 18 | +); |
| 19 | + |
| 20 | +export const googleAuthRoutes = new Elysia({ prefix: "/auth/google" }) |
| 21 | + .use(authMiddleware) |
| 22 | + .get("/authorize", async ({ cookie, redirect }) => { |
| 23 | + const state = generateState(); |
| 24 | + const codeVerifier = generateCodeVerifier(); |
| 25 | + const url = google.createAuthorizationURL(state, codeVerifier, [ |
| 26 | + "openid", |
| 27 | + "email", |
| 28 | + "profile", |
| 29 | + ]); |
| 30 | + |
| 31 | + cookie.google_oauth_state?.set({ |
| 32 | + value: state, |
| 33 | + httpOnly: true, |
| 34 | + maxAge: 60 * 10, |
| 35 | + path: "/", |
| 36 | + }); |
| 37 | + cookie.google_code_verifier?.set({ |
| 38 | + value: codeVerifier, |
| 39 | + httpOnly: true, |
| 40 | + maxAge: 60 * 10, |
| 41 | + path: "/", |
| 42 | + }); |
| 43 | + |
| 44 | + return redirect(url.toString()); |
| 45 | + }) |
| 46 | + .get( |
| 47 | + "/callback", |
| 48 | + async ({ query, cookie, jwt, redirect }) => { |
| 49 | + const { code, state } = query; |
| 50 | + const storedState = cookie.google_oauth_state?.value; |
| 51 | + const codeVerifier = cookie.google_code_verifier?.value; |
| 52 | + |
| 53 | + if (state !== storedState || typeof codeVerifier !== "string") { |
| 54 | + return redirect(`${env.CORS_ORIGIN}/signin?error=invalid_state`); |
| 55 | + } |
| 56 | + |
| 57 | + const tokens = await google.validateAuthorizationCode(code, codeVerifier); |
| 58 | + const idToken = tokens.idToken(); |
| 59 | + const claims = decodeIdToken(idToken) as { |
| 60 | + sub: string; |
| 61 | + email: string; |
| 62 | + name?: string; |
| 63 | + picture?: string; |
| 64 | + }; |
| 65 | + |
| 66 | + // Find existing account |
| 67 | + const [existingAccount] = await db |
| 68 | + .select() |
| 69 | + .from(accounts) |
| 70 | + .where( |
| 71 | + and( |
| 72 | + eq(accounts.provider, "google"), |
| 73 | + eq(accounts.providerAccountId, claims.sub), |
| 74 | + ), |
| 75 | + ); |
| 76 | + |
| 77 | + let user: typeof users.$inferSelect | undefined; |
| 78 | + if (existingAccount) { |
| 79 | + [user] = await db |
| 80 | + .select() |
| 81 | + .from(users) |
| 82 | + .where(eq(users.id, existingAccount.userId)); |
| 83 | + } else { |
| 84 | + // Check if user with email exists |
| 85 | + [user] = await db |
| 86 | + .select() |
| 87 | + .from(users) |
| 88 | + .where(eq(users.email, claims.email)); |
| 89 | + |
| 90 | + if (!user) { |
| 91 | + [user] = await db |
| 92 | + .insert(users) |
| 93 | + .values({ |
| 94 | + email: claims.email, |
| 95 | + name: claims.name ?? claims.email.split("@")[0], |
| 96 | + image: claims.picture, |
| 97 | + emailVerified: new Date(), |
| 98 | + }) |
| 99 | + .returning(); |
| 100 | + } |
| 101 | + |
| 102 | + if (!user) { |
| 103 | + return redirect( |
| 104 | + `${env.CORS_ORIGIN}/signin?error=user_creation_failed`, |
| 105 | + ); |
| 106 | + } |
| 107 | + |
| 108 | + // Link account |
| 109 | + await db.insert(accounts).values({ |
| 110 | + userId: user.id, |
| 111 | + type: "oauth", |
| 112 | + provider: "google", |
| 113 | + providerAccountId: claims.sub, |
| 114 | + accessToken: tokens.accessToken(), |
| 115 | + idToken: idToken, |
| 116 | + }); |
| 117 | + } |
| 118 | + |
| 119 | + if (!user) { |
| 120 | + return redirect(`${env.CORS_ORIGIN}/signin?error=user_not_found`); |
| 121 | + } |
| 122 | + |
| 123 | + const token = await jwt.sign({ |
| 124 | + id: user.id, |
| 125 | + email: user.email, |
| 126 | + name: user.name, |
| 127 | + }); |
| 128 | + |
| 129 | + cookie.token?.set({ |
| 130 | + value: token, |
| 131 | + httpOnly: true, |
| 132 | + maxAge: 7 * 24 * 60 * 60, |
| 133 | + path: "/", |
| 134 | + }); |
| 135 | + |
| 136 | + // Clear OAuth cookies |
| 137 | + cookie.google_oauth_state?.set({ value: "", maxAge: 0, path: "/" }); |
| 138 | + cookie.google_code_verifier?.set({ value: "", maxAge: 0, path: "/" }); |
| 139 | + |
| 140 | + return redirect(env.CORS_ORIGIN); |
| 141 | + }, |
| 142 | + { |
| 143 | + query: t.Object({ |
| 144 | + code: t.String(), |
| 145 | + state: t.String(), |
| 146 | + }), |
| 147 | + }, |
| 148 | + ); |
0 commit comments