forked from ugurkellecioglu/another-next-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.ts
82 lines (73 loc) · 2.21 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
import { DrizzleAdapter } from "@auth/drizzle-adapter"
import type { NextAuthConfig } from "next-auth"
import NextAuth, { User } from "next-auth"
import { encode as defaultEncode } from "next-auth/jwt"
import Credentials from "next-auth/providers/credentials"
import Discord from "next-auth/providers/discord"
import Facebook from "next-auth/providers/facebook"
import Github from "next-auth/providers/github"
import { v4 as uuid } from "uuid"
import { getUserFromDb } from "./actions/user.actions"
import { db } from "./lib/db"
const adapter = DrizzleAdapter(db)
const authConfig: NextAuthConfig = {
adapter,
providers: [
Github({
clientId: process.env.GITHUB_ID!,
clientSecret: process.env.GITHUB_SECRET!,
}),
Facebook({
clientId: process.env.FACEBOOK_ID!,
clientSecret: process.env.FACEBOOK_SECRET!,
}),
Discord({
clientId: process.env.DISCORD_CLIENT_ID!,
clientSecret: process.env.DISCORD_CLIENT_SECRET!,
}),
Credentials({
credentials: {
email: {},
password: {},
},
async authorize(credentials) {
const { email, password } = credentials
const res = await getUserFromDb(email as string, password as string)
if (res.success) {
return res.data as User
}
return null
},
}),
],
callbacks: {
async jwt({ token, user, account }) {
if (account?.provider === "credentials") {
token.credentials = true
}
return token
},
},
jwt: {
encode: async function (params) {
if (params.token?.credentials) {
const sessionToken = uuid()
if (!params.token.sub) {
throw new Error("No user ID found in token")
}
const createdSession = await adapter?.createSession?.({
sessionToken: sessionToken,
userId: params.token.sub,
expires: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000), // 30 days
})
if (!createdSession) {
throw new Error("Failed to create session")
}
return sessionToken
}
return defaultEncode(params)
},
},
secret: process.env.AUTH_SECRET!,
}
export const { handlers, signIn, signOut, auth } = NextAuth(authConfig)