Database
This commit is contained in:
59
lib/auth.ts
Normal file
59
lib/auth.ts
Normal file
@@ -0,0 +1,59 @@
|
||||
import { jwtVerify, SignJWT } from 'jose';
|
||||
import { cookies } from 'next/headers';
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
|
||||
const secret = new TextEncoder().encode(
|
||||
process.env.JWT_SECRET || 'default-secret-key'
|
||||
);
|
||||
|
||||
export interface SessionPayload {
|
||||
userId: string;
|
||||
username: string;
|
||||
iat?: number;
|
||||
exp?: number;
|
||||
}
|
||||
|
||||
export async function encrypt(payload: SessionPayload) {
|
||||
return await new SignJWT(payload as unknown as Record<string, unknown>)
|
||||
.setProtectedHeader({ alg: 'HS256' })
|
||||
.setIssuedAt()
|
||||
.setExpirationTime('24h')
|
||||
.sign(secret);
|
||||
}
|
||||
|
||||
export async function decrypt(token: string): Promise<SessionPayload | null> {
|
||||
try {
|
||||
const { payload } = await jwtVerify(token, secret, {
|
||||
algorithms: ['HS256'],
|
||||
});
|
||||
return payload as unknown as SessionPayload;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function getSession() {
|
||||
const cookieStore = await cookies();
|
||||
const token = cookieStore.get('session')?.value;
|
||||
if (!token) return null;
|
||||
return await decrypt(token);
|
||||
}
|
||||
|
||||
export async function withAuth(
|
||||
request: NextRequest,
|
||||
handler: (req: NextRequest, session: SessionPayload) => Promise<NextResponse>
|
||||
) {
|
||||
const token = request.cookies.get('session')?.value;
|
||||
|
||||
if (!token) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
}
|
||||
|
||||
const session = await decrypt(token);
|
||||
|
||||
if (!session) {
|
||||
return NextResponse.json({ error: 'Invalid token' }, { status: 401 });
|
||||
}
|
||||
|
||||
return handler(request, session);
|
||||
}
|
||||
Reference in New Issue
Block a user