Swadhin Biswas Feature/ai code reviewer (#79) · 8/16/2026
cfd400d
144 lines · 5.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
import { github } from "@/lib/oauth";
import { OAuth2RequestError } from "arctic";
import type { APIRoute } from "astro";
import { getDatabase, schema } from "@/db";
import { createSession } from "@/lib/auth";
import { logger } from "@/lib/logger";
import { and, eq } from "drizzle-orm";
import type { NodePgDatabase } from "drizzle-orm/node-postgres";

interface GitHubUser {
    id: number;
    login: string;
    name: string | null;
    avatar_url: string;
    email: string | null;
}

export const GET: APIRoute = async ({ url, cookies, redirect }) => {
    const code = url.searchParams.get("code");
    const state = url.searchParams.get("state");
    const storedState = cookies.get("github_oauth_state")?.value;

    cookies.delete("github_oauth_state", { path: "/" });

    if (!code || !state || !storedState || state !== storedState) {
        return redirect("/login?error=oauth_failed");
    }

    try {
        const tokens = await github.validateAuthorizationCode(code);
        const accessToken = tokens.accessToken();

        const response = await fetch("https://api.github.com/user", {
            headers: {
                Authorization: `Bearer ${accessToken}`,
                "User-Agent": "OpenCodeHub",
                Accept: "application/vnd.github+json",
            },
        });
        if (!response.ok) {
            logger.warn({ status: response.status }, "GitHub userinfo failed");
            return redirect("/login?error=oauth_failed");
        }
        const ghUser: GitHubUser = await response.json();

        const db = getDatabase() as NodePgDatabase<typeof schema>;

        // Check if OAuth account exists
        const existingOAuth = await db.query.oauthAccounts.findFirst({
            where: and(
                eq(schema.oauthAccounts.provider, "github"),
                eq(schema.oauthAccounts.providerAccountId, String(ghUser.id))
            ),
            with: { user: true },
        });

        let userId: string;

        if (existingOAuth) {
            await db
                .update(schema.oauthAccounts)
                .set({ accessToken })
                .where(eq(schema.oauthAccounts.id, existingOAuth.id));
            userId = existingOAuth.userId;
        } else {
            // Try to link by email
            let user = null;
            if (ghUser.email) {
                user = await db.query.users.findFirst({
                    where: eq(schema.users.email, ghUser.email),
                });
            }

            if (user) {
                await db.insert(schema.oauthAccounts).values({
                    id: crypto.randomUUID(),
                    userId: user.id,
                    provider: "github",
                    providerAccountId: String(ghUser.id),
                    accessToken,
                    createdAt: new Date(),
                });
                userId = user.id;
            } else {
                // Create user
                let username = ghUser.login || (ghUser.email || "gh").split("@")[0];
                let existingUsername = await db.query.users.findFirst({
                    where: eq(schema.users.username, username),
                });
                let suffix = 1;
                while (existingUsername) {
                    username = `${ghUser.login || "gh"}${suffix}`;
                    existingUsername = await db.query.users.findFirst({
                        where: eq(schema.users.username, username),
                    });
                    suffix++;
                }

                const newUserId = crypto.randomUUID();
                await db.insert(schema.users).values({
                    id: newUserId,
                    username,
                    // email is NOT NULL in the schema; GitHub may not expose it
                    // without extra scopes — derive a stable placeholder
                    email: ghUser.email || `${username}@users.noreply.opencodehub.local`,
                    displayName: ghUser.name || ghUser.login,
                    avatarUrl: ghUser.avatar_url,
                    passwordHash: null,
                    createdAt: new Date(),
                    updatedAt: new Date(),
                });
                await db.insert(schema.oauthAccounts).values({
                    id: crypto.randomUUID(),
                    userId: newUserId,
                    provider: "github",
                    providerAccountId: String(ghUser.id),
                    accessToken,
                    createdAt: new Date(),
                });
                userId = newUserId;
            }
        }

        // Create session
        const session = await createSession(userId);
        cookies.set("och_session", session.token, {
            httpOnly: true,
            secure: import.meta.env.PROD,
            sameSite: "lax",
            path: "/",
            maxAge: 60 * 60 * 24 * 7, // 7 days
        });

        return redirect("/");
    } catch (error) {
        if (error instanceof OAuth2RequestError) {
            logger.warn({ error }, "GitHub OAuth request error");
            return redirect("/login?error=oauth_failed");
        }
        logger.error({ error }, "GitHub OAuth callback error");
        return redirect("/login?error=oauth_failed");
    }
};