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'
11 type TokenInfo = { accessToken: string, refreshToken: string, accessTokenExpiresAt: Date, refreshTokenExpiresAt: Date }
12 let accessTokenCache: { [ accessToken: string ]: OAuthTokenModel } = {}
13 let userHavingToken: { [ userId: number ]: string } = {}
15 // ---------------------------------------------------------------------------
17 function deleteUserToken (userId: number, t?: Transaction) {
18 clearCacheByUserId(userId)
20 return OAuthTokenModel.deleteUserToken(userId, t)
23 function clearCacheByUserId (userId: number) {
24 const token = userHavingToken[userId]
25 if (token !== undefined) {
26 accessTokenCache[ token ] = undefined
27 userHavingToken[ userId ] = undefined
31 function clearCacheByToken (token: string) {
32 const tokenModel = accessTokenCache[ token ]
33 if (tokenModel !== undefined) {
34 userHavingToken[tokenModel.userId] = undefined
35 accessTokenCache[ token ] = undefined
39 function getAccessToken (bearerToken: string) {
40 logger.debug('Getting access token (bearerToken: ' + bearerToken + ').')
42 if (!bearerToken) return Bluebird.resolve(undefined)
44 if (accessTokenCache[bearerToken] !== undefined) return Bluebird.resolve(accessTokenCache[bearerToken])
46 return OAuthTokenModel.getByTokenAndPopulateUser(bearerToken)
50 if (Object.keys(accessTokenCache).length > CACHE.USER_TOKENS.MAX_SIZE) {
55 accessTokenCache[ bearerToken ] = tokenModel
56 userHavingToken[ tokenModel.userId ] = tokenModel.accessToken
63 function getClient (clientId: string, clientSecret: string) {
64 logger.debug('Getting Client (clientId: ' + clientId + ', clientSecret: ' + clientSecret + ').')
66 return OAuthClientModel.getByIdAndSecret(clientId, clientSecret)
69 function getRefreshToken (refreshToken: string) {
70 logger.debug('Getting RefreshToken (refreshToken: ' + refreshToken + ').')
72 return OAuthTokenModel.getByRefreshTokenAndPopulateClient(refreshToken)
75 async function getUser (usernameOrEmail: string, password: string) {
76 logger.debug('Getting User (username/email: ' + usernameOrEmail + ', password: ******).')
78 const user = await UserModel.loadByUsernameOrEmail(usernameOrEmail)
79 if (!user) return null
81 const passwordMatch = await user.isPasswordMatch(password)
82 if (passwordMatch === false) return null
84 if (user.blocked) throw new AccessDeniedError('User is blocked.')
86 if (CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION && user.emailVerified === false) {
87 throw new AccessDeniedError('User email is not verified.')
93 async function revokeToken (tokenInfo: TokenInfo) {
94 const token = await OAuthTokenModel.getByRefreshTokenAndPopulateUser(tokenInfo.refreshToken)
96 clearCacheByToken(token.accessToken)
99 .catch(err => logger.error('Cannot destroy token when revoking token.', { err }))
103 * Thanks to https://github.com/manjeshpv/node-oauth2-server-implementation/blob/master/components/oauth/mongo-models.js
104 * "As per the discussion we need set older date
105 * revokeToken will expected return a boolean in future version
106 * https://github.com/oauthjs/node-oauth2-server/pull/274
107 * https://github.com/oauthjs/node-oauth2-server/issues/290"
109 const expiredToken = token
110 expiredToken.refreshTokenExpiresAt = new Date('2015-05-28T06:59:53.000Z')
115 async function saveToken (token: TokenInfo, client: OAuthClientModel, user: UserModel) {
116 logger.debug('Saving token ' + token.accessToken + ' for client ' + client.id + ' and user ' + user.id + '.')
118 const tokenToCreate = {
119 accessToken: token.accessToken,
120 accessTokenExpiresAt: token.accessTokenExpiresAt,
121 refreshToken: token.refreshToken,
122 refreshTokenExpiresAt: token.refreshTokenExpiresAt,
123 oAuthClientId: client.id,
127 const tokenCreated = await OAuthTokenModel.create(tokenToCreate)
128 return Object.assign(tokenCreated, { client, user })
131 // ---------------------------------------------------------------------------
133 // See https://github.com/oauthjs/node-oauth2-server/wiki/Model-specification for the model specifications