diff options
Diffstat (limited to 'server/lib/oauth-model.ts')
-rw-r--r-- | server/lib/oauth-model.ts | 145 |
1 files changed, 116 insertions, 29 deletions
diff --git a/server/lib/oauth-model.ts b/server/lib/oauth-model.ts index 086856f41..dbcba897a 100644 --- a/server/lib/oauth-model.ts +++ b/server/lib/oauth-model.ts | |||
@@ -1,4 +1,4 @@ | |||
1 | import * as Bluebird from 'bluebird' | 1 | import * as express from 'express' |
2 | import { AccessDeniedError } from 'oauth2-server' | 2 | import { AccessDeniedError } from 'oauth2-server' |
3 | import { logger } from '../helpers/logger' | 3 | import { logger } from '../helpers/logger' |
4 | import { UserModel } from '../models/account/user' | 4 | import { UserModel } from '../models/account/user' |
@@ -9,6 +9,11 @@ import { Transaction } from 'sequelize' | |||
9 | import { CONFIG } from '../initializers/config' | 9 | import { CONFIG } from '../initializers/config' |
10 | import * as LRUCache from 'lru-cache' | 10 | import * as LRUCache from 'lru-cache' |
11 | import { MOAuthTokenUser } from '@server/typings/models/oauth/oauth-token' | 11 | import { MOAuthTokenUser } from '@server/typings/models/oauth/oauth-token' |
12 | import { MUser } from '@server/typings/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' | ||
12 | 17 | ||
13 | type TokenInfo = { accessToken: string, refreshToken: string, accessTokenExpiresAt: Date, refreshTokenExpiresAt: Date } | 18 | type TokenInfo = { accessToken: string, refreshToken: string, accessTokenExpiresAt: Date, refreshTokenExpiresAt: Date } |
14 | 19 | ||
@@ -41,22 +46,33 @@ function clearCacheByToken (token: string) { | |||
41 | } | 46 | } |
42 | } | 47 | } |
43 | 48 | ||
44 | function getAccessToken (bearerToken: string) { | 49 | async function getAccessToken (bearerToken: string) { |
45 | logger.debug('Getting access token (bearerToken: ' + bearerToken + ').') | 50 | logger.debug('Getting access token (bearerToken: ' + bearerToken + ').') |
46 | 51 | ||
47 | if (!bearerToken) return Bluebird.resolve(undefined) | 52 | if (!bearerToken) return undefined |
48 | 53 | ||
49 | if (accessTokenCache.has(bearerToken)) return Bluebird.resolve(accessTokenCache.get(bearerToken)) | 54 | let tokenModel: MOAuthTokenUser |
50 | 55 | ||
51 | return OAuthTokenModel.getByTokenAndPopulateUser(bearerToken) | 56 | if (accessTokenCache.has(bearerToken)) { |
52 | .then(tokenModel => { | 57 | tokenModel = accessTokenCache.get(bearerToken) |
53 | if (tokenModel) { | 58 | } else { |
54 | accessTokenCache.set(bearerToken, tokenModel) | 59 | tokenModel = await OAuthTokenModel.getByTokenAndPopulateUser(bearerToken) |
55 | userHavingToken.set(tokenModel.userId, tokenModel.accessToken) | ||
56 | } | ||
57 | 60 | ||
58 | return tokenModel | 61 | if (tokenModel) { |
59 | }) | 62 | accessTokenCache.set(bearerToken, tokenModel) |
63 | userHavingToken.set(tokenModel.userId, tokenModel.accessToken) | ||
64 | } | ||
65 | } | ||
66 | |||
67 | if (!tokenModel) return undefined | ||
68 | |||
69 | if (tokenModel.User.pluginAuth) { | ||
70 | const valid = await PluginManager.Instance.isTokenValid(tokenModel, 'access') | ||
71 | |||
72 | if (valid !== true) return undefined | ||
73 | } | ||
74 | |||
75 | return tokenModel | ||
60 | } | 76 | } |
61 | 77 | ||
62 | function getClient (clientId: string, clientSecret: string) { | 78 | function getClient (clientId: string, clientSecret: string) { |
@@ -65,20 +81,52 @@ function getClient (clientId: string, clientSecret: string) { | |||
65 | return OAuthClientModel.getByIdAndSecret(clientId, clientSecret) | 81 | return OAuthClientModel.getByIdAndSecret(clientId, clientSecret) |
66 | } | 82 | } |
67 | 83 | ||
68 | function getRefreshToken (refreshToken: string) { | 84 | async function getRefreshToken (refreshToken: string) { |
69 | logger.debug('Getting RefreshToken (refreshToken: ' + refreshToken + ').') | 85 | logger.debug('Getting RefreshToken (refreshToken: ' + refreshToken + ').') |
70 | 86 | ||
71 | return OAuthTokenModel.getByRefreshTokenAndPopulateClient(refreshToken) | 87 | const tokenInfo = await OAuthTokenModel.getByRefreshTokenAndPopulateClient(refreshToken) |
88 | if (!tokenInfo) return undefined | ||
89 | |||
90 | const tokenModel = tokenInfo.token | ||
91 | |||
92 | if (tokenModel.User.pluginAuth) { | ||
93 | const valid = await PluginManager.Instance.isTokenValid(tokenModel, 'refresh') | ||
94 | |||
95 | if (valid !== true) return undefined | ||
96 | } | ||
97 | |||
98 | return tokenInfo | ||
72 | } | 99 | } |
73 | 100 | ||
74 | async function getUser (usernameOrEmail: string, password: string) { | 101 | async function getUser (usernameOrEmail?: string, password?: string) { |
102 | const res: express.Response = this.request.res | ||
103 | |||
104 | // Special treatment coming from a plugin | ||
105 | if (res.locals.bypassLogin && res.locals.bypassLogin.bypass === true) { | ||
106 | const obj = res.locals.bypassLogin | ||
107 | logger.info('Bypassing oauth login by plugin %s.', obj.pluginName) | ||
108 | |||
109 | let user = await UserModel.loadByEmail(obj.user.email) | ||
110 | if (!user) user = await createUserFromExternal(obj.pluginName, obj.user) | ||
111 | |||
112 | // If the user does not belongs to a plugin, it was created before its installation | ||
113 | // Then we just go through a regular login process | ||
114 | if (user.pluginAuth !== null) { | ||
115 | // This user does not belong to this plugin, skip it | ||
116 | if (user.pluginAuth !== obj.pluginName) return null | ||
117 | |||
118 | return user | ||
119 | } | ||
120 | } | ||
121 | |||
75 | logger.debug('Getting User (username/email: ' + usernameOrEmail + ', password: ******).') | 122 | logger.debug('Getting User (username/email: ' + usernameOrEmail + ', password: ******).') |
76 | 123 | ||
77 | const user = await UserModel.loadByUsernameOrEmail(usernameOrEmail) | 124 | const user = await UserModel.loadByUsernameOrEmail(usernameOrEmail) |
78 | if (!user) return null | 125 | // If we don't find the user, or if the user belongs to a plugin |
126 | if (!user || user.pluginAuth !== null) return null | ||
79 | 127 | ||
80 | const passwordMatch = await user.isPasswordMatch(password) | 128 | const passwordMatch = await user.isPasswordMatch(password) |
81 | if (passwordMatch === false) return null | 129 | if (passwordMatch !== true) return null |
82 | 130 | ||
83 | if (user.blocked) throw new AccessDeniedError('User is blocked.') | 131 | if (user.blocked) throw new AccessDeniedError('User is blocked.') |
84 | 132 | ||
@@ -89,29 +137,36 @@ async function getUser (usernameOrEmail: string, password: string) { | |||
89 | return user | 137 | return user |
90 | } | 138 | } |
91 | 139 | ||
92 | async function revokeToken (tokenInfo: TokenInfo) { | 140 | async function revokeToken (tokenInfo: { refreshToken: string }) { |
141 | const res: express.Response = this.request.res | ||
93 | const token = await OAuthTokenModel.getByRefreshTokenAndPopulateUser(tokenInfo.refreshToken) | 142 | const token = await OAuthTokenModel.getByRefreshTokenAndPopulateUser(tokenInfo.refreshToken) |
143 | |||
94 | if (token) { | 144 | if (token) { |
145 | if (res.locals.explicitLogout === true && token.User.pluginAuth && token.authName) { | ||
146 | PluginManager.Instance.onLogout(token.User.pluginAuth, token.authName, token.User) | ||
147 | } | ||
148 | |||
95 | clearCacheByToken(token.accessToken) | 149 | clearCacheByToken(token.accessToken) |
96 | 150 | ||
97 | token.destroy() | 151 | token.destroy() |
98 | .catch(err => logger.error('Cannot destroy token when revoking token.', { err })) | 152 | .catch(err => logger.error('Cannot destroy token when revoking token.', { err })) |
153 | |||
154 | return true | ||
99 | } | 155 | } |
100 | 156 | ||
101 | /* | 157 | return false |
102 | * Thanks to https://github.com/manjeshpv/node-oauth2-server-implementation/blob/master/components/oauth/mongo-models.js | ||
103 | * "As per the discussion we need set older date | ||
104 | * revokeToken will expected return a boolean in future version | ||
105 | * https://github.com/oauthjs/node-oauth2-server/pull/274 | ||
106 | * https://github.com/oauthjs/node-oauth2-server/issues/290" | ||
107 | */ | ||
108 | const expiredToken = token | ||
109 | expiredToken.refreshTokenExpiresAt = new Date('2015-05-28T06:59:53.000Z') | ||
110 | |||
111 | return expiredToken | ||
112 | } | 158 | } |
113 | 159 | ||
114 | async function saveToken (token: TokenInfo, client: OAuthClientModel, user: UserModel) { | 160 | async function saveToken (token: TokenInfo, client: OAuthClientModel, user: UserModel) { |
161 | const res: express.Response = this.request.res | ||
162 | |||
163 | let authName: string = null | ||
164 | if (res.locals.bypassLogin?.bypass === true) { | ||
165 | authName = res.locals.bypassLogin.authName | ||
166 | } else if (res.locals.refreshTokenAuthName) { | ||
167 | authName = res.locals.refreshTokenAuthName | ||
168 | } | ||
169 | |||
115 | logger.debug('Saving token ' + token.accessToken + ' for client ' + client.id + ' and user ' + user.id + '.') | 170 | logger.debug('Saving token ' + token.accessToken + ' for client ' + client.id + ' and user ' + user.id + '.') |
116 | 171 | ||
117 | const tokenToCreate = { | 172 | const tokenToCreate = { |
@@ -119,11 +174,16 @@ async function saveToken (token: TokenInfo, client: OAuthClientModel, user: User | |||
119 | accessTokenExpiresAt: token.accessTokenExpiresAt, | 174 | accessTokenExpiresAt: token.accessTokenExpiresAt, |
120 | refreshToken: token.refreshToken, | 175 | refreshToken: token.refreshToken, |
121 | refreshTokenExpiresAt: token.refreshTokenExpiresAt, | 176 | refreshTokenExpiresAt: token.refreshTokenExpiresAt, |
177 | authName, | ||
122 | oAuthClientId: client.id, | 178 | oAuthClientId: client.id, |
123 | userId: user.id | 179 | userId: user.id |
124 | } | 180 | } |
125 | 181 | ||
126 | const tokenCreated = await OAuthTokenModel.create(tokenToCreate) | 182 | const tokenCreated = await OAuthTokenModel.create(tokenToCreate) |
183 | |||
184 | user.lastLoginDate = new Date() | ||
185 | await user.save() | ||
186 | |||
127 | return Object.assign(tokenCreated, { client, user }) | 187 | return Object.assign(tokenCreated, { client, user }) |
128 | } | 188 | } |
129 | 189 | ||
@@ -141,3 +201,30 @@ export { | |||
141 | revokeToken, | 201 | revokeToken, |
142 | saveToken | 202 | saveToken |
143 | } | 203 | } |
204 | |||
205 | async function createUserFromExternal (pluginAuth: string, options: { | ||
206 | username: string | ||
207 | email: string | ||
208 | role: UserRole | ||
209 | displayName: string | ||
210 | }) { | ||
211 | const userToCreate = new UserModel({ | ||
212 | username: options.username, | ||
213 | password: null, | ||
214 | email: options.email, | ||
215 | nsfwPolicy: CONFIG.INSTANCE.DEFAULT_NSFW_POLICY, | ||
216 | autoPlayVideo: true, | ||
217 | role: options.role, | ||
218 | videoQuota: CONFIG.USER.VIDEO_QUOTA, | ||
219 | videoQuotaDaily: CONFIG.USER.VIDEO_QUOTA_DAILY, | ||
220 | adminFlags: UserAdminFlag.NONE, | ||
221 | pluginAuth | ||
222 | }) as MUser | ||
223 | |||
224 | const { user } = await createUserAccountAndChannelAndPlaylist({ | ||
225 | userToCreate, | ||
226 | userDisplayName: options.displayName | ||
227 | }) | ||
228 | |||
229 | return user | ||
230 | } | ||