55 lines
1.8 KiB
TypeScript
55 lines
1.8 KiB
TypeScript
|
import Config from "./Config";
|
||
|
import FastifyCookie from "@fastify/cookie";
|
||
|
import FunkyArray from "funky-array";
|
||
|
import SessionUser from "./SessionUser";
|
||
|
import { FastifyReply, FastifyRequest } from "fastify";
|
||
|
import User from "../entities/User";
|
||
|
import { randomBytes } from "crypto";
|
||
|
|
||
|
type Cookies = { [cookieName: string]: string | undefined }
|
||
|
|
||
|
export default abstract class Session {
|
||
|
public static Sessions = new FunkyArray<string, SessionUser>();
|
||
|
public static SessionExpiryInterval = setInterval(() => {
|
||
|
const currentTime = Date.now();
|
||
|
for (const key of Session.Sessions.keys) {
|
||
|
const session = Session.Sessions.get(key);
|
||
|
if (!session || (session && currentTime >= session.validityPeriod.getTime())) {
|
||
|
Session.Sessions.remove(key);
|
||
|
}
|
||
|
}
|
||
|
}, 3600000);
|
||
|
|
||
|
public static AssignUserSession(res:FastifyReply, user:User) {
|
||
|
const validPeriod = new Date();
|
||
|
validPeriod.setTime(validPeriod.getTime() + Config.session.validity);
|
||
|
const key = randomBytes(Config.session.length).toString("hex");
|
||
|
|
||
|
Session.Sessions.set(key, new SessionUser(user.Id, validPeriod));
|
||
|
|
||
|
res.setCookie("MP_SESSION", key, {
|
||
|
path: "/",
|
||
|
signed: true
|
||
|
});
|
||
|
}
|
||
|
|
||
|
public static Clear(cookies:Cookies, res:FastifyReply) {
|
||
|
if ("MP_SESSION" in cookies && typeof(cookies["MP_SESSION"]) === "string") {
|
||
|
const key:unknown = FastifyCookie.unsign(cookies["MP_SESSION"], Config.session.secret);
|
||
|
Session.Sessions.remove(key as string);
|
||
|
|
||
|
res.clearCookie("MP_SESSION");
|
||
|
}
|
||
|
}
|
||
|
|
||
|
public static CheckValiditiy(cookies:Cookies) {
|
||
|
if ("MP_SESSION" in cookies && typeof(cookies["MP_SESSION"]) === "string") {
|
||
|
const key = FastifyCookie.unsign(cookies["MP_SESSION"], Config.session.secret);
|
||
|
if (key.valid && Session.Sessions.has(key.value ?? "badkey")) {
|
||
|
return Session.Sessions.get(key.value ?? "badkey");
|
||
|
}
|
||
|
}
|
||
|
|
||
|
return undefined;
|
||
|
}
|
||
|
}
|