oauth.ts 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import * as express from 'express'
  2. import * as OAuthServer from 'express-oauth-server'
  3. import 'express-validator'
  4. import { OAUTH_LIFETIME } from '../initializers'
  5. import { logger } from '../helpers/logger'
  6. const oAuthServer = new OAuthServer({
  7. useErrorHandler: true,
  8. accessTokenLifetime: OAUTH_LIFETIME.ACCESS_TOKEN,
  9. refreshTokenLifetime: OAUTH_LIFETIME.REFRESH_TOKEN,
  10. model: require('../lib/oauth-model')
  11. })
  12. function authenticate (req: express.Request, res: express.Response, next: express.NextFunction) {
  13. oAuthServer.authenticate()(req, res, err => {
  14. if (err) {
  15. logger.warn('Cannot authenticate.', { err })
  16. return res.status(err.status)
  17. .json({
  18. error: 'Token is invalid.',
  19. code: err.name
  20. })
  21. .end()
  22. }
  23. return next()
  24. })
  25. }
  26. function authenticatePromiseIfNeeded (req: express.Request, res: express.Response) {
  27. return new Promise(resolve => {
  28. // Already authenticated? (or tried to)
  29. if (res.locals.oauth && res.locals.oauth.token.User) return resolve()
  30. if (res.locals.authenticated === false) return res.sendStatus(401)
  31. authenticate(req, res, () => {
  32. return resolve()
  33. })
  34. })
  35. }
  36. function optionalAuthenticate (req: express.Request, res: express.Response, next: express.NextFunction) {
  37. if (req.header('authorization')) return authenticate(req, res, next)
  38. res.locals.authenticated = false
  39. return next()
  40. }
  41. function token (req: express.Request, res: express.Response, next: express.NextFunction) {
  42. return oAuthServer.token()(req, res, err => {
  43. if (err) {
  44. return res.status(err.status)
  45. .json({
  46. error: err.message,
  47. code: err.name
  48. })
  49. .end()
  50. }
  51. return next()
  52. })
  53. }
  54. // ---------------------------------------------------------------------------
  55. export {
  56. authenticate,
  57. authenticatePromiseIfNeeded,
  58. optionalAuthenticate,
  59. token
  60. }