[LeetCode] Design Authentication Manager

1797. Design Authentication Manager

There is an authentication system that works with authentication tokens. For each session, the user will receive a new authentication token that will expire timeToLive seconds after the currentTime. If the token is renewed, the expiry time will be extended to expire timeToLive seconds after the (potentially different) currentTime.

Implement the AuthenticationManager class:

  • AuthenticationManager(int timeToLive) constructs the AuthenticationManager and sets the timeToLive.
  • generate(string tokenId, int currentTime) generates a new token with the given tokenId at the given currentTime in seconds.
  • renew(string tokenId, int currentTime) renews the unexpired token with the given tokenId at the given currentTime in seconds. If there are no unexpired tokens with the given tokenId, the request is ignored, and nothing happens.
  • countUnexpiredTokens(int currentTime) returns the number of unexpired tokens at the given currentTime.

Note that if a token expires at time t, and another action happens on time t (renew or countUnexpiredTokens), the expiration takes place before the other actions.

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
class AuthenticationManager {
int ttl;
priority_queue<pair<int,string>,vector<pair<int,string>>,greater<pair<int,string>>> tokens;
unordered_map<string, int> ump;
void expire(int currentTime) {
while(!tokens.empty() and tokens.top().first <= currentTime) {
auto [t, tk] = tokens.top(); tokens.pop();
if(--ump[tk] == 0) ump.erase(tk);
}
}
public:
AuthenticationManager(int timeToLive): ttl(timeToLive) {}

void generate(string tokenId, int currentTime) {
ump[tokenId]++;
tokens.push({currentTime + ttl, tokenId});
}

void renew(string tokenId, int currentTime) {
expire(currentTime);
if(!ump.count(tokenId)) return;
generate(tokenId, currentTime);
}

int countUnexpiredTokens(int currentTime) {
expire(currentTime);
return ump.size();
}
};

/**
* Your AuthenticationManager object will be instantiated and called as such:
* AuthenticationManager* obj = new AuthenticationManager(timeToLive);
* obj->generate(tokenId,currentTime);
* obj->renew(tokenId,currentTime);
* int param_3 = obj->countUnexpiredTokens(currentTime);
*/
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/04/09/PS/LeetCode/design-authentication-manager/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.