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 allowExtendedTokenAttributes: true,
23 continueMiddleware: true,
24 model: require('./oauth-model')
27 // Token is the key, expiration date is the value
28 const authBypassTokens = new Map<string, {
40 async function handleLogin (req: express.Request, res: express.Response, next: express.NextFunction) {
41 const grantType = req.body.grant_type
43 if (grantType === 'password') {
44 if (req.body.externalAuthToken) proxifyExternalAuthBypass(req, res)
45 else await proxifyPasswordGrant(req, res)
46 } else if (grantType === 'refresh_token') {
47 await proxifyRefreshGrant(req, res)
50 return forwardTokenReq(req, res, next)
53 async function handleTokenRevocation (req: express.Request, res: express.Response) {
54 const token = res.locals.oauth.token
56 res.locals.explicitLogout = true
57 const result = await revokeToken(token)
59 // FIXME: uncomment when https://github.com/oauthjs/node-oauth2-server/pull/289 is released
60 // oAuthServer.revoke(req, res, err => {
62 // logger.warn('Error in revoke token handler.', { err })
64 // return res.status(err.status)
66 // error: err.message,
73 return res.json(result)
76 async function onExternalUserAuthenticated (options: {
79 authResult: RegisterServerExternalAuthenticatedResult
81 const { npmName, authName, authResult } = options
83 if (!authResult.req || !authResult.res) {
84 logger.error('Cannot authenticate external user for auth %s of plugin %s: no req or res are provided.', authName, npmName)
88 const { res } = authResult
90 if (!isAuthResultValid(npmName, authName, authResult)) {
91 res.redirect('/login?externalAuthError=true')
95 logger.info('Generating auth bypass token for %s in auth %s of plugin %s.', authResult.username, authName, npmName)
97 const bypassToken = await generateRandomString(32)
99 const expires = new Date()
100 expires.setTime(expires.getTime() + PLUGIN_EXTERNAL_AUTH_TOKEN_LIFETIME)
102 const user = buildUserResult(authResult)
103 authBypassTokens.set(bypassToken, {
111 const now = new Date()
112 for (const [ key, value ] of authBypassTokens) {
113 if (value.expires.getTime() < now.getTime()) {
114 authBypassTokens.delete(key)
118 res.redirect(`/login?externalAuthToken=${bypassToken}&username=${user.username}`)
121 // ---------------------------------------------------------------------------
123 export { oAuthServer, handleLogin, onExternalUserAuthenticated, handleTokenRevocation }
125 // ---------------------------------------------------------------------------
127 function forwardTokenReq (req: express.Request, res: express.Response, next?: express.NextFunction) {
128 return oAuthServer.token()(req, res, err => {
130 logger.warn('Login error.', { err })
132 return res.status(err.status)
139 if (next) return next()
143 async function proxifyRefreshGrant (req: express.Request, res: express.Response) {
144 const refreshToken = req.body.refresh_token
145 if (!refreshToken) return
147 const tokenModel = await OAuthTokenModel.loadByRefreshToken(refreshToken)
148 if (tokenModel?.authName) res.locals.refreshTokenAuthName = tokenModel.authName
151 async function proxifyPasswordGrant (req: express.Request, res: express.Response) {
152 const plugins = PluginManager.Instance.getIdAndPassAuths()
153 const pluginAuths: { npmName?: string, registerAuthOptions: RegisterServerAuthPassOptions }[] = []
155 for (const plugin of plugins) {
156 const auths = plugin.idAndPassAuths
158 for (const auth of auths) {
160 npmName: plugin.npmName,
161 registerAuthOptions: auth
166 pluginAuths.sort((a, b) => {
167 const aWeight = a.registerAuthOptions.getWeight()
168 const bWeight = b.registerAuthOptions.getWeight()
171 if (aWeight === bWeight) return 0
172 if (aWeight < bWeight) return 1
176 const loginOptions = {
177 id: req.body.username,
178 password: req.body.password
181 for (const pluginAuth of pluginAuths) {
182 const authOptions = pluginAuth.registerAuthOptions
183 const authName = authOptions.authName
184 const npmName = pluginAuth.npmName
187 'Using auth method %s of plugin %s to login %s with weight %d.',
188 authName, npmName, loginOptions.id, authOptions.getWeight()
192 const loginResult = await authOptions.login(loginOptions)
194 if (!loginResult) continue
195 if (!isAuthResultValid(pluginAuth.npmName, authOptions.authName, loginResult)) continue
198 'Login success with auth method %s of plugin %s for %s.',
199 authName, npmName, loginOptions.id
202 res.locals.bypassLogin = {
204 pluginName: pluginAuth.npmName,
205 authName: authOptions.authName,
206 user: buildUserResult(loginResult)
211 logger.error('Error in auth method %s of plugin %s', authOptions.authName, pluginAuth.npmName, { err })
216 function proxifyExternalAuthBypass (req: express.Request, res: express.Response) {
217 const obj = authBypassTokens.get(req.body.externalAuthToken)
219 logger.error('Cannot authenticate user with unknown bypass token')
220 return res.sendStatus(HttpStatusCode.BAD_REQUEST_400)
223 const { expires, user, authName, npmName } = obj
225 const now = new Date()
226 if (now.getTime() > expires.getTime()) {
227 logger.error('Cannot authenticate user with an expired external auth token')
228 return res.sendStatus(HttpStatusCode.BAD_REQUEST_400)
231 if (user.username !== req.body.username) {
232 logger.error('Cannot authenticate user %s with invalid username %s.', req.body.username)
233 return res.sendStatus(HttpStatusCode.BAD_REQUEST_400)
236 // Bypass oauth library validation
237 req.body.password = 'fake'
240 'Auth success with external auth method %s of plugin %s for %s.',
241 authName, npmName, user.email
244 res.locals.bypassLogin = {
252 function isAuthResultValid (npmName: string, authName: string, result: RegisterServerAuthenticatedResult) {
253 if (!isUserUsernameValid(result.username)) {
254 logger.error('Auth method %s of plugin %s did not provide a valid username.', authName, npmName, { username: result.username })
259 logger.error('Auth method %s of plugin %s did not provide a valid email.', authName, npmName, { email: result.email })
264 if (result.role && !isUserRoleValid(result.role)) {
265 logger.error('Auth method %s of plugin %s did not provide a valid role.', authName, npmName, { role: result.role })
269 // display name is optional
270 if (result.displayName && !isUserDisplayNameValid(result.displayName)) {
272 'Auth method %s of plugin %s did not provide a valid display name.',
273 authName, npmName, { displayName: result.displayName }
281 function buildUserResult (pluginResult: RegisterServerAuthenticatedResult) {
283 username: pluginResult.username,
284 email: pluginResult.email,
285 role: pluginResult.role ?? UserRole.USER,
286 displayName: pluginResult.displayName || pluginResult.username