forked from Bitcoindefi/OpenAO
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshared.ts
More file actions
239 lines (201 loc) · 6.14 KB
/
Copy pathshared.ts
File metadata and controls
239 lines (201 loc) · 6.14 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
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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
import { cookies } from "next/headers";
import { NextResponse } from "next/server";
import type { AuthErrorResponse, AuthSession } from "../../../lib/auth";
import { normalizeErrorPayload } from "../../../lib/api-errors";
import { AUTH_COOKIE_NAME } from "../../../lib/auth-session";
import { getApiBaseUrl } from "../../../lib/api-base-url";
const SESSION_MAX_AGE_SECONDS = 60 * 60 * 24 * 7;
const API_REQUEST_TIMEOUT_MS = 8000;
type ApiAuthResponse = AuthSession & {
sessionToken: string;
};
type CookieRequest = Pick<Request, "headers" | "url">;
export async function fetchApi(
path: string,
init?: RequestInit,
): Promise<Response> {
const controller = new AbortController();
const timeoutId = setTimeout(
() => controller.abort(),
API_REQUEST_TIMEOUT_MS,
);
try {
return await fetch(`${getApiBaseUrl()}${path}`, {
...init,
signal: controller.signal,
});
} catch (error) {
if (error instanceof Error && error.name === "AbortError") {
return NextResponse.json(
{
error: `La API no respondio dentro de ${API_REQUEST_TIMEOUT_MS}ms.`,
},
{ status: 504 },
);
}
throw error;
} finally {
clearTimeout(timeoutId);
}
}
export async function proxyJsonResponse(
response: Response,
): Promise<NextResponse> {
const result = normalizeErrorPayload(await response.json());
return NextResponse.json(result, { status: response.status });
}
function setSessionCookie(
response: NextResponse,
token: string,
request: CookieRequest,
): NextResponse {
response.cookies.set({
name: AUTH_COOKIE_NAME,
value: token,
httpOnly: true,
sameSite: "lax",
secure: shouldUseSecureCookies(request),
path: "/",
maxAge: SESSION_MAX_AGE_SECONDS,
});
return response;
}
export async function forwardSessionJsonRequest(
path: string,
init: RequestInit,
request: CookieRequest,
): Promise<NextResponse> {
const token = await getSessionTokenFromCookie();
if (!token) {
return NextResponse.json(
{ error: "Tu sesion no es valida o ya vencio." },
{ status: 401 },
);
}
const headers = new Headers(init.headers);
headers.set("Authorization", `Bearer ${token}`);
const response = await fetchApi(path, {
...init,
headers,
cache: "no-store",
});
if (response.status === 401) {
const cleared = await clearSessionCookie(request);
const proxied = await proxyJsonResponse(response);
return NextResponse.json(await proxied.json(), {
status: proxied.status,
headers: cleared.headers,
});
}
return setSessionCookie(await proxyJsonResponse(response), token, request);
}
function shouldUseSecureCookies(request: CookieRequest): boolean {
const forwardedProto = request.headers
.get("x-forwarded-proto")
?.split(",")[0]
?.trim();
if (forwardedProto) {
return forwardedProto === "https";
}
return new URL(request.url).protocol === "https:";
}
export async function forwardAuthRequest(
path: string,
body: unknown,
request: CookieRequest,
): Promise<NextResponse> {
const response = await fetchApi(path, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(body),
cache: "no-store",
});
const result = normalizeErrorPayload(
(await response.json()) as ApiAuthResponse | AuthErrorResponse,
);
if (!response.ok) {
return NextResponse.json(result, { status: response.status });
}
const nextResponse = NextResponse.json(result);
if (!("sessionToken" in result)) {
return nextResponse;
}
setSessionCookie(nextResponse, result.sessionToken, request);
return NextResponse.json(
{
account: result.account,
characters: result.characters,
selectedCharacterId: result.selectedCharacterId,
},
{
status: nextResponse.status,
headers: nextResponse.headers,
},
);
}
export async function getSessionTokenFromCookie(): Promise<string | null> {
const cookieStore = await cookies();
const token = cookieStore.get(AUTH_COOKIE_NAME)?.value?.trim();
return token || null;
}
export async function fetchApiSession(token: string): Promise<NextResponse> {
const response = await fetchApi("/auth/session", {
headers: {
Authorization: `Bearer ${token}`,
},
cache: "no-store",
});
return proxyJsonResponse(response);
}
export async function forwardLogout(
token: string | null,
request: CookieRequest,
): Promise<NextResponse> {
if (token) {
await fetchApi("/auth/logout", {
method: "POST",
headers: {
Authorization: `Bearer ${token}`,
},
cache: "no-store",
});
}
return clearSessionCookie(request);
}
export async function readSessionFromApi(
request: CookieRequest,
): Promise<NextResponse> {
const token = await getSessionTokenFromCookie();
if (!token) {
return NextResponse.json(
{ error: "Tu sesion no es valida o ya vencio." },
{ status: 401 },
);
}
const response = await fetchApiSession(token);
if (response.status === 401) {
const cleared = await clearSessionCookie(request);
return NextResponse.json(
{ error: "Tu sesion no es valida o ya vencio." },
{ status: 401, headers: cleared.headers },
);
}
return setSessionCookie(response, token, request);
}
export async function clearSessionCookie(
request: CookieRequest,
): Promise<NextResponse> {
const response = NextResponse.json({ ok: true });
response.cookies.set({
name: AUTH_COOKIE_NAME,
value: "",
httpOnly: true,
sameSite: "lax",
secure: shouldUseSecureCookies(request),
path: "/",
maxAge: 0,
});
return response;
}