]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/auth.ts
Upgrade sequelize to v6
[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,
22 continueMiddleware: true,
23 model: require('./oauth-model')
24})
25
4a8d113b
C
26// Token is the key, expiration date is the value
27const 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}>()
7fed6375 38
9107d791 39async function handleLogin (req: express.Request, res: express.Response, next: express.NextFunction) {
e307e4fc
C
40 const grantType = req.body.grant_type
41
4a8d113b
C
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 }
e307e4fc
C
48
49 return forwardTokenReq(req, res, next)
50}
51
52async function handleTokenRevocation (req: express.Request, res: express.Response) {
53 const token = res.locals.oauth.token
54
55 res.locals.explicitLogout = true
74fd2643 56 const result = await revokeToken(token)
e307e4fc
C
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
74fd2643 72 return res.json(result)
e307e4fc
C
73}
74
4a8d113b
C
75async function onExternalUserAuthenticated (options: {
76 npmName: string
77 authName: string
78 authResult: RegisterServerExternalAuthenticatedResult
79}) {
80 const { npmName, authName, authResult } = options
e307e4fc 81
4a8d113b
C
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
4a8d113b
C
87 const { res } = authResult
88
bc90883f
C
89 if (!isAuthResultValid(npmName, authName, authResult)) {
90 res.redirect('/login?externalAuthError=true')
91 return
92 }
93
4a8d113b
C
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)
4a8d113b
C
97
98 const expires = new Date()
9107d791 99 expires.setTime(expires.getTime() + PLUGIN_EXTERNAL_AUTH_TOKEN_LIFETIME)
4a8d113b
C
100
101 const user = buildUserResult(authResult)
102 authBypassTokens.set(bypassToken, {
103 expires,
104 user,
105 npmName,
106 authName
107 })
81c647ff
C
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 }
4a8d113b
C
116
117 res.redirect(`/login?externalAuthToken=${bypassToken}&username=${user.username}`)
e307e4fc
C
118}
119
120// ---------------------------------------------------------------------------
121
9107d791 122export { oAuthServer, handleLogin, onExternalUserAuthenticated, handleTokenRevocation }
4a8d113b
C
123
124// ---------------------------------------------------------------------------
125
126function forwardTokenReq (req: express.Request, res: express.Response, next?: express.NextFunction) {
e307e4fc
C
127 return oAuthServer.token()(req, res, err => {
128 if (err) {
129 logger.warn('Login error.', { err })
130
131 return res.status(err.status)
4a8d113b
C
132 .json({
133 error: err.message,
134 code: err.name
135 })
e307e4fc
C
136 }
137
4a8d113b 138 if (next) return next()
e307e4fc
C
139 })
140}
141
142async 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
150async function proxifyPasswordGrant (req: express.Request, res: express.Response) {
7fed6375
C
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
e1c55031 169 // DESC weight order
7fed6375 170 if (aWeight === bWeight) return 0
e1c55031 171 if (aWeight < bWeight) return 1
7fed6375
C
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) {
e1c55031 181 const authOptions = pluginAuth.registerAuthOptions
98813e69
C
182 const authName = authOptions.authName
183 const npmName = pluginAuth.npmName
e1c55031 184
7fed6375 185 logger.debug(
e1c55031 186 'Using auth method %s of plugin %s to login %s with weight %d.',
98813e69 187 authName, npmName, loginOptions.id, authOptions.getWeight()
7fed6375
C
188 )
189
055cfb11
C
190 try {
191 const loginResult = await authOptions.login(loginOptions)
4a8d113b
C
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)
055cfb11 206 }
4a8d113b
C
207
208 return
055cfb11
C
209 } catch (err) {
210 logger.error('Error in auth method %s of plugin %s', authOptions.authName, pluginAuth.npmName, { err })
7fed6375
C
211 }
212 }
7fed6375 213}
4a8d113b
C
214
215function 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')
2d53be02 219 return res.sendStatus(HttpStatusCode.BAD_REQUEST_400)
4a8d113b
C
220 }
221
222 const { expires, user, authName, npmName } = obj
223
224 const now = new Date()
225 if (now.getTime() > expires.getTime()) {
9107d791 226 logger.error('Cannot authenticate user with an expired external auth token')
2d53be02 227 return res.sendStatus(HttpStatusCode.BAD_REQUEST_400)
4a8d113b
C
228 }
229
230 if (user.username !== req.body.username) {
231 logger.error('Cannot authenticate user %s with invalid username %s.', req.body.username)
2d53be02 232 return res.sendStatus(HttpStatusCode.BAD_REQUEST_400)
4a8d113b
C
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
251function isAuthResultValid (npmName: string, authName: string, result: RegisterServerAuthenticatedResult) {
252 if (!isUserUsernameValid(result.username)) {
bc90883f 253 logger.error('Auth method %s of plugin %s did not provide a valid username.', authName, npmName, { username: result.username })
4a8d113b
C
254 return false
255 }
256
257 if (!result.email) {
bc90883f 258 logger.error('Auth method %s of plugin %s did not provide a valid email.', authName, npmName, { email: result.email })
4a8d113b
C
259 return false
260 }
261
262 // role is optional
263 if (result.role && !isUserRoleValid(result.role)) {
bc90883f 264 logger.error('Auth method %s of plugin %s did not provide a valid role.', authName, npmName, { role: result.role })
4a8d113b
C
265 return false
266 }
267
268 // display name is optional
269 if (result.displayName && !isUserDisplayNameValid(result.displayName)) {
bc90883f
C
270 logger.error(
271 'Auth method %s of plugin %s did not provide a valid display name.',
272 authName, npmName, { displayName: result.displayName }
273 )
4a8d113b
C
274 return false
275 }
276
277 return true
278}
279
280function buildUserResult (pluginResult: RegisterServerAuthenticatedResult) {
281 return {
282 username: pluginResult.username,
283 email: pluginResult.email,
9107d791 284 role: pluginResult.role ?? UserRole.USER,
4a8d113b
C
285 displayName: pluginResult.displayName || pluginResult.username
286 }
287}