app.ts 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import * as express from 'express';
  2. import { AddressInfo } from "net";
  3. import * as path from 'path';
  4. import * as bodyParser from 'body-parser';
  5. import route_index from './routes/index';
  6. import route_entity from './routes/entity';
  7. import { route_login, route_logout } from './routes/login';
  8. import LDAPFactory from './src/ldapInterface';
  9. import { Session } from './src/Security';
  10. import Security from './src/Security';
  11. const debug = require('debug')('LDAPManager:http');
  12. const app = express();
  13. declare global {
  14. namespace Express {
  15. interface Request {
  16. ldapManager: LDAPFactory
  17. session: Session | null
  18. isUserLogged: boolean
  19. }
  20. }
  21. }
  22. // view engine setup
  23. app.set('views', path.join(__dirname, 'views'));
  24. app.set('view engine', 'pug');
  25. app.use(express.static(path.join(__dirname, 'public')));
  26. app.use(bodyParser.json());
  27. app.use(bodyParser.urlencoded({ extended: true }));
  28. app.use((req, res, next) => {
  29. req.ldapManager = new LDAPFactory();
  30. req.session = Security.GetSession(req);
  31. req.isUserLogged = Security.IsUserLogged(req);
  32. res.socket && res.socket.once('close', () => {
  33. req.ldapManager.Release();
  34. });
  35. next();
  36. });
  37. //app.use('/', route_index);
  38. app.use('/', route_index);
  39. app.use('/entity', route_entity);
  40. app.use('/login', route_login);
  41. app.use('/logout', route_logout);
  42. // catch 404 and forward to error handler
  43. app.use((req, res, next) => {
  44. const err: any = new Error('Not Found');
  45. err['status'] = 404;
  46. next(err);
  47. });
  48. // error handlers
  49. // development error handler
  50. // will print stacktrace
  51. if (app.get('env') === 'development') {
  52. app.use((err: any, req: Express.Request, res: any, next: any) => { // eslint-disable-line @typescript-eslint/no-unused-vars
  53. res.status(err[ 'status' ] || 500);
  54. res.render('error', {
  55. message: err.message,
  56. error: err
  57. });
  58. });
  59. }
  60. // production error handler
  61. // no stacktraces leaked to user
  62. app.use((err: any, req: any, res: any, next: any) => { // eslint-disable-line @typescript-eslint/no-unused-vars
  63. res.status(err.status || 500);
  64. res.render('error', {
  65. message: err.message,
  66. error: {}
  67. });
  68. });
  69. app.set('port', process.env.PORT || 8080);
  70. const server = app.listen(app.get('port'), function () {
  71. debug(`Express server listening on port ${(server.address() as AddressInfo).port}`);
  72. });