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.',
23 res.locals.authenticated = true
29 function authenticateSocket (socket: Socket, next: (err?: any) => void) {
30 const accessToken = socket.handshake.query['accessToken']
32 logger.debug('Checking socket access token %s.', accessToken)
34 if (!accessToken) return next(new Error('No access token provided'))
35 if (typeof accessToken !== 'string') return next(new Error('Access token is invalid'))
37 getAccessToken(accessToken)
39 const now = new Date()
41 if (!tokenDB || tokenDB.accessTokenExpiresAt < now || tokenDB.refreshTokenExpiresAt < now) {
42 return next(new Error('Invalid access token.'))
45 socket.handshake.auth.user = tokenDB.User
49 .catch(err => logger.error('Cannot get access token.', { err }))
52 function authenticatePromiseIfNeeded (req: express.Request, res: express.Response, authenticateInQuery = false) {
53 return new Promise<void>(resolve => {
54 // Already authenticated? (or tried to)
55 if (res.locals.oauth?.token.User) return resolve()
57 if (res.locals.authenticated === false) return res.sendStatus(HttpStatusCode.UNAUTHORIZED_401)
59 authenticate(req, res, () => resolve(), authenticateInQuery)
63 function optionalAuthenticate (req: express.Request, res: express.Response, next: express.NextFunction) {
64 if (req.header('authorization')) return authenticate(req, res, next)
66 res.locals.authenticated = false
71 // ---------------------------------------------------------------------------
76 authenticatePromiseIfNeeded,