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