summaryrefslogtreecommitdiff
path: root/src/lib/token.ts
blob: 93ec0cf51a24bea118ee21bcf638924352bf3f41 (plain)
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import jwt_decode from "jwt-decode";
import axios from "axios";

export default class Token {
  get() {
    return sessionStorage.getItem("token");
  }

  set(token: string) {
    sessionStorage.setItem("token", token);
  }

  getRefresh() {
    return sessionStorage.getItem("refresh");
  }

  setRefresh(refresh_token: string) {
    sessionStorage.setItem("refresh", refresh_token);
  }

  present() {
    return sessionStorage.getItem("token") != null;
  }

  logout() {
    sessionStorage.removeItem("token");
    sessionStorage.removeItem("refresh");
  }

  refresh() {
    const options = {
      headers: {
        Authorization: `Bearer ${this.getRefresh()}`
      }
    }

    try {
      const response = axios.post('/refresh_tokens', null, options);
      this.setRefresh(response.data.refresh);
      this.set(response.data.token);
    } catch(error) {
      this.logout();
    }
  }

  getEmail() {
    return this.decode()?.data;
  }

  getRole() {
    return this.decode()?.aud;
  }

  getJTI() {
    return this.decode()?.jti;
  }

  getExpirationDate() {
    return this.decode()?.exp;
  }

  private decode(): { data: string; aud: string; jti: string; exp: number; } | null {
    const token = this.get();

    if(token != null)
      return jwt_decode(token);

    return null;
  }
}