Repository navigation
Expand file tree
/
Copy pathauth.ts
More file actions
135 lines (114 loc) · 2.41 KB
/
Copy pathauth.ts
File metadata and controls
135 lines (114 loc) · 2.41 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
import NextAuth from "next-auth";
import Credentials from "next-auth/providers/credentials";
import bcrypt from "bcryptjs";
import { getCloudflareContext } from "@opennextjs/cloudflare";
export const {
handlers,
auth,
signIn,
signOut,
} = NextAuth({
providers: [
Credentials({
name: "Credentials",
credentials: {
email: {
label: "Email",
type: "email",
},
password: {
label: "Password",
type: "password",
},
},
async authorize(credentials) {
if (
!credentials?.email ||
!credentials?.password
) {
return null;
}
const email = String(
credentials.email
)
.trim()
.toLowerCase();
const password = String(
credentials.password
);
try {
const { env } =
await getCloudflareContext();
const db = env.DB;
const user = await db
.prepare(
`
SELECT
id,
name,
email,
password
FROM users
WHERE email = ?
LIMIT 1
`
)
.bind(email)
.first<{
id: string;
name: string;
email: string;
password: string;
}>();
if (!user) {
return null;
}
const passwordValid =
await bcrypt.compare(
password,
user.password
);
if (!passwordValid) {
return null;
}
return {
id: String(user.id),
name: user.name,
email: user.email,
};
} catch (error) {
console.error(
"AUTH ERROR:",
error
);
return null;
}
},
}),
],
session: {
strategy: "jwt",
},
callbacks: {
async jwt({ token, user }) {
if (user?.id) {
token.sub = String(user.id);
}
return token;
},
async session({ session, token }) {
if (
session.user &&
token.sub
) {
session.user.id =
String(token.sub);
}
return session;
},
},
pages: {
signIn: "/login",
},
secret: process.env.AUTH_SECRET,
});