-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.ts
109 lines (100 loc) · 2.48 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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
import NextAuth, { type DefaultSession, User } from "next-auth"
import Credentials from "next-auth/providers/credentials"
import { CredentialsSignin } from "next-auth"
import axios from "axios"
import { JWT } from "next-auth/jwt"
declare module "next-auth" {
interface User {
userRoleId: number
userStatusId: number
username: string
photo: string
userToken: string
emailVerifiedAt: Date
createdAt: Date
updatedAt: Date
user_role: {
userRoleName: string
}
user_status: {
userStatusName: string
}
}
interface Session {
user: User & DefaultSession["user"]
}
}
declare module "next-auth/jwt" {
interface JWT {
user: User
}
}
export const { handlers, signIn, signOut, auth } = NextAuth({
providers: [
Credentials({
credentials: {
username: {},
password: {},
},
authorize: async (credentials) => {
try {
const backendUrl = process.env.BACKEND_URL
const response = await axios.post(`${backendUrl}/auth`, credentials)
const user = response.data.data.user
user.userToken = response.data.data.user_token.token
return user
} catch (error: any) {
if (error.response.data.message) {
throw new CredentialsSignin(error.response.data.message)
} else {
throw new Error("Something went wrong!")
}
}
},
}),
],
pages: {
signIn: "/",
},
callbacks: {
authorized: async ({ auth, request: { nextUrl } }) => {
const isLoggedIn = !!auth?.user
const isOnLogin = nextUrl.pathname == "/"
if (isLoggedIn) {
if (isOnLogin) {
return Response.redirect(new URL("/dashboard", nextUrl))
} else {
return true
}
} else {
if (isOnLogin) {
return false
} else {
const loginUrl = new URL("/", nextUrl)
loginUrl.searchParams.set("alert", "unauthorized")
return Response.redirect(loginUrl)
}
}
},
jwt({ token, user, trigger, session }) {
// login data
if (user) {
return { ...token, user }
}
// update profile
if (trigger === "update") {
return { ...token, user: { ...token.user, ...session.user } }
}
return token
},
session({ session, token }) {
return {
...session,
user: {
...session?.user,
...token.user,
},
}
},
},
})