64 lines
1.5 KiB
TypeScript
64 lines
1.5 KiB
TypeScript
import 'server-only'
|
|
import { cookies } from 'next/headers'
|
|
import { SignJWT, jwtVerify } from 'jose'
|
|
/* import { SessionPayload } from '@/app/lib/definitions' */
|
|
|
|
const secretKey = process.env.SESSION_SECRET
|
|
const encodedKey = new TextEncoder().encode(secretKey)
|
|
|
|
export async function encrypt(payload: any) {
|
|
return new SignJWT(payload)
|
|
.setProtectedHeader({ alg: 'HS256' })
|
|
.setIssuedAt()
|
|
.setExpirationTime('7d')
|
|
.sign(encodedKey)
|
|
}
|
|
|
|
export async function decrypt(session: string | undefined = '') {
|
|
try {
|
|
const { payload } = await jwtVerify(session, encodedKey, {
|
|
algorithms: ['HS256'],
|
|
})
|
|
return payload
|
|
} catch (error) {
|
|
console.log('Failed to verify session')
|
|
}
|
|
}
|
|
|
|
export async function createSession(token: string) {
|
|
const expiresAt = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000);
|
|
const session = await encrypt({ token, expiresAt });
|
|
const cookieStore = await cookies();
|
|
|
|
cookieStore.set('session', session, {
|
|
httpOnly: true,
|
|
secure: true,
|
|
expires: expiresAt,
|
|
sameSite: 'lax',
|
|
path: '/',
|
|
})
|
|
}
|
|
|
|
export async function getSessionToken(): Promise<string | null> {
|
|
const cookieStore = await cookies();
|
|
const sessionCookie = cookieStore.get('session')?.value;
|
|
|
|
if (!sessionCookie) {
|
|
return null;
|
|
}
|
|
|
|
const payload = await decrypt(sessionCookie);
|
|
|
|
if (payload && typeof payload === 'object' && 'token' in payload) {
|
|
return payload.token as string;
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
|
|
|
|
export async function deleteSession() {
|
|
const cookieStore = await cookies()
|
|
cookieStore.delete('session')
|
|
} |