-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.js
65 lines (59 loc) · 1.58 KB
/
auth.js
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
import NextAuth from 'next-auth'
import CredentialsProvider from 'next-auth/providers/credentials'
import { authConfig } from './auth.config'
import { connectToDB } from './app/lib/utils'
import bcrypt from 'bcrypt'
import { User } from './app/lib/models'
let loginErrorMsg = ''
export const getLoginErrorMsg = () => loginErrorMsg
const login = async (credentials) => {
try {
connectToDB()
const user = await User.findOne({ username: credentials.username })
if (!user) throw new Error('The user does not exist!')
const isPasswordCorrect = await bcrypt.compare(
credentials.password,
user.password
)
if (!isPasswordCorrect) throw new Error('Wrong password!')
return user
} catch (err) {
throw new Error(err.message)
}
}
export const { signIn, signOut, auth } = NextAuth({
...authConfig,
providers: [
CredentialsProvider({
async authorize(credentials) {
try {
const user = await login(credentials)
return user
} catch (err) {
loginErrorMsg = err.message
return null
}
},
}),
],
// ADD ADDITIONAL INFORMATION TO SESSION
callbacks: {
async jwt({ token, user }) {
if (user) {
token.username = user.username
token.isAdmin = user.isAdmin
token.img = user.img
}
return token
},
async session({ session, token }) {
if (token) {
session.username = token.username
session.email = token.email
session.isAdmin = token.isAdmin
session.img = token.img
}
return session
},
},
})