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