]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/commitdiff
Refactor auth flow
authorChocobozzz <me@florianbigard.com>
Fri, 12 Mar 2021 14:20:46 +0000 (15:20 +0100)
committerChocobozzz <me@florianbigard.com>
Wed, 24 Mar 2021 17:18:41 +0000 (18:18 +0100)
Reimplement some node-oauth2-server methods to remove hacky code needed by our external
login workflow

24 files changed:
client/src/app/shared/shared-main/auth/auth-interceptor.service.ts
package.json
server/controllers/api/users/index.ts
server/controllers/api/users/token.ts
server/controllers/plugins.ts
server/lib/auth/external-auth.ts [moved from server/lib/auth.ts with 61% similarity]
server/lib/auth/oauth-model.ts [moved from server/lib/oauth-model.ts with 63% similarity]
server/lib/auth/oauth.ts [new file with mode: 0644]
server/lib/auth/tokens-cache.ts [new file with mode: 0644]
server/lib/plugins/register-helpers.ts
server/middlewares/auth.ts [moved from server/middlewares/oauth.ts with 86% similarity]
server/middlewares/index.ts
server/middlewares/validators/videos/video-playlists.ts
server/middlewares/validators/videos/videos.ts
server/models/account/user-notification-setting.ts
server/models/account/user.ts
server/models/oauth/oauth-token.ts
server/tests/api/check-params/users.ts
server/tests/api/users/users.ts
server/tests/plugins/external-auth.ts
server/typings/express/index.d.ts
shared/extra-utils/miscs/sql.ts
shared/extra-utils/server/servers.ts
yarn.lock

index 3ddaffbdf35f2cc8b51e70fa532309326332b71d..4fe3b964d64770442cc19027df9da73d474cff1e 100644 (file)
@@ -27,7 +27,9 @@ export class AuthInterceptor implements HttpInterceptor {
                  catchError((err: HttpErrorResponse) => {
                    if (err.status === HttpStatusCode.UNAUTHORIZED_401 && err.error && err.error.code === 'invalid_token') {
                      return this.handleTokenExpired(req, next)
-                   } else if (err.status === HttpStatusCode.UNAUTHORIZED_401) {
+                   }
+
+                   if (err.status === HttpStatusCode.UNAUTHORIZED_401) {
                      return this.handleNotAuthenticated(err)
                    }
 
index 323275faffff7ec7f770ca69766ec063370635c4..aba07173ba3f4c45771c84fca8aaa2fcf1d1a1a2 100644 (file)
@@ -82,9 +82,6 @@
     "swagger-cli": "swagger-cli",
     "sass-lint": "sass-lint"
   },
-  "resolutions": {
-    "oauth2-server": "3.1.0-beta.1"
-  },
   "dependencies": {
     "apicache": "1.6.2",
     "async": "^3.0.1",
     "deep-object-diff": "^1.1.0",
     "email-templates": "^8.0.3",
     "express": "^4.12.4",
-    "express-oauth-server": "^2.0.0",
     "express-rate-limit": "^5.0.0",
     "express-validator": "^6.4.0",
     "flat": "^5.0.0",
index 3be1d55ae97122f649e575aaf58d16e89a8fd847..e2b1ea7cd8d8edb135ac18be1866e91fed16647a 100644 (file)
@@ -2,8 +2,10 @@ import * as express from 'express'
 import * as RateLimit from 'express-rate-limit'
 import { tokensRouter } from '@server/controllers/api/users/token'
 import { Hooks } from '@server/lib/plugins/hooks'
+import { OAuthTokenModel } from '@server/models/oauth/oauth-token'
 import { MUser, MUserAccountDefault } from '@server/types/models'
 import { UserCreate, UserRight, UserRole, UserUpdate } from '../../../../shared'
+import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
 import { UserAdminFlag } from '../../../../shared/models/users/user-flag.model'
 import { UserRegister } from '../../../../shared/models/users/user-register.model'
 import { auditLoggerFactory, getAuditIdFromRes, UserAuditView } from '../../../helpers/audit-logger'
@@ -14,7 +16,6 @@ import { WEBSERVER } from '../../../initializers/constants'
 import { sequelizeTypescript } from '../../../initializers/database'
 import { Emailer } from '../../../lib/emailer'
 import { Notifier } from '../../../lib/notifier'
-import { deleteUserToken } from '../../../lib/oauth-model'
 import { Redis } from '../../../lib/redis'
 import { createUserAccountAndChannelAndPlaylist, sendVerifyUserEmail } from '../../../lib/user'
 import {
@@ -52,7 +53,6 @@ import { myVideosHistoryRouter } from './my-history'
 import { myNotificationsRouter } from './my-notifications'
 import { mySubscriptionsRouter } from './my-subscriptions'
 import { myVideoPlaylistsRouter } from './my-video-playlists'
-import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
 
 const auditLogger = auditLoggerFactory('users')
 
@@ -335,7 +335,7 @@ async function updateUser (req: express.Request, res: express.Response) {
   const user = await userToUpdate.save()
 
   // Destroy user token to refresh rights
-  if (roleChanged || body.password !== undefined) await deleteUserToken(userToUpdate.id)
+  if (roleChanged || body.password !== undefined) await OAuthTokenModel.deleteUserToken(userToUpdate.id)
 
   auditLogger.update(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()), oldUserAuditView)
 
@@ -395,7 +395,7 @@ async function changeUserBlock (res: express.Response, user: MUserAccountDefault
   user.blockedReason = reason || null
 
   await sequelizeTypescript.transaction(async t => {
-    await deleteUserToken(user.id, t)
+    await OAuthTokenModel.deleteUserToken(user.id, t)
 
     await user.save({ transaction: t })
   })
index 82142935824375d42a6541e49d4e213bb01f386f..3eae28b34b9242515e4cef915697be3d1f68eaa5 100644 (file)
@@ -1,11 +1,14 @@
-import { handleLogin, handleTokenRevocation } from '@server/lib/auth'
+import * as express from 'express'
 import * as RateLimit from 'express-rate-limit'
+import { v4 as uuidv4 } from 'uuid'
+import { logger } from '@server/helpers/logger'
 import { CONFIG } from '@server/initializers/config'
-import * as express from 'express'
+import { getAuthNameFromRefreshGrant, getBypassFromExternalAuth, getBypassFromPasswordGrant } from '@server/lib/auth/external-auth'
+import { handleOAuthToken } from '@server/lib/auth/oauth'
+import { BypassLogin, revokeToken } from '@server/lib/auth/oauth-model'
 import { Hooks } from '@server/lib/plugins/hooks'
 import { asyncMiddleware, authenticate } from '@server/middlewares'
 import { ScopedToken } from '@shared/models/users/user-scoped-token'
-import { v4 as uuidv4 } from 'uuid'
 
 const tokensRouter = express.Router()
 
@@ -16,8 +19,7 @@ const loginRateLimiter = RateLimit({
 
 tokensRouter.post('/token',
   loginRateLimiter,
-  handleLogin,
-  tokenSuccess
+  asyncMiddleware(handleToken)
 )
 
 tokensRouter.post('/revoke-token',
@@ -42,10 +44,53 @@ export {
 }
 // ---------------------------------------------------------------------------
 
-function tokenSuccess (req: express.Request) {
-  const username = req.body.username
+async function handleToken (req: express.Request, res: express.Response, next: express.NextFunction) {
+  const grantType = req.body.grant_type
+
+  try {
+    const bypassLogin = await buildByPassLogin(req, grantType)
+
+    const refreshTokenAuthName = grantType === 'refresh_token'
+      ? await getAuthNameFromRefreshGrant(req.body.refresh_token)
+      : undefined
+
+    const options = {
+      refreshTokenAuthName,
+      bypassLogin
+    }
+
+    const token = await handleOAuthToken(req, options)
+
+    res.set('Cache-Control', 'no-store')
+    res.set('Pragma', 'no-cache')
+
+    Hooks.runAction('action:api.user.oauth2-got-token', { username: token.user.username, ip: req.ip })
+
+    return res.json({
+      token_type: 'Bearer',
 
-  Hooks.runAction('action:api.user.oauth2-got-token', { username, ip: req.ip })
+      access_token: token.accessToken,
+      refresh_token: token.refreshToken,
+
+      expires_in: token.accessTokenExpiresIn,
+      refresh_token_expires_in: token.refreshTokenExpiresIn
+    })
+  } catch (err) {
+    logger.warn('Login error', { err })
+
+    return res.status(err.code || 400).json({
+      code: err.name,
+      error: err.message
+    })
+  }
+}
+
+async function handleTokenRevocation (req: express.Request, res: express.Response) {
+  const token = res.locals.oauth.token
+
+  const result = await revokeToken(token, true)
+
+  return res.json(result)
 }
 
 function getScopedTokens (req: express.Request, res: express.Response) {
@@ -66,3 +111,14 @@ async function renewScopedTokens (req: express.Request, res: express.Response) {
     feedToken: user.feedToken
   } as ScopedToken)
 }
+
+async function buildByPassLogin (req: express.Request, grantType: string): Promise<BypassLogin> {
+  if (grantType !== 'password') return undefined
+
+  if (req.body.externalAuthToken) {
+    // Consistency with the getBypassFromPasswordGrant promise
+    return getBypassFromExternalAuth(req.body.username, req.body.externalAuthToken)
+  }
+
+  return getBypassFromPasswordGrant(req.body.username, req.body.password)
+}
index 6a1ccc0bf91c5439176eee6fab392e5371340a83..105f515184130196a093d5f2d842448e5e7542ca 100644 (file)
@@ -1,15 +1,15 @@
 import * as express from 'express'
-import { PLUGIN_GLOBAL_CSS_PATH } from '../initializers/constants'
 import { join } from 'path'
-import { PluginManager, RegisteredPlugin } from '../lib/plugins/plugin-manager'
-import { getPluginValidator, pluginStaticDirectoryValidator, getExternalAuthValidator } from '../middlewares/validators/plugins'
-import { serveThemeCSSValidator } from '../middlewares/validators/themes'
-import { HttpStatusCode } from '../../shared/core-utils/miscs/http-error-codes'
+import { logger } from '@server/helpers/logger'
+import { optionalAuthenticate } from '@server/middlewares/auth'
 import { getCompleteLocale, is18nLocale } from '../../shared/core-utils/i18n'
+import { HttpStatusCode } from '../../shared/core-utils/miscs/http-error-codes'
 import { PluginType } from '../../shared/models/plugins/plugin.type'
 import { isTestInstance } from '../helpers/core-utils'
-import { logger } from '@server/helpers/logger'
-import { optionalAuthenticate } from '@server/middlewares/oauth'
+import { PLUGIN_GLOBAL_CSS_PATH } from '../initializers/constants'
+import { PluginManager, RegisteredPlugin } from '../lib/plugins/plugin-manager'
+import { getExternalAuthValidator, getPluginValidator, pluginStaticDirectoryValidator } from '../middlewares/validators/plugins'
+import { serveThemeCSSValidator } from '../middlewares/validators/themes'
 
 const sendFileOptions = {
   maxAge: '30 days',
similarity index 61%
rename from server/lib/auth.ts
rename to server/lib/auth/external-auth.ts
index dbd421a7b3d6e0b33c1ecbf5dc2286475cc36452..80f5064b68cd3764b28868efb166553fec843655 100644 (file)
@@ -1,28 +1,16 @@
+
 import { isUserDisplayNameValid, isUserRoleValid, isUserUsernameValid } from '@server/helpers/custom-validators/users'
 import { logger } from '@server/helpers/logger'
 import { generateRandomString } from '@server/helpers/utils'
-import { OAUTH_LIFETIME, PLUGIN_EXTERNAL_AUTH_TOKEN_LIFETIME } from '@server/initializers/constants'
-import { revokeToken } from '@server/lib/oauth-model'
+import { PLUGIN_EXTERNAL_AUTH_TOKEN_LIFETIME } from '@server/initializers/constants'
 import { PluginManager } from '@server/lib/plugins/plugin-manager'
 import { OAuthTokenModel } from '@server/models/oauth/oauth-token'
-import { UserRole } from '@shared/models'
 import {
   RegisterServerAuthenticatedResult,
   RegisterServerAuthPassOptions,
   RegisterServerExternalAuthenticatedResult
 } from '@server/types/plugins/register-server-auth.model'
-import * as express from 'express'
-import * as OAuthServer from 'express-oauth-server'
-import { HttpStatusCode } from '@shared/core-utils/miscs/http-error-codes'
-
-const oAuthServer = new OAuthServer({
-  useErrorHandler: true,
-  accessTokenLifetime: OAUTH_LIFETIME.ACCESS_TOKEN,
-  refreshTokenLifetime: OAUTH_LIFETIME.REFRESH_TOKEN,
-  allowExtendedTokenAttributes: true,
-  continueMiddleware: true,
-  model: require('./oauth-model')
-})
+import { UserRole } from '@shared/models'
 
 // Token is the key, expiration date is the value
 const authBypassTokens = new Map<string, {
@@ -37,42 +25,6 @@ const authBypassTokens = new Map<string, {
   npmName: string
 }>()
 
-async function handleLogin (req: express.Request, res: express.Response, next: express.NextFunction) {
-  const grantType = req.body.grant_type
-
-  if (grantType === 'password') {
-    if (req.body.externalAuthToken) proxifyExternalAuthBypass(req, res)
-    else await proxifyPasswordGrant(req, res)
-  } else if (grantType === 'refresh_token') {
-    await proxifyRefreshGrant(req, res)
-  }
-
-  return forwardTokenReq(req, res, next)
-}
-
-async function handleTokenRevocation (req: express.Request, res: express.Response) {
-  const token = res.locals.oauth.token
-
-  res.locals.explicitLogout = true
-  const result = await revokeToken(token)
-
-  // FIXME: uncomment when https://github.com/oauthjs/node-oauth2-server/pull/289 is released
-  // oAuthServer.revoke(req, res, err => {
-  //   if (err) {
-  //     logger.warn('Error in revoke token handler.', { err })
-  //
-  //     return res.status(err.status)
-  //               .json({
-  //                 error: err.message,
-  //                 code: err.name
-  //               })
-  //               .end()
-  //   }
-  // })
-
-  return res.json(result)
-}
-
 async function onExternalUserAuthenticated (options: {
   npmName: string
   authName: string
@@ -107,7 +59,7 @@ async function onExternalUserAuthenticated (options: {
     authName
   })
 
-  // Cleanup
+  // Cleanup expired tokens
   const now = new Date()
   for (const [ key, value ] of authBypassTokens) {
     if (value.expires.getTime() < now.getTime()) {
@@ -118,37 +70,15 @@ async function onExternalUserAuthenticated (options: {
   res.redirect(`/login?externalAuthToken=${bypassToken}&username=${user.username}`)
 }
 
-// ---------------------------------------------------------------------------
-
-export { oAuthServer, handleLogin, onExternalUserAuthenticated, handleTokenRevocation }
-
-// ---------------------------------------------------------------------------
-
-function forwardTokenReq (req: express.Request, res: express.Response, next?: express.NextFunction) {
-  return oAuthServer.token()(req, res, err => {
-    if (err) {
-      logger.warn('Login error.', { err })
-
-      return res.status(err.status)
-        .json({
-          error: err.message,
-          code: err.name
-        })
-    }
-
-    if (next) return next()
-  })
-}
-
-async function proxifyRefreshGrant (req: express.Request, res: express.Response) {
-  const refreshToken = req.body.refresh_token
-  if (!refreshToken) return
+async function getAuthNameFromRefreshGrant (refreshToken?: string) {
+  if (!refreshToken) return undefined
 
   const tokenModel = await OAuthTokenModel.loadByRefreshToken(refreshToken)
-  if (tokenModel?.authName) res.locals.refreshTokenAuthName = tokenModel.authName
+
+  return tokenModel?.authName
 }
 
-async function proxifyPasswordGrant (req: express.Request, res: express.Response) {
+async function getBypassFromPasswordGrant (username: string, password: string) {
   const plugins = PluginManager.Instance.getIdAndPassAuths()
   const pluginAuths: { npmName?: string, registerAuthOptions: RegisterServerAuthPassOptions }[] = []
 
@@ -174,8 +104,8 @@ async function proxifyPasswordGrant (req: express.Request, res: express.Response
   })
 
   const loginOptions = {
-    id: req.body.username,
-    password: req.body.password
+    id: username,
+    password
   }
 
   for (const pluginAuth of pluginAuths) {
@@ -199,49 +129,41 @@ async function proxifyPasswordGrant (req: express.Request, res: express.Response
         authName, npmName, loginOptions.id
       )
 
-      res.locals.bypassLogin = {
+      return {
         bypass: true,
         pluginName: pluginAuth.npmName,
         authName: authOptions.authName,
         user: buildUserResult(loginResult)
       }
-
-      return
     } catch (err) {
       logger.error('Error in auth method %s of plugin %s', authOptions.authName, pluginAuth.npmName, { err })
     }
   }
+
+  return undefined
 }
 
-function proxifyExternalAuthBypass (req: express.Request, res: express.Response) {
-  const obj = authBypassTokens.get(req.body.externalAuthToken)
-  if (!obj) {
-    logger.error('Cannot authenticate user with unknown bypass token')
-    return res.sendStatus(HttpStatusCode.BAD_REQUEST_400)
-  }
+function getBypassFromExternalAuth (username: string, externalAuthToken: string) {
+  const obj = authBypassTokens.get(externalAuthToken)
+  if (!obj) throw new Error('Cannot authenticate user with unknown bypass token')
 
   const { expires, user, authName, npmName } = obj
 
   const now = new Date()
   if (now.getTime() > expires.getTime()) {
-    logger.error('Cannot authenticate user with an expired external auth token')
-    return res.sendStatus(HttpStatusCode.BAD_REQUEST_400)
+    throw new Error('Cannot authenticate user with an expired external auth token')
   }
 
-  if (user.username !== req.body.username) {
-    logger.error('Cannot authenticate user %s with invalid username %s.', req.body.username)
-    return res.sendStatus(HttpStatusCode.BAD_REQUEST_400)
+  if (user.username !== username) {
+    throw new Error(`Cannot authenticate user ${user.username} with invalid username ${username}`)
   }
 
-  // Bypass oauth library validation
-  req.body.password = 'fake'
-
   logger.info(
     'Auth success with external auth method %s of plugin %s for %s.',
     authName, npmName, user.email
   )
 
-  res.locals.bypassLogin = {
+  return {
     bypass: true,
     pluginName: npmName,
     authName: authName,
@@ -286,3 +208,12 @@ function buildUserResult (pluginResult: RegisterServerAuthenticatedResult) {
     displayName: pluginResult.displayName || pluginResult.username
   }
 }
+
+// ---------------------------------------------------------------------------
+
+export {
+  onExternalUserAuthenticated,
+  getBypassFromExternalAuth,
+  getAuthNameFromRefreshGrant,
+  getBypassFromPasswordGrant
+}
similarity index 63%
rename from server/lib/oauth-model.ts
rename to server/lib/auth/oauth-model.ts
index a2c53a2c9afb6fed41f543097a9b39a13fb0b288..c74869ee25cc8e70a1b67587503ef47bdf7d43c8 100644 (file)
@@ -1,49 +1,35 @@
-import * as express from 'express'
-import * as LRUCache from 'lru-cache'
 import { AccessDeniedError } from 'oauth2-server'
-import { Transaction } from 'sequelize'
 import { PluginManager } from '@server/lib/plugins/plugin-manager'
 import { ActorModel } from '@server/models/activitypub/actor'
+import { MOAuthClient } from '@server/types/models'
 import { MOAuthTokenUser } from '@server/types/models/oauth/oauth-token'
 import { MUser } from '@server/types/models/user/user'
 import { UserAdminFlag } from '@shared/models/users/user-flag.model'
 import { UserRole } from '@shared/models/users/user-role'
-import { logger } from '../helpers/logger'
-import { CONFIG } from '../initializers/config'
-import { LRU_CACHE } from '../initializers/constants'
-import { UserModel } from '../models/account/user'
-import { OAuthClientModel } from '../models/oauth/oauth-client'
-import { OAuthTokenModel } from '../models/oauth/oauth-token'
-import { createUserAccountAndChannelAndPlaylist } from './user'
-
-type TokenInfo = { accessToken: string, refreshToken: string, accessTokenExpiresAt: Date, refreshTokenExpiresAt: Date }
-
-const accessTokenCache = new LRUCache<string, MOAuthTokenUser>({ max: LRU_CACHE.USER_TOKENS.MAX_SIZE })
-const userHavingToken = new LRUCache<number, string>({ max: LRU_CACHE.USER_TOKENS.MAX_SIZE })
-
-// ---------------------------------------------------------------------------
-
-function deleteUserToken (userId: number, t?: Transaction) {
-  clearCacheByUserId(userId)
-
-  return OAuthTokenModel.deleteUserToken(userId, t)
+import { logger } from '../../helpers/logger'
+import { CONFIG } from '../../initializers/config'
+import { UserModel } from '../../models/account/user'
+import { OAuthClientModel } from '../../models/oauth/oauth-client'
+import { OAuthTokenModel } from '../../models/oauth/oauth-token'
+import { createUserAccountAndChannelAndPlaylist } from '../user'
+import { TokensCache } from './tokens-cache'
+
+type TokenInfo = {
+  accessToken: string
+  refreshToken: string
+  accessTokenExpiresAt: Date
+  refreshTokenExpiresAt: Date
 }
 
-function clearCacheByUserId (userId: number) {
-  const token = userHavingToken.get(userId)
-
-  if (token !== undefined) {
-    accessTokenCache.del(token)
-    userHavingToken.del(userId)
-  }
-}
-
-function clearCacheByToken (token: string) {
-  const tokenModel = accessTokenCache.get(token)
-
-  if (tokenModel !== undefined) {
-    userHavingToken.del(tokenModel.userId)
-    accessTokenCache.del(token)
+export type BypassLogin = {
+  bypass: boolean
+  pluginName: string
+  authName?: string
+  user: {
+    username: string
+    email: string
+    displayName: string
+    role: UserRole
   }
 }
 
@@ -54,15 +40,12 @@ async function getAccessToken (bearerToken: string) {
 
   let tokenModel: MOAuthTokenUser
 
-  if (accessTokenCache.has(bearerToken)) {
-    tokenModel = accessTokenCache.get(bearerToken)
+  if (TokensCache.Instance.hasToken(bearerToken)) {
+    tokenModel = TokensCache.Instance.getByToken(bearerToken)
   } else {
     tokenModel = await OAuthTokenModel.getByTokenAndPopulateUser(bearerToken)
 
-    if (tokenModel) {
-      accessTokenCache.set(bearerToken, tokenModel)
-      userHavingToken.set(tokenModel.userId, tokenModel.accessToken)
-    }
+    if (tokenModel) TokensCache.Instance.setToken(tokenModel)
   }
 
   if (!tokenModel) return undefined
@@ -99,16 +82,13 @@ async function getRefreshToken (refreshToken: string) {
   return tokenInfo
 }
 
-async function getUser (usernameOrEmail?: string, password?: string) {
-  const res: express.Response = this.request.res
-
+async function getUser (usernameOrEmail?: string, password?: string, bypassLogin?: BypassLogin) {
   // Special treatment coming from a plugin
-  if (res.locals.bypassLogin && res.locals.bypassLogin.bypass === true) {
-    const obj = res.locals.bypassLogin
-    logger.info('Bypassing oauth login by plugin %s.', obj.pluginName)
+  if (bypassLogin && bypassLogin.bypass === true) {
+    logger.info('Bypassing oauth login by plugin %s.', bypassLogin.pluginName)
 
-    let user = await UserModel.loadByEmail(obj.user.email)
-    if (!user) user = await createUserFromExternal(obj.pluginName, obj.user)
+    let user = await UserModel.loadByEmail(bypassLogin.user.email)
+    if (!user) user = await createUserFromExternal(bypassLogin.pluginName, bypassLogin.user)
 
     // Cannot create a user
     if (!user) throw new AccessDeniedError('Cannot create such user: an actor with that name already exists.')
@@ -117,7 +97,7 @@ async function getUser (usernameOrEmail?: string, password?: string) {
     // Then we just go through a regular login process
     if (user.pluginAuth !== null) {
       // This user does not belong to this plugin, skip it
-      if (user.pluginAuth !== obj.pluginName) return null
+      if (user.pluginAuth !== bypassLogin.pluginName) return null
 
       checkUserValidityOrThrow(user)
 
@@ -143,18 +123,20 @@ async function getUser (usernameOrEmail?: string, password?: string) {
   return user
 }
 
-async function revokeToken (tokenInfo: { refreshToken: string }): Promise<{ success: boolean, redirectUrl?: string }> {
-  const res: express.Response = this.request.res
+async function revokeToken (
+  tokenInfo: { refreshToken: string },
+  explicitLogout?: boolean
+): Promise<{ success: boolean, redirectUrl?: string }> {
   const token = await OAuthTokenModel.getByRefreshTokenAndPopulateUser(tokenInfo.refreshToken)
 
   if (token) {
     let redirectUrl: string
 
-    if (res.locals.explicitLogout === true && token.User.pluginAuth && token.authName) {
+    if (explicitLogout === true && token.User.pluginAuth && token.authName) {
       redirectUrl = await PluginManager.Instance.onLogout(token.User.pluginAuth, token.authName, token.User, this.request)
     }
 
-    clearCacheByToken(token.accessToken)
+    TokensCache.Instance.clearCacheByToken(token.accessToken)
 
     token.destroy()
          .catch(err => logger.error('Cannot destroy token when revoking token.', { err }))
@@ -165,14 +147,22 @@ async function revokeToken (tokenInfo: { refreshToken: string }): Promise<{ succ
   return { success: false }
 }
 
-async function saveToken (token: TokenInfo, client: OAuthClientModel, user: UserModel) {
-  const res: express.Response = this.request.res
-
+async function saveToken (
+  token: TokenInfo,
+  client: MOAuthClient,
+  user: MUser,
+  options: {
+    refreshTokenAuthName?: string
+    bypassLogin?: BypassLogin
+  } = {}
+) {
+  const { refreshTokenAuthName, bypassLogin } = options
   let authName: string = null
-  if (res.locals.bypassLogin?.bypass === true) {
-    authName = res.locals.bypassLogin.authName
-  } else if (res.locals.refreshTokenAuthName) {
-    authName = res.locals.refreshTokenAuthName
+
+  if (bypassLogin?.bypass === true) {
+    authName = bypassLogin.authName
+  } else if (refreshTokenAuthName) {
+    authName = refreshTokenAuthName
   }
 
   logger.debug('Saving token ' + token.accessToken + ' for client ' + client.id + ' and user ' + user.id + '.')
@@ -199,17 +189,12 @@ async function saveToken (token: TokenInfo, client: OAuthClientModel, user: User
     refreshTokenExpiresAt: tokenCreated.refreshTokenExpiresAt,
     client,
     user,
-    refresh_token_expires_in: Math.floor((tokenCreated.refreshTokenExpiresAt.getTime() - new Date().getTime()) / 1000)
+    accessTokenExpiresIn: buildExpiresIn(tokenCreated.accessTokenExpiresAt),
+    refreshTokenExpiresIn: buildExpiresIn(tokenCreated.refreshTokenExpiresAt)
   }
 }
 
-// ---------------------------------------------------------------------------
-
-// See https://github.com/oauthjs/node-oauth2-server/wiki/Model-specification for the model specifications
 export {
-  deleteUserToken,
-  clearCacheByUserId,
-  clearCacheByToken,
   getAccessToken,
   getClient,
   getRefreshToken,
@@ -218,6 +203,8 @@ export {
   saveToken
 }
 
+// ---------------------------------------------------------------------------
+
 async function createUserFromExternal (pluginAuth: string, options: {
   username: string
   email: string
@@ -252,3 +239,7 @@ async function createUserFromExternal (pluginAuth: string, options: {
 function checkUserValidityOrThrow (user: MUser) {
   if (user.blocked) throw new AccessDeniedError('User is blocked.')
 }
+
+function buildExpiresIn (expiresAt: Date) {
+  return Math.floor((expiresAt.getTime() - new Date().getTime()) / 1000)
+}
diff --git a/server/lib/auth/oauth.ts b/server/lib/auth/oauth.ts
new file mode 100644 (file)
index 0000000..5b6130d
--- /dev/null
@@ -0,0 +1,180 @@
+import * as express from 'express'
+import {
+  InvalidClientError,
+  InvalidGrantError,
+  InvalidRequestError,
+  Request,
+  Response,
+  UnauthorizedClientError,
+  UnsupportedGrantTypeError
+} from 'oauth2-server'
+import { randomBytesPromise, sha1 } from '@server/helpers/core-utils'
+import { MOAuthClient } from '@server/types/models'
+import { OAUTH_LIFETIME } from '../../initializers/constants'
+import { BypassLogin, getClient, getRefreshToken, getUser, revokeToken, saveToken } from './oauth-model'
+
+/**
+ *
+ * Reimplement some functions of OAuth2Server to inject external auth methods
+ *
+ */
+
+const oAuthServer = new (require('oauth2-server'))({
+  accessTokenLifetime: OAUTH_LIFETIME.ACCESS_TOKEN,
+  refreshTokenLifetime: OAUTH_LIFETIME.REFRESH_TOKEN,
+
+  // See https://github.com/oauthjs/node-oauth2-server/wiki/Model-specification for the model specifications
+  model: require('./oauth-model')
+})
+
+// ---------------------------------------------------------------------------
+
+async function handleOAuthToken (req: express.Request, options: { refreshTokenAuthName?: string, bypassLogin?: BypassLogin }) {
+  const request = new Request(req)
+  const { refreshTokenAuthName, bypassLogin } = options
+
+  if (request.method !== 'POST') {
+    throw new InvalidRequestError('Invalid request: method must be POST')
+  }
+
+  if (!request.is([ 'application/x-www-form-urlencoded' ])) {
+    throw new InvalidRequestError('Invalid request: content must be application/x-www-form-urlencoded')
+  }
+
+  const clientId = request.body.client_id
+  const clientSecret = request.body.client_secret
+
+  if (!clientId || !clientSecret) {
+    throw new InvalidClientError('Invalid client: cannot retrieve client credentials')
+  }
+
+  const client = await getClient(clientId, clientSecret)
+  if (!client) {
+    throw new InvalidClientError('Invalid client: client is invalid')
+  }
+
+  const grantType = request.body.grant_type
+  if (!grantType) {
+    throw new InvalidRequestError('Missing parameter: `grant_type`')
+  }
+
+  if (![ 'password', 'refresh_token' ].includes(grantType)) {
+    throw new UnsupportedGrantTypeError('Unsupported grant type: `grant_type` is invalid')
+  }
+
+  if (!client.grants.includes(grantType)) {
+    throw new UnauthorizedClientError('Unauthorized client: `grant_type` is invalid')
+  }
+
+  if (grantType === 'password') {
+    return handlePasswordGrant({
+      request,
+      client,
+      bypassLogin
+    })
+  }
+
+  return handleRefreshGrant({
+    request,
+    client,
+    refreshTokenAuthName
+  })
+}
+
+async function handleOAuthAuthenticate (
+  req: express.Request,
+  res: express.Response,
+  authenticateInQuery = false
+) {
+  const options = authenticateInQuery
+    ? { allowBearerTokensInQueryString: true }
+    : {}
+
+  return oAuthServer.authenticate(new Request(req), new Response(res), options)
+}
+
+export {
+  handleOAuthToken,
+  handleOAuthAuthenticate
+}
+
+// ---------------------------------------------------------------------------
+
+async function handlePasswordGrant (options: {
+  request: Request
+  client: MOAuthClient
+  bypassLogin?: BypassLogin
+}) {
+  const { request, client, bypassLogin } = options
+
+  if (!request.body.username) {
+    throw new InvalidRequestError('Missing parameter: `username`')
+  }
+
+  if (!bypassLogin && !request.body.password) {
+    throw new InvalidRequestError('Missing parameter: `password`')
+  }
+
+  const user = await getUser(request.body.username, request.body.password, bypassLogin)
+  if (!user) throw new InvalidGrantError('Invalid grant: user credentials are invalid')
+
+  const token = await buildToken()
+
+  return saveToken(token, client, user, { bypassLogin })
+}
+
+async function handleRefreshGrant (options: {
+  request: Request
+  client: MOAuthClient
+  refreshTokenAuthName: string
+}) {
+  const { request, client, refreshTokenAuthName } = options
+
+  if (!request.body.refresh_token) {
+    throw new InvalidRequestError('Missing parameter: `refresh_token`')
+  }
+
+  const refreshToken = await getRefreshToken(request.body.refresh_token)
+
+  if (!refreshToken) {
+    throw new InvalidGrantError('Invalid grant: refresh token is invalid')
+  }
+
+  if (refreshToken.client.id !== client.id) {
+    throw new InvalidGrantError('Invalid grant: refresh token is invalid')
+  }
+
+  if (refreshToken.refreshTokenExpiresAt && refreshToken.refreshTokenExpiresAt < new Date()) {
+    throw new InvalidGrantError('Invalid grant: refresh token has expired')
+  }
+
+  await revokeToken({ refreshToken: refreshToken.refreshToken })
+
+  const token = await buildToken()
+
+  return saveToken(token, client, refreshToken.user, { refreshTokenAuthName })
+}
+
+function generateRandomToken () {
+  return randomBytesPromise(256)
+    .then(buffer => sha1(buffer))
+}
+
+function getTokenExpiresAt (type: 'access' | 'refresh') {
+  const lifetime = type === 'access'
+    ? OAUTH_LIFETIME.ACCESS_TOKEN
+    : OAUTH_LIFETIME.REFRESH_TOKEN
+
+  return new Date(Date.now() + lifetime * 1000)
+}
+
+async function buildToken () {
+  const [ accessToken, refreshToken ] = await Promise.all([ generateRandomToken(), generateRandomToken() ])
+
+  return {
+    accessToken,
+    refreshToken,
+    accessTokenExpiresAt: getTokenExpiresAt('access'),
+    refreshTokenExpiresAt: getTokenExpiresAt('refresh')
+  }
+}
diff --git a/server/lib/auth/tokens-cache.ts b/server/lib/auth/tokens-cache.ts
new file mode 100644 (file)
index 0000000..b027ce6
--- /dev/null
@@ -0,0 +1,52 @@
+import * as LRUCache from 'lru-cache'
+import { MOAuthTokenUser } from '@server/types/models'
+import { LRU_CACHE } from '../../initializers/constants'
+
+export class TokensCache {
+
+  private static instance: TokensCache
+
+  private readonly accessTokenCache = new LRUCache<string, MOAuthTokenUser>({ max: LRU_CACHE.USER_TOKENS.MAX_SIZE })
+  private readonly userHavingToken = new LRUCache<number, string>({ max: LRU_CACHE.USER_TOKENS.MAX_SIZE })
+
+  private constructor () { }
+
+  static get Instance () {
+    return this.instance || (this.instance = new this())
+  }
+
+  hasToken (token: string) {
+    return this.accessTokenCache.has(token)
+  }
+
+  getByToken (token: string) {
+    return this.accessTokenCache.get(token)
+  }
+
+  setToken (token: MOAuthTokenUser) {
+    this.accessTokenCache.set(token.accessToken, token)
+    this.userHavingToken.set(token.userId, token.accessToken)
+  }
+
+  deleteUserToken (userId: number) {
+    this.clearCacheByUserId(userId)
+  }
+
+  clearCacheByUserId (userId: number) {
+    const token = this.userHavingToken.get(userId)
+
+    if (token !== undefined) {
+      this.accessTokenCache.del(token)
+      this.userHavingToken.del(userId)
+    }
+  }
+
+  clearCacheByToken (token: string) {
+    const tokenModel = this.accessTokenCache.get(token)
+
+    if (tokenModel !== undefined) {
+      this.userHavingToken.del(tokenModel.userId)
+      this.accessTokenCache.del(token)
+    }
+  }
+}
index 1f2a88c274d54119e521bc80c8a22d64e4438d75..9b5e1a5462af714e322a1d9cb0968992fda08227 100644 (file)
@@ -7,7 +7,7 @@ import {
   VIDEO_PLAYLIST_PRIVACIES,
   VIDEO_PRIVACIES
 } from '@server/initializers/constants'
-import { onExternalUserAuthenticated } from '@server/lib/auth'
+import { onExternalUserAuthenticated } from '@server/lib/auth/external-auth'
 import { PluginModel } from '@server/models/server/plugin'
 import {
   RegisterServerAuthExternalOptions,
similarity index 86%
rename from server/middlewares/oauth.ts
rename to server/middlewares/auth.ts
index 280595acc3a08b27c8eab9fd3c0a2bd161e63e3a..f38373624c1cccf006c3be35de067cdf7c552516 100644 (file)
@@ -1,15 +1,19 @@
 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 { 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) {
-  const options = authenticateInQuery ? { allowBearerTokensInQueryString: true } : {}
+  handleOAuthAuthenticate(req, res, authenticateInQuery)
+    .then((token: any) => {
+      res.locals.oauth = { token }
+      res.locals.authenticated = true
 
-  oAuthServer.authenticate(options)(req, res, err => {
-    if (err) {
+      return next()
+    })
+    .catch(err => {
       logger.warn('Cannot authenticate.', { err })
 
       return res.status(err.status)
@@ -17,13 +21,7 @@ function authenticate (req: express.Request, res: express.Response, next: expres
           error: 'Token is invalid.',
           code: err.name
         })
-        .end()
-    }
-
-    res.locals.authenticated = true
-
-    return next()
-  })
+    })
 }
 
 function authenticateSocket (socket: Socket, next: (err?: any) => void) {
index b758a8586b19fb89a3adf9697260ee76eb2c7048..3e280e16f590a182396934a8b070cea72ee28ee4 100644 (file)
@@ -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'
index 0fba4f5fdfc0d66a1d83e21696b3316133b79073..c872d045e0a150655d3a4b8e65e7bf287e066334 100644 (file)
@@ -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([
index 37cc07b94477c17be57608473330da88b725a469..4d31d3dcb076e6cd4a1644fe2b9719ca519e1b38 100644 (file)
@@ -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([
index de150129922ca57e0dced2524d2a9c222030d331..138051528d6f493da896a79773d37294f56c2093 100644 (file)
@@ -12,10 +12,10 @@ import {
   Table,
   UpdatedAt
 } from 'sequelize-typescript'
+import { TokensCache } from '@server/lib/auth/tokens-cache'
 import { MNotificationSettingFormattable } from '@server/types/models'
 import { UserNotificationSetting, UserNotificationSettingValue } from '../../../shared/models/users/user-notification-setting.model'
 import { isUserNotificationSettingValid } from '../../helpers/custom-validators/user-notifications'
-import { clearCacheByUserId } from '../../lib/oauth-model'
 import { throwIfNotValid } from '../utils'
 import { UserModel } from './user'
 
@@ -195,7 +195,7 @@ export class UserNotificationSettingModel extends Model {
   @AfterUpdate
   @AfterDestroy
   static removeTokenCache (instance: UserNotificationSettingModel) {
-    return clearCacheByUserId(instance.userId)
+    return TokensCache.Instance.clearCacheByUserId(instance.userId)
   }
 
   toFormattedJSON (this: MNotificationSettingFormattable): UserNotificationSetting {
index c1f22b76aaad87c4195416c0096d6e1ffacd80fe..a7a65c48972f6023e2e369f39f355f97bc4e5440 100644 (file)
@@ -21,6 +21,7 @@ import {
   Table,
   UpdatedAt
 } from 'sequelize-typescript'
+import { TokensCache } from '@server/lib/auth/tokens-cache'
 import {
   MMyUserFormattable,
   MUser,
@@ -58,7 +59,6 @@ import {
 } from '../../helpers/custom-validators/users'
 import { comparePassword, cryptPassword } from '../../helpers/peertube-crypto'
 import { DEFAULT_USER_THEME_NAME, NSFW_POLICY_TYPES } from '../../initializers/constants'
-import { clearCacheByUserId } from '../../lib/oauth-model'
 import { getThemeOrDefault } from '../../lib/plugins/theme-utils'
 import { ActorModel } from '../activitypub/actor'
 import { ActorFollowModel } from '../activitypub/actor-follow'
@@ -411,7 +411,7 @@ export class UserModel extends Model {
   @AfterUpdate
   @AfterDestroy
   static removeTokenCache (instance: UserModel) {
-    return clearCacheByUserId(instance.id)
+    return TokensCache.Instance.clearCacheByUserId(instance.id)
   }
 
   static countTotal () {
index 6bc6cf27c6fcf6bd5ef0f44c7565456eaeb13f2c..27e643aa71cf0aba93e18fb8a15d4903d6c36c2a 100644 (file)
@@ -12,9 +12,10 @@ import {
   Table,
   UpdatedAt
 } from 'sequelize-typescript'
+import { TokensCache } from '@server/lib/auth/tokens-cache'
+import { MUserAccountId } from '@server/types/models'
 import { MOAuthTokenUser } from '@server/types/models/oauth/oauth-token'
 import { logger } from '../../helpers/logger'
-import { clearCacheByToken } from '../../lib/oauth-model'
 import { AccountModel } from '../account/account'
 import { UserModel } from '../account/user'
 import { ActorModel } from '../activitypub/actor'
@@ -26,9 +27,7 @@ export type OAuthTokenInfo = {
   client: {
     id: number
   }
-  user: {
-    id: number
-  }
+  user: MUserAccountId
   token: MOAuthTokenUser
 }
 
@@ -133,7 +132,7 @@ export class OAuthTokenModel extends Model {
   @AfterUpdate
   @AfterDestroy
   static removeTokenCache (token: OAuthTokenModel) {
-    return clearCacheByToken(token.accessToken)
+    return TokensCache.Instance.clearCacheByToken(token.accessToken)
   }
 
   static loadByRefreshToken (refreshToken: string) {
@@ -206,6 +205,8 @@ export class OAuthTokenModel extends Model {
   }
 
   static deleteUserToken (userId: number, t?: Transaction) {
+    TokensCache.Instance.deleteUserToken(userId)
+
     const query = {
       where: {
         userId
index 0a13f5b678cefc1168b4b4dae95200c37a43c5f3..2b03fde2d05028adcbe92e91e95f1ee213b55d5e 100644 (file)
@@ -241,7 +241,7 @@ describe('Test users API validators', function () {
     })
 
     it('Should succeed with no password on a server with smtp enabled', async function () {
-      this.timeout(10000)
+      this.timeout(20000)
 
       killallServers([ server ])
 
index 62a59033fe10ed39a27c3ba6c0f0078c1d56ef8f..cea98aac7b9f9fc40d9434927f80a0f427f06f05 100644 (file)
@@ -4,10 +4,12 @@ import 'mocha'
 import * as chai from 'chai'
 import { AbuseState, AbuseUpdate, MyUser, User, UserRole, Video, VideoPlaylistType } from '@shared/models'
 import { CustomConfig } from '@shared/models/server'
+import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
 import {
   addVideoCommentThread,
   blockUser,
   cleanupTests,
+  closeAllSequelize,
   createUser,
   deleteMe,
   flushAndRunServer,
@@ -24,6 +26,7 @@ import {
   getVideoChannel,
   getVideosList,
   installPlugin,
+  killallServers,
   login,
   makePutBodyRequest,
   rateVideo,
@@ -31,7 +34,9 @@ import {
   removeUser,
   removeVideo,
   reportAbuse,
+  reRunServer,
   ServerInfo,
+  setTokenField,
   testImage,
   unblockUser,
   updateAbuse,
@@ -44,10 +49,9 @@ import {
   waitJobs
 } from '../../../../shared/extra-utils'
 import { follow } from '../../../../shared/extra-utils/server/follows'
-import { logout, serverLogin, setAccessTokensToServers } from '../../../../shared/extra-utils/users/login'
+import { logout, refreshToken, setAccessTokensToServers } from '../../../../shared/extra-utils/users/login'
 import { getMyVideos } from '../../../../shared/extra-utils/videos/videos'
 import { UserAdminFlag } from '../../../../shared/models/users/user-flag.model'
-import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
 
 const expect = chai.expect
 
@@ -89,6 +93,7 @@ describe('Test users', function () {
       const client = { id: 'client', secret: server.client.secret }
       const res = await login(server.url, client, server.user, HttpStatusCode.BAD_REQUEST_400)
 
+      expect(res.body.code).to.equal('invalid_client')
       expect(res.body.error).to.contain('client is invalid')
     })
 
@@ -96,6 +101,7 @@ describe('Test users', function () {
       const client = { id: server.client.id, secret: 'coucou' }
       const res = await login(server.url, client, server.user, HttpStatusCode.BAD_REQUEST_400)
 
+      expect(res.body.code).to.equal('invalid_client')
       expect(res.body.error).to.contain('client is invalid')
     })
   })
@@ -106,6 +112,7 @@ describe('Test users', function () {
       const user = { username: 'captain crochet', password: server.user.password }
       const res = await login(server.url, server.client, user, HttpStatusCode.BAD_REQUEST_400)
 
+      expect(res.body.code).to.equal('invalid_grant')
       expect(res.body.error).to.contain('credentials are invalid')
     })
 
@@ -113,6 +120,7 @@ describe('Test users', function () {
       const user = { username: server.user.username, password: 'mew_three' }
       const res = await login(server.url, server.client, user, HttpStatusCode.BAD_REQUEST_400)
 
+      expect(res.body.code).to.equal('invalid_grant')
       expect(res.body.error).to.contain('credentials are invalid')
     })
 
@@ -245,12 +253,44 @@ describe('Test users', function () {
     })
 
     it('Should be able to login again', async function () {
-      server.accessToken = await serverLogin(server)
+      const res = await login(server.url, server.client, server.user)
+      server.accessToken = res.body.access_token
+      server.refreshToken = res.body.refresh_token
+    })
+
+    it('Should be able to get my user information again', async function () {
+      await getMyUserInformation(server.url, server.accessToken)
+    })
+
+    it('Should have an expired access token', async function () {
+      this.timeout(15000)
+
+      await setTokenField(server.internalServerNumber, server.accessToken, 'accessTokenExpiresAt', new Date().toISOString())
+      await setTokenField(server.internalServerNumber, server.accessToken, 'refreshTokenExpiresAt', new Date().toISOString())
+
+      killallServers([ server ])
+      await reRunServer(server)
+
+      await getMyUserInformation(server.url, server.accessToken, 401)
+    })
+
+    it('Should not be able to refresh an access token with an expired refresh token', async function () {
+      await refreshToken(server, server.refreshToken, 400)
     })
 
-    it('Should have an expired access token')
+    it('Should refresh the token', async function () {
+      this.timeout(15000)
+
+      const futureDate = new Date(new Date().getTime() + 1000 * 60).toISOString()
+      await setTokenField(server.internalServerNumber, server.accessToken, 'refreshTokenExpiresAt', futureDate)
 
-    it('Should refresh the token')
+      killallServers([ server ])
+      await reRunServer(server)
+
+      const res = await refreshToken(server, server.refreshToken)
+      server.accessToken = res.body.access_token
+      server.refreshToken = res.body.refresh_token
+    })
 
     it('Should be able to get my user information again', async function () {
       await getMyUserInformation(server.url, server.accessToken)
@@ -976,6 +1016,7 @@ describe('Test users', function () {
   })
 
   after(async function () {
+    await closeAllSequelize([ server ])
     await cleanupTests([ server ])
   })
 })
index a1b5e8f5da06c2a42239f76c9d1c45ccce28d2ea..5addb45c7826be08d5c2b2cf34556792ab481c6b 100644 (file)
@@ -137,7 +137,7 @@ describe('Test external auth plugins', function () {
 
     await loginUsingExternalToken(server, 'cyan', externalAuthToken, HttpStatusCode.BAD_REQUEST_400)
 
-    await waitUntilLog(server, 'expired external auth token')
+    await waitUntilLog(server, 'expired external auth token', 2)
   })
 
   it('Should auto login Cyan, create the user and use the token', async function () {
index 66acfb3f5ea7c4db9f6de142cba09988a9b4c9c8..b0004dc7b7818a48ed0355e7a94023c43147f26c 100644 (file)
@@ -17,7 +17,6 @@ import { MPlugin, MServer, MServerBlocklist } from '@server/types/models/server'
 import { MVideoImportDefault } from '@server/types/models/video/video-import'
 import { MVideoPlaylistElement, MVideoPlaylistElementVideoUrlPlaylistPrivacy } from '@server/types/models/video/video-playlist-element'
 import { MAccountVideoRateAccountVideo } from '@server/types/models/video/video-rate'
-import { UserRole } from '@shared/models'
 import { RegisteredPlugin } from '../../lib/plugins/plugin-manager'
 import {
   MAccountDefault,
@@ -49,22 +48,6 @@ declare module 'express' {
 }
 
 interface PeerTubeLocals {
-  bypassLogin?: {
-    bypass: boolean
-    pluginName: string
-    authName?: string
-    user: {
-      username: string
-      email: string
-      displayName: string
-      role: UserRole
-    }
-  }
-
-  refreshTokenAuthName?: string
-
-  explicitLogout?: boolean
-
   videoAll?: MVideoFullLight
   onlyImmutableVideo?: MVideoImmutable
   onlyVideo?: MVideoThumbnail
index 345e5bc1647cf9f1ee256470433f3014a62a7b3b..35e493456691c695b706a04efacfed33dd48ea10 100644 (file)
@@ -130,6 +130,14 @@ function setActorFollowScores (internalServerNumber: number, newScore: number) {
   return seq.query(`UPDATE "actorFollow" SET "score" = ${newScore}`, options)
 }
 
+function setTokenField (internalServerNumber: number, accessToken: string, field: string, value: string) {
+  const seq = getSequelize(internalServerNumber)
+
+  const options = { type: QueryTypes.UPDATE }
+
+  return seq.query(`UPDATE "oAuthToken" SET "${field}" = '${value}' WHERE "accessToken" = '${accessToken}'`, options)
+}
+
 export {
   setVideoField,
   setPlaylistField,
@@ -139,6 +147,7 @@ export {
   setPluginLatestVersion,
   selectQuery,
   deleteAll,
+  setTokenField,
   updateQuery,
   setActorFollowScores,
   closeAllSequelize,
index 08d05ef36ed630a6a558c314935463f64b1013e1..779a3cc36da6988a9bc73c77d434bfc9ce6b8779 100644 (file)
@@ -37,6 +37,7 @@ interface ServerInfo {
   customConfigFile?: string
 
   accessToken?: string
+  refreshToken?: string
   videoChannel?: VideoChannel
 
   video?: {
index 5546830be1a84b735f4fff932ed9158f9b08e762..d2891d9224f2f99bd643053824c0806666d56302 100644 (file)
--- a/yarn.lock
+++ b/yarn.lock
@@ -1657,7 +1657,7 @@ bluebird@^2.10.0:
   resolved "https://registry.yarnpkg.com/bluebird/-/bluebird-2.11.0.tgz#534b9033c022c9579c56ba3b3e5a5caafbb650e1"
   integrity sha1-U0uQM8AiyVecVro7Plpcqvu2UOE=
 
-bluebird@^3.0.5, bluebird@^3.5.0, bluebird@^3.5.1, bluebird@^3.7.2:
+bluebird@^3.5.0, bluebird@^3.5.1, bluebird@^3.7.2:
   version "3.7.2"
   resolved "https://registry.yarnpkg.com/bluebird/-/bluebird-3.7.2.tgz#9f229c15be272454ffa973ace0dbee79a1b0c36f"
   integrity sha512-XpNj6GDQzdfW+r2Wnn7xiSAd7TM3jzkxGXBGTtWKuSXv1xUV+azxAm8jdWZN06QTQk+2N2XB9jRDkvbmQmcRtg==
@@ -3401,15 +3401,6 @@ exif-parser@^0.1.12:
   resolved "https://registry.yarnpkg.com/exif-parser/-/exif-parser-0.1.12.tgz#58a9d2d72c02c1f6f02a0ef4a9166272b7760922"
   integrity sha1-WKnS1ywCwfbwKg70qRZicrd2CSI=
 
-express-oauth-server@^2.0.0:
-  version "2.0.0"
-  resolved "https://registry.yarnpkg.com/express-oauth-server/-/express-oauth-server-2.0.0.tgz#57b08665c1201532f52c4c02f19709238b99a48d"
-  integrity sha1-V7CGZcEgFTL1LEwC8ZcJI4uZpI0=
-  dependencies:
-    bluebird "^3.0.5"
-    express "^4.13.3"
-    oauth2-server "3.0.0"
-
 express-rate-limit@^5.0.0:
   version "5.2.6"
   resolved "https://registry.yarnpkg.com/express-rate-limit/-/express-rate-limit-5.2.6.tgz#b454e1be8a252081bda58460e0a25bf43ee0f7b0"
@@ -3423,7 +3414,7 @@ express-validator@^6.4.0:
     lodash "^4.17.20"
     validator "^13.5.2"
 
-express@^4.12.4, express@^4.13.3, express@^4.16.4, express@^4.17.1:
+express@^4.12.4, express@^4.16.4, express@^4.17.1:
   version "4.17.1"
   resolved "https://registry.yarnpkg.com/express/-/express-4.17.1.tgz#4491fc38605cf51f8629d39c2b5d026f98a4c134"
   integrity sha512-mHJ9O79RqluphRrcw2X/GTh3k9tVv8YcoyY4Kkh4WDMUYKRZUq0h1o0w2rrrxBqM7VoeUVqgb27xlEMXTnYt4g==
@@ -5892,7 +5883,7 @@ oauth-sign@~0.9.0:
   resolved "https://registry.yarnpkg.com/oauth-sign/-/oauth-sign-0.9.0.tgz#47a7b016baa68b5fa0ecf3dee08a85c679ac6455"
   integrity sha512-fexhUFFPTGV8ybAtSIGbV6gOkSv8UtRbDBnAyLQw4QPKkgNlsH2ByPGtMUqdWkos6YCRmAqViwgZrJc/mRDzZQ==
 
-oauth2-server@3.0.0, oauth2-server@3.1.0-beta.1:
+oauth2-server@3.1.0-beta.1:
   version "3.1.0-beta.1"
   resolved "https://registry.yarnpkg.com/oauth2-server/-/oauth2-server-3.1.0-beta.1.tgz#159ee4d32d148c2dc7a39f7b1ce872e039b91a41"
   integrity sha512-FWLl/YC5NGvGzAtclhmlY9fG0nKwDP7xPiPOi5fZ4APO34BmF/vxsEp22spJNuSOrGEsp9W7jKtFCI3UBSvx5w==