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