This commit is contained in:
Şahan Hasret
2025-11-21 17:46:30 +03:00
parent c0b7fb463e
commit 76c31274d5
46 changed files with 3675 additions and 1043 deletions

59
lib/auth.ts Normal file
View 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);
}