40 lines
1.0 KiB
TypeScript
40 lines
1.0 KiB
TypeScript
import { SignJWT, jwtVerify } from 'jose';
|
|
import { cookies } from 'next/headers';
|
|
import { NextRequest, NextResponse } from 'next/server';
|
|
|
|
const secretKey = process.env.JWT_SECRET || 'fallback_secret';
|
|
const key = new TextEncoder().encode(secretKey);
|
|
|
|
export async function encrypt(payload: any) {
|
|
return await new SignJWT(payload)
|
|
.setProtectedHeader({ alg: 'HS256' })
|
|
.setIssuedAt()
|
|
.setExpirationTime('2h')
|
|
.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) {
|
|
// Real login logic will be in a server action, this is just for session management
|
|
}
|
|
|
|
export async function logout() {
|
|
(await cookies()).set('session', '', { expires: new Date(0) });
|
|
}
|
|
|
|
export async function getSession() {
|
|
const session = (await cookies()).get('session')?.value;
|
|
if (!session) return null;
|
|
try {
|
|
return await decrypt(session);
|
|
} catch (e) {
|
|
return null;
|
|
}
|
|
}
|