-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.ts
More file actions
78 lines (65 loc) · 1.92 KB
/
Copy pathauth.ts
File metadata and controls
78 lines (65 loc) · 1.92 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
import bcrypt from "bcryptjs";
import jwt from "jsonwebtoken";
import { cookies } from "next/headers";
import type { User } from "@prisma/client";
import { prisma } from "@/lib/prisma";
export const AUTH_COOKIE = "auth_token";
const JWT_SECRET = process.env.JWT_SECRET ?? "dev-secret-change-me-in-production";
const SESSION_TTL_SECONDS = 60 * 60 * 24 * 7; // 7 days
const SESSION_TTL = "7d";
export interface SessionPayload {
sub: string; // user id
email: string;
}
export async function hashPassword(password: string): Promise<string> {
return bcrypt.hash(password, 12);
}
export async function verifyPassword(
password: string,
hash: string,
): Promise<boolean> {
return bcrypt.compare(password, hash);
}
export function signSessionToken(payload: SessionPayload): string {
return jwt.sign(payload, JWT_SECRET, { expiresIn: SESSION_TTL });
}
export function verifySessionToken(token: string): SessionPayload | null {
try {
const decoded = jwt.verify(token, JWT_SECRET);
if (typeof decoded === "string" || !decoded.sub || !decoded.email) {
return null;
}
return { sub: decoded.sub as string, email: decoded.email as string };
} catch {
return null;
}
}
export async function getSessionUser(): Promise<User | null> {
const cookieStore = await cookies();
const token = cookieStore.get(AUTH_COOKIE)?.value;
if (!token) return null;
const payload = verifySessionToken(token);
if (!payload) return null;
const user = await prisma.user.findUnique({
where: { id: payload.sub },
});
return user ?? null;
}
export function sessionCookieOptions() {
return {
httpOnly: true,
sameSite: "lax" as const,
secure: process.env.NODE_ENV === "production",
path: "/",
maxAge: SESSION_TTL_SECONDS,
};
}
export function sanitizeUser(user: User) {
return {
id: user.id,
name: user.name,
email: user.email,
isAdmin: user.isAdmin,
createdAt: user.createdAt,
};
}