1 import express from 'express'
2 import { Socket } from 'socket.io'
3 import { getAccessToken } from '@server/lib/auth/oauth-model'
4 import { HttpStatusCode } from '../../shared/models/http/http-error-codes'
5 import { logger } from '../helpers/logger'
6 import { handleOAuthAuthenticate } from '../lib/auth/oauth'
8 function authenticate (req: express.Request, res: express.Response, next: express.NextFunction) {
9 handleOAuthAuthenticate(req, res)
10 .then((token: any) => {
11 res.locals.oauth = { token }
12 res.locals.authenticated = true
17 logger.info('Cannot authenticate.', { err })
21 message: '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'))
33 if (typeof accessToken !== 'string') return next(new Error('Access token is invalid'))
35 getAccessToken(accessToken)
37 const now = new Date()
39 if (!tokenDB || tokenDB.accessTokenExpiresAt < now || tokenDB.refreshTokenExpiresAt < now) {
40 return next(new Error('Invalid access token.'))
43 socket.handshake.auth.user = tokenDB.User
47 .catch(err => logger.error('Cannot get access token.', { err }))
50 function authenticatePromise (req: express.Request, res: express.Response) {
51 return new Promise<void>(resolve => {
52 // Already authenticated? (or tried to)
53 if (res.locals.oauth?.token.User) return resolve()
55 if (res.locals.authenticated === false) {
57 status: HttpStatusCode.UNAUTHORIZED_401,
58 message: 'Not authenticated'
62 authenticate(req, res, () => resolve())
66 function optionalAuthenticate (req: express.Request, res: express.Response, next: express.NextFunction) {
67 if (req.header('authorization')) return authenticate(req, res, next)
69 res.locals.authenticated = false
74 // ---------------------------------------------------------------------------