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