aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/middlewares/oauth.ts
diff options
context:
space:
mode:
Diffstat (limited to 'server/middlewares/oauth.ts')
-rw-r--r--server/middlewares/oauth.ts38
1 files changed, 38 insertions, 0 deletions
diff --git a/server/middlewares/oauth.ts b/server/middlewares/oauth.ts
index 5233b66bd..1d193d467 100644
--- a/server/middlewares/oauth.ts
+++ b/server/middlewares/oauth.ts
@@ -3,6 +3,8 @@ import * as OAuthServer from 'express-oauth-server'
3import 'express-validator' 3import 'express-validator'
4import { OAUTH_LIFETIME } from '../initializers' 4import { OAUTH_LIFETIME } from '../initializers'
5import { logger } from '../helpers/logger' 5import { logger } from '../helpers/logger'
6import { Socket } from 'socket.io'
7import { getAccessToken } from '../lib/oauth-model'
6 8
7const oAuthServer = new OAuthServer({ 9const oAuthServer = new OAuthServer({
8 useErrorHandler: true, 10 useErrorHandler: true,
@@ -28,9 +30,43 @@ function authenticate (req: express.Request, res: express.Response, next: expres
28 }) 30 })
29} 31}
30 32
33function authenticateSocket (socket: Socket, next: (err?: any) => void) {
34 const accessToken = socket.handshake.query.accessToken
35
36 logger.debug('Checking socket access token %s.', accessToken)
37
38 getAccessToken(accessToken)
39 .then(tokenDB => {
40 const now = new Date()
41
42 if (!tokenDB || tokenDB.accessTokenExpiresAt < now || tokenDB.refreshTokenExpiresAt < now) {
43 return next(new Error('Invalid access token.'))
44 }
45
46 socket.handshake.query.user = tokenDB.User
47
48 return next()
49 })
50}
51
52function authenticatePromiseIfNeeded (req: express.Request, res: express.Response) {
53 return new Promise(resolve => {
54 // Already authenticated? (or tried to)
55 if (res.locals.oauth && res.locals.oauth.token.User) return resolve()
56
57 if (res.locals.authenticated === false) return res.sendStatus(401)
58
59 authenticate(req, res, () => {
60 return resolve()
61 })
62 })
63}
64
31function optionalAuthenticate (req: express.Request, res: express.Response, next: express.NextFunction) { 65function optionalAuthenticate (req: express.Request, res: express.Response, next: express.NextFunction) {
32 if (req.header('authorization')) return authenticate(req, res, next) 66 if (req.header('authorization')) return authenticate(req, res, next)
33 67
68 res.locals.authenticated = false
69
34 return next() 70 return next()
35} 71}
36 72
@@ -53,6 +89,8 @@ function token (req: express.Request, res: express.Response, next: express.NextF
53 89
54export { 90export {
55 authenticate, 91 authenticate,
92 authenticateSocket,
93 authenticatePromiseIfNeeded,
56 optionalAuthenticate, 94 optionalAuthenticate,
57 token 95 token
58} 96}