-
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathroute.ts
More file actions
168 lines (140 loc) · 4.06 KB
/
route.ts
File metadata and controls
168 lines (140 loc) · 4.06 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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
import { and, eq } from 'drizzle-orm';
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/db';
import { users } from '@/db/schema/users';
import { setAuthCookie, signAuthToken } from '@/lib/auth';
import { consumeOAuthState } from '@/lib/auth/oauth-state';
import { authEnv } from '@/lib/env/auth';
type GithubTokenResponse = {
access_token: string;
token_type: string;
scope: string;
};
type GithubUser = {
id: number;
login: string;
name: string | null;
avatar_url: string;
};
type GithubEmail = {
email: string;
primary: boolean;
verified: boolean;
};
const GITHUB_HEADERS = {
'User-Agent': 'devlovers-app',
};
export async function GET(req: NextRequest) {
const code = req.nextUrl.searchParams.get('code');
const state = req.nextUrl.searchParams.get('state');
if (!(await consumeOAuthState(state))) {
return NextResponse.redirect(new URL('/login', req.url));
}
if (!code) {
return NextResponse.redirect(new URL('/login', req.url));
}
const tokenRes = await fetch('https://github.com/login/oauth/access_token', {
method: 'POST',
headers: {
Accept: 'application/json',
},
body: new URLSearchParams({
client_id: authEnv.github.clientId,
client_secret: authEnv.github.clientSecret,
code,
redirect_uri: authEnv.github.redirectUri,
}),
});
if (!tokenRes.ok) {
console.error('GitHub token exchange failed', await tokenRes.text());
return NextResponse.redirect(new URL('/login', req.url));
}
const tokenData = (await tokenRes.json()) as GithubTokenResponse;
const userRes = await fetch('https://api.github.com/user', {
headers: {
...GITHUB_HEADERS,
Authorization: `Bearer ${tokenData.access_token}`,
},
});
if (!userRes.ok) {
return NextResponse.redirect(new URL('/login', req.url));
}
const ghUser = (await userRes.json()) as GithubUser;
const emailsRes = await fetch('https://api.github.com/user/emails', {
headers: {
...GITHUB_HEADERS,
Authorization: `Bearer ${tokenData.access_token}`,
},
});
if (!emailsRes.ok) {
return NextResponse.redirect(new URL('/login', req.url));
}
const emails = (await emailsRes.json()) as GithubEmail[];
const primaryEmail = emails.find(e => e.primary && e.verified)?.email;
if (!primaryEmail) {
return NextResponse.redirect(new URL('/login', req.url));
}
const githubId = String(ghUser.id);
let user = null;
const [githubUser] = await db
.select({
id: users.id,
email: users.email,
role: users.role,
})
.from(users)
.where(and(eq(users.providerId, githubId), eq(users.provider, 'github')))
.limit(1);
if (githubUser) {
user = githubUser;
} else {
const [emailUser] = await db
.select({
id: users.id,
emailVerified: users.emailVerified,
image: users.image,
name: users.name,
})
.from(users)
.where(eq(users.email, primaryEmail))
.limit(1);
if (emailUser) {
const image =
emailUser.image && emailUser.image !== 'null'
? emailUser.image
: ghUser.avatar_url;
const [updatedUser] = await db
.update(users)
.set({
provider: 'github',
providerId: githubId,
emailVerified: emailUser.emailVerified ?? new Date(),
image,
name: emailUser.name ?? ghUser.name ?? ghUser.login,
})
.where(eq(users.id, emailUser.id))
.returning();
user = updatedUser;
} else {
const [created] = await db
.insert(users)
.values({
email: primaryEmail,
name: ghUser.name ?? ghUser.login,
image: ghUser.avatar_url,
provider: 'github',
providerId: githubId,
emailVerified: new Date(),
})
.returning();
user = created;
}
}
const token = signAuthToken({
userId: user.id,
email: user.email,
role: user.role === 'admin' ? 'admin' : 'user',
});
await setAuthCookie(token);
return NextResponse.redirect(new URL('/dashboard', req.url));
}