From f201a749929ec8094a7ba6bcab7b196870ca5a5e Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Thu, 20 Sep 2018 11:31:48 +0200 Subject: Cache user token --- server/lib/oauth-model.ts | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) (limited to 'server/lib/oauth-model.ts') diff --git a/server/lib/oauth-model.ts b/server/lib/oauth-model.ts index 2f8667e19..5cbe60b82 100644 --- a/server/lib/oauth-model.ts +++ b/server/lib/oauth-model.ts @@ -4,15 +4,50 @@ import { UserModel } from '../models/account/user' import { OAuthClientModel } from '../models/oauth/oauth-client' import { OAuthTokenModel } from '../models/oauth/oauth-token' import { CONFIG } from '../initializers/constants' +import { Transaction } from 'sequelize' type TokenInfo = { accessToken: string, refreshToken: string, accessTokenExpiresAt: Date, refreshTokenExpiresAt: Date } +const accessTokenCache: { [ accessToken: string ]: OAuthTokenModel } = {} +const userHavingToken: { [ userId: number ]: string } = {} // --------------------------------------------------------------------------- +function deleteUserToken (userId: number, t?: Transaction) { + clearCacheByUserId(userId) + + return OAuthTokenModel.deleteUserToken(userId, t) +} + +function clearCacheByUserId (userId: number) { + const token = userHavingToken[userId] + if (token !== undefined) { + accessTokenCache[ token ] = undefined + userHavingToken[ userId ] = undefined + } +} + +function clearCacheByToken (token: string) { + const tokenModel = accessTokenCache[ token ] + if (tokenModel !== undefined) { + userHavingToken[tokenModel.userId] = undefined + accessTokenCache[ token ] = undefined + } +} + function getAccessToken (bearerToken: string) { logger.debug('Getting access token (bearerToken: ' + bearerToken + ').') + if (accessTokenCache[bearerToken] !== undefined) return accessTokenCache[bearerToken] + return OAuthTokenModel.getByTokenAndPopulateUser(bearerToken) + .then(tokenModel => { + if (tokenModel) { + accessTokenCache[ bearerToken ] = tokenModel + userHavingToken[ tokenModel.userId ] = tokenModel.accessToken + } + + return tokenModel + }) } function getClient (clientId: string, clientSecret: string) { @@ -48,6 +83,8 @@ async function getUser (usernameOrEmail: string, password: string) { async function revokeToken (tokenInfo: TokenInfo) { const token = await OAuthTokenModel.getByRefreshTokenAndPopulateUser(tokenInfo.refreshToken) if (token) { + clearCacheByToken(token.accessToken) + token.destroy() .catch(err => logger.error('Cannot destroy token when revoking token.', { err })) } @@ -85,6 +122,9 @@ async function saveToken (token: TokenInfo, client: OAuthClientModel, user: User // See https://github.com/oauthjs/node-oauth2-server/wiki/Model-specification for the model specifications export { + deleteUserToken, + clearCacheByUserId, + clearCacheByToken, getAccessToken, getClient, getRefreshToken, -- cgit v1.2.3