1 import { isUserDisplayNameValid, isUserRoleValid, isUserUsernameValid } from '@server/helpers/custom-validators/users'
2 import { logger } from '@server/helpers/logger'
3 import { generateRandomString } from '@server/helpers/utils'
4 import { OAUTH_LIFETIME, PLUGIN_EXTERNAL_AUTH_TOKEN_LIFETIME } from '@server/initializers/constants'
5 import { revokeToken } from '@server/lib/oauth-model'
6 import { PluginManager } from '@server/lib/plugins/plugin-manager'
7 import { OAuthTokenModel } from '@server/models/oauth/oauth-token'
8 import { UserRole } from '@shared/models'
10 RegisterServerAuthenticatedResult,
11 RegisterServerAuthPassOptions,
12 RegisterServerExternalAuthenticatedResult
13 } from '@shared/models/plugins/register-server-auth.model'
14 import * as express from 'express'
15 import * as OAuthServer from 'express-oauth-server'
17 const oAuthServer = new OAuthServer({
18 useErrorHandler: true,
19 accessTokenLifetime: OAUTH_LIFETIME.ACCESS_TOKEN,
20 refreshTokenLifetime: OAUTH_LIFETIME.REFRESH_TOKEN,
21 continueMiddleware: true,
22 model: require('./oauth-model')
25 // Token is the key, expiration date is the value
26 const authBypassTokens = new Map<string, {
38 async function handleLogin (req: express.Request, res: express.Response, next: express.NextFunction) {
39 const grantType = req.body.grant_type
41 if (grantType === 'password') {
42 if (req.body.externalAuthToken) proxifyExternalAuthBypass(req, res)
43 else await proxifyPasswordGrant(req, res)
44 } else if (grantType === 'refresh_token') {
45 await proxifyRefreshGrant(req, res)
48 return forwardTokenReq(req, res, next)
51 async function handleTokenRevocation (req: express.Request, res: express.Response) {
52 const token = res.locals.oauth.token
54 res.locals.explicitLogout = true
55 await revokeToken(token)
57 // FIXME: uncomment when https://github.com/oauthjs/node-oauth2-server/pull/289 is released
58 // oAuthServer.revoke(req, res, err => {
60 // logger.warn('Error in revoke token handler.', { err })
62 // return res.status(err.status)
64 // error: err.message,
74 async function onExternalUserAuthenticated (options: {
77 authResult: RegisterServerExternalAuthenticatedResult
79 const { npmName, authName, authResult } = options
81 if (!authResult.req || !authResult.res) {
82 logger.error('Cannot authenticate external user for auth %s of plugin %s: no req or res are provided.', authName, npmName)
86 if (!isAuthResultValid(npmName, authName, authResult)) return
88 const { res } = authResult
90 logger.info('Generating auth bypass token for %s in auth %s of plugin %s.', authResult.username, authName, npmName)
92 const bypassToken = await generateRandomString(32)
94 const expires = new Date()
95 expires.setTime(expires.getTime() + PLUGIN_EXTERNAL_AUTH_TOKEN_LIFETIME)
97 const user = buildUserResult(authResult)
98 authBypassTokens.set(bypassToken, {
105 res.redirect(`/login?externalAuthToken=${bypassToken}&username=${user.username}`)
108 // ---------------------------------------------------------------------------
110 export { oAuthServer, handleLogin, onExternalUserAuthenticated, handleTokenRevocation }
112 // ---------------------------------------------------------------------------
114 function forwardTokenReq (req: express.Request, res: express.Response, next?: express.NextFunction) {
115 return oAuthServer.token()(req, res, err => {
117 logger.warn('Login error.', { err })
119 return res.status(err.status)
126 if (next) return next()
130 async function proxifyRefreshGrant (req: express.Request, res: express.Response) {
131 const refreshToken = req.body.refresh_token
132 if (!refreshToken) return
134 const tokenModel = await OAuthTokenModel.loadByRefreshToken(refreshToken)
135 if (tokenModel?.authName) res.locals.refreshTokenAuthName = tokenModel.authName
138 async function proxifyPasswordGrant (req: express.Request, res: express.Response) {
139 const plugins = PluginManager.Instance.getIdAndPassAuths()
140 const pluginAuths: { npmName?: string, registerAuthOptions: RegisterServerAuthPassOptions }[] = []
142 for (const plugin of plugins) {
143 const auths = plugin.idAndPassAuths
145 for (const auth of auths) {
147 npmName: plugin.npmName,
148 registerAuthOptions: auth
153 pluginAuths.sort((a, b) => {
154 const aWeight = a.registerAuthOptions.getWeight()
155 const bWeight = b.registerAuthOptions.getWeight()
158 if (aWeight === bWeight) return 0
159 if (aWeight < bWeight) return 1
163 const loginOptions = {
164 id: req.body.username,
165 password: req.body.password
168 for (const pluginAuth of pluginAuths) {
169 const authOptions = pluginAuth.registerAuthOptions
170 const authName = authOptions.authName
171 const npmName = pluginAuth.npmName
174 'Using auth method %s of plugin %s to login %s with weight %d.',
175 authName, npmName, loginOptions.id, authOptions.getWeight()
179 const loginResult = await authOptions.login(loginOptions)
181 if (!loginResult) continue
182 if (!isAuthResultValid(pluginAuth.npmName, authOptions.authName, loginResult)) continue
185 'Login success with auth method %s of plugin %s for %s.',
186 authName, npmName, loginOptions.id
189 res.locals.bypassLogin = {
191 pluginName: pluginAuth.npmName,
192 authName: authOptions.authName,
193 user: buildUserResult(loginResult)
198 logger.error('Error in auth method %s of plugin %s', authOptions.authName, pluginAuth.npmName, { err })
203 function proxifyExternalAuthBypass (req: express.Request, res: express.Response) {
204 const obj = authBypassTokens.get(req.body.externalAuthToken)
206 logger.error('Cannot authenticate user with unknown bypass token')
207 return res.sendStatus(400)
210 const { expires, user, authName, npmName } = obj
212 const now = new Date()
213 if (now.getTime() > expires.getTime()) {
214 logger.error('Cannot authenticate user with an expired external auth token')
215 return res.sendStatus(400)
218 if (user.username !== req.body.username) {
219 logger.error('Cannot authenticate user %s with invalid username %s.', req.body.username)
220 return res.sendStatus(400)
223 // Bypass oauth library validation
224 req.body.password = 'fake'
227 'Auth success with external auth method %s of plugin %s for %s.',
228 authName, npmName, user.email
231 res.locals.bypassLogin = {
239 function isAuthResultValid (npmName: string, authName: string, result: RegisterServerAuthenticatedResult) {
240 if (!isUserUsernameValid(result.username)) {
241 logger.error('Auth method %s of plugin %s did not provide a valid username.', authName, npmName, { result })
246 logger.error('Auth method %s of plugin %s did not provide a valid email.', authName, npmName, { result })
251 if (result.role && !isUserRoleValid(result.role)) {
252 logger.error('Auth method %s of plugin %s did not provide a valid role.', authName, npmName, { result })
256 // display name is optional
257 if (result.displayName && !isUserDisplayNameValid(result.displayName)) {
258 logger.error('Auth method %s of plugin %s did not provide a valid display name.', authName, npmName, { result })
265 function buildUserResult (pluginResult: RegisterServerAuthenticatedResult) {
267 username: pluginResult.username,
268 email: pluginResult.email,
269 role: pluginResult.role ?? UserRole.USER,
270 displayName: pluginResult.displayName || pluginResult.username