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'
23 export type ExternalUser =
24 Pick<MUser, 'username' | 'email' | 'role' | 'adminFlags' | 'videoQuotaDaily' | 'videoQuota'> &
25 { displayName: string }
27 // Token is the key, expiration date is the value
28 const authBypassTokens = new Map<string, {
35 async function onExternalUserAuthenticated (options: {
38 authResult: RegisterServerExternalAuthenticatedResult
40 const { npmName, authName, authResult } = options
42 if (!authResult.req || !authResult.res) {
43 logger.error('Cannot authenticate external user for auth %s of plugin %s: no req or res are provided.', authName, npmName)
47 const { res } = authResult
49 if (!isAuthResultValid(npmName, authName, authResult)) {
50 res.redirect('/login?externalAuthError=true')
54 logger.info('Generating auth bypass token for %s in auth %s of plugin %s.', authResult.username, authName, npmName)
56 const bypassToken = await generateRandomString(32)
58 const expires = new Date()
59 expires.setTime(expires.getTime() + PLUGIN_EXTERNAL_AUTH_TOKEN_LIFETIME)
61 const user = buildUserResult(authResult)
62 authBypassTokens.set(bypassToken, {
69 // Cleanup expired tokens
70 const now = new Date()
71 for (const [ key, value ] of authBypassTokens) {
72 if (value.expires.getTime() < now.getTime()) {
73 authBypassTokens.delete(key)
77 res.redirect(`/login?externalAuthToken=${bypassToken}&username=${user.username}`)
80 async function getAuthNameFromRefreshGrant (refreshToken?: string) {
81 if (!refreshToken) return undefined
83 const tokenModel = await OAuthTokenModel.loadByRefreshToken(refreshToken)
85 return tokenModel?.authName
88 async function getBypassFromPasswordGrant (username: string, password: string) {
89 const plugins = PluginManager.Instance.getIdAndPassAuths()
90 const pluginAuths: { npmName?: string, registerAuthOptions: RegisterServerAuthPassOptions }[] = []
92 for (const plugin of plugins) {
93 const auths = plugin.idAndPassAuths
95 for (const auth of auths) {
97 npmName: plugin.npmName,
98 registerAuthOptions: auth
103 pluginAuths.sort((a, b) => {
104 const aWeight = a.registerAuthOptions.getWeight()
105 const bWeight = b.registerAuthOptions.getWeight()
108 if (aWeight === bWeight) return 0
109 if (aWeight < bWeight) return 1
113 const loginOptions = {
118 for (const pluginAuth of pluginAuths) {
119 const authOptions = pluginAuth.registerAuthOptions
120 const authName = authOptions.authName
121 const npmName = pluginAuth.npmName
124 'Using auth method %s of plugin %s to login %s with weight %d.',
125 authName, npmName, loginOptions.id, authOptions.getWeight()
129 const loginResult = await authOptions.login(loginOptions)
131 if (!loginResult) continue
132 if (!isAuthResultValid(pluginAuth.npmName, authOptions.authName, loginResult)) continue
135 'Login success with auth method %s of plugin %s for %s.',
136 authName, npmName, loginOptions.id
141 pluginName: pluginAuth.npmName,
142 authName: authOptions.authName,
143 user: buildUserResult(loginResult)
146 logger.error('Error in auth method %s of plugin %s', authOptions.authName, pluginAuth.npmName, { err })
153 function getBypassFromExternalAuth (username: string, externalAuthToken: string) {
154 const obj = authBypassTokens.get(externalAuthToken)
155 if (!obj) throw new Error('Cannot authenticate user with unknown bypass token')
157 const { expires, user, authName, npmName } = obj
159 const now = new Date()
160 if (now.getTime() > expires.getTime()) {
161 throw new Error('Cannot authenticate user with an expired external auth token')
164 if (user.username !== username) {
165 throw new Error(`Cannot authenticate user ${user.username} with invalid username ${username}`)
169 'Auth success with external auth method %s of plugin %s for %s.',
170 authName, npmName, user.email
181 function isAuthResultValid (npmName: string, authName: string, result: RegisterServerAuthenticatedResult) {
182 const returnError = (field: string) => {
183 logger.error('Auth method %s of plugin %s did not provide a valid %s.', authName, npmName, field, { [field]: result[field] })
187 if (!isUserUsernameValid(result.username)) return returnError('username')
188 if (!result.email) return returnError('email')
190 // Following fields are optional
191 if (result.role && !isUserRoleValid(result.role)) return returnError('role')
192 if (result.displayName && !isUserDisplayNameValid(result.displayName)) return returnError('displayName')
193 if (result.adminFlags && !isUserAdminFlagsValid(result.adminFlags)) return returnError('adminFlags')
194 if (result.videoQuota && !isUserVideoQuotaValid(result.videoQuota + '')) return returnError('videoQuota')
195 if (result.videoQuotaDaily && !isUserVideoQuotaDailyValid(result.videoQuotaDaily + '')) return returnError('videoQuotaDaily')
200 function buildUserResult (pluginResult: RegisterServerAuthenticatedResult) {
202 username: pluginResult.username,
203 email: pluginResult.email,
204 role: pluginResult.role ?? UserRole.USER,
205 displayName: pluginResult.displayName || pluginResult.username,
207 adminFlags: pluginResult.adminFlags ?? UserAdminFlag.NONE,
209 videoQuota: pluginResult.videoQuota,
210 videoQuotaDaily: pluginResult.videoQuotaDaily
214 // ---------------------------------------------------------------------------
217 onExternalUserAuthenticated,
218 getBypassFromExternalAuth,
219 getAuthNameFromRefreshGrant,
220 getBypassFromPasswordGrant