aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/lib/auth/oauth-model.ts
diff options
context:
space:
mode:
Diffstat (limited to 'server/lib/auth/oauth-model.ts')
-rw-r--r--server/lib/auth/oauth-model.ts245
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 @@
1import { AccessDeniedError } from 'oauth2-server'
2import { PluginManager } from '@server/lib/plugins/plugin-manager'
3import { ActorModel } from '@server/models/activitypub/actor'
4import { MOAuthClient } from '@server/types/models'
5import { MOAuthTokenUser } from '@server/types/models/oauth/oauth-token'
6import { MUser } from '@server/types/models/user/user'
7import { UserAdminFlag } from '@shared/models/users/user-flag.model'
8import { UserRole } from '@shared/models/users/user-role'
9import { logger } from '../../helpers/logger'
10import { CONFIG } from '../../initializers/config'
11import { UserModel } from '../../models/account/user'
12import { OAuthClientModel } from '../../models/oauth/oauth-client'
13import { OAuthTokenModel } from '../../models/oauth/oauth-token'
14import { createUserAccountAndChannelAndPlaylist } from '../user'
15import { TokensCache } from './tokens-cache'
16
17type TokenInfo = {
18 accessToken: string
19 refreshToken: string
20 accessTokenExpiresAt: Date
21 refreshTokenExpiresAt: Date
22}
23
24export 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
36async 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
62function getClient (clientId: string, clientSecret: string) {
63 logger.debug('Getting Client (clientId: ' + clientId + ', clientSecret: ' + clientSecret + ').')
64
65 return OAuthClientModel.getByIdAndSecret(clientId, clientSecret)
66}
67
68async 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
85async 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
126async 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
150async 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
197export {
198 getAccessToken,
199 getClient,
200 getRefreshToken,
201 getUser,
202 revokeToken,
203 saveToken
204}
205
206// ---------------------------------------------------------------------------
207
208async 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
239function checkUserValidityOrThrow (user: MUser) {
240 if (user.blocked) throw new AccessDeniedError('User is blocked.')
241}
242
243function buildExpiresIn (expiresAt: Date) {
244 return Math.floor((expiresAt.getTime() - new Date().getTime()) / 1000)
245}