-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.ts
52 lines (42 loc) · 1.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
import { lucia } from "~/lib/auth.server";
import type { Request, Response, NextFunction } from "express";
import { parseCookies } from "oslo/cookie";
import { verifyRequestOrigin } from "lucia";
export async function auth(request: Request, response: Response) {
const sessionId = parseCookies(request.headers.cookie || "").get(
lucia.sessionCookieName
);
if (!sessionId) {
return { user: null, session: null };
}
const result = await lucia.validateSession(sessionId);
if (result.session && result.session.fresh) {
const sessionCookie = lucia.createSessionCookie(result.session.id);
response.setHeader("Set-Cookie", sessionCookie.serialize());
}
if (!result.session) {
const sessionCookie = lucia.createBlankSessionCookie();
response.setHeader("Set-Cookie", sessionCookie.serialize());
}
return result;
}
export function csrfProtection(
request: Request,
response: Response,
next: NextFunction
) {
if (request.method === "GET") {
return next();
}
const originHeader = request.headers.origin ?? null;
// NOTE: You may need to use `X-Forwarded-Host` instead
const hostHeader = request.headers.host ?? null;
if (
!originHeader ||
!hostHeader ||
!verifyRequestOrigin(originHeader, [hostHeader])
) {
return response.status(403).end();
}
return next();
}