-
Notifications
You must be signed in to change notification settings - Fork 1
/
auth.ts
201 lines (178 loc) · 5.32 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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
import type { User } from "next-auth";
import { decode, type JWT } from "next-auth/jwt";
import NextAuth from "next-auth";
import KakaoProvider from "next-auth/providers/kakao";
import { getRefreshToken, postOauthLogin } from "@/apis/auth/auth";
import { SocialLoginRequest } from "@/apis/auth/authType";
import { getMe } from "@/apis/user/me/me";
import { env } from "@/env";
import { decodeToken } from "@/lib/jwt";
import type { UserMeResponse } from "@/apis/user/me/meType";
const serviceReadyRoute = ["/chat", "/map", "/calander"];
const matchersForAuth = ["/mypage"];
const matchersForSignIn = ["/auth/sign-in"];
export const { handlers, auth, signIn, signOut, unstable_update } = NextAuth({
providers: [
KakaoProvider({
clientId: env.AUTH_KAKAO_ID,
clientSecret: env.AUTH_KAKAO_SECRET,
}),
],
secret: env.AUTH_SECRET,
pages: {
signIn: "/auth/sign-in",
signOut: "/auth/sign-in",
error: "/auth/sign-in",
},
callbacks: {
authorized: async ({ request, auth }) => {
if (matchersForAuth.some((v) => v == request.nextUrl.pathname)) {
return !!auth;
}
if (
!request.nextUrl.pathname.includes("onboarding") &&
!request.nextUrl.pathname.includes("sign-in") &&
!!auth?.accessToken &&
!auth?.user.isProfileRegistered
) {
return false;
}
return true;
},
redirect: async ({ url, baseUrl }) => {
if (url.startsWith("/")) return `${baseUrl}${url}`;
if (url) {
const { search, origin } = new URL(url);
const callbackUrl = new URLSearchParams(search).get("callbackUrl");
if (callbackUrl)
return callbackUrl.startsWith("/")
? `${baseUrl}${callbackUrl}`
: callbackUrl;
if (origin === baseUrl) return url;
}
return baseUrl;
},
async jwt({ token, session, user, trigger, account }) {
if (trigger === "update") {
token.user = {
...session.user,
};
}
if (user) {
if (account && account.access_token) {
const body: SocialLoginRequest = {
id: user.id as string,
email: user.email as string,
accessToken: account.access_token as string,
};
const { accessToken, refreshToken } = await postOauthLogin(body);
const userResponse = await getMe({
headers: {
Authorization: `Bearer ${accessToken}`,
},
});
token.user = { ...user, ...userResponse };
token = {
...token,
refreshToken,
accessToken,
};
return token;
}
}
if (!token.accessToken) {
return null;
}
if (!!token.accessToken) {
const decodedJWT = decodeToken(token.accessToken);
if (decodedJWT) {
token.exp = decodedJWT.exp;
}
}
if (
!!token.refreshToken &&
token?.exp &&
token?.exp * 1000 < Date.now()
) {
const { accessToken, refreshToken } = await getRefreshToken(
token.refreshToken,
);
token.accessToken = accessToken;
token.refreshToken = refreshToken;
}
return token;
},
async session({ session, token }) {
if (token?.accessToken) {
session.user = {
...session.user,
userId: token.user.userId as number,
email: token.user.email as string,
nickname: token.user.nickname as string,
statusMessage: token.user.statusMessage as string,
profileImage: token.user.profileImage as string,
userTypeId: token.user.userTypeId as number,
isProfileRegistered: token.user.isProfileRegistered as boolean,
};
session.accessToken = token.accessToken;
session.refreshToken = token.refreshToken;
session.exp = token.exp;
session.iat = token.iat;
session.sub = token.sub;
}
return session;
},
},
// ? 인증 및 데이터베이스 작업에 대한 디버그 메시지를 사용하려면 디버그를 true로 설정합니다.
// debug: process.env.NODE_ENV !== "production" ? true : false,
});
declare module "next-auth" {
// * 카카오 Account 응답에 맞게 수정
interface Account {
access_token?: string;
token_type?: string;
refresh_token?: string;
expires_in?: number;
refresh_token_expires_in?: number;
expires_at?: number;
provider: string;
providerAccountId: string;
}
// * 세션이 accessToken 필드값 추가 ( 필요에 따라 더 추가 )
interface Session {
user: User & UserMeResponse;
accessToken?: string;
refreshToken?: string;
exp?: number;
iat?: number;
sub?: string;
}
interface User {
userId: number;
nickname: string;
statusMessage: string;
profileImage: string;
isProfileRegistered: boolean;
userTypeId: number;
}
}
declare module "next-auth/jwt" {
interface JWT {
user: {
userId?: number;
email?: string;
nickname?: string;
statusMessage?: string;
profileImage?: string;
userTypeId?: number;
accessToken?: string;
refreshToken?: string;
isProfileRegistered?: boolean;
};
accessToken?: string;
refreshToken?: string;
exp?: number;
iat?: number;
sub?: string;
}
}