4 isUserDisplayNameValid,
7 isUserVideoQuotaDailyValid,
9 } from '@server/helpers/custom-validators/users'
10 import { logger } from '@server/helpers/logger'
11 import { generateRandomString } from '@server/helpers/utils'
12 import { PLUGIN_EXTERNAL_AUTH_TOKEN_LIFETIME } from '@server/initializers/constants'
13 import { PluginManager } from '@server/lib/plugins/plugin-manager'
14 import { OAuthTokenModel } from '@server/models/oauth/oauth-token'
15 import { MUser } from '@server/types/models'
17 RegisterServerAuthenticatedResult,
18 RegisterServerAuthPassOptions,
19 RegisterServerExternalAuthenticatedResult
20 } from '@server/types/plugins/register-server-auth.model'
21 import { UserAdminFlag, UserRole } from '@shared/models'
22 import { BypassLogin } from './oauth-model'
24 export type ExternalUser =
25 Pick<MUser, 'username' | 'email' | 'role' | 'adminFlags' | 'videoQuotaDaily' | 'videoQuota'> &
26 { displayName: string }
28 // Token is the key, expiration date is the value
29 const authBypassTokens = new Map<string, {
32 userUpdater: RegisterServerAuthenticatedResult['userUpdater']
37 async function onExternalUserAuthenticated (options: {
40 authResult: RegisterServerExternalAuthenticatedResult
42 const { npmName, authName, authResult } = options
44 if (!authResult.req || !authResult.res) {
45 logger.error('Cannot authenticate external user for auth %s of plugin %s: no req or res are provided.', authName, npmName)
49 const { res } = authResult
51 if (!isAuthResultValid(npmName, authName, authResult)) {
52 res.redirect('/login?externalAuthError=true')
56 logger.info('Generating auth bypass token for %s in auth %s of plugin %s.', authResult.username, authName, npmName)
58 const bypassToken = await generateRandomString(32)
60 const expires = new Date()
61 expires.setTime(expires.getTime() + PLUGIN_EXTERNAL_AUTH_TOKEN_LIFETIME)
63 const user = buildUserResult(authResult)
64 authBypassTokens.set(bypassToken, {
69 userUpdater: authResult.userUpdater
72 // Cleanup expired tokens
73 const now = new Date()
74 for (const [ key, value ] of authBypassTokens) {
75 if (value.expires.getTime() < now.getTime()) {
76 authBypassTokens.delete(key)
80 res.redirect(`/login?externalAuthToken=${bypassToken}&username=${user.username}`)
83 async function getAuthNameFromRefreshGrant (refreshToken?: string) {
84 if (!refreshToken) return undefined
86 const tokenModel = await OAuthTokenModel.loadByRefreshToken(refreshToken)
88 return tokenModel?.authName
91 async function getBypassFromPasswordGrant (username: string, password: string): Promise<BypassLogin> {
92 const plugins = PluginManager.Instance.getIdAndPassAuths()
93 const pluginAuths: { npmName?: string, registerAuthOptions: RegisterServerAuthPassOptions }[] = []
95 for (const plugin of plugins) {
96 const auths = plugin.idAndPassAuths
98 for (const auth of auths) {
100 npmName: plugin.npmName,
101 registerAuthOptions: auth
106 pluginAuths.sort((a, b) => {
107 const aWeight = a.registerAuthOptions.getWeight()
108 const bWeight = b.registerAuthOptions.getWeight()
111 if (aWeight === bWeight) return 0
112 if (aWeight < bWeight) return 1
116 const loginOptions = {
121 for (const pluginAuth of pluginAuths) {
122 const authOptions = pluginAuth.registerAuthOptions
123 const authName = authOptions.authName
124 const npmName = pluginAuth.npmName
127 'Using auth method %s of plugin %s to login %s with weight %d.',
128 authName, npmName, loginOptions.id, authOptions.getWeight()
132 const loginResult = await authOptions.login(loginOptions)
134 if (!loginResult) continue
135 if (!isAuthResultValid(pluginAuth.npmName, authOptions.authName, loginResult)) continue
138 'Login success with auth method %s of plugin %s for %s.',
139 authName, npmName, loginOptions.id
144 pluginName: pluginAuth.npmName,
145 authName: authOptions.authName,
146 user: buildUserResult(loginResult),
147 userUpdater: loginResult.userUpdater
150 logger.error('Error in auth method %s of plugin %s', authOptions.authName, pluginAuth.npmName, { err })
157 function getBypassFromExternalAuth (username: string, externalAuthToken: string): BypassLogin {
158 const obj = authBypassTokens.get(externalAuthToken)
159 if (!obj) throw new Error('Cannot authenticate user with unknown bypass token')
161 const { expires, user, authName, npmName } = obj
163 const now = new Date()
164 if (now.getTime() > expires.getTime()) {
165 throw new Error('Cannot authenticate user with an expired external auth token')
168 if (user.username !== username) {
169 throw new Error(`Cannot authenticate user ${user.username} with invalid username ${username}`)
173 'Auth success with external auth method %s of plugin %s for %s.',
174 authName, npmName, user.email
181 userUpdater: obj.userUpdater,
186 function isAuthResultValid (npmName: string, authName: string, result: RegisterServerAuthenticatedResult) {
187 const returnError = (field: string) => {
188 logger.error('Auth method %s of plugin %s did not provide a valid %s.', authName, npmName, field, { [field]: result[field] })
192 if (!isUserUsernameValid(result.username)) return returnError('username')
193 if (!result.email) return returnError('email')
195 // Following fields are optional
196 if (result.role && !isUserRoleValid(result.role)) return returnError('role')
197 if (result.displayName && !isUserDisplayNameValid(result.displayName)) return returnError('displayName')
198 if (result.adminFlags && !isUserAdminFlagsValid(result.adminFlags)) return returnError('adminFlags')
199 if (result.videoQuota && !isUserVideoQuotaValid(result.videoQuota + '')) return returnError('videoQuota')
200 if (result.videoQuotaDaily && !isUserVideoQuotaDailyValid(result.videoQuotaDaily + '')) return returnError('videoQuotaDaily')
202 if (result.userUpdater && typeof result.userUpdater !== 'function') {
203 logger.error('Auth method %s of plugin %s did not provide a valid user updater function.', authName, npmName)
210 function buildUserResult (pluginResult: RegisterServerAuthenticatedResult) {
212 username: pluginResult.username,
213 email: pluginResult.email,
214 role: pluginResult.role ?? UserRole.USER,
215 displayName: pluginResult.displayName || pluginResult.username,
217 adminFlags: pluginResult.adminFlags ?? UserAdminFlag.NONE,
219 videoQuota: pluginResult.videoQuota,
220 videoQuotaDaily: pluginResult.videoQuotaDaily
224 // ---------------------------------------------------------------------------
227 onExternalUserAuthenticated,
228 getBypassFromExternalAuth,
229 getAuthNameFromRefreshGrant,
230 getBypassFromPasswordGrant