forked from balazsorban44/auth-poc-next
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlib.ts
62 lines (51 loc) · 1.67 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
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(formData: FormData) {
// Verify credentials && get the user
const user = { email: formData.get("email"), name: "John" };
// Create the session
const expires = new Date(Date.now() + 10 * 1000);
const session = await encrypt({ user, expires });
// Save the session in a cookie
cookies().set("session", session, { expires, httpOnly: true });
}
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;
}