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