]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/auth/oauth-model.ts
Prevent invalid watch sections
[github/Chocobozzz/PeerTube.git] / server / lib / auth / oauth-model.ts
1 import express from 'express'
2 import { AccessDeniedError } from '@node-oauth/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 { pick } from '@shared/core-utils'
9 import { UserRole } from '@shared/models/users/user-role'
10 import { logger } from '../../helpers/logger'
11 import { CONFIG } from '../../initializers/config'
12 import { OAuthClientModel } from '../../models/oauth/oauth-client'
13 import { OAuthTokenModel } from '../../models/oauth/oauth-token'
14 import { UserModel } from '../../models/user/user'
15 import { buildUser, 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
120 // If we don't find the user, or if the user belongs to a plugin
121 if (!user || user.pluginAuth !== null || !password) return null
122
123 const passwordMatch = await user.isPasswordMatch(password)
124 if (passwordMatch !== true) return null
125
126 checkUserValidityOrThrow(user)
127
128 if (CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION && user.emailVerified === false) {
129 throw new AccessDeniedError('User email is not verified.')
130 }
131
132 return user
133 }
134
135 async function revokeToken (
136 tokenInfo: { refreshToken: string },
137 options: {
138 req?: express.Request
139 explicitLogout?: boolean
140 } = {}
141 ): Promise<{ success: boolean, redirectUrl?: string }> {
142 const { req, explicitLogout } = options
143
144 const token = await OAuthTokenModel.getByRefreshTokenAndPopulateUser(tokenInfo.refreshToken)
145
146 if (token) {
147 let redirectUrl: string
148
149 if (explicitLogout === true && token.User.pluginAuth && token.authName) {
150 redirectUrl = await PluginManager.Instance.onLogout(token.User.pluginAuth, token.authName, token.User, req)
151 }
152
153 TokensCache.Instance.clearCacheByToken(token.accessToken)
154
155 token.destroy()
156 .catch(err => logger.error('Cannot destroy token when revoking token.', { err }))
157
158 return { success: true, redirectUrl }
159 }
160
161 return { success: false }
162 }
163
164 async function saveToken (
165 token: TokenInfo,
166 client: MOAuthClient,
167 user: MUser,
168 options: {
169 refreshTokenAuthName?: string
170 bypassLogin?: BypassLogin
171 } = {}
172 ) {
173 const { refreshTokenAuthName, bypassLogin } = options
174 let authName: string = null
175
176 if (bypassLogin?.bypass === true) {
177 authName = bypassLogin.authName
178 } else if (refreshTokenAuthName) {
179 authName = refreshTokenAuthName
180 }
181
182 logger.debug('Saving token ' + token.accessToken + ' for client ' + client.id + ' and user ' + user.id + '.')
183
184 const tokenToCreate = {
185 accessToken: token.accessToken,
186 accessTokenExpiresAt: token.accessTokenExpiresAt,
187 refreshToken: token.refreshToken,
188 refreshTokenExpiresAt: token.refreshTokenExpiresAt,
189 authName,
190 oAuthClientId: client.id,
191 userId: user.id
192 }
193
194 const tokenCreated = await OAuthTokenModel.create(tokenToCreate)
195
196 user.lastLoginDate = new Date()
197 await user.save()
198
199 return {
200 accessToken: tokenCreated.accessToken,
201 accessTokenExpiresAt: tokenCreated.accessTokenExpiresAt,
202 refreshToken: tokenCreated.refreshToken,
203 refreshTokenExpiresAt: tokenCreated.refreshTokenExpiresAt,
204 client,
205 user,
206 accessTokenExpiresIn: buildExpiresIn(tokenCreated.accessTokenExpiresAt),
207 refreshTokenExpiresIn: buildExpiresIn(tokenCreated.refreshTokenExpiresAt)
208 }
209 }
210
211 export {
212 getAccessToken,
213 getClient,
214 getRefreshToken,
215 getUser,
216 revokeToken,
217 saveToken
218 }
219
220 // ---------------------------------------------------------------------------
221
222 async function createUserFromExternal (pluginAuth: string, options: {
223 username: string
224 email: string
225 role: UserRole
226 displayName: string
227 }) {
228 // Check an actor does not already exists with that name (removed user)
229 const actor = await ActorModel.loadLocalByName(options.username)
230 if (actor) return null
231
232 const userToCreate = buildUser({
233 ...pick(options, [ 'username', 'email', 'role' ]),
234
235 emailVerified: null,
236 password: null,
237 pluginAuth
238 })
239
240 const { user } = await createUserAccountAndChannelAndPlaylist({
241 userToCreate,
242 userDisplayName: options.displayName
243 })
244
245 return user
246 }
247
248 function checkUserValidityOrThrow (user: MUser) {
249 if (user.blocked) throw new AccessDeniedError('User is blocked.')
250 }
251
252 function buildExpiresIn (expiresAt: Date) {
253 return Math.floor((expiresAt.getTime() - new Date().getTime()) / 1000)
254 }