]>
Commit | Line | Data |
---|---|---|
4a8d113b | 1 | import { isUserDisplayNameValid, isUserRoleValid, isUserUsernameValid } from '@server/helpers/custom-validators/users' |
7fed6375 | 2 | import { logger } from '@server/helpers/logger' |
4a8d113b | 3 | import { generateRandomString } from '@server/helpers/utils' |
9107d791 | 4 | import { OAUTH_LIFETIME, PLUGIN_EXTERNAL_AUTH_TOKEN_LIFETIME } from '@server/initializers/constants' |
e1c55031 | 5 | import { revokeToken } from '@server/lib/oauth-model' |
4a8d113b | 6 | import { PluginManager } from '@server/lib/plugins/plugin-manager' |
e307e4fc | 7 | import { OAuthTokenModel } from '@server/models/oauth/oauth-token' |
4a8d113b C |
8 | import { UserRole } from '@shared/models' |
9 | import { | |
10 | RegisterServerAuthenticatedResult, | |
11 | RegisterServerAuthPassOptions, | |
12 | RegisterServerExternalAuthenticatedResult | |
67ed6552 | 13 | } from '@server/types/plugins/register-server-auth.model' |
4a8d113b C |
14 | import * as express from 'express' |
15 | import * as OAuthServer from 'express-oauth-server' | |
7fed6375 C |
16 | |
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') | |
23 | }) | |
24 | ||
4a8d113b C |
25 | // Token is the key, expiration date is the value |
26 | const authBypassTokens = new Map<string, { | |
27 | expires: Date | |
28 | user: { | |
29 | username: string | |
30 | email: string | |
31 | displayName: string | |
32 | role: UserRole | |
33 | } | |
34 | authName: string | |
35 | npmName: string | |
36 | }>() | |
7fed6375 | 37 | |
9107d791 | 38 | async function handleLogin (req: express.Request, res: express.Response, next: express.NextFunction) { |
e307e4fc C |
39 | const grantType = req.body.grant_type |
40 | ||
4a8d113b C |
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) | |
46 | } | |
e307e4fc C |
47 | |
48 | return forwardTokenReq(req, res, next) | |
49 | } | |
50 | ||
51 | async function handleTokenRevocation (req: express.Request, res: express.Response) { | |
52 | const token = res.locals.oauth.token | |
53 | ||
54 | res.locals.explicitLogout = true | |
55 | await revokeToken(token) | |
56 | ||
57 | // FIXME: uncomment when https://github.com/oauthjs/node-oauth2-server/pull/289 is released | |
58 | // oAuthServer.revoke(req, res, err => { | |
59 | // if (err) { | |
60 | // logger.warn('Error in revoke token handler.', { err }) | |
61 | // | |
62 | // return res.status(err.status) | |
63 | // .json({ | |
64 | // error: err.message, | |
65 | // code: err.name | |
66 | // }) | |
67 | // .end() | |
68 | // } | |
69 | // }) | |
70 | ||
dadc90bc | 71 | return res.json() |
e307e4fc C |
72 | } |
73 | ||
4a8d113b C |
74 | async function onExternalUserAuthenticated (options: { |
75 | npmName: string | |
76 | authName: string | |
77 | authResult: RegisterServerExternalAuthenticatedResult | |
78 | }) { | |
79 | const { npmName, authName, authResult } = options | |
e307e4fc | 80 | |
4a8d113b C |
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) | |
83 | return | |
84 | } | |
85 | ||
4a8d113b C |
86 | const { res } = authResult |
87 | ||
bc90883f C |
88 | if (!isAuthResultValid(npmName, authName, authResult)) { |
89 | res.redirect('/login?externalAuthError=true') | |
90 | return | |
91 | } | |
92 | ||
4a8d113b C |
93 | logger.info('Generating auth bypass token for %s in auth %s of plugin %s.', authResult.username, authName, npmName) |
94 | ||
95 | const bypassToken = await generateRandomString(32) | |
4a8d113b C |
96 | |
97 | const expires = new Date() | |
9107d791 | 98 | expires.setTime(expires.getTime() + PLUGIN_EXTERNAL_AUTH_TOKEN_LIFETIME) |
4a8d113b C |
99 | |
100 | const user = buildUserResult(authResult) | |
101 | authBypassTokens.set(bypassToken, { | |
102 | expires, | |
103 | user, | |
104 | npmName, | |
105 | authName | |
106 | }) | |
81c647ff C |
107 | |
108 | // Cleanup | |
109 | const now = new Date() | |
110 | for (const [ key, value ] of authBypassTokens) { | |
111 | if (value.expires.getTime() < now.getTime()) { | |
112 | authBypassTokens.delete(key) | |
113 | } | |
114 | } | |
4a8d113b C |
115 | |
116 | res.redirect(`/login?externalAuthToken=${bypassToken}&username=${user.username}`) | |
e307e4fc C |
117 | } |
118 | ||
119 | // --------------------------------------------------------------------------- | |
120 | ||
9107d791 | 121 | export { oAuthServer, handleLogin, onExternalUserAuthenticated, handleTokenRevocation } |
4a8d113b C |
122 | |
123 | // --------------------------------------------------------------------------- | |
124 | ||
125 | function forwardTokenReq (req: express.Request, res: express.Response, next?: express.NextFunction) { | |
e307e4fc C |
126 | return oAuthServer.token()(req, res, err => { |
127 | if (err) { | |
128 | logger.warn('Login error.', { err }) | |
129 | ||
130 | return res.status(err.status) | |
4a8d113b C |
131 | .json({ |
132 | error: err.message, | |
133 | code: err.name | |
134 | }) | |
e307e4fc C |
135 | } |
136 | ||
4a8d113b | 137 | if (next) return next() |
e307e4fc C |
138 | }) |
139 | } | |
140 | ||
141 | async function proxifyRefreshGrant (req: express.Request, res: express.Response) { | |
142 | const refreshToken = req.body.refresh_token | |
143 | if (!refreshToken) return | |
144 | ||
145 | const tokenModel = await OAuthTokenModel.loadByRefreshToken(refreshToken) | |
146 | if (tokenModel?.authName) res.locals.refreshTokenAuthName = tokenModel.authName | |
147 | } | |
148 | ||
149 | async function proxifyPasswordGrant (req: express.Request, res: express.Response) { | |
7fed6375 C |
150 | const plugins = PluginManager.Instance.getIdAndPassAuths() |
151 | const pluginAuths: { npmName?: string, registerAuthOptions: RegisterServerAuthPassOptions }[] = [] | |
152 | ||
153 | for (const plugin of plugins) { | |
154 | const auths = plugin.idAndPassAuths | |
155 | ||
156 | for (const auth of auths) { | |
157 | pluginAuths.push({ | |
158 | npmName: plugin.npmName, | |
159 | registerAuthOptions: auth | |
160 | }) | |
161 | } | |
162 | } | |
163 | ||
164 | pluginAuths.sort((a, b) => { | |
165 | const aWeight = a.registerAuthOptions.getWeight() | |
166 | const bWeight = b.registerAuthOptions.getWeight() | |
167 | ||
e1c55031 | 168 | // DESC weight order |
7fed6375 | 169 | if (aWeight === bWeight) return 0 |
e1c55031 | 170 | if (aWeight < bWeight) return 1 |
7fed6375 C |
171 | return -1 |
172 | }) | |
173 | ||
174 | const loginOptions = { | |
175 | id: req.body.username, | |
176 | password: req.body.password | |
177 | } | |
178 | ||
179 | for (const pluginAuth of pluginAuths) { | |
e1c55031 | 180 | const authOptions = pluginAuth.registerAuthOptions |
98813e69 C |
181 | const authName = authOptions.authName |
182 | const npmName = pluginAuth.npmName | |
e1c55031 | 183 | |
7fed6375 | 184 | logger.debug( |
e1c55031 | 185 | 'Using auth method %s of plugin %s to login %s with weight %d.', |
98813e69 | 186 | authName, npmName, loginOptions.id, authOptions.getWeight() |
7fed6375 C |
187 | ) |
188 | ||
055cfb11 C |
189 | try { |
190 | const loginResult = await authOptions.login(loginOptions) | |
4a8d113b C |
191 | |
192 | if (!loginResult) continue | |
193 | if (!isAuthResultValid(pluginAuth.npmName, authOptions.authName, loginResult)) continue | |
194 | ||
195 | logger.info( | |
196 | 'Login success with auth method %s of plugin %s for %s.', | |
197 | authName, npmName, loginOptions.id | |
198 | ) | |
199 | ||
200 | res.locals.bypassLogin = { | |
201 | bypass: true, | |
202 | pluginName: pluginAuth.npmName, | |
203 | authName: authOptions.authName, | |
204 | user: buildUserResult(loginResult) | |
055cfb11 | 205 | } |
4a8d113b C |
206 | |
207 | return | |
055cfb11 C |
208 | } catch (err) { |
209 | logger.error('Error in auth method %s of plugin %s', authOptions.authName, pluginAuth.npmName, { err }) | |
7fed6375 C |
210 | } |
211 | } | |
7fed6375 | 212 | } |
4a8d113b C |
213 | |
214 | function proxifyExternalAuthBypass (req: express.Request, res: express.Response) { | |
215 | const obj = authBypassTokens.get(req.body.externalAuthToken) | |
216 | if (!obj) { | |
217 | logger.error('Cannot authenticate user with unknown bypass token') | |
218 | return res.sendStatus(400) | |
219 | } | |
220 | ||
221 | const { expires, user, authName, npmName } = obj | |
222 | ||
223 | const now = new Date() | |
224 | if (now.getTime() > expires.getTime()) { | |
9107d791 | 225 | logger.error('Cannot authenticate user with an expired external auth token') |
4a8d113b C |
226 | return res.sendStatus(400) |
227 | } | |
228 | ||
229 | if (user.username !== req.body.username) { | |
230 | logger.error('Cannot authenticate user %s with invalid username %s.', req.body.username) | |
231 | return res.sendStatus(400) | |
232 | } | |
233 | ||
234 | // Bypass oauth library validation | |
235 | req.body.password = 'fake' | |
236 | ||
237 | logger.info( | |
238 | 'Auth success with external auth method %s of plugin %s for %s.', | |
239 | authName, npmName, user.email | |
240 | ) | |
241 | ||
242 | res.locals.bypassLogin = { | |
243 | bypass: true, | |
244 | pluginName: npmName, | |
245 | authName: authName, | |
246 | user | |
247 | } | |
248 | } | |
249 | ||
250 | function isAuthResultValid (npmName: string, authName: string, result: RegisterServerAuthenticatedResult) { | |
251 | if (!isUserUsernameValid(result.username)) { | |
bc90883f | 252 | logger.error('Auth method %s of plugin %s did not provide a valid username.', authName, npmName, { username: result.username }) |
4a8d113b C |
253 | return false |
254 | } | |
255 | ||
256 | if (!result.email) { | |
bc90883f | 257 | logger.error('Auth method %s of plugin %s did not provide a valid email.', authName, npmName, { email: result.email }) |
4a8d113b C |
258 | return false |
259 | } | |
260 | ||
261 | // role is optional | |
262 | if (result.role && !isUserRoleValid(result.role)) { | |
bc90883f | 263 | logger.error('Auth method %s of plugin %s did not provide a valid role.', authName, npmName, { role: result.role }) |
4a8d113b C |
264 | return false |
265 | } | |
266 | ||
267 | // display name is optional | |
268 | if (result.displayName && !isUserDisplayNameValid(result.displayName)) { | |
bc90883f C |
269 | logger.error( |
270 | 'Auth method %s of plugin %s did not provide a valid display name.', | |
271 | authName, npmName, { displayName: result.displayName } | |
272 | ) | |
4a8d113b C |
273 | return false |
274 | } | |
275 | ||
276 | return true | |
277 | } | |
278 | ||
279 | function buildUserResult (pluginResult: RegisterServerAuthenticatedResult) { | |
280 | return { | |
281 | username: pluginResult.username, | |
282 | email: pluginResult.email, | |
9107d791 | 283 | role: pluginResult.role ?? UserRole.USER, |
4a8d113b C |
284 | displayName: pluginResult.displayName || pluginResult.username |
285 | } | |
286 | } |