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