1 import * as express from 'express'
2 import { OAUTH_LIFETIME } from '@server/initializers/constants'
3 import * as OAuthServer from 'express-oauth-server'
4 import { PluginManager } from '@server/lib/plugins/plugin-manager'
5 import { RegisterServerAuthPassOptions } from '@shared/models/plugins/register-server-auth.model'
6 import { logger } from '@server/helpers/logger'
7 import { UserRole } from '@shared/models'
8 import { revokeToken } from '@server/lib/oauth-model'
9 import { OAuthTokenModel } from '@server/models/oauth/oauth-token'
10 import { isUserUsernameValid, isUserRoleValid, isUserDisplayNameValid } from '@server/helpers/custom-validators/users'
12 const oAuthServer = new OAuthServer({
13 useErrorHandler: true,
14 accessTokenLifetime: OAUTH_LIFETIME.ACCESS_TOKEN,
15 refreshTokenLifetime: OAUTH_LIFETIME.REFRESH_TOKEN,
16 continueMiddleware: true,
17 model: require('./oauth-model')
20 function onExternalAuthPlugin (npmName: string, username: string, email: string) {
24 async function handleIdAndPassLogin (req: express.Request, res: express.Response, next: express.NextFunction) {
25 const grantType = req.body.grant_type
27 if (grantType === 'password') await proxifyPasswordGrant(req, res)
28 else if (grantType === 'refresh_token') await proxifyRefreshGrant(req, res)
30 return forwardTokenReq(req, res, next)
33 async function handleTokenRevocation (req: express.Request, res: express.Response) {
34 const token = res.locals.oauth.token
36 res.locals.explicitLogout = true
37 await revokeToken(token)
39 // FIXME: uncomment when https://github.com/oauthjs/node-oauth2-server/pull/289 is released
40 // oAuthServer.revoke(req, res, err => {
42 // logger.warn('Error in revoke token handler.', { err })
44 // return res.status(err.status)
46 // error: err.message,
53 return res.sendStatus(200)
56 // ---------------------------------------------------------------------------
65 // ---------------------------------------------------------------------------
67 function forwardTokenReq (req: express.Request, res: express.Response, next: express.NextFunction) {
68 return oAuthServer.token()(req, res, err => {
70 logger.warn('Login error.', { err })
72 return res.status(err.status)
84 async function proxifyRefreshGrant (req: express.Request, res: express.Response) {
85 const refreshToken = req.body.refresh_token
86 if (!refreshToken) return
88 const tokenModel = await OAuthTokenModel.loadByRefreshToken(refreshToken)
89 if (tokenModel?.authName) res.locals.refreshTokenAuthName = tokenModel.authName
92 async function proxifyPasswordGrant (req: express.Request, res: express.Response) {
93 const plugins = PluginManager.Instance.getIdAndPassAuths()
94 const pluginAuths: { npmName?: string, registerAuthOptions: RegisterServerAuthPassOptions }[] = []
96 for (const plugin of plugins) {
97 const auths = plugin.idAndPassAuths
99 for (const auth of auths) {
101 npmName: plugin.npmName,
102 registerAuthOptions: auth
107 pluginAuths.sort((a, b) => {
108 const aWeight = a.registerAuthOptions.getWeight()
109 const bWeight = b.registerAuthOptions.getWeight()
112 if (aWeight === bWeight) return 0
113 if (aWeight < bWeight) return 1
117 const loginOptions = {
118 id: req.body.username,
119 password: req.body.password
122 for (const pluginAuth of pluginAuths) {
123 const authOptions = pluginAuth.registerAuthOptions
124 const authName = authOptions.authName
125 const npmName = pluginAuth.npmName
128 'Using auth method %s of plugin %s to login %s with weight %d.',
129 authName, npmName, loginOptions.id, authOptions.getWeight()
133 const loginResult = await authOptions.login(loginOptions)
136 'Login success with auth method %s of plugin %s for %s.',
137 authName, npmName, loginOptions.id
140 if (!isUserUsernameValid(loginResult.username)) {
141 logger.error('Auth method %s of plugin %s did not provide a valid username.', authName, npmName, { loginResult })
145 if (!loginResult.email) {
146 logger.error('Auth method %s of plugin %s did not provide a valid email.', authName, npmName, { loginResult })
151 if (loginResult.role && !isUserRoleValid(loginResult.role)) {
152 logger.error('Auth method %s of plugin %s did not provide a valid role.', authName, npmName, { loginResult })
156 // display name is optional
157 if (loginResult.displayName && !isUserDisplayNameValid(loginResult.displayName)) {
158 logger.error('Auth method %s of plugin %s did not provide a valid display name.', authName, npmName, { loginResult })
162 res.locals.bypassLogin = {
164 pluginName: pluginAuth.npmName,
165 authName: authOptions.authName,
167 username: loginResult.username,
168 email: loginResult.email,
169 role: loginResult.role || UserRole.USER,
170 displayName: loginResult.displayName || loginResult.username
177 logger.error('Error in auth method %s of plugin %s', authOptions.authName, pluginAuth.npmName, { err })