68 lines
1.6 KiB
TypeScript
68 lines
1.6 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 secretKey = 'AAA+sq1yKte/gMgUUu/B/OyXqr45/LMYplPVOlWc+uo='
|
|
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, email: string) {
|
|
const expiresAt = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000);
|
|
const session = await encrypt({
|
|
token,
|
|
email,
|
|
expiresAt
|
|
});
|
|
const cookieStore = await cookies();
|
|
|
|
cookieStore.set('session', session, {
|
|
httpOnly: true,
|
|
secure: false,
|
|
expires: expiresAt,
|
|
sameSite: 'lax',
|
|
path: '/',
|
|
});
|
|
}
|
|
|
|
export async function getSessionData(type: 'token' | 'email'): 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' && type in payload) {
|
|
return payload[type] as string;
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
|
|
export async function deleteSession() {
|
|
const cookieStore = await cookies()
|
|
cookieStore.delete('session');
|
|
} |