1 import * as express from 'express'
2 import { Socket } from 'socket.io'
3 import { oAuthServer } from '@server/lib/auth'
4 import { logger } from '../helpers/logger'
5 import { getAccessToken } from '../lib/oauth-model'
6 import { HttpStatusCode } from '../../shared/core-utils/miscs/http-error-codes'
8 function authenticate (req: express.Request, res: express.Response, next: express.NextFunction, authenticateInQuery = false) {
9 const options = authenticateInQuery ? { allowBearerTokensInQueryString: true } : {}
11 oAuthServer.authenticate(options)(req, res, err => {
13 logger.warn('Cannot authenticate.', { err })
15 return res.status(err.status)
17 error: 'Token is invalid.',
27 function authenticateSocket (socket: Socket, next: (err?: any) => void) {
28 const accessToken = socket.handshake.query['accessToken']
30 logger.debug('Checking socket access token %s.', accessToken)
32 if (!accessToken) return next(new Error('No access token provided'))
34 getAccessToken(accessToken)
36 const now = new Date()
38 if (!tokenDB || tokenDB.accessTokenExpiresAt < now || tokenDB.refreshTokenExpiresAt < now) {
39 return next(new Error('Invalid access token.'))
42 socket.handshake.query['user'] = tokenDB.User
46 .catch(err => logger.error('Cannot get access token.', { err }))
49 function authenticatePromiseIfNeeded (req: express.Request, res: express.Response, authenticateInQuery = false) {
50 return new Promise(resolve => {
51 // Already authenticated? (or tried to)
52 if (res.locals.oauth?.token.User) return resolve()
54 if (res.locals.authenticated === false) return res.sendStatus(HttpStatusCode.UNAUTHORIZED_401)
56 authenticate(req, res, () => resolve(), authenticateInQuery)
60 function optionalAuthenticate (req: express.Request, res: express.Response, next: express.NextFunction) {
61 if (req.header('authorization')) return authenticate(req, res, next)
63 res.locals.authenticated = false
68 // ---------------------------------------------------------------------------
73 authenticatePromiseIfNeeded,