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 '@server/types/plugins/register-server-auth.model'
14 import * as express from 'express'
15 import * as OAuthServer from 'express-oauth-server'
16 import { HttpStatusCode } from '@shared/core-utils/miscs/http-error-codes'
18 const oAuthServer = new OAuthServer({
19 useErrorHandler: true,
20 accessTokenLifetime: OAUTH_LIFETIME.ACCESS_TOKEN,
21 refreshTokenLifetime: OAUTH_LIFETIME.REFRESH_TOKEN,
22 continueMiddleware: true,
23 model: require('./oauth-model')
26 // Token is the key, expiration date is the value
27 const authBypassTokens = new Map<string, {
39 async function handleLogin (req: express.Request, res: express.Response, next: express.NextFunction) {
40 const grantType = req.body.grant_type
42 if (grantType === 'password') {
43 if (req.body.externalAuthToken) proxifyExternalAuthBypass(req, res)
44 else await proxifyPasswordGrant(req, res)
45 } else if (grantType === 'refresh_token') {
46 await proxifyRefreshGrant(req, res)
49 return forwardTokenReq(req, res, next)
52 async function handleTokenRevocation (req: express.Request, res: express.Response) {
53 const token = res.locals.oauth.token
55 res.locals.explicitLogout = true
56 const result = await revokeToken(token)
58 // FIXME: uncomment when https://github.com/oauthjs/node-oauth2-server/pull/289 is released
59 // oAuthServer.revoke(req, res, err => {
61 // logger.warn('Error in revoke token handler.', { err })
63 // return res.status(err.status)
65 // error: err.message,
72 return res.json(result)
75 async function onExternalUserAuthenticated (options: {
78 authResult: RegisterServerExternalAuthenticatedResult
80 const { npmName, authName, authResult } = options
82 if (!authResult.req || !authResult.res) {
83 logger.error('Cannot authenticate external user for auth %s of plugin %s: no req or res are provided.', authName, npmName)
87 const { res } = authResult
89 if (!isAuthResultValid(npmName, authName, authResult)) {
90 res.redirect('/login?externalAuthError=true')
94 logger.info('Generating auth bypass token for %s in auth %s of plugin %s.', authResult.username, authName, npmName)
96 const bypassToken = await generateRandomString(32)
98 const expires = new Date()
99 expires.setTime(expires.getTime() + PLUGIN_EXTERNAL_AUTH_TOKEN_LIFETIME)
101 const user = buildUserResult(authResult)
102 authBypassTokens.set(bypassToken, {
110 const now = new Date()
111 for (const [ key, value ] of authBypassTokens) {
112 if (value.expires.getTime() < now.getTime()) {
113 authBypassTokens.delete(key)
117 res.redirect(`/login?externalAuthToken=${bypassToken}&username=${user.username}`)
120 // ---------------------------------------------------------------------------
122 export { oAuthServer, handleLogin, onExternalUserAuthenticated, handleTokenRevocation }
124 // ---------------------------------------------------------------------------
126 function forwardTokenReq (req: express.Request, res: express.Response, next?: express.NextFunction) {
127 return oAuthServer.token()(req, res, err => {
129 logger.warn('Login error.', { err })
131 return res.status(err.status)
138 if (next) return next()
142 async function proxifyRefreshGrant (req: express.Request, res: express.Response) {
143 const refreshToken = req.body.refresh_token
144 if (!refreshToken) return
146 const tokenModel = await OAuthTokenModel.loadByRefreshToken(refreshToken)
147 if (tokenModel?.authName) res.locals.refreshTokenAuthName = tokenModel.authName
150 async function proxifyPasswordGrant (req: express.Request, res: express.Response) {
151 const plugins = PluginManager.Instance.getIdAndPassAuths()
152 const pluginAuths: { npmName?: string, registerAuthOptions: RegisterServerAuthPassOptions }[] = []
154 for (const plugin of plugins) {
155 const auths = plugin.idAndPassAuths
157 for (const auth of auths) {
159 npmName: plugin.npmName,
160 registerAuthOptions: auth
165 pluginAuths.sort((a, b) => {
166 const aWeight = a.registerAuthOptions.getWeight()
167 const bWeight = b.registerAuthOptions.getWeight()
170 if (aWeight === bWeight) return 0
171 if (aWeight < bWeight) return 1
175 const loginOptions = {
176 id: req.body.username,
177 password: req.body.password
180 for (const pluginAuth of pluginAuths) {
181 const authOptions = pluginAuth.registerAuthOptions
182 const authName = authOptions.authName
183 const npmName = pluginAuth.npmName
186 'Using auth method %s of plugin %s to login %s with weight %d.',
187 authName, npmName, loginOptions.id, authOptions.getWeight()
191 const loginResult = await authOptions.login(loginOptions)
193 if (!loginResult) continue
194 if (!isAuthResultValid(pluginAuth.npmName, authOptions.authName, loginResult)) continue
197 'Login success with auth method %s of plugin %s for %s.',
198 authName, npmName, loginOptions.id
201 res.locals.bypassLogin = {
203 pluginName: pluginAuth.npmName,
204 authName: authOptions.authName,
205 user: buildUserResult(loginResult)
210 logger.error('Error in auth method %s of plugin %s', authOptions.authName, pluginAuth.npmName, { err })
215 function proxifyExternalAuthBypass (req: express.Request, res: express.Response) {
216 const obj = authBypassTokens.get(req.body.externalAuthToken)
218 logger.error('Cannot authenticate user with unknown bypass token')
219 return res.sendStatus(HttpStatusCode.BAD_REQUEST_400)
222 const { expires, user, authName, npmName } = obj
224 const now = new Date()
225 if (now.getTime() > expires.getTime()) {
226 logger.error('Cannot authenticate user with an expired external auth token')
227 return res.sendStatus(HttpStatusCode.BAD_REQUEST_400)
230 if (user.username !== req.body.username) {
231 logger.error('Cannot authenticate user %s with invalid username %s.', req.body.username)
232 return res.sendStatus(HttpStatusCode.BAD_REQUEST_400)
235 // Bypass oauth library validation
236 req.body.password = 'fake'
239 'Auth success with external auth method %s of plugin %s for %s.',
240 authName, npmName, user.email
243 res.locals.bypassLogin = {
251 function isAuthResultValid (npmName: string, authName: string, result: RegisterServerAuthenticatedResult) {
252 if (!isUserUsernameValid(result.username)) {
253 logger.error('Auth method %s of plugin %s did not provide a valid username.', authName, npmName, { username: result.username })
258 logger.error('Auth method %s of plugin %s did not provide a valid email.', authName, npmName, { email: result.email })
263 if (result.role && !isUserRoleValid(result.role)) {
264 logger.error('Auth method %s of plugin %s did not provide a valid role.', authName, npmName, { role: result.role })
268 // display name is optional
269 if (result.displayName && !isUserDisplayNameValid(result.displayName)) {
271 'Auth method %s of plugin %s did not provide a valid display name.',
272 authName, npmName, { displayName: result.displayName }
280 function buildUserResult (pluginResult: RegisterServerAuthenticatedResult) {
282 username: pluginResult.username,
283 email: pluginResult.email,
284 role: pluginResult.role ?? UserRole.USER,
285 displayName: pluginResult.displayName || pluginResult.username