]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/middlewares/auth.ts
Fix build
[github/Chocobozzz/PeerTube.git] / server / middlewares / auth.ts
1 import * as 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'
7
8 function authenticate (req: express.Request, res: express.Response, next: express.NextFunction, authenticateInQuery = false) {
9 handleOAuthAuthenticate(req, res, authenticateInQuery)
10 .then((token: any) => {
11 res.locals.oauth = { token }
12 res.locals.authenticated = true
13
14 return next()
15 })
16 .catch(err => {
17 logger.warn('Cannot authenticate.', { err })
18
19 return res.fail({
20 status: err.status,
21 message: 'Token is invalid',
22 type: err.name
23 })
24 })
25 }
26
27 function authenticateSocket (socket: Socket, next: (err?: any) => void) {
28 const accessToken = socket.handshake.query['accessToken']
29
30 logger.debug('Checking socket access token %s.', accessToken)
31
32 if (!accessToken) return next(new Error('No access token provided'))
33 if (typeof accessToken !== 'string') return next(new Error('Access token is invalid'))
34
35 getAccessToken(accessToken)
36 .then(tokenDB => {
37 const now = new Date()
38
39 if (!tokenDB || tokenDB.accessTokenExpiresAt < now || tokenDB.refreshTokenExpiresAt < now) {
40 return next(new Error('Invalid access token.'))
41 }
42
43 socket.handshake.auth.user = tokenDB.User
44
45 return next()
46 })
47 .catch(err => logger.error('Cannot get access token.', { err }))
48 }
49
50 function authenticatePromiseIfNeeded (req: express.Request, res: express.Response, authenticateInQuery = false) {
51 return new Promise<void>(resolve => {
52 // Already authenticated? (or tried to)
53 if (res.locals.oauth?.token.User) return resolve()
54
55 if (res.locals.authenticated === false) {
56 return res.fail({
57 status: HttpStatusCode.UNAUTHORIZED_401,
58 message: 'Not authenticated'
59 })
60 }
61
62 authenticate(req, res, () => resolve(), authenticateInQuery)
63 })
64 }
65
66 function optionalAuthenticate (req: express.Request, res: express.Response, next: express.NextFunction) {
67 if (req.header('authorization')) return authenticate(req, res, next)
68
69 res.locals.authenticated = false
70
71 return next()
72 }
73
74 // ---------------------------------------------------------------------------
75
76 export {
77 authenticate,
78 authenticateSocket,
79 authenticatePromiseIfNeeded,
80 optionalAuthenticate
81 }