From f43db2f46ee50bacb402a6ef42d768694c2bc9a8 Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Fri, 12 Mar 2021 15:20:46 +0100 Subject: Refactor auth flow Reimplement some node-oauth2-server methods to remove hacky code needed by our external login workflow --- server/middlewares/auth.ts | 76 +++++++++++++++++++++ server/middlewares/index.ts | 2 +- server/middlewares/oauth.ts | 78 ---------------------- .../validators/videos/video-playlists.ts | 2 +- server/middlewares/validators/videos/videos.ts | 2 +- 5 files changed, 79 insertions(+), 81 deletions(-) create mode 100644 server/middlewares/auth.ts delete mode 100644 server/middlewares/oauth.ts (limited to 'server/middlewares') diff --git a/server/middlewares/auth.ts b/server/middlewares/auth.ts new file mode 100644 index 000000000..f38373624 --- /dev/null +++ b/server/middlewares/auth.ts @@ -0,0 +1,76 @@ +import * as express from 'express' +import { Socket } from 'socket.io' +import { getAccessToken } from '@server/lib/auth/oauth-model' +import { HttpStatusCode } from '../../shared/core-utils/miscs/http-error-codes' +import { logger } from '../helpers/logger' +import { handleOAuthAuthenticate } from '../lib/auth/oauth' + +function authenticate (req: express.Request, res: express.Response, next: express.NextFunction, authenticateInQuery = false) { + handleOAuthAuthenticate(req, res, authenticateInQuery) + .then((token: any) => { + res.locals.oauth = { token } + res.locals.authenticated = true + + return next() + }) + .catch(err => { + logger.warn('Cannot authenticate.', { err }) + + return res.status(err.status) + .json({ + error: 'Token is invalid.', + code: err.name + }) + }) +} + +function authenticateSocket (socket: Socket, next: (err?: any) => void) { + const accessToken = socket.handshake.query['accessToken'] + + logger.debug('Checking socket access token %s.', accessToken) + + if (!accessToken) return next(new Error('No access token provided')) + if (typeof accessToken !== 'string') return next(new Error('Access token is invalid')) + + getAccessToken(accessToken) + .then(tokenDB => { + const now = new Date() + + if (!tokenDB || tokenDB.accessTokenExpiresAt < now || tokenDB.refreshTokenExpiresAt < now) { + return next(new Error('Invalid access token.')) + } + + socket.handshake.auth.user = tokenDB.User + + return next() + }) + .catch(err => logger.error('Cannot get access token.', { err })) +} + +function authenticatePromiseIfNeeded (req: express.Request, res: express.Response, authenticateInQuery = false) { + return new Promise(resolve => { + // Already authenticated? (or tried to) + if (res.locals.oauth?.token.User) return resolve() + + if (res.locals.authenticated === false) return res.sendStatus(HttpStatusCode.UNAUTHORIZED_401) + + authenticate(req, res, () => resolve(), authenticateInQuery) + }) +} + +function optionalAuthenticate (req: express.Request, res: express.Response, next: express.NextFunction) { + if (req.header('authorization')) return authenticate(req, res, next) + + res.locals.authenticated = false + + return next() +} + +// --------------------------------------------------------------------------- + +export { + authenticate, + authenticateSocket, + authenticatePromiseIfNeeded, + optionalAuthenticate +} diff --git a/server/middlewares/index.ts b/server/middlewares/index.ts index b758a8586..3e280e16f 100644 --- a/server/middlewares/index.ts +++ b/server/middlewares/index.ts @@ -1,7 +1,7 @@ export * from './validators' export * from './activitypub' export * from './async' -export * from './oauth' +export * from './auth' export * from './pagination' export * from './servers' export * from './sort' diff --git a/server/middlewares/oauth.ts b/server/middlewares/oauth.ts deleted file mode 100644 index 280595acc..000000000 --- a/server/middlewares/oauth.ts +++ /dev/null @@ -1,78 +0,0 @@ -import * as express from 'express' -import { Socket } from 'socket.io' -import { oAuthServer } from '@server/lib/auth' -import { logger } from '../helpers/logger' -import { getAccessToken } from '../lib/oauth-model' -import { HttpStatusCode } from '../../shared/core-utils/miscs/http-error-codes' - -function authenticate (req: express.Request, res: express.Response, next: express.NextFunction, authenticateInQuery = false) { - const options = authenticateInQuery ? { allowBearerTokensInQueryString: true } : {} - - oAuthServer.authenticate(options)(req, res, err => { - if (err) { - logger.warn('Cannot authenticate.', { err }) - - return res.status(err.status) - .json({ - error: 'Token is invalid.', - code: err.name - }) - .end() - } - - res.locals.authenticated = true - - return next() - }) -} - -function authenticateSocket (socket: Socket, next: (err?: any) => void) { - const accessToken = socket.handshake.query['accessToken'] - - logger.debug('Checking socket access token %s.', accessToken) - - if (!accessToken) return next(new Error('No access token provided')) - if (typeof accessToken !== 'string') return next(new Error('Access token is invalid')) - - getAccessToken(accessToken) - .then(tokenDB => { - const now = new Date() - - if (!tokenDB || tokenDB.accessTokenExpiresAt < now || tokenDB.refreshTokenExpiresAt < now) { - return next(new Error('Invalid access token.')) - } - - socket.handshake.auth.user = tokenDB.User - - return next() - }) - .catch(err => logger.error('Cannot get access token.', { err })) -} - -function authenticatePromiseIfNeeded (req: express.Request, res: express.Response, authenticateInQuery = false) { - return new Promise(resolve => { - // Already authenticated? (or tried to) - if (res.locals.oauth?.token.User) return resolve() - - if (res.locals.authenticated === false) return res.sendStatus(HttpStatusCode.UNAUTHORIZED_401) - - authenticate(req, res, () => resolve(), authenticateInQuery) - }) -} - -function optionalAuthenticate (req: express.Request, res: express.Response, next: express.NextFunction) { - if (req.header('authorization')) return authenticate(req, res, next) - - res.locals.authenticated = false - - return next() -} - -// --------------------------------------------------------------------------- - -export { - authenticate, - authenticateSocket, - authenticatePromiseIfNeeded, - optionalAuthenticate -} diff --git a/server/middlewares/validators/videos/video-playlists.ts b/server/middlewares/validators/videos/video-playlists.ts index 0fba4f5fd..c872d045e 100644 --- a/server/middlewares/validators/videos/video-playlists.ts +++ b/server/middlewares/validators/videos/video-playlists.ts @@ -29,7 +29,7 @@ import { doesVideoChannelIdExist, doesVideoExist, doesVideoPlaylistExist, VideoP import { CONSTRAINTS_FIELDS } from '../../../initializers/constants' import { VideoPlaylistElementModel } from '../../../models/video/video-playlist-element' import { MVideoPlaylist } from '../../../types/models/video/video-playlist' -import { authenticatePromiseIfNeeded } from '../../oauth' +import { authenticatePromiseIfNeeded } from '../../auth' import { areValidationErrors } from '../utils' const videoPlaylistsAddValidator = getCommonPlaylistEditAttributes().concat([ diff --git a/server/middlewares/validators/videos/videos.ts b/server/middlewares/validators/videos/videos.ts index 37cc07b94..4d31d3dcb 100644 --- a/server/middlewares/validators/videos/videos.ts +++ b/server/middlewares/validators/videos/videos.ts @@ -54,7 +54,7 @@ import { isLocalVideoAccepted } from '../../../lib/moderation' import { Hooks } from '../../../lib/plugins/hooks' import { AccountModel } from '../../../models/account/account' import { VideoModel } from '../../../models/video/video' -import { authenticatePromiseIfNeeded } from '../../oauth' +import { authenticatePromiseIfNeeded } from '../../auth' import { areValidationErrors } from '../utils' const videosAddValidator = getCommonVideoEditAttributes().concat([ -- cgit v1.2.3