oauth-model.ts 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  1. import * as Bluebird from 'bluebird'
  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 { CACHE } from '../initializers/constants'
  8. import { Transaction } from 'sequelize'
  9. import { CONFIG } from '../initializers/config'
  10. type TokenInfo = { accessToken: string, refreshToken: string, accessTokenExpiresAt: Date, refreshTokenExpiresAt: Date }
  11. let accessTokenCache: { [ accessToken: string ]: OAuthTokenModel } = {}
  12. let userHavingToken: { [ userId: number ]: string } = {}
  13. // ---------------------------------------------------------------------------
  14. function deleteUserToken (userId: number, t?: Transaction) {
  15. clearCacheByUserId(userId)
  16. return OAuthTokenModel.deleteUserToken(userId, t)
  17. }
  18. function clearCacheByUserId (userId: number) {
  19. const token = userHavingToken[userId]
  20. if (token !== undefined) {
  21. accessTokenCache[ token ] = undefined
  22. userHavingToken[ userId ] = undefined
  23. }
  24. }
  25. function clearCacheByToken (token: string) {
  26. const tokenModel = accessTokenCache[ token ]
  27. if (tokenModel !== undefined) {
  28. userHavingToken[tokenModel.userId] = undefined
  29. accessTokenCache[ token ] = undefined
  30. }
  31. }
  32. function getAccessToken (bearerToken: string) {
  33. logger.debug('Getting access token (bearerToken: ' + bearerToken + ').')
  34. if (!bearerToken) return Bluebird.resolve(undefined)
  35. if (accessTokenCache[bearerToken] !== undefined) return Bluebird.resolve(accessTokenCache[bearerToken])
  36. return OAuthTokenModel.getByTokenAndPopulateUser(bearerToken)
  37. .then(tokenModel => {
  38. if (tokenModel) {
  39. // Reinit our cache
  40. if (Object.keys(accessTokenCache).length > CACHE.USER_TOKENS.MAX_SIZE) {
  41. accessTokenCache = {}
  42. userHavingToken = {}
  43. }
  44. accessTokenCache[ bearerToken ] = tokenModel
  45. userHavingToken[ tokenModel.userId ] = tokenModel.accessToken
  46. }
  47. return tokenModel
  48. })
  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. function getRefreshToken (refreshToken: string) {
  55. logger.debug('Getting RefreshToken (refreshToken: ' + refreshToken + ').')
  56. return OAuthTokenModel.getByRefreshTokenAndPopulateClient(refreshToken)
  57. }
  58. async function getUser (usernameOrEmail: string, password: string) {
  59. logger.debug('Getting User (username/email: ' + usernameOrEmail + ', password: ******).')
  60. const user = await UserModel.loadByUsernameOrEmail(usernameOrEmail)
  61. if (!user) return null
  62. const passwordMatch = await user.isPasswordMatch(password)
  63. if (passwordMatch === false) return null
  64. if (user.blocked) throw new AccessDeniedError('User is blocked.')
  65. if (CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION && user.emailVerified === false) {
  66. throw new AccessDeniedError('User email is not verified.')
  67. }
  68. return user
  69. }
  70. async function revokeToken (tokenInfo: TokenInfo) {
  71. const token = await OAuthTokenModel.getByRefreshTokenAndPopulateUser(tokenInfo.refreshToken)
  72. if (token) {
  73. clearCacheByToken(token.accessToken)
  74. token.destroy()
  75. .catch(err => logger.error('Cannot destroy token when revoking token.', { err }))
  76. }
  77. /*
  78. * Thanks to https://github.com/manjeshpv/node-oauth2-server-implementation/blob/master/components/oauth/mongo-models.js
  79. * "As per the discussion we need set older date
  80. * revokeToken will expected return a boolean in future version
  81. * https://github.com/oauthjs/node-oauth2-server/pull/274
  82. * https://github.com/oauthjs/node-oauth2-server/issues/290"
  83. */
  84. const expiredToken = token
  85. expiredToken.refreshTokenExpiresAt = new Date('2015-05-28T06:59:53.000Z')
  86. return expiredToken
  87. }
  88. async function saveToken (token: TokenInfo, client: OAuthClientModel, user: UserModel) {
  89. logger.debug('Saving token ' + token.accessToken + ' for client ' + client.id + ' and user ' + user.id + '.')
  90. const tokenToCreate = {
  91. accessToken: token.accessToken,
  92. accessTokenExpiresAt: token.accessTokenExpiresAt,
  93. refreshToken: token.refreshToken,
  94. refreshTokenExpiresAt: token.refreshTokenExpiresAt,
  95. oAuthClientId: client.id,
  96. userId: user.id
  97. }
  98. const tokenCreated = await OAuthTokenModel.create(tokenToCreate)
  99. return Object.assign(tokenCreated, { client, user })
  100. }
  101. // ---------------------------------------------------------------------------
  102. // See https://github.com/oauthjs/node-oauth2-server/wiki/Model-specification for the model specifications
  103. export {
  104. deleteUserToken,
  105. clearCacheByUserId,
  106. clearCacheByToken,
  107. getAccessToken,
  108. getClient,
  109. getRefreshToken,
  110. getUser,
  111. revokeToken,
  112. saveToken
  113. }