-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.ts
86 lines (77 loc) · 2.07 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
import type { DefaultSession, User, NextAuthOptions } from "next-auth";
import clientPromise from "@mongodb";
import bcrypt from "bcrypt";
import { WithId } from "mongodb";
import CredentialsProvider from "next-auth/providers/credentials";
declare module "next-auth" {
/** The User that is returned from authorize */
interface User {
/** The user's role. */
role: string;
}
}
declare module "next-auth" {
/**
* Returned by `useSession`, `getSession` and received as a prop on the `SessionProvider` React Context
*/
interface Session {
user: {
/** The user's postal address. */
address: string;
} & DefaultSession["user"];
}
}
declare module "next-auth/jwt" {
interface JWT {
/** The user's role. */
role: string;
}
}
export type UserDocument = WithId<{
email: string;
hash: string;
role: string;
}>;
export const config = {
providers: [
CredentialsProvider({
name: "Credentials",
credentials: {
email: { label: "Email", type: "email", placeholder: "email" },
password: { label: "Password", type: "password" },
},
async authorize(credentials) {
if (!credentials?.email || !credentials?.password) {
return null;
}
const mongo = await clientPromise;
const user = await mongo
.db("olsen-park")
.collection<UserDocument>("users")
.findOne({ email: credentials.email });
if (!user) {
return null;
}
const passwordsMatch = await bcrypt.compare(
credentials.password,
user.hash
);
if (!passwordsMatch) {
return Promise.resolve(null);
}
return Promise.resolve({ email: user.email, role: user.role } as User);
},
}),
],
pages: {
signIn: "/login",
},
callbacks: {
async jwt({ token, user, account, profile, isNewUser }) {
return { ...token, ...(user && { role: user.role }) };
},
session: async ({ session, token, user }) => {
return { ...session, role: token.role };
},
},
} as NextAuthOptions;