Mist, jetzt vielleicht
This commit is contained in:
70
lib/session.ts
Normal file
70
lib/session.ts
Normal file
@@ -0,0 +1,70 @@
|
||||
import { cookies } from 'next/headers';
|
||||
import { SignJWT, jwtVerify } from 'jose';
|
||||
|
||||
const SESSION_COOKIE_NAME = 'auth_session';
|
||||
const SESSION_DURATION = 7 * 24 * 60 * 60 * 1000; // 7 Tage
|
||||
|
||||
const secretKey = process.env.AUTH_SECRET || 'default-secret-change-in-production';
|
||||
const key = new TextEncoder().encode(secretKey);
|
||||
|
||||
export interface SessionData {
|
||||
username: string;
|
||||
isAuthenticated: boolean;
|
||||
expiresAt: number;
|
||||
}
|
||||
|
||||
async function encrypt(payload: SessionData): Promise<string> {
|
||||
return await new SignJWT(payload as unknown as Record<string, unknown>)
|
||||
.setProtectedHeader({ alg: 'HS256' })
|
||||
.setIssuedAt()
|
||||
.setExpirationTime(new Date(payload.expiresAt))
|
||||
.sign(key);
|
||||
}
|
||||
|
||||
async function decrypt(token: string): Promise<SessionData | null> {
|
||||
try {
|
||||
const { payload } = await jwtVerify(token, key, {
|
||||
algorithms: ['HS256'],
|
||||
});
|
||||
return {
|
||||
username: payload.username as string,
|
||||
isAuthenticated: payload.isAuthenticated as boolean,
|
||||
expiresAt: payload.expiresAt as number,
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function createSession(username: string): Promise<void> {
|
||||
const expiresAt = Date.now() + SESSION_DURATION;
|
||||
const session: SessionData = { username, isAuthenticated: true, expiresAt };
|
||||
const encryptedSession = await encrypt(session);
|
||||
const cookieStore = await cookies();
|
||||
cookieStore.set(SESSION_COOKIE_NAME, encryptedSession, {
|
||||
httpOnly: true,
|
||||
secure: process.env.NODE_ENV === 'production',
|
||||
expires: expiresAt,
|
||||
sameSite: 'lax',
|
||||
path: '/',
|
||||
});
|
||||
}
|
||||
|
||||
export async function getSession(): Promise<SessionData | null> {
|
||||
const cookieStore = await cookies();
|
||||
const cookie = cookieStore.get(SESSION_COOKIE_NAME);
|
||||
if (!cookie?.value) return null;
|
||||
const session = await decrypt(cookie.value);
|
||||
if (!session || session.expiresAt < Date.now()) return null;
|
||||
return session;
|
||||
}
|
||||
|
||||
export async function deleteSession(): Promise<void> {
|
||||
const cookieStore = await cookies();
|
||||
cookieStore.delete(SESSION_COOKIE_NAME);
|
||||
}
|
||||
|
||||
export async function isAuthenticated(): Promise<boolean> {
|
||||
const session = await getSession();
|
||||
return session?.isAuthenticated ?? false;
|
||||
}
|
||||
Reference in New Issue
Block a user