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'
19 type TokenInfo = { accessToken: string, refreshToken: string, accessTokenExpiresAt: Date, refreshTokenExpiresAt: Date }
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 })
24 // ---------------------------------------------------------------------------
26 function deleteUserToken (userId: number, t?: Transaction) {
27 clearCacheByUserId(userId)
29 return OAuthTokenModel.deleteUserToken(userId, t)
32 function clearCacheByUserId (userId: number) {
33 const token = userHavingToken.get(userId)
35 if (token !== undefined) {
36 accessTokenCache.del(token)
37 userHavingToken.del(userId)
41 function clearCacheByToken (token: string) {
42 const tokenModel = accessTokenCache.get(token)
44 if (tokenModel !== undefined) {
45 userHavingToken.del(tokenModel.userId)
46 accessTokenCache.del(token)
50 async function getAccessToken (bearerToken: string) {
51 logger.debug('Getting access token (bearerToken: ' + bearerToken + ').')
53 if (!bearerToken) return undefined
55 let tokenModel: MOAuthTokenUser
57 if (accessTokenCache.has(bearerToken)) {
58 tokenModel = accessTokenCache.get(bearerToken)
60 tokenModel = await OAuthTokenModel.getByTokenAndPopulateUser(bearerToken)
63 accessTokenCache.set(bearerToken, tokenModel)
64 userHavingToken.set(tokenModel.userId, tokenModel.accessToken)
68 if (!tokenModel) return undefined
70 if (tokenModel.User.pluginAuth) {
71 const valid = await PluginManager.Instance.isTokenValid(tokenModel, 'access')
73 if (valid !== true) return undefined
79 function getClient (clientId: string, clientSecret: string) {
80 logger.debug('Getting Client (clientId: ' + clientId + ', clientSecret: ' + clientSecret + ').')
82 return OAuthClientModel.getByIdAndSecret(clientId, clientSecret)
85 async function getRefreshToken (refreshToken: string) {
86 logger.debug('Getting RefreshToken (refreshToken: ' + refreshToken + ').')
88 const tokenInfo = await OAuthTokenModel.getByRefreshTokenAndPopulateClient(refreshToken)
89 if (!tokenInfo) return undefined
91 const tokenModel = tokenInfo.token
93 if (tokenModel.User.pluginAuth) {
94 const valid = await PluginManager.Instance.isTokenValid(tokenModel, 'refresh')
96 if (valid !== true) return undefined
102 async function getUser (usernameOrEmail?: string, password?: string) {
103 const res: express.Response = this.request.res
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)
110 let user = await UserModel.loadByEmail(obj.user.email)
111 if (!user) user = await createUserFromExternal(obj.pluginName, obj.user)
113 // Cannot create a user
114 if (!user) throw new AccessDeniedError('Cannot create such user: an actor with that name already exists.')
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
126 logger.debug('Getting User (username/email: ' + usernameOrEmail + ', password: ******).')
128 const user = await UserModel.loadByUsernameOrEmail(usernameOrEmail)
129 // If we don't find the user, or if the user belongs to a plugin
130 if (!user || user.pluginAuth !== null || !password) return null
132 const passwordMatch = await user.isPasswordMatch(password)
133 if (passwordMatch !== true) return null
135 if (user.blocked) throw new AccessDeniedError('User is blocked.')
137 if (CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION && user.emailVerified === false) {
138 throw new AccessDeniedError('User email is not verified.')
144 async function revokeToken (tokenInfo: { refreshToken: string }): Promise<{ success: boolean, redirectUrl?: string }> {
145 const res: express.Response = this.request.res
146 const token = await OAuthTokenModel.getByRefreshTokenAndPopulateUser(tokenInfo.refreshToken)
149 let redirectUrl: string
151 if (res.locals.explicitLogout === true && token.User.pluginAuth && token.authName) {
152 redirectUrl = await PluginManager.Instance.onLogout(token.User.pluginAuth, token.authName, token.User, this.request)
155 clearCacheByToken(token.accessToken)
158 .catch(err => logger.error('Cannot destroy token when revoking token.', { err }))
160 return { success: true, redirectUrl }
163 return { success: false }
166 async function saveToken (token: TokenInfo, client: OAuthClientModel, user: UserModel) {
167 const res: express.Response = this.request.res
169 let authName: string = null
170 if (res.locals.bypassLogin?.bypass === true) {
171 authName = res.locals.bypassLogin.authName
172 } else if (res.locals.refreshTokenAuthName) {
173 authName = res.locals.refreshTokenAuthName
176 logger.debug('Saving token ' + token.accessToken + ' for client ' + client.id + ' and user ' + user.id + '.')
178 const tokenToCreate = {
179 accessToken: token.accessToken,
180 accessTokenExpiresAt: token.accessTokenExpiresAt,
181 refreshToken: token.refreshToken,
182 refreshTokenExpiresAt: token.refreshTokenExpiresAt,
184 oAuthClientId: client.id,
188 const tokenCreated = await OAuthTokenModel.create(tokenToCreate)
190 user.lastLoginDate = new Date()
193 return Object.assign(tokenCreated, { client, user })
196 // ---------------------------------------------------------------------------
198 // See https://github.com/oauthjs/node-oauth2-server/wiki/Model-specification for the model specifications
211 async function createUserFromExternal (pluginAuth: string, options: {
217 // Check an actor does not already exists with that name (removed user)
218 const actor = await ActorModel.loadLocalByName(options.username)
219 if (actor) return null
221 const userToCreate = new UserModel({
222 username: options.username,
224 email: options.email,
225 nsfwPolicy: CONFIG.INSTANCE.DEFAULT_NSFW_POLICY,
228 videoQuota: CONFIG.USER.VIDEO_QUOTA,
229 videoQuotaDaily: CONFIG.USER.VIDEO_QUOTA_DAILY,
230 adminFlags: UserAdminFlag.NONE,
234 const { user } = await createUserAccountAndChannelAndPlaylist({
236 userDisplayName: options.displayName