-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlib.ts
73 lines (61 loc) · 1.91 KB
/
lib.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
import Axios from "clients/Axios";
import { SignJWT, jwtVerify } from "jose";
import { cookies } from "next/headers";
import { NextRequest, NextResponse } from "next/server";
const secretKey = "secret";
const key = new TextEncoder().encode(secretKey);
export async function encrypt(payload: any) {
return await new SignJWT(payload)
.setProtectedHeader({ alg: "HS256" })
.setIssuedAt()
.setExpirationTime("10 sec from now")
.sign(key);
}
export async function decrypt(input: string): Promise<any> {
const { payload } = await jwtVerify(input, key, {
algorithms: ["HS256"],
});
return payload;
}
export async function login(username, password) {
try {
// Make the request to the proxied backend API endpoint
const response = await Axios.post("/api/users/login", {
username,
password,
});
console.log(response.data);
const user = { username, password };
// Create the session
const expires = new Date(Date.now() + 10 * 1000);
const session = await encrypt(user);
// Save the session in a cookie
cookies().set("session", session, { expires, httpOnly: true });
} catch (error) {
console.error("Failed to login:", error);
}
}
export async function logout() {
// Destroy the session
cookies().set("session", "", { expires: new Date(0) });
}
export async function getSession() {
const session = cookies().get("session")?.value;
if (!session) return null;
return await decrypt(session);
}
export async function updateSession(request: NextRequest) {
const session = request.cookies.get("session")?.value;
if (!session) return;
// Refresh the session so it doesn't expire
const parsed = await decrypt(session);
parsed.expires = new Date(Date.now() + 10 * 1000);
const res = NextResponse.next();
res.cookies.set({
name: "session",
value: await encrypt(parsed),
httpOnly: true,
expires: parsed.expires,
});
return res;
}