oauth.ts 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. import * as express from 'express'
  2. import * as OAuthServer from 'express-oauth-server'
  3. import { OAUTH_LIFETIME } from '../initializers/constants'
  4. import { logger } from '../helpers/logger'
  5. import { Socket } from 'socket.io'
  6. import { getAccessToken } from '../lib/oauth-model'
  7. const oAuthServer = new OAuthServer({
  8. useErrorHandler: true,
  9. accessTokenLifetime: OAUTH_LIFETIME.ACCESS_TOKEN,
  10. refreshTokenLifetime: OAUTH_LIFETIME.REFRESH_TOKEN,
  11. model: require('../lib/oauth-model')
  12. })
  13. function authenticate (req: express.Request, res: express.Response, next: express.NextFunction) {
  14. oAuthServer.authenticate()(req, res, err => {
  15. if (err) {
  16. logger.warn('Cannot authenticate.', { err })
  17. return res.status(err.status)
  18. .json({
  19. error: 'Token is invalid.',
  20. code: err.name
  21. })
  22. .end()
  23. }
  24. return next()
  25. })
  26. }
  27. function authenticateSocket (socket: Socket, next: (err?: any) => void) {
  28. const accessToken = socket.handshake.query.accessToken
  29. logger.debug('Checking socket access token %s.', accessToken)
  30. if (!accessToken) return next(new Error('No access token provided'))
  31. getAccessToken(accessToken)
  32. .then(tokenDB => {
  33. const now = new Date()
  34. if (!tokenDB || tokenDB.accessTokenExpiresAt < now || tokenDB.refreshTokenExpiresAt < now) {
  35. return next(new Error('Invalid access token.'))
  36. }
  37. socket.handshake.query.user = tokenDB.User
  38. return next()
  39. })
  40. }
  41. function authenticatePromiseIfNeeded (req: express.Request, res: express.Response) {
  42. return new Promise(resolve => {
  43. // Already authenticated? (or tried to)
  44. if (res.locals.oauth && res.locals.oauth.token.User) return resolve()
  45. if (res.locals.authenticated === false) return res.sendStatus(401)
  46. authenticate(req, res, () => {
  47. return resolve()
  48. })
  49. })
  50. }
  51. function optionalAuthenticate (req: express.Request, res: express.Response, next: express.NextFunction) {
  52. if (req.header('authorization')) return authenticate(req, res, next)
  53. res.locals.authenticated = false
  54. return next()
  55. }
  56. function token (req: express.Request, res: express.Response, next: express.NextFunction) {
  57. return oAuthServer.token()(req, res, err => {
  58. if (err) {
  59. return res.status(err.status)
  60. .json({
  61. error: err.message,
  62. code: err.name
  63. })
  64. .end()
  65. }
  66. return next()
  67. })
  68. }
  69. // ---------------------------------------------------------------------------
  70. export {
  71. authenticate,
  72. authenticateSocket,
  73. authenticatePromiseIfNeeded,
  74. optionalAuthenticate,
  75. token
  76. }