]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/auth/oauth-model.ts
Add log on user plugin auth conflict
[github/Chocobozzz/PeerTube.git] / server / lib / auth / oauth-model.ts
1 import express from 'express'
2 import { AccessDeniedError } from 'oauth2-server'
3 import { PluginManager } from '@server/lib/plugins/plugin-manager'
4 import { ActorModel } from '@server/models/actor/actor'
5 import { MOAuthClient } from '@server/types/models'
6 import { MOAuthTokenUser } from '@server/types/models/oauth/oauth-token'
7 import { MUser } from '@server/types/models/user/user'
8 import { UserAdminFlag } from '@shared/models/users/user-flag.model'
9 import { UserRole } from '@shared/models/users/user-role'
10 import { logger } from '../../helpers/logger'
11 import { CONFIG } from '../../initializers/config'
12 import { UserModel } from '../../models/user/user'
13 import { OAuthClientModel } from '../../models/oauth/oauth-client'
14 import { OAuthTokenModel } from '../../models/oauth/oauth-token'
15 import { createUserAccountAndChannelAndPlaylist } from '../user'
16 import { TokensCache } from './tokens-cache'
17
18 type TokenInfo = {
19 accessToken: string
20 refreshToken: string
21 accessTokenExpiresAt: Date
22 refreshTokenExpiresAt: Date
23 }
24
25 export type BypassLogin = {
26 bypass: boolean
27 pluginName: string
28 authName?: string
29 user: {
30 username: string
31 email: string
32 displayName: string
33 role: UserRole
34 }
35 }
36
37 async function getAccessToken (bearerToken: string) {
38 logger.debug('Getting access token (bearerToken: ' + bearerToken + ').')
39
40 if (!bearerToken) return undefined
41
42 let tokenModel: MOAuthTokenUser
43
44 if (TokensCache.Instance.hasToken(bearerToken)) {
45 tokenModel = TokensCache.Instance.getByToken(bearerToken)
46 } else {
47 tokenModel = await OAuthTokenModel.getByTokenAndPopulateUser(bearerToken)
48
49 if (tokenModel) TokensCache.Instance.setToken(tokenModel)
50 }
51
52 if (!tokenModel) return undefined
53
54 if (tokenModel.User.pluginAuth) {
55 const valid = await PluginManager.Instance.isTokenValid(tokenModel, 'access')
56
57 if (valid !== true) return undefined
58 }
59
60 return tokenModel
61 }
62
63 function getClient (clientId: string, clientSecret: string) {
64 logger.debug('Getting Client (clientId: ' + clientId + ', clientSecret: ' + clientSecret + ').')
65
66 return OAuthClientModel.getByIdAndSecret(clientId, clientSecret)
67 }
68
69 async function getRefreshToken (refreshToken: string) {
70 logger.debug('Getting RefreshToken (refreshToken: ' + refreshToken + ').')
71
72 const tokenInfo = await OAuthTokenModel.getByRefreshTokenAndPopulateClient(refreshToken)
73 if (!tokenInfo) return undefined
74
75 const tokenModel = tokenInfo.token
76
77 if (tokenModel.User.pluginAuth) {
78 const valid = await PluginManager.Instance.isTokenValid(tokenModel, 'refresh')
79
80 if (valid !== true) return undefined
81 }
82
83 return tokenInfo
84 }
85
86 async function getUser (usernameOrEmail?: string, password?: string, bypassLogin?: BypassLogin) {
87 // Special treatment coming from a plugin
88 if (bypassLogin && bypassLogin.bypass === true) {
89 logger.info('Bypassing oauth login by plugin %s.', bypassLogin.pluginName)
90
91 let user = await UserModel.loadByEmail(bypassLogin.user.email)
92 if (!user) user = await createUserFromExternal(bypassLogin.pluginName, bypassLogin.user)
93
94 // Cannot create a user
95 if (!user) throw new AccessDeniedError('Cannot create such user: an actor with that name already exists.')
96
97 // If the user does not belongs to a plugin, it was created before its installation
98 // Then we just go through a regular login process
99 if (user.pluginAuth !== null) {
100 // This user does not belong to this plugin, skip it
101 if (user.pluginAuth !== bypassLogin.pluginName) {
102 logger.info(
103 'Cannot bypass oauth login by plugin %s because %s has another plugin auth method (%s).',
104 bypassLogin.pluginName, bypassLogin.user.email, user.pluginAuth
105 )
106
107 return null
108 }
109
110 checkUserValidityOrThrow(user)
111
112 return user
113 }
114 }
115
116 logger.debug('Getting User (username/email: ' + usernameOrEmail + ', password: ******).')
117
118 const user = await UserModel.loadByUsernameOrEmail(usernameOrEmail)
119 // If we don't find the user, or if the user belongs to a plugin
120 if (!user || user.pluginAuth !== null || !password) return null
121
122 const passwordMatch = await user.isPasswordMatch(password)
123 if (passwordMatch !== true) return null
124
125 checkUserValidityOrThrow(user)
126
127 if (CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION && user.emailVerified === false) {
128 throw new AccessDeniedError('User email is not verified.')
129 }
130
131 return user
132 }
133
134 async function revokeToken (
135 tokenInfo: { refreshToken: string },
136 options: {
137 req?: express.Request
138 explicitLogout?: boolean
139 } = {}
140 ): Promise<{ success: boolean, redirectUrl?: string }> {
141 const { req, explicitLogout } = options
142
143 const token = await OAuthTokenModel.getByRefreshTokenAndPopulateUser(tokenInfo.refreshToken)
144
145 if (token) {
146 let redirectUrl: string
147
148 if (explicitLogout === true && token.User.pluginAuth && token.authName) {
149 redirectUrl = await PluginManager.Instance.onLogout(token.User.pluginAuth, token.authName, token.User, req)
150 }
151
152 TokensCache.Instance.clearCacheByToken(token.accessToken)
153
154 token.destroy()
155 .catch(err => logger.error('Cannot destroy token when revoking token.', { err }))
156
157 return { success: true, redirectUrl }
158 }
159
160 return { success: false }
161 }
162
163 async function saveToken (
164 token: TokenInfo,
165 client: MOAuthClient,
166 user: MUser,
167 options: {
168 refreshTokenAuthName?: string
169 bypassLogin?: BypassLogin
170 } = {}
171 ) {
172 const { refreshTokenAuthName, bypassLogin } = options
173 let authName: string = null
174
175 if (bypassLogin?.bypass === true) {
176 authName = bypassLogin.authName
177 } else if (refreshTokenAuthName) {
178 authName = refreshTokenAuthName
179 }
180
181 logger.debug('Saving token ' + token.accessToken + ' for client ' + client.id + ' and user ' + user.id + '.')
182
183 const tokenToCreate = {
184 accessToken: token.accessToken,
185 accessTokenExpiresAt: token.accessTokenExpiresAt,
186 refreshToken: token.refreshToken,
187 refreshTokenExpiresAt: token.refreshTokenExpiresAt,
188 authName,
189 oAuthClientId: client.id,
190 userId: user.id
191 }
192
193 const tokenCreated = await OAuthTokenModel.create(tokenToCreate)
194
195 user.lastLoginDate = new Date()
196 await user.save()
197
198 return {
199 accessToken: tokenCreated.accessToken,
200 accessTokenExpiresAt: tokenCreated.accessTokenExpiresAt,
201 refreshToken: tokenCreated.refreshToken,
202 refreshTokenExpiresAt: tokenCreated.refreshTokenExpiresAt,
203 client,
204 user,
205 accessTokenExpiresIn: buildExpiresIn(tokenCreated.accessTokenExpiresAt),
206 refreshTokenExpiresIn: buildExpiresIn(tokenCreated.refreshTokenExpiresAt)
207 }
208 }
209
210 export {
211 getAccessToken,
212 getClient,
213 getRefreshToken,
214 getUser,
215 revokeToken,
216 saveToken
217 }
218
219 // ---------------------------------------------------------------------------
220
221 async function createUserFromExternal (pluginAuth: string, options: {
222 username: string
223 email: string
224 role: UserRole
225 displayName: string
226 }) {
227 // Check an actor does not already exists with that name (removed user)
228 const actor = await ActorModel.loadLocalByName(options.username)
229 if (actor) return null
230
231 const userToCreate = new UserModel({
232 username: options.username,
233 password: null,
234 email: options.email,
235 nsfwPolicy: CONFIG.INSTANCE.DEFAULT_NSFW_POLICY,
236 p2pEnabled: CONFIG.DEFAULTS.P2P.WEBAPP.ENABLED,
237 autoPlayVideo: true,
238 role: options.role,
239 videoQuota: CONFIG.USER.VIDEO_QUOTA,
240 videoQuotaDaily: CONFIG.USER.VIDEO_QUOTA_DAILY,
241 adminFlags: UserAdminFlag.NONE,
242 pluginAuth
243 }) as MUser
244
245 const { user } = await createUserAccountAndChannelAndPlaylist({
246 userToCreate,
247 userDisplayName: options.displayName
248 })
249
250 return user
251 }
252
253 function checkUserValidityOrThrow (user: MUser) {
254 if (user.blocked) throw new AccessDeniedError('User is blocked.')
255 }
256
257 function buildExpiresIn (expiresAt: Date) {
258 return Math.floor((expiresAt.getTime() - new Date().getTime()) / 1000)
259 }