mirror of
https://github.com/Chocobozzz/PeerTube.git
synced 2025-10-05 19:42:24 +02:00
server/server -> server/core
This commit is contained in:
parent
114327d4ce
commit
5a3d0650c9
838 changed files with 111 additions and 111 deletions
230
server/core/lib/auth/external-auth.ts
Normal file
230
server/core/lib/auth/external-auth.ts
Normal file
|
@ -0,0 +1,230 @@
|
|||
import {
|
||||
isUserAdminFlagsValid,
|
||||
isUserDisplayNameValid,
|
||||
isUserRoleValid,
|
||||
isUserUsernameValid,
|
||||
isUserVideoQuotaDailyValid,
|
||||
isUserVideoQuotaValid
|
||||
} from '@server/helpers/custom-validators/users.js'
|
||||
import { logger } from '@server/helpers/logger.js'
|
||||
import { generateRandomString } from '@server/helpers/utils.js'
|
||||
import { PLUGIN_EXTERNAL_AUTH_TOKEN_LIFETIME } from '@server/initializers/constants.js'
|
||||
import { PluginManager } from '@server/lib/plugins/plugin-manager.js'
|
||||
import { OAuthTokenModel } from '@server/models/oauth/oauth-token.js'
|
||||
import { MUser } from '@server/types/models/index.js'
|
||||
import {
|
||||
RegisterServerAuthenticatedResult,
|
||||
RegisterServerAuthPassOptions,
|
||||
RegisterServerExternalAuthenticatedResult
|
||||
} from '@server/types/plugins/register-server-auth.model.js'
|
||||
import { UserAdminFlag, UserRole } from '@peertube/peertube-models'
|
||||
import { BypassLogin } from './oauth-model.js'
|
||||
|
||||
export type ExternalUser =
|
||||
Pick<MUser, 'username' | 'email' | 'role' | 'adminFlags' | 'videoQuotaDaily' | 'videoQuota'> &
|
||||
{ displayName: string }
|
||||
|
||||
// Token is the key, expiration date is the value
|
||||
const authBypassTokens = new Map<string, {
|
||||
expires: Date
|
||||
user: ExternalUser
|
||||
userUpdater: RegisterServerAuthenticatedResult['userUpdater']
|
||||
authName: string
|
||||
npmName: string
|
||||
}>()
|
||||
|
||||
async function onExternalUserAuthenticated (options: {
|
||||
npmName: string
|
||||
authName: string
|
||||
authResult: RegisterServerExternalAuthenticatedResult
|
||||
}) {
|
||||
const { npmName, authName, authResult } = options
|
||||
|
||||
if (!authResult.req || !authResult.res) {
|
||||
logger.error('Cannot authenticate external user for auth %s of plugin %s: no req or res are provided.', authName, npmName)
|
||||
return
|
||||
}
|
||||
|
||||
const { res } = authResult
|
||||
|
||||
if (!isAuthResultValid(npmName, authName, authResult)) {
|
||||
res.redirect('/login?externalAuthError=true')
|
||||
return
|
||||
}
|
||||
|
||||
logger.info('Generating auth bypass token for %s in auth %s of plugin %s.', authResult.username, authName, npmName)
|
||||
|
||||
const bypassToken = await generateRandomString(32)
|
||||
|
||||
const expires = new Date()
|
||||
expires.setTime(expires.getTime() + PLUGIN_EXTERNAL_AUTH_TOKEN_LIFETIME)
|
||||
|
||||
const user = buildUserResult(authResult)
|
||||
authBypassTokens.set(bypassToken, {
|
||||
expires,
|
||||
user,
|
||||
npmName,
|
||||
authName,
|
||||
userUpdater: authResult.userUpdater
|
||||
})
|
||||
|
||||
// Cleanup expired tokens
|
||||
const now = new Date()
|
||||
for (const [ key, value ] of authBypassTokens) {
|
||||
if (value.expires.getTime() < now.getTime()) {
|
||||
authBypassTokens.delete(key)
|
||||
}
|
||||
}
|
||||
|
||||
res.redirect(`/login?externalAuthToken=${bypassToken}&username=${user.username}`)
|
||||
}
|
||||
|
||||
async function getAuthNameFromRefreshGrant (refreshToken?: string) {
|
||||
if (!refreshToken) return undefined
|
||||
|
||||
const tokenModel = await OAuthTokenModel.loadByRefreshToken(refreshToken)
|
||||
|
||||
return tokenModel?.authName
|
||||
}
|
||||
|
||||
async function getBypassFromPasswordGrant (username: string, password: string): Promise<BypassLogin> {
|
||||
const plugins = PluginManager.Instance.getIdAndPassAuths()
|
||||
const pluginAuths: { npmName?: string, registerAuthOptions: RegisterServerAuthPassOptions }[] = []
|
||||
|
||||
for (const plugin of plugins) {
|
||||
const auths = plugin.idAndPassAuths
|
||||
|
||||
for (const auth of auths) {
|
||||
pluginAuths.push({
|
||||
npmName: plugin.npmName,
|
||||
registerAuthOptions: auth
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pluginAuths.sort((a, b) => {
|
||||
const aWeight = a.registerAuthOptions.getWeight()
|
||||
const bWeight = b.registerAuthOptions.getWeight()
|
||||
|
||||
// DESC weight order
|
||||
if (aWeight === bWeight) return 0
|
||||
if (aWeight < bWeight) return 1
|
||||
return -1
|
||||
})
|
||||
|
||||
const loginOptions = {
|
||||
id: username,
|
||||
password
|
||||
}
|
||||
|
||||
for (const pluginAuth of pluginAuths) {
|
||||
const authOptions = pluginAuth.registerAuthOptions
|
||||
const authName = authOptions.authName
|
||||
const npmName = pluginAuth.npmName
|
||||
|
||||
logger.debug(
|
||||
'Using auth method %s of plugin %s to login %s with weight %d.',
|
||||
authName, npmName, loginOptions.id, authOptions.getWeight()
|
||||
)
|
||||
|
||||
try {
|
||||
const loginResult = await authOptions.login(loginOptions)
|
||||
|
||||
if (!loginResult) continue
|
||||
if (!isAuthResultValid(pluginAuth.npmName, authOptions.authName, loginResult)) continue
|
||||
|
||||
logger.info(
|
||||
'Login success with auth method %s of plugin %s for %s.',
|
||||
authName, npmName, loginOptions.id
|
||||
)
|
||||
|
||||
return {
|
||||
bypass: true,
|
||||
pluginName: pluginAuth.npmName,
|
||||
authName: authOptions.authName,
|
||||
user: buildUserResult(loginResult),
|
||||
userUpdater: loginResult.userUpdater
|
||||
}
|
||||
} catch (err) {
|
||||
logger.error('Error in auth method %s of plugin %s', authOptions.authName, pluginAuth.npmName, { err })
|
||||
}
|
||||
}
|
||||
|
||||
return undefined
|
||||
}
|
||||
|
||||
function getBypassFromExternalAuth (username: string, externalAuthToken: string): BypassLogin {
|
||||
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()) {
|
||||
throw new Error('Cannot authenticate user with an expired external auth token')
|
||||
}
|
||||
|
||||
if (user.username !== username) {
|
||||
throw new Error(`Cannot authenticate user ${user.username} with invalid username ${username}`)
|
||||
}
|
||||
|
||||
logger.info(
|
||||
'Auth success with external auth method %s of plugin %s for %s.',
|
||||
authName, npmName, user.email
|
||||
)
|
||||
|
||||
return {
|
||||
bypass: true,
|
||||
pluginName: npmName,
|
||||
authName,
|
||||
userUpdater: obj.userUpdater,
|
||||
user
|
||||
}
|
||||
}
|
||||
|
||||
function isAuthResultValid (npmName: string, authName: string, result: RegisterServerAuthenticatedResult) {
|
||||
const returnError = (field: string) => {
|
||||
logger.error('Auth method %s of plugin %s did not provide a valid %s.', authName, npmName, field, { [field]: result[field] })
|
||||
return false
|
||||
}
|
||||
|
||||
if (!isUserUsernameValid(result.username)) return returnError('username')
|
||||
if (!result.email) return returnError('email')
|
||||
|
||||
// Following fields are optional
|
||||
if (result.role && !isUserRoleValid(result.role)) return returnError('role')
|
||||
if (result.displayName && !isUserDisplayNameValid(result.displayName)) return returnError('displayName')
|
||||
if (result.adminFlags && !isUserAdminFlagsValid(result.adminFlags)) return returnError('adminFlags')
|
||||
if (result.videoQuota && !isUserVideoQuotaValid(result.videoQuota + '')) return returnError('videoQuota')
|
||||
if (result.videoQuotaDaily && !isUserVideoQuotaDailyValid(result.videoQuotaDaily + '')) return returnError('videoQuotaDaily')
|
||||
|
||||
if (result.userUpdater && typeof result.userUpdater !== 'function') {
|
||||
logger.error('Auth method %s of plugin %s did not provide a valid user updater function.', authName, npmName)
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
function buildUserResult (pluginResult: RegisterServerAuthenticatedResult) {
|
||||
return {
|
||||
username: pluginResult.username,
|
||||
email: pluginResult.email,
|
||||
role: pluginResult.role ?? UserRole.USER,
|
||||
displayName: pluginResult.displayName || pluginResult.username,
|
||||
|
||||
adminFlags: pluginResult.adminFlags ?? UserAdminFlag.NONE,
|
||||
|
||||
videoQuota: pluginResult.videoQuota,
|
||||
videoQuotaDaily: pluginResult.videoQuotaDaily
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export {
|
||||
onExternalUserAuthenticated,
|
||||
getBypassFromExternalAuth,
|
||||
getAuthNameFromRefreshGrant,
|
||||
getBypassFromPasswordGrant
|
||||
}
|
294
server/core/lib/auth/oauth-model.ts
Normal file
294
server/core/lib/auth/oauth-model.ts
Normal file
|
@ -0,0 +1,294 @@
|
|||
import express from 'express'
|
||||
import { AccessDeniedError } from '@node-oauth/oauth2-server'
|
||||
import { PluginManager } from '@server/lib/plugins/plugin-manager.js'
|
||||
import { AccountModel } from '@server/models/account/account.js'
|
||||
import { AuthenticatedResultUpdaterFieldName, RegisterServerAuthenticatedResult } from '@server/types/index.js'
|
||||
import { MOAuthClient } from '@server/types/models/index.js'
|
||||
import { MOAuthTokenUser } from '@server/types/models/oauth/oauth-token.js'
|
||||
import { MUser, MUserDefault } from '@server/types/models/user/user.js'
|
||||
import { pick } from '@peertube/peertube-core-utils'
|
||||
import { AttributesOnly } from '@peertube/peertube-typescript-utils'
|
||||
import { logger } from '../../helpers/logger.js'
|
||||
import { CONFIG } from '../../initializers/config.js'
|
||||
import { OAuthClientModel } from '../../models/oauth/oauth-client.js'
|
||||
import { OAuthTokenModel } from '../../models/oauth/oauth-token.js'
|
||||
import { UserModel } from '../../models/user/user.js'
|
||||
import { findAvailableLocalActorName } from '../local-actor.js'
|
||||
import { buildUser, createUserAccountAndChannelAndPlaylist } from '../user.js'
|
||||
import { ExternalUser } from './external-auth.js'
|
||||
import { TokensCache } from './tokens-cache.js'
|
||||
|
||||
type TokenInfo = {
|
||||
accessToken: string
|
||||
refreshToken: string
|
||||
accessTokenExpiresAt: Date
|
||||
refreshTokenExpiresAt: Date
|
||||
}
|
||||
|
||||
export type BypassLogin = {
|
||||
bypass: boolean
|
||||
pluginName: string
|
||||
authName?: string
|
||||
user: ExternalUser
|
||||
userUpdater: RegisterServerAuthenticatedResult['userUpdater']
|
||||
}
|
||||
|
||||
async function getAccessToken (bearerToken: string) {
|
||||
logger.debug('Getting access token.')
|
||||
|
||||
if (!bearerToken) return undefined
|
||||
|
||||
let tokenModel: MOAuthTokenUser
|
||||
|
||||
if (TokensCache.Instance.hasToken(bearerToken)) {
|
||||
tokenModel = TokensCache.Instance.getByToken(bearerToken)
|
||||
} else {
|
||||
tokenModel = await OAuthTokenModel.getByTokenAndPopulateUser(bearerToken)
|
||||
|
||||
if (tokenModel) TokensCache.Instance.setToken(tokenModel)
|
||||
}
|
||||
|
||||
if (!tokenModel) return undefined
|
||||
|
||||
if (tokenModel.User.pluginAuth) {
|
||||
const valid = await PluginManager.Instance.isTokenValid(tokenModel, 'access')
|
||||
|
||||
if (valid !== true) return undefined
|
||||
}
|
||||
|
||||
return tokenModel
|
||||
}
|
||||
|
||||
function getClient (clientId: string, clientSecret: string) {
|
||||
logger.debug('Getting Client (clientId: ' + clientId + ', clientSecret: ' + clientSecret + ').')
|
||||
|
||||
return OAuthClientModel.getByIdAndSecret(clientId, clientSecret)
|
||||
}
|
||||
|
||||
async function getRefreshToken (refreshToken: string) {
|
||||
logger.debug('Getting RefreshToken (refreshToken: ' + refreshToken + ').')
|
||||
|
||||
const tokenInfo = await OAuthTokenModel.getByRefreshTokenAndPopulateClient(refreshToken)
|
||||
if (!tokenInfo) return undefined
|
||||
|
||||
const tokenModel = tokenInfo.token
|
||||
|
||||
if (tokenModel.User.pluginAuth) {
|
||||
const valid = await PluginManager.Instance.isTokenValid(tokenModel, 'refresh')
|
||||
|
||||
if (valid !== true) return undefined
|
||||
}
|
||||
|
||||
return tokenInfo
|
||||
}
|
||||
|
||||
async function getUser (usernameOrEmail?: string, password?: string, bypassLogin?: BypassLogin) {
|
||||
// Special treatment coming from a plugin
|
||||
if (bypassLogin && bypassLogin.bypass === true) {
|
||||
logger.info('Bypassing oauth login by plugin %s.', bypassLogin.pluginName)
|
||||
|
||||
let user = await UserModel.loadByEmail(bypassLogin.user.email)
|
||||
|
||||
if (!user) user = await createUserFromExternal(bypassLogin.pluginName, bypassLogin.user)
|
||||
else user = await updateUserFromExternal(user, bypassLogin.user, bypassLogin.userUpdater)
|
||||
|
||||
// Cannot create a user
|
||||
if (!user) throw new AccessDeniedError('Cannot create such user: an actor with that name already exists.')
|
||||
|
||||
// If the user does not belongs to a plugin, it was created before its installation
|
||||
// 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 !== bypassLogin.pluginName) {
|
||||
logger.info(
|
||||
'Cannot bypass oauth login by plugin %s because %s has another plugin auth method (%s).',
|
||||
bypassLogin.pluginName, bypassLogin.user.email, user.pluginAuth
|
||||
)
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
checkUserValidityOrThrow(user)
|
||||
|
||||
return user
|
||||
}
|
||||
}
|
||||
|
||||
logger.debug('Getting User (username/email: ' + usernameOrEmail + ', password: ******).')
|
||||
|
||||
const user = await UserModel.loadByUsernameOrEmail(usernameOrEmail)
|
||||
|
||||
// If we don't find the user, or if the user belongs to a plugin
|
||||
if (!user || user.pluginAuth !== null || !password) return null
|
||||
|
||||
const passwordMatch = await user.isPasswordMatch(password)
|
||||
if (passwordMatch !== true) return null
|
||||
|
||||
checkUserValidityOrThrow(user)
|
||||
|
||||
if (CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION && user.emailVerified === false) {
|
||||
throw new AccessDeniedError('User email is not verified.')
|
||||
}
|
||||
|
||||
return user
|
||||
}
|
||||
|
||||
async function revokeToken (
|
||||
tokenInfo: { refreshToken: string },
|
||||
options: {
|
||||
req?: express.Request
|
||||
explicitLogout?: boolean
|
||||
} = {}
|
||||
): Promise<{ success: boolean, redirectUrl?: string }> {
|
||||
const { req, explicitLogout } = options
|
||||
|
||||
const token = await OAuthTokenModel.getByRefreshTokenAndPopulateUser(tokenInfo.refreshToken)
|
||||
|
||||
if (token) {
|
||||
let redirectUrl: string
|
||||
|
||||
if (explicitLogout === true && token.User.pluginAuth && token.authName) {
|
||||
redirectUrl = await PluginManager.Instance.onLogout(token.User.pluginAuth, token.authName, token.User, req)
|
||||
}
|
||||
|
||||
TokensCache.Instance.clearCacheByToken(token.accessToken)
|
||||
|
||||
token.destroy()
|
||||
.catch(err => logger.error('Cannot destroy token when revoking token.', { err }))
|
||||
|
||||
return { success: true, redirectUrl }
|
||||
}
|
||||
|
||||
return { success: false }
|
||||
}
|
||||
|
||||
async function saveToken (
|
||||
token: TokenInfo,
|
||||
client: MOAuthClient,
|
||||
user: MUser,
|
||||
options: {
|
||||
refreshTokenAuthName?: string
|
||||
bypassLogin?: BypassLogin
|
||||
} = {}
|
||||
) {
|
||||
const { refreshTokenAuthName, bypassLogin } = options
|
||||
let authName: string = null
|
||||
|
||||
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 + '.')
|
||||
|
||||
const tokenToCreate = {
|
||||
accessToken: token.accessToken,
|
||||
accessTokenExpiresAt: token.accessTokenExpiresAt,
|
||||
refreshToken: token.refreshToken,
|
||||
refreshTokenExpiresAt: token.refreshTokenExpiresAt,
|
||||
authName,
|
||||
oAuthClientId: client.id,
|
||||
userId: user.id
|
||||
}
|
||||
|
||||
const tokenCreated = await OAuthTokenModel.create(tokenToCreate)
|
||||
|
||||
user.lastLoginDate = new Date()
|
||||
await user.save()
|
||||
|
||||
return {
|
||||
accessToken: tokenCreated.accessToken,
|
||||
accessTokenExpiresAt: tokenCreated.accessTokenExpiresAt,
|
||||
refreshToken: tokenCreated.refreshToken,
|
||||
refreshTokenExpiresAt: tokenCreated.refreshTokenExpiresAt,
|
||||
client,
|
||||
user,
|
||||
accessTokenExpiresIn: buildExpiresIn(tokenCreated.accessTokenExpiresAt),
|
||||
refreshTokenExpiresIn: buildExpiresIn(tokenCreated.refreshTokenExpiresAt)
|
||||
}
|
||||
}
|
||||
|
||||
export {
|
||||
getAccessToken,
|
||||
getClient,
|
||||
getRefreshToken,
|
||||
getUser,
|
||||
revokeToken,
|
||||
saveToken
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async function createUserFromExternal (pluginAuth: string, userOptions: ExternalUser) {
|
||||
const username = await findAvailableLocalActorName(userOptions.username)
|
||||
|
||||
const userToCreate = buildUser({
|
||||
...pick(userOptions, [ 'email', 'role', 'adminFlags', 'videoQuota', 'videoQuotaDaily' ]),
|
||||
|
||||
username,
|
||||
emailVerified: null,
|
||||
password: null,
|
||||
pluginAuth
|
||||
})
|
||||
|
||||
const { user } = await createUserAccountAndChannelAndPlaylist({
|
||||
userToCreate,
|
||||
userDisplayName: userOptions.displayName
|
||||
})
|
||||
|
||||
return user
|
||||
}
|
||||
|
||||
async function updateUserFromExternal (
|
||||
user: MUserDefault,
|
||||
userOptions: ExternalUser,
|
||||
userUpdater: RegisterServerAuthenticatedResult['userUpdater']
|
||||
) {
|
||||
if (!userUpdater) return user
|
||||
|
||||
{
|
||||
type UserAttributeKeys = keyof AttributesOnly<UserModel>
|
||||
const mappingKeys: { [ id in UserAttributeKeys ]?: AuthenticatedResultUpdaterFieldName } = {
|
||||
role: 'role',
|
||||
adminFlags: 'adminFlags',
|
||||
videoQuota: 'videoQuota',
|
||||
videoQuotaDaily: 'videoQuotaDaily'
|
||||
}
|
||||
|
||||
for (const modelKey of Object.keys(mappingKeys)) {
|
||||
const pluginOptionKey = mappingKeys[modelKey]
|
||||
|
||||
const newValue = userUpdater({ fieldName: pluginOptionKey, currentValue: user[modelKey], newValue: userOptions[pluginOptionKey] })
|
||||
user.set(modelKey, newValue)
|
||||
}
|
||||
}
|
||||
|
||||
{
|
||||
type AccountAttributeKeys = keyof Partial<AttributesOnly<AccountModel>>
|
||||
const mappingKeys: { [ id in AccountAttributeKeys ]?: AuthenticatedResultUpdaterFieldName } = {
|
||||
name: 'displayName'
|
||||
}
|
||||
|
||||
for (const modelKey of Object.keys(mappingKeys)) {
|
||||
const optionKey = mappingKeys[modelKey]
|
||||
|
||||
const newValue = userUpdater({ fieldName: optionKey, currentValue: user.Account[modelKey], newValue: userOptions[optionKey] })
|
||||
user.Account.set(modelKey, newValue)
|
||||
}
|
||||
}
|
||||
|
||||
logger.debug('Updated user %s with plugin userUpdated function.', user.email, { user, userOptions })
|
||||
|
||||
user.Account = await user.Account.save()
|
||||
|
||||
return user.save()
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
230
server/core/lib/auth/oauth.ts
Normal file
230
server/core/lib/auth/oauth.ts
Normal file
|
@ -0,0 +1,230 @@
|
|||
import express from 'express'
|
||||
import OAuth2Server, {
|
||||
InvalidClientError,
|
||||
InvalidGrantError,
|
||||
InvalidRequestError,
|
||||
Request,
|
||||
Response,
|
||||
UnauthorizedClientError,
|
||||
UnsupportedGrantTypeError
|
||||
} from '@node-oauth/oauth2-server'
|
||||
import { randomBytesPromise } from '@server/helpers/core-utils.js'
|
||||
import { isOTPValid } from '@server/helpers/otp.js'
|
||||
import { CONFIG } from '@server/initializers/config.js'
|
||||
import { UserRegistrationModel } from '@server/models/user/user-registration.js'
|
||||
import { MOAuthClient } from '@server/types/models/index.js'
|
||||
import { sha1 } from '@peertube/peertube-node-utils'
|
||||
import { HttpStatusCode, ServerErrorCode, UserRegistrationState } from '@peertube/peertube-models'
|
||||
import { OTP } from '../../initializers/constants.js'
|
||||
import { BypassLogin, getAccessToken, getClient, getRefreshToken, getUser, revokeToken, saveToken } from './oauth-model.js'
|
||||
|
||||
class MissingTwoFactorError extends Error {
|
||||
code = HttpStatusCode.UNAUTHORIZED_401
|
||||
name = ServerErrorCode.MISSING_TWO_FACTOR
|
||||
}
|
||||
|
||||
class InvalidTwoFactorError extends Error {
|
||||
code = HttpStatusCode.BAD_REQUEST_400
|
||||
name = ServerErrorCode.INVALID_TWO_FACTOR
|
||||
}
|
||||
|
||||
class RegistrationWaitingForApproval extends Error {
|
||||
code = HttpStatusCode.BAD_REQUEST_400
|
||||
name = ServerErrorCode.ACCOUNT_WAITING_FOR_APPROVAL
|
||||
}
|
||||
|
||||
class RegistrationApprovalRejected extends Error {
|
||||
code = HttpStatusCode.BAD_REQUEST_400
|
||||
name = ServerErrorCode.ACCOUNT_APPROVAL_REJECTED
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* Reimplement some functions of OAuth2Server to inject external auth methods
|
||||
*
|
||||
*/
|
||||
const oAuthServer = new OAuth2Server({
|
||||
// Wants seconds
|
||||
accessTokenLifetime: CONFIG.OAUTH2.TOKEN_LIFETIME.ACCESS_TOKEN / 1000,
|
||||
refreshTokenLifetime: CONFIG.OAUTH2.TOKEN_LIFETIME.REFRESH_TOKEN / 1000,
|
||||
|
||||
// See https://github.com/oauthjs/node-oauth2-server/wiki/Model-specification for the model specifications
|
||||
model: {
|
||||
getAccessToken,
|
||||
getClient,
|
||||
getRefreshToken,
|
||||
getUser,
|
||||
revokeToken,
|
||||
saveToken
|
||||
} as any // FIXME: typings
|
||||
})
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
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
|
||||
})
|
||||
}
|
||||
|
||||
function handleOAuthAuthenticate (
|
||||
req: express.Request,
|
||||
res: express.Response
|
||||
) {
|
||||
return oAuthServer.authenticate(new Request(req), new Response(res))
|
||||
}
|
||||
|
||||
export {
|
||||
MissingTwoFactorError,
|
||||
InvalidTwoFactorError,
|
||||
|
||||
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) {
|
||||
const registration = await UserRegistrationModel.loadByEmailOrUsername(request.body.username)
|
||||
|
||||
if (registration?.state === UserRegistrationState.REJECTED) {
|
||||
throw new RegistrationApprovalRejected('Registration approval for this account has been rejected')
|
||||
} else if (registration?.state === UserRegistrationState.PENDING) {
|
||||
throw new RegistrationWaitingForApproval('Registration for this account is awaiting approval')
|
||||
}
|
||||
|
||||
throw new InvalidGrantError('Invalid grant: user credentials are invalid')
|
||||
}
|
||||
|
||||
if (user.otpSecret) {
|
||||
if (!request.headers[OTP.HEADER_NAME]) {
|
||||
throw new MissingTwoFactorError('Missing two factor header')
|
||||
}
|
||||
|
||||
if (await isOTPValid({ encryptedSecret: user.otpSecret, token: request.headers[OTP.HEADER_NAME] }) !== true) {
|
||||
throw new InvalidTwoFactorError('Invalid two factor header')
|
||||
}
|
||||
}
|
||||
|
||||
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'
|
||||
? CONFIG.OAUTH2.TOKEN_LIFETIME.ACCESS_TOKEN
|
||||
: CONFIG.OAUTH2.TOKEN_LIFETIME.REFRESH_TOKEN
|
||||
|
||||
return new Date(Date.now() + lifetime)
|
||||
}
|
||||
|
||||
async function buildToken () {
|
||||
const [ accessToken, refreshToken ] = await Promise.all([ generateRandomToken(), generateRandomToken() ])
|
||||
|
||||
return {
|
||||
accessToken,
|
||||
refreshToken,
|
||||
accessTokenExpiresAt: getTokenExpiresAt('access'),
|
||||
refreshTokenExpiresAt: getTokenExpiresAt('refresh')
|
||||
}
|
||||
}
|
52
server/core/lib/auth/tokens-cache.ts
Normal file
52
server/core/lib/auth/tokens-cache.ts
Normal file
|
@ -0,0 +1,52 @@
|
|||
import { LRUCache } from 'lru-cache'
|
||||
import { MOAuthTokenUser } from '@server/types/models/index.js'
|
||||
import { LRU_CACHE } from '../../initializers/constants.js'
|
||||
|
||||
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.delete(token)
|
||||
this.userHavingToken.delete(userId)
|
||||
}
|
||||
}
|
||||
|
||||
clearCacheByToken (token: string) {
|
||||
const tokenModel = this.accessTokenCache.get(token)
|
||||
|
||||
if (tokenModel !== undefined) {
|
||||
this.userHavingToken.delete(tokenModel.userId)
|
||||
this.accessTokenCache.delete(token)
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue