aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/lib/auth/tokens-cache.ts
blob: e7b12159b7504e4e122a3aead4aea00fa925219f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import { LRUCache } from 'lru-cache'
import { MOAuthTokenUser } from '@server/types/models'
import { LRU_CACHE } from '../../initializers/constants'

export class TokensCache {

  private static instance: TokensCache

  private readonly accessTokenCache = new LRUCache<string, MOAuthTokenUser>({ max: LRU_CACHE.USER_TOKENS.MAX_SIZE })
  private readonly userHavingToken = new LRUCache<number, string>({ max: LRU_CACHE.USER_TOKENS.MAX_SIZE })

  private constructor () { }

  static get Instance () {
    return this.instance || (this.instance = new this())
  }

  hasToken (token: string) {
    return this.accessTokenCache.has(token)
  }

  getByToken (token: string) {
    return this.accessTokenCache.get(token)
  }

  setToken (token: MOAuthTokenUser) {
    this.accessTokenCache.set(token.accessToken, token)
    this.userHavingToken.set(token.userId, token.accessToken)
  }

  deleteUserToken (userId: number) {
    this.clearCacheByUserId(userId)
  }

  clearCacheByUserId (userId: number) {
    const token = this.userHavingToken.get(userId)

    if (token !== undefined) {
      this.accessTokenCache.delete(token)
      this.userHavingToken.delete(userId)
    }
  }

  clearCacheByToken (token: string) {
    const tokenModel = this.accessTokenCache.get(token)

    if (tokenModel !== undefined) {
      this.userHavingToken.delete(tokenModel.userId)
      this.accessTokenCache.delete(token)
    }
  }
}