]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/auth.ts
Fix plugin storeData
[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
13} from '@shared/models/plugins/register-server-auth.model'
14import * as express from 'express'
15import * as OAuthServer from 'express-oauth-server'
7fed6375
C
16
17const 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
26const 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 38async 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
51async 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
74async 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 })
107
108 res.redirect(`/login?externalAuthToken=${bypassToken}&username=${user.username}`)
e307e4fc
C
109}
110
111// ---------------------------------------------------------------------------
112
9107d791 113export { oAuthServer, handleLogin, onExternalUserAuthenticated, handleTokenRevocation }
4a8d113b
C
114
115// ---------------------------------------------------------------------------
116
117function forwardTokenReq (req: express.Request, res: express.Response, next?: express.NextFunction) {
e307e4fc
C
118 return oAuthServer.token()(req, res, err => {
119 if (err) {
120 logger.warn('Login error.', { err })
121
122 return res.status(err.status)
4a8d113b
C
123 .json({
124 error: err.message,
125 code: err.name
126 })
e307e4fc
C
127 }
128
4a8d113b 129 if (next) return next()
e307e4fc
C
130 })
131}
132
133async function proxifyRefreshGrant (req: express.Request, res: express.Response) {
134 const refreshToken = req.body.refresh_token
135 if (!refreshToken) return
136
137 const tokenModel = await OAuthTokenModel.loadByRefreshToken(refreshToken)
138 if (tokenModel?.authName) res.locals.refreshTokenAuthName = tokenModel.authName
139}
140
141async function proxifyPasswordGrant (req: express.Request, res: express.Response) {
7fed6375
C
142 const plugins = PluginManager.Instance.getIdAndPassAuths()
143 const pluginAuths: { npmName?: string, registerAuthOptions: RegisterServerAuthPassOptions }[] = []
144
145 for (const plugin of plugins) {
146 const auths = plugin.idAndPassAuths
147
148 for (const auth of auths) {
149 pluginAuths.push({
150 npmName: plugin.npmName,
151 registerAuthOptions: auth
152 })
153 }
154 }
155
156 pluginAuths.sort((a, b) => {
157 const aWeight = a.registerAuthOptions.getWeight()
158 const bWeight = b.registerAuthOptions.getWeight()
159
e1c55031 160 // DESC weight order
7fed6375 161 if (aWeight === bWeight) return 0
e1c55031 162 if (aWeight < bWeight) return 1
7fed6375
C
163 return -1
164 })
165
166 const loginOptions = {
167 id: req.body.username,
168 password: req.body.password
169 }
170
171 for (const pluginAuth of pluginAuths) {
e1c55031 172 const authOptions = pluginAuth.registerAuthOptions
98813e69
C
173 const authName = authOptions.authName
174 const npmName = pluginAuth.npmName
e1c55031 175
7fed6375 176 logger.debug(
e1c55031 177 'Using auth method %s of plugin %s to login %s with weight %d.',
98813e69 178 authName, npmName, loginOptions.id, authOptions.getWeight()
7fed6375
C
179 )
180
055cfb11
C
181 try {
182 const loginResult = await authOptions.login(loginOptions)
4a8d113b
C
183
184 if (!loginResult) continue
185 if (!isAuthResultValid(pluginAuth.npmName, authOptions.authName, loginResult)) continue
186
187 logger.info(
188 'Login success with auth method %s of plugin %s for %s.',
189 authName, npmName, loginOptions.id
190 )
191
192 res.locals.bypassLogin = {
193 bypass: true,
194 pluginName: pluginAuth.npmName,
195 authName: authOptions.authName,
196 user: buildUserResult(loginResult)
055cfb11 197 }
4a8d113b
C
198
199 return
055cfb11
C
200 } catch (err) {
201 logger.error('Error in auth method %s of plugin %s', authOptions.authName, pluginAuth.npmName, { err })
7fed6375
C
202 }
203 }
7fed6375 204}
4a8d113b
C
205
206function proxifyExternalAuthBypass (req: express.Request, res: express.Response) {
207 const obj = authBypassTokens.get(req.body.externalAuthToken)
208 if (!obj) {
209 logger.error('Cannot authenticate user with unknown bypass token')
210 return res.sendStatus(400)
211 }
212
213 const { expires, user, authName, npmName } = obj
214
215 const now = new Date()
216 if (now.getTime() > expires.getTime()) {
9107d791 217 logger.error('Cannot authenticate user with an expired external auth token')
4a8d113b
C
218 return res.sendStatus(400)
219 }
220
221 if (user.username !== req.body.username) {
222 logger.error('Cannot authenticate user %s with invalid username %s.', req.body.username)
223 return res.sendStatus(400)
224 }
225
226 // Bypass oauth library validation
227 req.body.password = 'fake'
228
229 logger.info(
230 'Auth success with external auth method %s of plugin %s for %s.',
231 authName, npmName, user.email
232 )
233
234 res.locals.bypassLogin = {
235 bypass: true,
236 pluginName: npmName,
237 authName: authName,
238 user
239 }
240}
241
242function isAuthResultValid (npmName: string, authName: string, result: RegisterServerAuthenticatedResult) {
243 if (!isUserUsernameValid(result.username)) {
bc90883f 244 logger.error('Auth method %s of plugin %s did not provide a valid username.', authName, npmName, { username: result.username })
4a8d113b
C
245 return false
246 }
247
248 if (!result.email) {
bc90883f 249 logger.error('Auth method %s of plugin %s did not provide a valid email.', authName, npmName, { email: result.email })
4a8d113b
C
250 return false
251 }
252
253 // role is optional
254 if (result.role && !isUserRoleValid(result.role)) {
bc90883f 255 logger.error('Auth method %s of plugin %s did not provide a valid role.', authName, npmName, { role: result.role })
4a8d113b
C
256 return false
257 }
258
259 // display name is optional
260 if (result.displayName && !isUserDisplayNameValid(result.displayName)) {
bc90883f
C
261 logger.error(
262 'Auth method %s of plugin %s did not provide a valid display name.',
263 authName, npmName, { displayName: result.displayName }
264 )
4a8d113b
C
265 return false
266 }
267
268 return true
269}
270
271function buildUserResult (pluginResult: RegisterServerAuthenticatedResult) {
272 return {
273 username: pluginResult.username,
274 email: pluginResult.email,
9107d791 275 role: pluginResult.role ?? UserRole.USER,
4a8d113b
C
276 displayName: pluginResult.displayName || pluginResult.username
277 }
278}