54 lines
1.3 KiB
TypeScript
54 lines
1.3 KiB
TypeScript
import jwt, { SignOptions } from 'jsonwebtoken'
|
|
import type Session from '.'
|
|
import CookieManager from '../../libs/CookieManager'
|
|
|
|
export interface SessionOptions {
|
|
cookieName: string
|
|
security: SignOptions
|
|
key?: string
|
|
privateKey?: string
|
|
publicKey?: string
|
|
}
|
|
|
|
|
|
export default class SessionDao {
|
|
|
|
private options: SessionOptions = {
|
|
cookieName: 'session',
|
|
security: {
|
|
algorithm: 'ES512'
|
|
},
|
|
privateKey: import.meta.env.PRIVATE_KEY ?? '',
|
|
publicKey: import.meta.env.PUBLIC_KEY ?? ''
|
|
}
|
|
|
|
public getSession(req: Request): Session | null {
|
|
const cookie = new CookieManager(req.headers.get('Cookie') ?? '').get(this.options.cookieName)
|
|
if (!cookie) {
|
|
return null
|
|
}
|
|
try {
|
|
return jwt.verify(cookie, (this.options.publicKey || this.options.key) as string) as Session
|
|
} catch {
|
|
return null
|
|
}
|
|
}
|
|
|
|
public setSession(session: Session, res: ResponseInit & { readonly headers: Headers; }) {
|
|
const token = jwt.sign(session, (this.options.privateKey || this.options.key) as string, this.options.security)
|
|
CookieManager.addCookie(res, {
|
|
key: this.options.cookieName,
|
|
value: token,
|
|
httpOnly: true,
|
|
path: '/',
|
|
secure: true,
|
|
sameSite: 'Strict',
|
|
maxAge: 365000
|
|
})
|
|
}
|
|
|
|
public removeSession(res: ResponseInit & { readonly headers: Headers; }) {
|
|
|
|
}
|
|
}
|