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