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 { 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/typings/models/oauth/oauth-token'
13 type TokenInfo = { accessToken: string, refreshToken: string, accessTokenExpiresAt: Date, refreshTokenExpiresAt: Date }
15 const accessTokenCache = new LRUCache<string, MOAuthTokenUser>({ max: LRU_CACHE.USER_TOKENS.MAX_SIZE })
16 const userHavingToken = new LRUCache<number, string>({ max: LRU_CACHE.USER_TOKENS.MAX_SIZE })
18 // ---------------------------------------------------------------------------
20 function deleteUserToken (userId: number, t?: Transaction) {
21 clearCacheByUserId(userId)
23 return OAuthTokenModel.deleteUserToken(userId, t)
26 function clearCacheByUserId (userId: number) {
27 const token = userHavingToken.get(userId)
29 if (token !== undefined) {
30 accessTokenCache.del(token)
31 userHavingToken.del(userId)
35 function clearCacheByToken (token: string) {
36 const tokenModel = accessTokenCache.get(token)
38 if (tokenModel !== undefined) {
39 userHavingToken.del(tokenModel.userId)
40 accessTokenCache.del(token)
44 function getAccessToken (bearerToken: string) {
45 logger.debug('Getting access token (bearerToken: ' + bearerToken + ').')
47 if (!bearerToken) return Bluebird.resolve(undefined)
49 if (accessTokenCache.has(bearerToken)) return Bluebird.resolve(accessTokenCache.get(bearerToken))
51 return OAuthTokenModel.getByTokenAndPopulateUser(bearerToken)
54 accessTokenCache.set(bearerToken, tokenModel)
55 userHavingToken.set(tokenModel.userId, tokenModel.accessToken)
62 function getClient (clientId: string, clientSecret: string) {
63 logger.debug('Getting Client (clientId: ' + clientId + ', clientSecret: ' + clientSecret + ').')
65 return OAuthClientModel.getByIdAndSecret(clientId, clientSecret)
68 function getRefreshToken (refreshToken: string) {
69 logger.debug('Getting RefreshToken (refreshToken: ' + refreshToken + ').')
71 return OAuthTokenModel.getByRefreshTokenAndPopulateClient(refreshToken)
74 async function getUser (usernameOrEmail: string, password: string) {
75 logger.debug('Getting User (username/email: ' + usernameOrEmail + ', password: ******).')
77 const user = await UserModel.loadByUsernameOrEmail(usernameOrEmail)
78 if (!user) return null
80 const passwordMatch = await user.isPasswordMatch(password)
81 if (passwordMatch === false) return null
83 if (user.blocked) throw new AccessDeniedError('User is blocked.')
85 if (CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION && user.emailVerified === false) {
86 throw new AccessDeniedError('User email is not verified.')
92 async function revokeToken (tokenInfo: TokenInfo) {
93 const token = await OAuthTokenModel.getByRefreshTokenAndPopulateUser(tokenInfo.refreshToken)
95 clearCacheByToken(token.accessToken)
98 .catch(err => logger.error('Cannot destroy token when revoking token.', { err }))
102 * Thanks to https://github.com/manjeshpv/node-oauth2-server-implementation/blob/master/components/oauth/mongo-models.js
103 * "As per the discussion we need set older date
104 * revokeToken will expected return a boolean in future version
105 * https://github.com/oauthjs/node-oauth2-server/pull/274
106 * https://github.com/oauthjs/node-oauth2-server/issues/290"
108 const expiredToken = token
109 expiredToken.refreshTokenExpiresAt = new Date('2015-05-28T06:59:53.000Z')
114 async function saveToken (token: TokenInfo, client: OAuthClientModel, user: UserModel) {
115 logger.debug('Saving token ' + token.accessToken + ' for client ' + client.id + ' and user ' + user.id + '.')
117 const tokenToCreate = {
118 accessToken: token.accessToken,
119 accessTokenExpiresAt: token.accessTokenExpiresAt,
120 refreshToken: token.refreshToken,
121 refreshTokenExpiresAt: token.refreshTokenExpiresAt,
122 oAuthClientId: client.id,
126 const tokenCreated = await OAuthTokenModel.create(tokenToCreate)
127 return Object.assign(tokenCreated, { client, user })
130 // ---------------------------------------------------------------------------
132 // See https://github.com/oauthjs/node-oauth2-server/wiki/Model-specification for the model specifications