]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/auth.ts
Stricter email options typings
[github/Chocobozzz/PeerTube.git] / server / lib / auth.ts
CommitLineData
4a8d113b 1import { isUserDisplayNameValid, isUserRoleValid, isUserUsernameValid } from '@server/helpers/custom-validators/users'
7fed6375 2import { logger } from '@server/helpers/logger'
4a8d113b 3import { generateRandomString } from '@server/helpers/utils'
9107d791 4import { OAUTH_LIFETIME, PLUGIN_EXTERNAL_AUTH_TOKEN_LIFETIME } from '@server/initializers/constants'
e1c55031 5import { revokeToken } from '@server/lib/oauth-model'
4a8d113b 6import { PluginManager } from '@server/lib/plugins/plugin-manager'
e307e4fc 7import { OAuthTokenModel } from '@server/models/oauth/oauth-token'
4a8d113b
C
8import { UserRole } from '@shared/models'
9import {
10 RegisterServerAuthenticatedResult,
11 RegisterServerAuthPassOptions,
12 RegisterServerExternalAuthenticatedResult
67ed6552 13} from '@server/types/plugins/register-server-auth.model'
4a8d113b
C
14import * as express from 'express'
15import * as OAuthServer from 'express-oauth-server'
2d53be02 16import { HttpStatusCode } from '@shared/core-utils/miscs/http-error-codes'
7fed6375
C
17
18const oAuthServer = new OAuthServer({
19 useErrorHandler: true,
20 accessTokenLifetime: OAUTH_LIFETIME.ACCESS_TOKEN,
21 refreshTokenLifetime: OAUTH_LIFETIME.REFRESH_TOKEN,
e7812bf0 22 allowExtendedTokenAttributes: true,
7fed6375
C
23 continueMiddleware: true,
24 model: require('./oauth-model')
25})
26
4a8d113b
C
27// Token is the key, expiration date is the value
28const 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}>()
7fed6375 39
9107d791 40async function handleLogin (req: express.Request, res: express.Response, next: express.NextFunction) {
e307e4fc
C
41 const grantType = req.body.grant_type
42
4a8d113b
C
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 }
e307e4fc
C
49
50 return forwardTokenReq(req, res, next)
51}
52
53async function handleTokenRevocation (req: express.Request, res: express.Response) {
54 const token = res.locals.oauth.token
55
56 res.locals.explicitLogout = true
74fd2643 57 const result = await revokeToken(token)
e307e4fc
C
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
74fd2643 73 return res.json(result)
e307e4fc
C
74}
75
4a8d113b
C
76async function onExternalUserAuthenticated (options: {
77 npmName: string
78 authName: string
79 authResult: RegisterServerExternalAuthenticatedResult
80}) {
81 const { npmName, authName, authResult } = options
e307e4fc 82
4a8d113b
C
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
4a8d113b
C
88 const { res } = authResult
89
bc90883f
C
90 if (!isAuthResultValid(npmName, authName, authResult)) {
91 res.redirect('/login?externalAuthError=true')
92 return
93 }
94
4a8d113b
C
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)
4a8d113b
C
98
99 const expires = new Date()
9107d791 100 expires.setTime(expires.getTime() + PLUGIN_EXTERNAL_AUTH_TOKEN_LIFETIME)
4a8d113b
C
101
102 const user = buildUserResult(authResult)
103 authBypassTokens.set(bypassToken, {
104 expires,
105 user,
106 npmName,
107 authName
108 })
81c647ff
C
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 }
4a8d113b
C
117
118 res.redirect(`/login?externalAuthToken=${bypassToken}&username=${user.username}`)
e307e4fc
C
119}
120
121// ---------------------------------------------------------------------------
122
9107d791 123export { oAuthServer, handleLogin, onExternalUserAuthenticated, handleTokenRevocation }
4a8d113b
C
124
125// ---------------------------------------------------------------------------
126
127function forwardTokenReq (req: express.Request, res: express.Response, next?: express.NextFunction) {
e307e4fc
C
128 return oAuthServer.token()(req, res, err => {
129 if (err) {
130 logger.warn('Login error.', { err })
131
132 return res.status(err.status)
4a8d113b
C
133 .json({
134 error: err.message,
135 code: err.name
136 })
e307e4fc
C
137 }
138
4a8d113b 139 if (next) return next()
e307e4fc
C
140 })
141}
142
143async 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
151async function proxifyPasswordGrant (req: express.Request, res: express.Response) {
7fed6375
C
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
e1c55031 170 // DESC weight order
7fed6375 171 if (aWeight === bWeight) return 0
e1c55031 172 if (aWeight < bWeight) return 1
7fed6375
C
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) {
e1c55031 182 const authOptions = pluginAuth.registerAuthOptions
98813e69
C
183 const authName = authOptions.authName
184 const npmName = pluginAuth.npmName
e1c55031 185
7fed6375 186 logger.debug(
e1c55031 187 'Using auth method %s of plugin %s to login %s with weight %d.',
98813e69 188 authName, npmName, loginOptions.id, authOptions.getWeight()
7fed6375
C
189 )
190
055cfb11
C
191 try {
192 const loginResult = await authOptions.login(loginOptions)
4a8d113b
C
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)
055cfb11 207 }
4a8d113b
C
208
209 return
055cfb11
C
210 } catch (err) {
211 logger.error('Error in auth method %s of plugin %s', authOptions.authName, pluginAuth.npmName, { err })
7fed6375
C
212 }
213 }
7fed6375 214}
4a8d113b
C
215
216function 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')
2d53be02 220 return res.sendStatus(HttpStatusCode.BAD_REQUEST_400)
4a8d113b
C
221 }
222
223 const { expires, user, authName, npmName } = obj
224
225 const now = new Date()
226 if (now.getTime() > expires.getTime()) {
9107d791 227 logger.error('Cannot authenticate user with an expired external auth token')
2d53be02 228 return res.sendStatus(HttpStatusCode.BAD_REQUEST_400)
4a8d113b
C
229 }
230
231 if (user.username !== req.body.username) {
232 logger.error('Cannot authenticate user %s with invalid username %s.', req.body.username)
2d53be02 233 return res.sendStatus(HttpStatusCode.BAD_REQUEST_400)
4a8d113b
C
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
252function isAuthResultValid (npmName: string, authName: string, result: RegisterServerAuthenticatedResult) {
253 if (!isUserUsernameValid(result.username)) {
bc90883f 254 logger.error('Auth method %s of plugin %s did not provide a valid username.', authName, npmName, { username: result.username })
4a8d113b
C
255 return false
256 }
257
258 if (!result.email) {
bc90883f 259 logger.error('Auth method %s of plugin %s did not provide a valid email.', authName, npmName, { email: result.email })
4a8d113b
C
260 return false
261 }
262
263 // role is optional
264 if (result.role && !isUserRoleValid(result.role)) {
bc90883f 265 logger.error('Auth method %s of plugin %s did not provide a valid role.', authName, npmName, { role: result.role })
4a8d113b
C
266 return false
267 }
268
269 // display name is optional
270 if (result.displayName && !isUserDisplayNameValid(result.displayName)) {
bc90883f
C
271 logger.error(
272 'Auth method %s of plugin %s did not provide a valid display name.',
273 authName, npmName, { displayName: result.displayName }
274 )
4a8d113b
C
275 return false
276 }
277
278 return true
279}
280
281function buildUserResult (pluginResult: RegisterServerAuthenticatedResult) {
282 return {
283 username: pluginResult.username,
284 email: pluginResult.email,
9107d791 285 role: pluginResult.role ?? UserRole.USER,
4a8d113b
C
286 displayName: pluginResult.displayName || pluginResult.username
287 }
288}