-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathserver-auth.ts
More file actions
152 lines (126 loc) Β· 3.8 KB
/
server-auth.ts
File metadata and controls
152 lines (126 loc) Β· 3.8 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
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
import { cookies } from 'next/headers';
import { getServerSession } from 'next-auth';
import { getToken } from 'next-auth/jwt';
import type { JWT } from 'next-auth/jwt';
import { authOptions } from '@/lib/auth';
export const CLIENT_SESSION_TOKEN = 'server-session';
const authDebugEnabled = process.env.AUTH_DEBUG === 'true';
export async function getAppAuthSession() {
const session = await getServerSession(authOptions);
if (authDebugEnabled) {
console.info('[auth][session]', {
source: 'getAppAuthSession',
hasUser: Boolean(session?.user),
userId: session?.user?.id ?? null,
userEmail: session?.user?.email ?? null,
error: session?.error ?? null
});
}
return session;
}
export async function getApiAccessToken() {
const token = await getJwtTokenFromCookies();
if (!token || isAccessTokenExpired(token)) {
return null;
}
return typeof token.accessToken === 'string' ? token.accessToken : null;
}
export async function getIdToken() {
const token = await getJwtTokenFromCookies();
if (!token) {
return null;
}
return typeof token.idToken === 'string' ? token.idToken : null;
}
export async function getJwtTokenFromCookies() {
const cookieStore = await cookies();
const allCookies = cookieStore.getAll();
if (!allCookies.length) {
if (authDebugEnabled) {
console.warn('[auth][token]', {
source: 'getJwtTokenFromCookies',
reason: 'no-cookies'
});
}
return null;
}
const req = {
cookies: cookieStore,
headers: {
cookie: allCookies.map((cookie) => `${cookie.name}=${cookie.value}`).join('; ')
}
} as unknown as Parameters<typeof getToken>[0]['req'];
const sessionCookieVariants = [
{
cookieName: '__Secure-next-auth.session-token',
secureCookie: true
},
{
cookieName: 'next-auth.session-token',
secureCookie: false
}
].filter(({ cookieName }) =>
allCookies.some(
(cookie) => cookie.name === cookieName || cookie.name.startsWith(`${cookieName}.`)
)
);
if (authDebugEnabled) {
console.info('[auth][token]', {
source: 'getJwtTokenFromCookies',
availableCookieNames: allCookies.map((cookie) => cookie.name),
sessionCookieVariants: sessionCookieVariants.map((variant) => variant.cookieName)
});
}
for (const variant of sessionCookieVariants) {
const token = (await getToken({
req,
secret: process.env.AUTH_SECRET,
cookieName: variant.cookieName,
secureCookie: variant.secureCookie
})) as JWT | null;
if (authDebugEnabled) {
console.info('[auth][token]', {
source: 'getJwtTokenFromCookies',
attemptedCookieName: variant.cookieName,
hasToken: Boolean(token),
hasAccessToken: typeof token?.accessToken === 'string',
hasIdToken: typeof token?.idToken === 'string',
error: token?.error ?? null
});
}
if (token) {
return token;
}
}
const fallbackToken = (await getToken({
req,
secret: process.env.AUTH_SECRET
})) as JWT | null;
if (authDebugEnabled) {
console.info('[auth][token]', {
source: 'getJwtTokenFromCookies',
attemptedCookieName: 'default',
hasToken: Boolean(fallbackToken),
hasAccessToken: typeof fallbackToken?.accessToken === 'string',
hasIdToken: typeof fallbackToken?.idToken === 'string',
error: fallbackToken?.error ?? null
});
}
return fallbackToken;
}
export function isAccessTokenExpired(token: JWT | null) {
if (!token || typeof token.accessToken !== 'string') {
return true;
}
if (token.error === 'AccessTokenExpired') {
return true;
}
if (
typeof token.accessTokenExpiresAt === 'number' &&
Number.isFinite(token.accessTokenExpiresAt) &&
Date.now() >= token.accessTokenExpiresAt
) {
return true;
}
return false;
}