diff options
Diffstat (limited to 'server/lib/auth/oauth-model.ts')
-rw-r--r-- | server/lib/auth/oauth-model.ts | 251 |
1 files changed, 251 insertions, 0 deletions
diff --git a/server/lib/auth/oauth-model.ts b/server/lib/auth/oauth-model.ts new file mode 100644 index 000000000..b9c69eb2d --- /dev/null +++ b/server/lib/auth/oauth-model.ts | |||
@@ -0,0 +1,251 @@ | |||
1 | import * as express from 'express' | ||
2 | import { AccessDeniedError } from 'oauth2-server' | ||
3 | import { PluginManager } from '@server/lib/plugins/plugin-manager' | ||
4 | import { ActorModel } from '@server/models/activitypub/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/account/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) return null | ||
102 | |||
103 | checkUserValidityOrThrow(user) | ||
104 | |||
105 | return user | ||
106 | } | ||
107 | } | ||
108 | |||
109 | logger.debug('Getting User (username/email: ' + usernameOrEmail + ', password: ******).') | ||
110 | |||
111 | const user = await UserModel.loadByUsernameOrEmail(usernameOrEmail) | ||
112 | // If we don't find the user, or if the user belongs to a plugin | ||
113 | if (!user || user.pluginAuth !== null || !password) return null | ||
114 | |||
115 | const passwordMatch = await user.isPasswordMatch(password) | ||
116 | if (passwordMatch !== true) return null | ||
117 | |||
118 | checkUserValidityOrThrow(user) | ||
119 | |||
120 | if (CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION && user.emailVerified === false) { | ||
121 | throw new AccessDeniedError('User email is not verified.') | ||
122 | } | ||
123 | |||
124 | return user | ||
125 | } | ||
126 | |||
127 | async function revokeToken ( | ||
128 | tokenInfo: { refreshToken: string }, | ||
129 | options: { | ||
130 | req?: express.Request | ||
131 | explicitLogout?: boolean | ||
132 | } = {} | ||
133 | ): Promise<{ success: boolean, redirectUrl?: string }> { | ||
134 | const { req, explicitLogout } = options | ||
135 | |||
136 | const token = await OAuthTokenModel.getByRefreshTokenAndPopulateUser(tokenInfo.refreshToken) | ||
137 | |||
138 | if (token) { | ||
139 | let redirectUrl: string | ||
140 | |||
141 | if (explicitLogout === true && token.User.pluginAuth && token.authName) { | ||
142 | redirectUrl = await PluginManager.Instance.onLogout(token.User.pluginAuth, token.authName, token.User, req) | ||
143 | } | ||
144 | |||
145 | TokensCache.Instance.clearCacheByToken(token.accessToken) | ||
146 | |||
147 | token.destroy() | ||
148 | .catch(err => logger.error('Cannot destroy token when revoking token.', { err })) | ||
149 | |||
150 | return { success: true, redirectUrl } | ||
151 | } | ||
152 | |||
153 | return { success: false } | ||
154 | } | ||
155 | |||
156 | async function saveToken ( | ||
157 | token: TokenInfo, | ||
158 | client: MOAuthClient, | ||
159 | user: MUser, | ||
160 | options: { | ||
161 | refreshTokenAuthName?: string | ||
162 | bypassLogin?: BypassLogin | ||
163 | } = {} | ||
164 | ) { | ||
165 | const { refreshTokenAuthName, bypassLogin } = options | ||
166 | let authName: string = null | ||
167 | |||
168 | if (bypassLogin?.bypass === true) { | ||
169 | authName = bypassLogin.authName | ||
170 | } else if (refreshTokenAuthName) { | ||
171 | authName = refreshTokenAuthName | ||
172 | } | ||
173 | |||
174 | logger.debug('Saving token ' + token.accessToken + ' for client ' + client.id + ' and user ' + user.id + '.') | ||
175 | |||
176 | const tokenToCreate = { | ||
177 | accessToken: token.accessToken, | ||
178 | accessTokenExpiresAt: token.accessTokenExpiresAt, | ||
179 | refreshToken: token.refreshToken, | ||
180 | refreshTokenExpiresAt: token.refreshTokenExpiresAt, | ||
181 | authName, | ||
182 | oAuthClientId: client.id, | ||
183 | userId: user.id | ||
184 | } | ||
185 | |||
186 | const tokenCreated = await OAuthTokenModel.create(tokenToCreate) | ||
187 | |||
188 | user.lastLoginDate = new Date() | ||
189 | await user.save() | ||
190 | |||
191 | return { | ||
192 | accessToken: tokenCreated.accessToken, | ||
193 | accessTokenExpiresAt: tokenCreated.accessTokenExpiresAt, | ||
194 | refreshToken: tokenCreated.refreshToken, | ||
195 | refreshTokenExpiresAt: tokenCreated.refreshTokenExpiresAt, | ||
196 | client, | ||
197 | user, | ||
198 | accessTokenExpiresIn: buildExpiresIn(tokenCreated.accessTokenExpiresAt), | ||
199 | refreshTokenExpiresIn: buildExpiresIn(tokenCreated.refreshTokenExpiresAt) | ||
200 | } | ||
201 | } | ||
202 | |||
203 | export { | ||
204 | getAccessToken, | ||
205 | getClient, | ||
206 | getRefreshToken, | ||
207 | getUser, | ||
208 | revokeToken, | ||
209 | saveToken | ||
210 | } | ||
211 | |||
212 | // --------------------------------------------------------------------------- | ||
213 | |||
214 | async function createUserFromExternal (pluginAuth: string, options: { | ||
215 | username: string | ||
216 | email: string | ||
217 | role: UserRole | ||
218 | displayName: string | ||
219 | }) { | ||
220 | // Check an actor does not already exists with that name (removed user) | ||
221 | const actor = await ActorModel.loadLocalByName(options.username) | ||
222 | if (actor) return null | ||
223 | |||
224 | const userToCreate = new UserModel({ | ||
225 | username: options.username, | ||
226 | password: null, | ||
227 | email: options.email, | ||
228 | nsfwPolicy: CONFIG.INSTANCE.DEFAULT_NSFW_POLICY, | ||
229 | autoPlayVideo: true, | ||
230 | role: options.role, | ||
231 | videoQuota: CONFIG.USER.VIDEO_QUOTA, | ||
232 | videoQuotaDaily: CONFIG.USER.VIDEO_QUOTA_DAILY, | ||
233 | adminFlags: UserAdminFlag.NONE, | ||
234 | pluginAuth | ||
235 | }) as MUser | ||
236 | |||
237 | const { user } = await createUserAccountAndChannelAndPlaylist({ | ||
238 | userToCreate, | ||
239 | userDisplayName: options.displayName | ||
240 | }) | ||
241 | |||
242 | return user | ||
243 | } | ||
244 | |||
245 | function checkUserValidityOrThrow (user: MUser) { | ||
246 | if (user.blocked) throw new AccessDeniedError('User is blocked.') | ||
247 | } | ||
248 | |||
249 | function buildExpiresIn (expiresAt: Date) { | ||
250 | return Math.floor((expiresAt.getTime() - new Date().getTime()) / 1000) | ||
251 | } | ||