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