-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.ts
More file actions
86 lines (83 loc) · 2.59 KB
/
Copy pathauth.ts
File metadata and controls
86 lines (83 loc) · 2.59 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
import { bagistoFetch } from 'lib/bagisto';
import { CustomerLogin } from 'lib/bagisto/mutations/customer-login';
import { TOKEN } from 'lib/constants';
import { isObject } from 'lib/type-guards';
import NextAuth, { NextAuthOptions } from 'next-auth';
import CredentialsProvider from 'next-auth/providers/credentials';
import { cookies } from 'next/headers';
export const authOptions: NextAuthOptions = {
providers: [
CredentialsProvider({
name: 'Credentials',
credentials: {
username: { label: 'username', type: 'username', placeholder: 'jsmith' },
password: { label: 'Password', type: 'password' }
},
authorize: async (
credentials: Record<'password' | 'username', string> | undefined
): Promise<any> => {
/* Getting Token from generateCustomerToken */
const input = {
email: credentials?.username,
password: credentials?.password
};
try {
const res = await bagistoFetch<any>({
query: CustomerLogin,
variables: {
input
},
cache: 'no-store'
});
console.log(res);
if (
res?.status === 200 &&
isObject(res?.body?.data) &&
isObject(res?.body?.data?.customerLogin)
) {
const customerInfo = res?.body?.data?.customerLogin;
cookies().set(TOKEN, customerInfo?.accessToken);
return {
firstname: customerInfo.customer.firstName,
lastname: customerInfo.customer.lastName,
name: customerInfo.customer.name,
token: customerInfo.accessToken,
email: customerInfo.customer.email,
tokenLifeTime: customerInfo.expiresIn
};
} else {
throw new Error('Something went wrong.');
}
} catch (error: any) {
throw new Error((error?.error?.message as string) || 'Something went wrong!');
}
}
})
],
secret: process.env.NEXTAUTH_SECRET,
callbacks: {
jwt: async ({ token, user }) => {
if (isObject(user) && user.token) {
token.accessToken = user.token;
token.role = 'customer';
}
return token;
},
async session({ session, token }) {
return {
...session,
user: {
...session.user,
accessToken: token.accessToken as string,
role: token.role
},
error: token.error
};
}
},
pages: {
signIn: '/customer/login',
error: '/login'
}
};
export const handler = NextAuth(authOptions);