import { Request, Response } from 'express'; const crypto = require('crypto'); const START_DATE_TS = (new Date()).getTime(); const COOKIE_KEY = "sessId"; const SESSION_TIME = 36000; // 10 min, FIXME config export class Session { constructor(req: Request) { this.mExpireTs = 0; this.mUsername = null; this.mHash = crypto.createHash('sha1').update( (new Date()).toISOString() + "__salt__" + req.connection.remoteAddress + "" + req.connection.remotePort + "" + START_DATE_TS ).digest('hex'); this.Ping(); } public IsValid(): boolean { return ((new Date()).getTime() < this.mExpireTs) && this.mUsername !== null; } public GetUsername(): string { return this.mUsername || ""; } public Login(username: string) { this.mUsername = username; } public GetHash(): string { return this.mHash; } public Ping(): void { this.mExpireTs = (new Date()).getTime() + SESSION_TIME; } private mExpireTs: number; private mUsername: string | null; private mHash: string; } export var SessionManager = new class { public GetSession(req: Request): Session { const sessionId: string | undefined = req.mCookies.get(COOKIE_KEY); return (sessionId ? this.mStoredSessions.get(sessionId) : undefined) || new Session(req); } public Write(res: Response, sess: Session) { res.cookie(COOKIE_KEY, sess.GetHash()); this.mStoredSessions.set(sess.GetHash(), sess); } private mStoredSessions: Map = new Map(); }();