ニジカ投稿局 https://tv.nizika.tv
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

298 lines
9.2 KiB

  1. import express from 'express'
  2. import { AccessDeniedError } from '@node-oauth/oauth2-server'
  3. import { PluginManager } from '@server/lib/plugins/plugin-manager.js'
  4. import { AccountModel } from '@server/models/account/account.js'
  5. import { AuthenticatedResultUpdaterFieldName, RegisterServerAuthenticatedResult } from '@server/types/index.js'
  6. import { MOAuthClient } from '@server/types/models/index.js'
  7. import { MOAuthTokenUser } from '@server/types/models/oauth/oauth-token.js'
  8. import { MUser, MUserDefault } from '@server/types/models/user/user.js'
  9. import { pick } from '@peertube/peertube-core-utils'
  10. import { AttributesOnly } from '@peertube/peertube-typescript-utils'
  11. import { logger } from '../../helpers/logger.js'
  12. import { CONFIG } from '../../initializers/config.js'
  13. import { OAuthClientModel } from '../../models/oauth/oauth-client.js'
  14. import { OAuthTokenModel } from '../../models/oauth/oauth-token.js'
  15. import { UserModel } from '../../models/user/user.js'
  16. import { findAvailableLocalActorName } from '../local-actor.js'
  17. import { buildUser, createUserAccountAndChannelAndPlaylist } from '../user.js'
  18. import { ExternalUser } from './external-auth.js'
  19. import { TokensCache } from './tokens-cache.js'
  20. type TokenInfo = {
  21. accessToken: string
  22. refreshToken: string
  23. accessTokenExpiresAt: Date
  24. refreshTokenExpiresAt: Date
  25. }
  26. export type BypassLogin = {
  27. bypass: boolean
  28. pluginName: string
  29. authName?: string
  30. user: ExternalUser
  31. userUpdater: RegisterServerAuthenticatedResult['userUpdater']
  32. }
  33. async function getAccessToken (bearerToken: string) {
  34. logger.debug('Getting access token.')
  35. if (!bearerToken) return undefined
  36. let tokenModel: MOAuthTokenUser
  37. if (TokensCache.Instance.hasToken(bearerToken)) {
  38. tokenModel = TokensCache.Instance.getByToken(bearerToken)
  39. } else {
  40. tokenModel = await OAuthTokenModel.getByTokenAndPopulateUser(bearerToken)
  41. if (tokenModel) TokensCache.Instance.setToken(tokenModel)
  42. }
  43. if (!tokenModel) return undefined
  44. if (tokenModel.User.pluginAuth) {
  45. const valid = await PluginManager.Instance.isTokenValid(tokenModel, 'access')
  46. if (valid !== true) return undefined
  47. }
  48. return tokenModel
  49. }
  50. function getClient (clientId: string, clientSecret: string) {
  51. logger.debug('Getting Client (clientId: ' + clientId + ', clientSecret: ' + clientSecret + ').')
  52. return OAuthClientModel.getByIdAndSecret(clientId, clientSecret)
  53. }
  54. async function getRefreshToken (refreshToken: string) {
  55. logger.debug('Getting RefreshToken (refreshToken: ' + refreshToken + ').')
  56. const tokenInfo = await OAuthTokenModel.getByRefreshTokenAndPopulateClient(refreshToken)
  57. if (!tokenInfo) return undefined
  58. const tokenModel = tokenInfo.token
  59. if (tokenModel.User.pluginAuth) {
  60. const valid = await PluginManager.Instance.isTokenValid(tokenModel, 'refresh')
  61. if (valid !== true) return undefined
  62. }
  63. return tokenInfo
  64. }
  65. async function getUser (usernameOrEmail?: string, password?: string, bypassLogin?: BypassLogin) {
  66. // Special treatment coming from a plugin
  67. if (bypassLogin && bypassLogin.bypass === true) {
  68. logger.info('Bypassing oauth login by plugin %s.', bypassLogin.pluginName)
  69. let user = await UserModel.loadByEmail(bypassLogin.user.email)
  70. if (!user) {
  71. user = await createUserFromExternal(bypassLogin.pluginName, bypassLogin.user)
  72. } else if (user.pluginAuth === bypassLogin.pluginName) {
  73. user = await updateUserFromExternal(user, bypassLogin.user, bypassLogin.userUpdater)
  74. }
  75. // Cannot create a user
  76. if (!user) throw new AccessDeniedError('Cannot create such user: an actor with that name already exists.')
  77. // If the user does not belongs to a plugin, it was created before its installation
  78. // Then we just go through a regular login process
  79. if (user.pluginAuth !== null) {
  80. // This user does not belong to this plugin, skip it
  81. if (user.pluginAuth !== bypassLogin.pluginName) {
  82. logger.info(
  83. 'Cannot bypass oauth login by plugin %s because %s has another plugin auth method (%s).',
  84. bypassLogin.pluginName, bypassLogin.user.email, user.pluginAuth
  85. )
  86. return null
  87. }
  88. checkUserValidityOrThrow(user)
  89. return user
  90. }
  91. }
  92. logger.debug('Getting User (username/email: ' + usernameOrEmail + ', password: ******).')
  93. const user = await UserModel.loadByUsernameOrEmail(usernameOrEmail)
  94. // If we don't find the user, or if the user belongs to a plugin
  95. if (!user || user.pluginAuth !== null || !password) return null
  96. const passwordMatch = await user.isPasswordMatch(password)
  97. if (passwordMatch !== true) return null
  98. checkUserValidityOrThrow(user)
  99. if (CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION && user.emailVerified === false) {
  100. throw new AccessDeniedError('User email is not verified.')
  101. }
  102. return user
  103. }
  104. async function revokeToken (
  105. tokenInfo: { refreshToken: string },
  106. options: {
  107. req?: express.Request
  108. explicitLogout?: boolean
  109. } = {}
  110. ): Promise<{ success: boolean, redirectUrl?: string }> {
  111. const { req, explicitLogout } = options
  112. const token = await OAuthTokenModel.getByRefreshTokenAndPopulateUser(tokenInfo.refreshToken)
  113. if (token) {
  114. let redirectUrl: string
  115. if (explicitLogout === true && token.User.pluginAuth && token.authName) {
  116. redirectUrl = await PluginManager.Instance.onLogout(token.User.pluginAuth, token.authName, token.User, req)
  117. }
  118. TokensCache.Instance.clearCacheByToken(token.accessToken)
  119. token.destroy()
  120. .catch(err => logger.error('Cannot destroy token when revoking token.', { err }))
  121. return { success: true, redirectUrl }
  122. }
  123. return { success: false }
  124. }
  125. async function saveToken (
  126. token: TokenInfo,
  127. client: MOAuthClient,
  128. user: MUser,
  129. options: {
  130. refreshTokenAuthName?: string
  131. bypassLogin?: BypassLogin
  132. } = {}
  133. ) {
  134. const { refreshTokenAuthName, bypassLogin } = options
  135. let authName: string = null
  136. if (bypassLogin?.bypass === true) {
  137. authName = bypassLogin.authName
  138. } else if (refreshTokenAuthName) {
  139. authName = refreshTokenAuthName
  140. }
  141. logger.debug('Saving token ' + token.accessToken + ' for client ' + client.id + ' and user ' + user.id + '.')
  142. const tokenToCreate = {
  143. accessToken: token.accessToken,
  144. accessTokenExpiresAt: token.accessTokenExpiresAt,
  145. refreshToken: token.refreshToken,
  146. refreshTokenExpiresAt: token.refreshTokenExpiresAt,
  147. authName,
  148. oAuthClientId: client.id,
  149. userId: user.id
  150. }
  151. const tokenCreated = await OAuthTokenModel.create(tokenToCreate)
  152. user.lastLoginDate = new Date()
  153. await user.save()
  154. return {
  155. accessToken: tokenCreated.accessToken,
  156. accessTokenExpiresAt: tokenCreated.accessTokenExpiresAt,
  157. refreshToken: tokenCreated.refreshToken,
  158. refreshTokenExpiresAt: tokenCreated.refreshTokenExpiresAt,
  159. client,
  160. user,
  161. accessTokenExpiresIn: buildExpiresIn(tokenCreated.accessTokenExpiresAt),
  162. refreshTokenExpiresIn: buildExpiresIn(tokenCreated.refreshTokenExpiresAt)
  163. }
  164. }
  165. export {
  166. getAccessToken,
  167. getClient,
  168. getRefreshToken,
  169. getUser,
  170. revokeToken,
  171. saveToken
  172. }
  173. // ---------------------------------------------------------------------------
  174. async function createUserFromExternal (pluginAuth: string, userOptions: ExternalUser) {
  175. const username = await findAvailableLocalActorName(userOptions.username)
  176. const userToCreate = buildUser({
  177. ...pick(userOptions, [ 'email', 'role', 'adminFlags', 'videoQuota', 'videoQuotaDaily' ]),
  178. username,
  179. emailVerified: null,
  180. password: null,
  181. pluginAuth
  182. })
  183. const { user } = await createUserAccountAndChannelAndPlaylist({
  184. userToCreate,
  185. userDisplayName: userOptions.displayName
  186. })
  187. return user
  188. }
  189. async function updateUserFromExternal (
  190. user: MUserDefault,
  191. userOptions: ExternalUser,
  192. userUpdater: RegisterServerAuthenticatedResult['userUpdater']
  193. ) {
  194. if (!userUpdater) return user
  195. {
  196. type UserAttributeKeys = keyof AttributesOnly<UserModel>
  197. const mappingKeys: { [ id in UserAttributeKeys ]?: AuthenticatedResultUpdaterFieldName } = {
  198. role: 'role',
  199. adminFlags: 'adminFlags',
  200. videoQuota: 'videoQuota',
  201. videoQuotaDaily: 'videoQuotaDaily'
  202. }
  203. for (const modelKey of Object.keys(mappingKeys)) {
  204. const pluginOptionKey = mappingKeys[modelKey]
  205. const newValue = userUpdater({ fieldName: pluginOptionKey, currentValue: user[modelKey], newValue: userOptions[pluginOptionKey] })
  206. user.set(modelKey, newValue)
  207. }
  208. }
  209. {
  210. type AccountAttributeKeys = keyof Partial<AttributesOnly<AccountModel>>
  211. const mappingKeys: { [ id in AccountAttributeKeys ]?: AuthenticatedResultUpdaterFieldName } = {
  212. name: 'displayName'
  213. }
  214. for (const modelKey of Object.keys(mappingKeys)) {
  215. const optionKey = mappingKeys[modelKey]
  216. const newValue = userUpdater({ fieldName: optionKey, currentValue: user.Account[modelKey], newValue: userOptions[optionKey] })
  217. user.Account.set(modelKey, newValue)
  218. }
  219. }
  220. logger.debug('Updated user %s with plugin userUpdated function.', user.email, { user, userOptions })
  221. user.Account = await user.Account.save()
  222. return user.save()
  223. }
  224. function checkUserValidityOrThrow (user: MUser) {
  225. if (user.blocked) throw new AccessDeniedError('User is blocked.')
  226. }
  227. function buildExpiresIn (expiresAt: Date) {
  228. return Math.floor((expiresAt.getTime() - new Date().getTime()) / 1000)
  229. }