]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/middlewares/oauth.ts
plugins: add optional authentication for routes
[github/Chocobozzz/PeerTube.git] / server / middlewares / oauth.ts
CommitLineData
69818c93 1import * as express from 'express'
cef534ed 2import { Socket } from 'socket.io'
e1c55031 3import { oAuthServer } from '@server/lib/auth'
fce7fe04
C
4import { logger } from '../helpers/logger'
5import { getAccessToken } from '../lib/oauth-model'
2d53be02 6import { HttpStatusCode } from '../../shared/core-utils/miscs/http-error-codes'
9457bf88 7
eccf70f0
C
8function authenticate (req: express.Request, res: express.Response, next: express.NextFunction, authenticateInQuery = false) {
9 const options = authenticateInQuery ? { allowBearerTokensInQueryString: true } : {}
10
11 oAuthServer.authenticate(options)(req, res, err => {
0c1cbbfe 12 if (err) {
0883b324
C
13 logger.warn('Cannot authenticate.', { err })
14
93e4a311
C
15 return res.status(err.status)
16 .json({
5960f923 17 error: 'Token is invalid.',
93e4a311
C
18 code: err.name
19 })
20 .end()
eec63bbc 21 }
0c1cbbfe
C
22
23 return next()
24 })
25}
26
cef534ed 27function authenticateSocket (socket: Socket, next: (err?: any) => void) {
fce7fe04 28 const accessToken = socket.handshake.query['accessToken']
cef534ed
C
29
30 logger.debug('Checking socket access token %s.', accessToken)
31
3acc5084
C
32 if (!accessToken) return next(new Error('No access token provided'))
33
cef534ed
C
34 getAccessToken(accessToken)
35 .then(tokenDB => {
36 const now = new Date()
37
38 if (!tokenDB || tokenDB.accessTokenExpiresAt < now || tokenDB.refreshTokenExpiresAt < now) {
39 return next(new Error('Invalid access token.'))
40 }
41
fce7fe04 42 socket.handshake.query['user'] = tokenDB.User
cef534ed
C
43
44 return next()
45 })
a1587156 46 .catch(err => logger.error('Cannot get access token.', { err }))
cef534ed
C
47}
48
eccf70f0 49function authenticatePromiseIfNeeded (req: express.Request, res: express.Response, authenticateInQuery = false) {
8d427346
C
50 return new Promise(resolve => {
51 // Already authenticated? (or tried to)
faa9d434 52 if (res.locals.oauth?.token.User) return resolve()
8d427346 53
2d53be02 54 if (res.locals.authenticated === false) return res.sendStatus(HttpStatusCode.UNAUTHORIZED_401)
8d427346 55
eccf70f0 56 authenticate(req, res, () => resolve(), authenticateInQuery)
8d427346
C
57 })
58}
59
0883b324
C
60function optionalAuthenticate (req: express.Request, res: express.Response, next: express.NextFunction) {
61 if (req.header('authorization')) return authenticate(req, res, next)
62
8d427346
C
63 res.locals.authenticated = false
64
0883b324
C
65 return next()
66}
67
9457bf88
C
68// ---------------------------------------------------------------------------
69
65fcc311
C
70export {
71 authenticate,
cef534ed 72 authenticateSocket,
8d427346 73 authenticatePromiseIfNeeded,
7fed6375 74 optionalAuthenticate
65fcc311 75}