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'
8 const oAuthServer = new OAuthServer({
10 accessTokenLifetime: OAUTH_LIFETIME.ACCESS_TOKEN,
11 refreshTokenLifetime: OAUTH_LIFETIME.REFRESH_TOKEN,
12 continueMiddleware: true,
13 model: require('../lib/oauth-model')
16 function authenticate (req: express.Request, res: express.Response, next: express.NextFunction, authenticateInQuery = false) {
17 const options = authenticateInQuery ? { allowBearerTokensInQueryString: true } : {}
19 oAuthServer.authenticate(options)(req, res, err => {
21 logger.warn('Cannot authenticate.', { err })
23 return res.status(err.status)
25 error: 'Token is invalid.',
35 function authenticateSocket (socket: Socket, next: (err?: any) => void) {
36 const accessToken = socket.handshake.query.accessToken
38 logger.debug('Checking socket access token %s.', accessToken)
40 if (!accessToken) return next(new Error('No access token provided'))
42 getAccessToken(accessToken)
44 const now = new Date()
46 if (!tokenDB || tokenDB.accessTokenExpiresAt < now || tokenDB.refreshTokenExpiresAt < now) {
47 return next(new Error('Invalid access token.'))
50 socket.handshake.query.user = tokenDB.User
56 function authenticatePromiseIfNeeded (req: express.Request, res: express.Response, authenticateInQuery = false) {
57 return new Promise(resolve => {
58 // Already authenticated? (or tried to)
59 if (res.locals.oauth && res.locals.oauth.token.User) return resolve()
61 if (res.locals.authenticated === false) return res.sendStatus(401)
63 authenticate(req, res, () => resolve(), authenticateInQuery)
67 function optionalAuthenticate (req: express.Request, res: express.Response, next: express.NextFunction) {
68 if (req.header('authorization')) return authenticate(req, res, next)
70 res.locals.authenticated = false
75 function token (req: express.Request, res: express.Response, next: express.NextFunction) {
76 return oAuthServer.token()(req, res, err => {
78 return res.status(err.status)
90 // ---------------------------------------------------------------------------
95 authenticatePromiseIfNeeded,