-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
auth.ts
142 lines (123 loc) · 4.26 KB
/
auth.ts
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
import { sql } from "@vercel/postgres";
import { getUserIdFromEmail, getPurchasedCourses } from "@/lib/queries";
import NextAuth, { NextAuthConfig } from 'next-auth'
import GitHub from 'next-auth/providers/github'
import type { Provider } from 'next-auth/providers'
import EmailProvider from 'next-auth/providers/email'
import PostgresAdapter from "@auth/pg-adapter"
import { createPool } from '@vercel/postgres';
declare module "next-auth" {
interface Profile {
login?: string;
}
}
const pool = createPool();
const providers: Provider[] = [
GitHub({
clientId: process.env.GITHUB_ID,
clientSecret: process.env.GITHUB_SECRET
}),
EmailProvider({
server: {
host: process.env.EMAIL_SERVER_HOST,
port: process.env.EMAIL_SERVER_PORT,
auth: {
user: process.env.EMAIL_SERVER_USER,
pass: process.env.EMAIL_SERVER_PASSWORD
}
},
from: process.env.EMAIL_FROM
})
]
export const providerMap = providers.map((provider) => {
if (typeof provider === "function") {
const providerData = provider()
return { id: providerData.id, name: providerData.name }
} else {
return { id: provider.id, name: provider.name }
}
})
export const { auth, handlers, signIn, signOut } = NextAuth({
adapter: PostgresAdapter(pool),
pages: {
signIn: '/login'
},
providers,
callbacks: {
async signIn({ user, account, profile, email, credentials }) {
if (account) {
console.log(`signIn callback: %o, %o, %o, %o, %o`, user, account, profile, email, credentials);
let githubUsername, userFullName, userEmailAddress;
if (account.provider === 'github') {
// Extract GitHub profile info
githubUsername = profile!.login!;
userFullName = profile!.name!;
} else if (account.provider === 'email') {
// Get email profile info
userEmailAddress = user!.email!;
}
console.log(`signIn callback githubUsername: ${githubUsername}, userFullName: ${userFullName}, userEmailAddress: ${userEmailAddress}`);
try {
console.log('Checking if user already exists in database...')
// Check if student record already exists
let existingStudent;
if (githubUsername) {
existingStudent = await sql`
SELECT *
FROM users
WHERE github_username = ${githubUsername}
`;
} else if (userEmailAddress) {
existingStudent = await sql`
SELECT *
FROM users
WHERE email = ${userEmailAddress}
`;
}
console.log(`existingStudent: %o`, existingStudent);
let userId;
if (existingStudent && existingStudent.rowCount > 0) {
// Student found, use id
userId = existingStudent.rows[0].id;
console.log(`Found existing student with id: ${userId}`);
} else {
// Create new student
let createValues;
if (githubUsername) {
createValues = {
github_username: githubUsername,
name: userFullName
};
} else if (userEmailAddress) {
createValues = {
email: userEmailAddress
};
}
console.log(`Creating new user with values: %o`, createValues);
const createRes = await sql`
INSERT INTO users (github_username, name, email)
VALUES (${githubUsername}, ${userFullName}, ${userEmailAddress})
RETURNING id
`;
userId = createRes.rows[0].id;
}
} catch (error) {
console.error(error);
}
return true;
}
},
async session({ session, user, token }) {
console.log(`session method callback: %o, %o, %o`, session, user, token);
console.log(`session.user.email: ${session!.user!.email}`);
const userId = await getUserIdFromEmail(session!.user!.email!);
console.log(`userId: ${userId}`);
// Add purchased courses to the session object
session!.user!.purchased_courses = await getPurchasedCourses(Number(userId));
console.log(`session before return: %o`, session);
return {
...session,
};
}
}
} as NextAuthConfig)