2 import { isUserDisplayNameValid, isUserRoleValid, isUserUsernameValid } from '@server/helpers/custom-validators/users'
3 import { logger } from '@server/helpers/logger'
4 import { generateRandomString } from '@server/helpers/utils'
5 import { PLUGIN_EXTERNAL_AUTH_TOKEN_LIFETIME } from '@server/initializers/constants'
6 import { PluginManager } from '@server/lib/plugins/plugin-manager'
7 import { OAuthTokenModel } from '@server/models/oauth/oauth-token'
9 RegisterServerAuthenticatedResult,
10 RegisterServerAuthPassOptions,
11 RegisterServerExternalAuthenticatedResult
12 } from '@server/types/plugins/register-server-auth.model'
13 import { UserRole } from '@shared/models'
15 // Token is the key, expiration date is the value
16 const authBypassTokens = new Map<string, {
28 async function onExternalUserAuthenticated (options: {
31 authResult: RegisterServerExternalAuthenticatedResult
33 const { npmName, authName, authResult } = options
35 if (!authResult.req || !authResult.res) {
36 logger.error('Cannot authenticate external user for auth %s of plugin %s: no req or res are provided.', authName, npmName)
40 const { res } = authResult
42 if (!isAuthResultValid(npmName, authName, authResult)) {
43 res.redirect('/login?externalAuthError=true')
47 logger.info('Generating auth bypass token for %s in auth %s of plugin %s.', authResult.username, authName, npmName)
49 const bypassToken = await generateRandomString(32)
51 const expires = new Date()
52 expires.setTime(expires.getTime() + PLUGIN_EXTERNAL_AUTH_TOKEN_LIFETIME)
54 const user = buildUserResult(authResult)
55 authBypassTokens.set(bypassToken, {
62 // Cleanup expired tokens
63 const now = new Date()
64 for (const [ key, value ] of authBypassTokens) {
65 if (value.expires.getTime() < now.getTime()) {
66 authBypassTokens.delete(key)
70 res.redirect(`/login?externalAuthToken=${bypassToken}&username=${user.username}`)
73 async function getAuthNameFromRefreshGrant (refreshToken?: string) {
74 if (!refreshToken) return undefined
76 const tokenModel = await OAuthTokenModel.loadByRefreshToken(refreshToken)
78 return tokenModel?.authName
81 async function getBypassFromPasswordGrant (username: string, password: string) {
82 const plugins = PluginManager.Instance.getIdAndPassAuths()
83 const pluginAuths: { npmName?: string, registerAuthOptions: RegisterServerAuthPassOptions }[] = []
85 for (const plugin of plugins) {
86 const auths = plugin.idAndPassAuths
88 for (const auth of auths) {
90 npmName: plugin.npmName,
91 registerAuthOptions: auth
96 pluginAuths.sort((a, b) => {
97 const aWeight = a.registerAuthOptions.getWeight()
98 const bWeight = b.registerAuthOptions.getWeight()
101 if (aWeight === bWeight) return 0
102 if (aWeight < bWeight) return 1
106 const loginOptions = {
111 for (const pluginAuth of pluginAuths) {
112 const authOptions = pluginAuth.registerAuthOptions
113 const authName = authOptions.authName
114 const npmName = pluginAuth.npmName
117 'Using auth method %s of plugin %s to login %s with weight %d.',
118 authName, npmName, loginOptions.id, authOptions.getWeight()
122 const loginResult = await authOptions.login(loginOptions)
124 if (!loginResult) continue
125 if (!isAuthResultValid(pluginAuth.npmName, authOptions.authName, loginResult)) continue
128 'Login success with auth method %s of plugin %s for %s.',
129 authName, npmName, loginOptions.id
134 pluginName: pluginAuth.npmName,
135 authName: authOptions.authName,
136 user: buildUserResult(loginResult)
139 logger.error('Error in auth method %s of plugin %s', authOptions.authName, pluginAuth.npmName, { err })
146 function getBypassFromExternalAuth (username: string, externalAuthToken: string) {
147 const obj = authBypassTokens.get(externalAuthToken)
148 if (!obj) throw new Error('Cannot authenticate user with unknown bypass token')
150 const { expires, user, authName, npmName } = obj
152 const now = new Date()
153 if (now.getTime() > expires.getTime()) {
154 throw new Error('Cannot authenticate user with an expired external auth token')
157 if (user.username !== username) {
158 throw new Error(`Cannot authenticate user ${user.username} with invalid username ${username}`)
162 'Auth success with external auth method %s of plugin %s for %s.',
163 authName, npmName, user.email
174 function isAuthResultValid (npmName: string, authName: string, result: RegisterServerAuthenticatedResult) {
175 if (!isUserUsernameValid(result.username)) {
176 logger.error('Auth method %s of plugin %s did not provide a valid username.', authName, npmName, { username: result.username })
181 logger.error('Auth method %s of plugin %s did not provide a valid email.', authName, npmName, { email: result.email })
186 if (result.role && !isUserRoleValid(result.role)) {
187 logger.error('Auth method %s of plugin %s did not provide a valid role.', authName, npmName, { role: result.role })
191 // display name is optional
192 if (result.displayName && !isUserDisplayNameValid(result.displayName)) {
194 'Auth method %s of plugin %s did not provide a valid display name.',
195 authName, npmName, { displayName: result.displayName }
203 function buildUserResult (pluginResult: RegisterServerAuthenticatedResult) {
205 username: pluginResult.username,
206 email: pluginResult.email,
207 role: pluginResult.role ?? UserRole.USER,
208 displayName: pluginResult.displayName || pluginResult.username
212 // ---------------------------------------------------------------------------
215 onExternalUserAuthenticated,
216 getBypassFromExternalAuth,
217 getAuthNameFromRefreshGrant,
218 getBypassFromPasswordGrant