]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/auth/external-auth.ts
External auth can set more user fields
[github/Chocobozzz/PeerTube.git] / server / lib / auth / external-auth.ts
1
2 import {
3 isUserAdminFlagsValid,
4 isUserDisplayNameValid,
5 isUserRoleValid,
6 isUserUsernameValid,
7 isUserVideoQuotaDailyValid,
8 isUserVideoQuotaValid
9 } from '@server/helpers/custom-validators/users'
10 import { logger } from '@server/helpers/logger'
11 import { generateRandomString } from '@server/helpers/utils'
12 import { PLUGIN_EXTERNAL_AUTH_TOKEN_LIFETIME } from '@server/initializers/constants'
13 import { PluginManager } from '@server/lib/plugins/plugin-manager'
14 import { OAuthTokenModel } from '@server/models/oauth/oauth-token'
15 import { MUser } from '@server/types/models'
16 import {
17 RegisterServerAuthenticatedResult,
18 RegisterServerAuthPassOptions,
19 RegisterServerExternalAuthenticatedResult
20 } from '@server/types/plugins/register-server-auth.model'
21 import { UserAdminFlag, UserRole } from '@shared/models'
22
23 export type ExternalUser =
24 Pick<MUser, 'username' | 'email' | 'role' | 'adminFlags' | 'videoQuotaDaily' | 'videoQuota'> &
25 { displayName: string }
26
27 // Token is the key, expiration date is the value
28 const authBypassTokens = new Map<string, {
29 expires: Date
30 user: ExternalUser
31 authName: string
32 npmName: string
33 }>()
34
35 async function onExternalUserAuthenticated (options: {
36 npmName: string
37 authName: string
38 authResult: RegisterServerExternalAuthenticatedResult
39 }) {
40 const { npmName, authName, authResult } = options
41
42 if (!authResult.req || !authResult.res) {
43 logger.error('Cannot authenticate external user for auth %s of plugin %s: no req or res are provided.', authName, npmName)
44 return
45 }
46
47 const { res } = authResult
48
49 if (!isAuthResultValid(npmName, authName, authResult)) {
50 res.redirect('/login?externalAuthError=true')
51 return
52 }
53
54 logger.info('Generating auth bypass token for %s in auth %s of plugin %s.', authResult.username, authName, npmName)
55
56 const bypassToken = await generateRandomString(32)
57
58 const expires = new Date()
59 expires.setTime(expires.getTime() + PLUGIN_EXTERNAL_AUTH_TOKEN_LIFETIME)
60
61 const user = buildUserResult(authResult)
62 authBypassTokens.set(bypassToken, {
63 expires,
64 user,
65 npmName,
66 authName
67 })
68
69 // Cleanup expired tokens
70 const now = new Date()
71 for (const [ key, value ] of authBypassTokens) {
72 if (value.expires.getTime() < now.getTime()) {
73 authBypassTokens.delete(key)
74 }
75 }
76
77 res.redirect(`/login?externalAuthToken=${bypassToken}&username=${user.username}`)
78 }
79
80 async function getAuthNameFromRefreshGrant (refreshToken?: string) {
81 if (!refreshToken) return undefined
82
83 const tokenModel = await OAuthTokenModel.loadByRefreshToken(refreshToken)
84
85 return tokenModel?.authName
86 }
87
88 async function getBypassFromPasswordGrant (username: string, password: string) {
89 const plugins = PluginManager.Instance.getIdAndPassAuths()
90 const pluginAuths: { npmName?: string, registerAuthOptions: RegisterServerAuthPassOptions }[] = []
91
92 for (const plugin of plugins) {
93 const auths = plugin.idAndPassAuths
94
95 for (const auth of auths) {
96 pluginAuths.push({
97 npmName: plugin.npmName,
98 registerAuthOptions: auth
99 })
100 }
101 }
102
103 pluginAuths.sort((a, b) => {
104 const aWeight = a.registerAuthOptions.getWeight()
105 const bWeight = b.registerAuthOptions.getWeight()
106
107 // DESC weight order
108 if (aWeight === bWeight) return 0
109 if (aWeight < bWeight) return 1
110 return -1
111 })
112
113 const loginOptions = {
114 id: username,
115 password
116 }
117
118 for (const pluginAuth of pluginAuths) {
119 const authOptions = pluginAuth.registerAuthOptions
120 const authName = authOptions.authName
121 const npmName = pluginAuth.npmName
122
123 logger.debug(
124 'Using auth method %s of plugin %s to login %s with weight %d.',
125 authName, npmName, loginOptions.id, authOptions.getWeight()
126 )
127
128 try {
129 const loginResult = await authOptions.login(loginOptions)
130
131 if (!loginResult) continue
132 if (!isAuthResultValid(pluginAuth.npmName, authOptions.authName, loginResult)) continue
133
134 logger.info(
135 'Login success with auth method %s of plugin %s for %s.',
136 authName, npmName, loginOptions.id
137 )
138
139 return {
140 bypass: true,
141 pluginName: pluginAuth.npmName,
142 authName: authOptions.authName,
143 user: buildUserResult(loginResult)
144 }
145 } catch (err) {
146 logger.error('Error in auth method %s of plugin %s', authOptions.authName, pluginAuth.npmName, { err })
147 }
148 }
149
150 return undefined
151 }
152
153 function getBypassFromExternalAuth (username: string, externalAuthToken: string) {
154 const obj = authBypassTokens.get(externalAuthToken)
155 if (!obj) throw new Error('Cannot authenticate user with unknown bypass token')
156
157 const { expires, user, authName, npmName } = obj
158
159 const now = new Date()
160 if (now.getTime() > expires.getTime()) {
161 throw new Error('Cannot authenticate user with an expired external auth token')
162 }
163
164 if (user.username !== username) {
165 throw new Error(`Cannot authenticate user ${user.username} with invalid username ${username}`)
166 }
167
168 logger.info(
169 'Auth success with external auth method %s of plugin %s for %s.',
170 authName, npmName, user.email
171 )
172
173 return {
174 bypass: true,
175 pluginName: npmName,
176 authName,
177 user
178 }
179 }
180
181 function isAuthResultValid (npmName: string, authName: string, result: RegisterServerAuthenticatedResult) {
182 const returnError = (field: string) => {
183 logger.error('Auth method %s of plugin %s did not provide a valid %s.', authName, npmName, field, { [field]: result[field] })
184 return false
185 }
186
187 if (!isUserUsernameValid(result.username)) return returnError('username')
188 if (!result.email) return returnError('email')
189
190 // Following fields are optional
191 if (result.role && !isUserRoleValid(result.role)) return returnError('role')
192 if (result.displayName && !isUserDisplayNameValid(result.displayName)) return returnError('displayName')
193 if (result.adminFlags && !isUserAdminFlagsValid(result.adminFlags)) return returnError('adminFlags')
194 if (result.videoQuota && !isUserVideoQuotaValid(result.videoQuota + '')) return returnError('videoQuota')
195 if (result.videoQuotaDaily && !isUserVideoQuotaDailyValid(result.videoQuotaDaily + '')) return returnError('videoQuotaDaily')
196
197 return true
198 }
199
200 function buildUserResult (pluginResult: RegisterServerAuthenticatedResult) {
201 return {
202 username: pluginResult.username,
203 email: pluginResult.email,
204 role: pluginResult.role ?? UserRole.USER,
205 displayName: pluginResult.displayName || pluginResult.username,
206
207 adminFlags: pluginResult.adminFlags ?? UserAdminFlag.NONE,
208
209 videoQuota: pluginResult.videoQuota,
210 videoQuotaDaily: pluginResult.videoQuotaDaily
211 }
212 }
213
214 // ---------------------------------------------------------------------------
215
216 export {
217 onExternalUserAuthenticated,
218 getBypassFromExternalAuth,
219 getAuthNameFromRefreshGrant,
220 getBypassFromPasswordGrant
221 }