diff options
author | Chocobozzz <me@florianbigard.com> | 2021-03-12 15:20:46 +0100 |
---|---|---|
committer | Chocobozzz <me@florianbigard.com> | 2021-03-24 18:18:41 +0100 |
commit | f43db2f46ee50bacb402a6ef42d768694c2bc9a8 (patch) | |
tree | bce2574e94d48e8602387615a07ee691e98e23e4 /server/lib/auth/oauth-model.ts | |
parent | cae2df6bdc3c3590df32bf7431a617177be30429 (diff) | |
download | PeerTube-f43db2f46ee50bacb402a6ef42d768694c2bc9a8.tar.gz PeerTube-f43db2f46ee50bacb402a6ef42d768694c2bc9a8.tar.zst PeerTube-f43db2f46ee50bacb402a6ef42d768694c2bc9a8.zip |
Refactor auth flow
Reimplement some node-oauth2-server methods to remove hacky code needed by our external
login workflow
Diffstat (limited to 'server/lib/auth/oauth-model.ts')
-rw-r--r-- | server/lib/auth/oauth-model.ts | 245 |
1 files changed, 245 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..c74869ee2 --- /dev/null +++ b/server/lib/auth/oauth-model.ts | |||
@@ -0,0 +1,245 @@ | |||
1 | import { AccessDeniedError } from 'oauth2-server' | ||
2 | import { PluginManager } from '@server/lib/plugins/plugin-manager' | ||
3 | import { ActorModel } from '@server/models/activitypub/actor' | ||
4 | import { MOAuthClient } from '@server/types/models' | ||
5 | import { MOAuthTokenUser } from '@server/types/models/oauth/oauth-token' | ||
6 | import { MUser } from '@server/types/models/user/user' | ||
7 | import { UserAdminFlag } from '@shared/models/users/user-flag.model' | ||
8 | import { UserRole } from '@shared/models/users/user-role' | ||
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 | ||
22 | } | ||
23 | |||
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 | ||
33 | } | ||
34 | } | ||
35 | |||
36 | async function getAccessToken (bearerToken: string) { | ||
37 | logger.debug('Getting access token (bearerToken: ' + bearerToken + ').') | ||
38 | |||
39 | if (!bearerToken) return undefined | ||
40 | |||
41 | let tokenModel: MOAuthTokenUser | ||
42 | |||
43 | if (TokensCache.Instance.hasToken(bearerToken)) { | ||
44 | tokenModel = TokensCache.Instance.getByToken(bearerToken) | ||
45 | } else { | ||
46 | tokenModel = await OAuthTokenModel.getByTokenAndPopulateUser(bearerToken) | ||
47 | |||
48 | if (tokenModel) TokensCache.Instance.setToken(tokenModel) | ||
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 | ||
60 | } | ||
61 | |||
62 | function getClient (clientId: string, clientSecret: string) { | ||
63 | logger.debug('Getting Client (clientId: ' + clientId + ', clientSecret: ' + clientSecret + ').') | ||
64 | |||
65 | return OAuthClientModel.getByIdAndSecret(clientId, clientSecret) | ||
66 | } | ||
67 | |||
68 | async function getRefreshToken (refreshToken: string) { | ||
69 | logger.debug('Getting RefreshToken (refreshToken: ' + refreshToken + ').') | ||
70 | |||
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 | ||
83 | } | ||
84 | |||
85 | async function getUser (usernameOrEmail?: string, password?: string, bypassLogin?: BypassLogin) { | ||
86 | // Special treatment coming from a plugin | ||
87 | if (bypassLogin && bypassLogin.bypass === true) { | ||
88 | logger.info('Bypassing oauth login by plugin %s.', bypassLogin.pluginName) | ||
89 | |||
90 | let user = await UserModel.loadByEmail(bypassLogin.user.email) | ||
91 | if (!user) user = await createUserFromExternal(bypassLogin.pluginName, bypassLogin.user) | ||
92 | |||
93 | // Cannot create a user | ||
94 | if (!user) throw new AccessDeniedError('Cannot create such user: an actor with that name already exists.') | ||
95 | |||
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 | ||
100 | if (user.pluginAuth !== bypassLogin.pluginName) return null | ||
101 | |||
102 | checkUserValidityOrThrow(user) | ||
103 | |||
104 | return user | ||
105 | } | ||
106 | } | ||
107 | |||
108 | logger.debug('Getting User (username/email: ' + usernameOrEmail + ', password: ******).') | ||
109 | |||
110 | const user = await UserModel.loadByUsernameOrEmail(usernameOrEmail) | ||
111 | // If we don't find the user, or if the user belongs to a plugin | ||
112 | if (!user || user.pluginAuth !== null || !password) return null | ||
113 | |||
114 | const passwordMatch = await user.isPasswordMatch(password) | ||
115 | if (passwordMatch !== true) return null | ||
116 | |||
117 | checkUserValidityOrThrow(user) | ||
118 | |||
119 | if (CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION && user.emailVerified === false) { | ||
120 | throw new AccessDeniedError('User email is not verified.') | ||
121 | } | ||
122 | |||
123 | return user | ||
124 | } | ||
125 | |||
126 | async function revokeToken ( | ||
127 | tokenInfo: { refreshToken: string }, | ||
128 | explicitLogout?: boolean | ||
129 | ): Promise<{ success: boolean, redirectUrl?: string }> { | ||
130 | const token = await OAuthTokenModel.getByRefreshTokenAndPopulateUser(tokenInfo.refreshToken) | ||
131 | |||
132 | if (token) { | ||
133 | let redirectUrl: string | ||
134 | |||
135 | if (explicitLogout === true && token.User.pluginAuth && token.authName) { | ||
136 | redirectUrl = await PluginManager.Instance.onLogout(token.User.pluginAuth, token.authName, token.User, this.request) | ||
137 | } | ||
138 | |||
139 | TokensCache.Instance.clearCacheByToken(token.accessToken) | ||
140 | |||
141 | token.destroy() | ||
142 | .catch(err => logger.error('Cannot destroy token when revoking token.', { err })) | ||
143 | |||
144 | return { success: true, redirectUrl } | ||
145 | } | ||
146 | |||
147 | return { success: false } | ||
148 | } | ||
149 | |||
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 | ||
160 | let authName: string = null | ||
161 | |||
162 | if (bypassLogin?.bypass === true) { | ||
163 | authName = bypassLogin.authName | ||
164 | } else if (refreshTokenAuthName) { | ||
165 | authName = refreshTokenAuthName | ||
166 | } | ||
167 | |||
168 | logger.debug('Saving token ' + token.accessToken + ' for client ' + client.id + ' and user ' + user.id + '.') | ||
169 | |||
170 | const tokenToCreate = { | ||
171 | accessToken: token.accessToken, | ||
172 | accessTokenExpiresAt: token.accessTokenExpiresAt, | ||
173 | refreshToken: token.refreshToken, | ||
174 | refreshTokenExpiresAt: token.refreshTokenExpiresAt, | ||
175 | authName, | ||
176 | oAuthClientId: client.id, | ||
177 | userId: user.id | ||
178 | } | ||
179 | |||
180 | const tokenCreated = await OAuthTokenModel.create(tokenToCreate) | ||
181 | |||
182 | user.lastLoginDate = new Date() | ||
183 | await user.save() | ||
184 | |||
185 | return { | ||
186 | accessToken: tokenCreated.accessToken, | ||
187 | accessTokenExpiresAt: tokenCreated.accessTokenExpiresAt, | ||
188 | refreshToken: tokenCreated.refreshToken, | ||
189 | refreshTokenExpiresAt: tokenCreated.refreshTokenExpiresAt, | ||
190 | client, | ||
191 | user, | ||
192 | accessTokenExpiresIn: buildExpiresIn(tokenCreated.accessTokenExpiresAt), | ||
193 | refreshTokenExpiresIn: buildExpiresIn(tokenCreated.refreshTokenExpiresAt) | ||
194 | } | ||
195 | } | ||
196 | |||
197 | export { | ||
198 | getAccessToken, | ||
199 | getClient, | ||
200 | getRefreshToken, | ||
201 | getUser, | ||
202 | revokeToken, | ||
203 | saveToken | ||
204 | } | ||
205 | |||
206 | // --------------------------------------------------------------------------- | ||
207 | |||
208 | async function createUserFromExternal (pluginAuth: string, options: { | ||
209 | username: string | ||
210 | email: string | ||
211 | role: UserRole | ||
212 | displayName: string | ||
213 | }) { | ||
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 | |||
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 | } | ||
238 | |||
239 | function checkUserValidityOrThrow (user: MUser) { | ||
240 | if (user.blocked) throw new AccessDeniedError('User is blocked.') | ||
241 | } | ||
242 | |||
243 | function buildExpiresIn (expiresAt: Date) { | ||
244 | return Math.floor((expiresAt.getTime() - new Date().getTime()) / 1000) | ||
245 | } | ||