handler-base.class.ts 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. import csurf from 'csurf';
  2. import { createHash } from 'crypto';
  3. import { NextFunction, Request, Response, Router, RouterOptions, json as jsonBodyParser } from 'express';
  4. import moment from 'moment';
  5. import { ChatController } from '../../controllers/chat-controller.class';
  6. import { ControllerPool } from '../../controllers/lib/controller-pool.interface';
  7. import { AuthenticationException } from '../../model/err/authentication.exception';
  8. import { SessionHandler } from './session-handler.class';
  9. const STATIC_USERS = {
  10. testuser: 'bc2d5cc456b81caa403661411cc72a309c39677d035b74b713a5ba02412d9eff' // pass1234
  11. };
  12. export abstract class HandlerBase implements ControllerPool {
  13. private _router: Router;
  14. private _chatCtrl?: ChatController;
  15. constructor(private sessionHandler?: SessionHandler, auth?: boolean, options?: RouterOptions) {
  16. this._router = Router(options);
  17. if (this.sessionHandler) {
  18. this._router.use(this.sessionHandler.handler);
  19. if (auth) {
  20. this._router.use(this.authHandler.bind(this));
  21. }
  22. }
  23. }
  24. public get router(): Router {
  25. return this._router;
  26. }
  27. public get chat(): ChatController {
  28. if (!this._chatCtrl) {
  29. this._chatCtrl = new ChatController(this);
  30. }
  31. return this._chatCtrl;
  32. }
  33. protected avoidCache = (req, res, next) => {
  34. res.setHeader('Expires', 'Mon, 26 Jul 1997 05:00:00 GMT');
  35. res.setHeader('Last-Modified', `${moment().format('ddd, DD MMM YYYY HH:mm:ss')} CEST`);
  36. res.setHeader('Cache-Control', 'no-cache, max-age=0, must-revalidate, no-store');
  37. res.setHeader('Pragma', 'no-cache');
  38. next();
  39. };
  40. protected csrf(options?: { ignorePath: string[] }) {
  41. options = {
  42. ignorePath: [],
  43. ...options
  44. };
  45. return (req, res, next) => {
  46. if (options.ignorePath.includes(req.path)) {
  47. return next();
  48. }
  49. csurf({
  50. ignoreMethods: ['GET', 'HEAD', 'OPTIONS']
  51. })(req, res, (err?: any) => {
  52. if (err) return next(err);
  53. const proto = req.get('x-forwarded-proto') || req.protocol;
  54. res.cookie('XSRF-TOKEN', req.csrfToken(), {
  55. httpOnly: false,
  56. secure: proto === 'https',
  57. sameSite: 'strict'
  58. });
  59. next();
  60. });
  61. };
  62. }
  63. private async authHandler(
  64. req: Request<any, any, any, any, Record<string, any>>,
  65. res: Response<any, Record<string, any>>,
  66. next: NextFunction
  67. ): Promise<void> {
  68. // Is there already a recovered session available -> skip auth handling
  69. if (req.session && req.session.user) {
  70. return next();
  71. }
  72. // Login Requests Handling
  73. let loginUser, loginPass;
  74. if (req.method === 'POST' && req.body && req.body.user && req.body.password) {
  75. // JSON Post Body Login
  76. loginUser = req.body.user;
  77. loginPass = req.body.password;
  78. } else if (process.env.ENABLE_BASIC_AUTH && req.header('Authorization')?.substring(0, 5).toLowerCase() === 'basic') {
  79. // Basic Auth Login ( ^- Enable only for DEV)
  80. [loginUser, loginPass] = Buffer.from(req.header('Authorization').substring(6), 'base64').toString().split(':');
  81. if (!process.env.UNIT_TEST_MODE) console.log('[INFO]', 'Authenticating via Basic Auth: ', loginUser);
  82. }
  83. if (loginUser && loginPass) {
  84. try {
  85. // --------------------------------------------- //
  86. // TODO: Implement your "real" login here.
  87. // This is just an example implementation based
  88. // on a STATIC_USERS array defined above ;)
  89. // --------------------------------------------- //
  90. const pass = STATIC_USERS[loginUser];
  91. if (pass && pass === HandlerBase.hashPassword(loginPass)) {
  92. req.session.user = loginUser; // Hint: you can even store complex object types in a session, not just a string
  93. req.session.save();
  94. return next();
  95. }
  96. } catch (e) {
  97. return next(e);
  98. }
  99. }
  100. next(new AuthenticationException('No Session / Session Expired'));
  101. }
  102. public static hashPassword(password: string, salt?: string): string {
  103. if (!salt) {
  104. salt = process.env.PASSWORD_SALT;
  105. }
  106. return createHash('sha256').update(`${salt}${password}`).digest('hex');
  107. }
  108. }