-
Notifications
You must be signed in to change notification settings - Fork 3
/
auth.ts
79 lines (76 loc) · 2.13 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
import NextAuth, { type DefaultSession } from 'next-auth'
import CredentialsProvider from 'next-auth/providers/credentials' // Import CredentialsProvider
declare module 'next-auth' {
interface Session {
user: {
/** The user's id. */
id: string
jwt: string
role: string
} & DefaultSession['user']
}
}
export const {
handlers: { GET, POST },
auth
} = NextAuth({
// Specify the authentication providers
secret: "sdfdf3432T%RGTF#$t",
providers: [
// CredentialsProvider for username and password authentication
CredentialsProvider({
name: 'Credentials',
credentials: {
username: { label: "Username", type: "text" },
password: { label: "Password", type: "password" }
},
async authorize(credentials, req) {
// Replace "/api/auth" with your actual authentication endpoint
const res = await fetch(`http://localhost:3000/api/u`, {
// const res = await fetch(`https://hai-doc-prod.coffeecodes.in/api/u`, {
method: 'POST',
body: JSON.stringify(credentials),
headers: { "Content-Type": "application/json" },
})
const r = await res.json()
console.log(r)
let user = {
id: "",
message: "",
type: "",
token: ""
}
user.message = "Logged in";
user.token = r.data;
if (!res.ok) {
throw new Error(user.message);
}
// If the response is ok and user data is returned, authenticate the user
if (res.ok && user) {
return {...user}
}
return null;
}
}),
],
callbacks: {
jwt({ token, user }) {
if (user && 'token' in user && 'type' in user) {
token.jwt = user.token
token.type = user.type
}
return token
},
session({ session, token }) {
// Assign the user ID from the token to the session's user object
if (session?.user) {
session.user.jwt = String(token.jwt)
session.user.role = String(token.type)
}
return session
}
},
pages: {
signIn: '/login', // Custom sign-in page URL
}
});