Session.ts 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import { Request, Response } from 'express';
  2. const crypto = require('crypto');
  3. const START_DATE_TS = (new Date()).getTime();
  4. const COOKIE_KEY = "sessId";
  5. const SESSION_TIME = 36000; // 10 min, FIXME config
  6. export class Session {
  7. constructor(req: Request) {
  8. this.mExpireTs = 0;
  9. this.mUsername = null;
  10. this.mHash = crypto.createHash('sha1').update(
  11. (new Date()).toISOString()
  12. + "__salt__"
  13. + req.connection.remoteAddress
  14. + ""
  15. + req.connection.remotePort
  16. + ""
  17. + START_DATE_TS
  18. ).digest('hex');
  19. this.Ping();
  20. }
  21. public IsValid(): boolean {
  22. return ((new Date()).getTime() < this.mExpireTs) &&
  23. this.mUsername !== null;
  24. }
  25. public GetUsername(): string {
  26. return this.mUsername || "";
  27. }
  28. public Login(username: string) {
  29. this.mUsername = username;
  30. }
  31. public GetHash(): string {
  32. return this.mHash;
  33. }
  34. public Ping(): void {
  35. this.mExpireTs = (new Date()).getTime() + SESSION_TIME;
  36. }
  37. private mExpireTs: number;
  38. private mUsername: string | null;
  39. private mHash: string;
  40. }
  41. export var SessionManager = new class {
  42. public GetSession(req: Request): Session {
  43. const sessionId: string | undefined = req.mCookies.get(COOKIE_KEY);
  44. return (sessionId ? this.mStoredSessions.get(sessionId) : undefined) || new Session(req);
  45. }
  46. public Write(res: Response, sess: Session) {
  47. res.cookie(COOKIE_KEY, sess.GetHash());
  48. this.mStoredSessions.set(sess.GetHash(), sess);
  49. }
  50. private mStoredSessions: Map<string, Session> = new Map();
  51. }();