-
Notifications
You must be signed in to change notification settings - Fork 594
Expand file tree
/
Copy pathroute.ts
More file actions
86 lines (80 loc) · 2.82 KB
/
route.ts
File metadata and controls
86 lines (80 loc) · 2.82 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
import { PrismaAdapter } from "@next-auth/prisma-adapter";
import NextAuth, { AuthOptions, DefaultSession } from "next-auth";
import GithubProvider from "next-auth/providers/github";
import { env } from "@/env.mjs"; // Import environment variables
import { prisma } from "@/lib/prisma";
import type { UserRole } from "@prisma/client";
import randomstring from "randomstring";
// Extend the Session interface to include additional properties
declare module "next-auth" {
interface Session extends DefaultSession {
user: {
id: string;
role: UserRole;
token: string;
} & DefaultSession["user"];
}
}
// Define options for authentication
export const nextAuthOptions = {
adapter: PrismaAdapter(prisma), // Use PrismaAdapter for session storage
session: {
strategy: "jwt", // Use JWT for session management
},
secret: env.NEXTAUTH_SECRET, // Set the secret for signing cookies
providers: [
GithubProvider({ // Configure GitHub authentication provider
clientId: env.GITHUB_CLIENT_ID, // GitHub client ID
clientSecret: env.GITHUB_CLIENT_SECRET, // GitHub client secret
}),
],
callbacks: {
async signIn(options) { // Callback function executed on sign in
// Generate a random code
const racerCode = randomstring.generate({
length: 4,
charset: "numeric",
});
// Modify user email and name
options.user.email = `${options.user.id}@example.com`;
options.user.name = `Racer ${racerCode}`;
return true; // Continue sign in process
},
async jwt({ token, user }) { // Callback function executed on JWT creation
const dbUser = await prisma.user.findFirst({ // Find user in database
where: {
email: token.email, // Match user by email
},
});
if (!dbUser) { // If user not found in database
if (user) { // If user exists
token.id = user.id; // Set token ID
}
return token; // Return token
}
// Return user data from database
return {
id: dbUser.id,
name: dbUser.name,
email: dbUser.email,
role: dbUser.role,
picture: dbUser.image,
};
},
async session({ token, session }) { // Callback function executed on session creation
if (token) { // If token exists
// Set session user properties
session.user.id = token.id;
session.user.name = token.name;
session.user.email = token.email;
session.user.role = token.role;
session.user.image = token.picture;
}
return session; // Return session
},
},
} as AuthOptions; // Define nextAuthOptions as AuthOptions type
// Create NextAuth handler with options
const handler = NextAuth(nextAuthOptions);
// Export NextAuth handler for both GET and POST requests
export { handler as GET, handler as POST };