oauth-model.ts 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  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'
  18. type TokenInfo = { accessToken: string, refreshToken: string, accessTokenExpiresAt: Date, refreshTokenExpiresAt: Date }
  19. const accessTokenCache = new LRUCache<string, MOAuthTokenUser>({ max: LRU_CACHE.USER_TOKENS.MAX_SIZE })
  20. const userHavingToken = new LRUCache<number, string>({ max: LRU_CACHE.USER_TOKENS.MAX_SIZE })
  21. // ---------------------------------------------------------------------------
  22. function deleteUserToken (userId: number, t?: Transaction) {
  23. clearCacheByUserId(userId)
  24. return OAuthTokenModel.deleteUserToken(userId, t)
  25. }
  26. function clearCacheByUserId (userId: number) {
  27. const token = userHavingToken.get(userId)
  28. if (token !== undefined) {
  29. accessTokenCache.del(token)
  30. userHavingToken.del(userId)
  31. }
  32. }
  33. function clearCacheByToken (token: string) {
  34. const tokenModel = accessTokenCache.get(token)
  35. if (tokenModel !== undefined) {
  36. userHavingToken.del(tokenModel.userId)
  37. accessTokenCache.del(token)
  38. }
  39. }
  40. async function getAccessToken (bearerToken: string) {
  41. logger.debug('Getting access token (bearerToken: ' + bearerToken + ').')
  42. if (!bearerToken) return undefined
  43. let tokenModel: MOAuthTokenUser
  44. if (accessTokenCache.has(bearerToken)) {
  45. tokenModel = accessTokenCache.get(bearerToken)
  46. } else {
  47. tokenModel = await OAuthTokenModel.getByTokenAndPopulateUser(bearerToken)
  48. if (tokenModel) {
  49. accessTokenCache.set(bearerToken, tokenModel)
  50. userHavingToken.set(tokenModel.userId, tokenModel.accessToken)
  51. }
  52. }
  53. if (!tokenModel) return undefined
  54. if (tokenModel.User.pluginAuth) {
  55. const valid = await PluginManager.Instance.isTokenValid(tokenModel, 'access')
  56. if (valid !== true) return undefined
  57. }
  58. return tokenModel
  59. }
  60. function getClient (clientId: string, clientSecret: string) {
  61. logger.debug('Getting Client (clientId: ' + clientId + ', clientSecret: ' + clientSecret + ').')
  62. return OAuthClientModel.getByIdAndSecret(clientId, clientSecret)
  63. }
  64. async function getRefreshToken (refreshToken: string) {
  65. logger.debug('Getting RefreshToken (refreshToken: ' + refreshToken + ').')
  66. const tokenInfo = await OAuthTokenModel.getByRefreshTokenAndPopulateClient(refreshToken)
  67. if (!tokenInfo) return undefined
  68. const tokenModel = tokenInfo.token
  69. if (tokenModel.User.pluginAuth) {
  70. const valid = await PluginManager.Instance.isTokenValid(tokenModel, 'refresh')
  71. if (valid !== true) return undefined
  72. }
  73. return tokenInfo
  74. }
  75. async function getUser (usernameOrEmail?: string, password?: string) {
  76. const res: express.Response = this.request.res
  77. // Special treatment coming from a plugin
  78. if (res.locals.bypassLogin && res.locals.bypassLogin.bypass === true) {
  79. const obj = res.locals.bypassLogin
  80. logger.info('Bypassing oauth login by plugin %s.', obj.pluginName)
  81. let user = await UserModel.loadByEmail(obj.user.email)
  82. if (!user) user = await createUserFromExternal(obj.pluginName, obj.user)
  83. // Cannot create a user
  84. if (!user) throw new AccessDeniedError('Cannot create such user: an actor with that name already exists.')
  85. // If the user does not belongs to a plugin, it was created before its installation
  86. // Then we just go through a regular login process
  87. if (user.pluginAuth !== null) {
  88. // This user does not belong to this plugin, skip it
  89. if (user.pluginAuth !== obj.pluginName) return null
  90. return user
  91. }
  92. }
  93. logger.debug('Getting User (username/email: ' + usernameOrEmail + ', password: ******).')
  94. const user = await UserModel.loadByUsernameOrEmail(usernameOrEmail)
  95. // If we don't find the user, or if the user belongs to a plugin
  96. if (!user || user.pluginAuth !== null || !password) return null
  97. const passwordMatch = await user.isPasswordMatch(password)
  98. if (passwordMatch !== true) return null
  99. if (user.blocked) throw new AccessDeniedError('User is blocked.')
  100. if (CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION && user.emailVerified === false) {
  101. throw new AccessDeniedError('User email is not verified.')
  102. }
  103. return user
  104. }
  105. async function revokeToken (tokenInfo: { refreshToken: string }): Promise<{ success: boolean, redirectUrl?: string }> {
  106. const res: express.Response = this.request.res
  107. const token = await OAuthTokenModel.getByRefreshTokenAndPopulateUser(tokenInfo.refreshToken)
  108. if (token) {
  109. let redirectUrl: string
  110. if (res.locals.explicitLogout === true && token.User.pluginAuth && token.authName) {
  111. redirectUrl = await PluginManager.Instance.onLogout(token.User.pluginAuth, token.authName, token.User, this.request)
  112. }
  113. clearCacheByToken(token.accessToken)
  114. token.destroy()
  115. .catch(err => logger.error('Cannot destroy token when revoking token.', { err }))
  116. return { success: true, redirectUrl }
  117. }
  118. return { success: false }
  119. }
  120. async function saveToken (token: TokenInfo, client: OAuthClientModel, user: UserModel) {
  121. const res: express.Response = this.request.res
  122. let authName: string = null
  123. if (res.locals.bypassLogin?.bypass === true) {
  124. authName = res.locals.bypassLogin.authName
  125. } else if (res.locals.refreshTokenAuthName) {
  126. authName = res.locals.refreshTokenAuthName
  127. }
  128. logger.debug('Saving token ' + token.accessToken + ' for client ' + client.id + ' and user ' + user.id + '.')
  129. const tokenToCreate = {
  130. accessToken: token.accessToken,
  131. accessTokenExpiresAt: token.accessTokenExpiresAt,
  132. refreshToken: token.refreshToken,
  133. refreshTokenExpiresAt: token.refreshTokenExpiresAt,
  134. authName,
  135. oAuthClientId: client.id,
  136. userId: user.id
  137. }
  138. const tokenCreated = await OAuthTokenModel.create(tokenToCreate)
  139. user.lastLoginDate = new Date()
  140. await user.save()
  141. return Object.assign(tokenCreated, { client, user })
  142. }
  143. // ---------------------------------------------------------------------------
  144. // See https://github.com/oauthjs/node-oauth2-server/wiki/Model-specification for the model specifications
  145. export {
  146. deleteUserToken,
  147. clearCacheByUserId,
  148. clearCacheByToken,
  149. getAccessToken,
  150. getClient,
  151. getRefreshToken,
  152. getUser,
  153. revokeToken,
  154. saveToken
  155. }
  156. async function createUserFromExternal (pluginAuth: string, options: {
  157. username: string
  158. email: string
  159. role: UserRole
  160. displayName: string
  161. }) {
  162. // Check an actor does not already exists with that name (removed user)
  163. const actor = await ActorModel.loadLocalByName(options.username)
  164. if (actor) return null
  165. const userToCreate = new UserModel({
  166. username: options.username,
  167. password: null,
  168. email: options.email,
  169. nsfwPolicy: CONFIG.INSTANCE.DEFAULT_NSFW_POLICY,
  170. autoPlayVideo: true,
  171. role: options.role,
  172. videoQuota: CONFIG.USER.VIDEO_QUOTA,
  173. videoQuotaDaily: CONFIG.USER.VIDEO_QUOTA_DAILY,
  174. adminFlags: UserAdminFlag.NONE,
  175. pluginAuth
  176. }) as MUser
  177. const { user } = await createUserAccountAndChannelAndPlaylist({
  178. userToCreate,
  179. userDisplayName: options.displayName
  180. })
  181. return user
  182. }