-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathauth.ts
81 lines (74 loc) · 2.37 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
import NextAuth from "next-auth";
import { jwtDecode } from "jwt-decode";
import { userInfo } from "@/types/next-auth";
import { JWT } from "next-auth/jwt";
import Credentials from "@auth/core/providers/credentials";
const BASE_URL = process.env.NEXT_PUBLIC_APIBASE_URL;
export const {
handlers: { GET, POST },
auth,
signIn,
signOut,
} = NextAuth({
providers: [
Credentials({
credentials: {},
async authorize(credentials) {
if (!credentials) return null;
const { email, password } = credentials as any;
const res = await fetch(`${BASE_URL}/auth/login`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email, password }),
});
const user = await res.json();
if (res.ok && user) {
return user;
} else {
throw new Error(user.message || "Authentication failed");
}
},
}),
],
callbacks: {
async jwt({ token, user }) {
if (user) {
token.access = user?.access;
token.refresh = user?.refresh;
token.expiresAt = Math.floor(Date.now() / 1000 + 60 * 60 * 24);
token.userInfo = jwtDecode<userInfo>(user?.access);
return token;
} else if (Date.now() < token?.expiresAt * 1000) {
return token;
} else {
try {
const res = await fetch(`${BASE_URL}/auth/refresh`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ refresh: token.refresh }),
});
const tokens = await res.json();
if (!res.ok) throw tokens;
token.access = tokens?.access;
token.expiresAt = Math.floor(Date.now() / 1000 + 60 * 60 * 24);
return token;
} catch (error) {
console.error("Error refreshing access token", error);
return { ...token, error: "RefreshAccessTokenError" as const };
}
}
},
// @ts-ignore
async session({ session, token }) {
const { userInfo, refresh, access, error } = token;
session.user = userInfo;
session.accessToken = access;
session.refreshToken = refresh;
session.error = error;
return session;
},
},
pages: { signIn: "/login" },
secret: process.env.NEXTAUTH_SECRET,
session: { strategy: "jwt", maxAge: 3 * 24 * 60 * 60 },
});