]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/shared/auth/user.model.ts
98852f8355c834dfda754ef45591afa07365038b
[github/Chocobozzz/PeerTube.git] / client / src / app / shared / auth / user.model.ts
1 export class User {
2 private static KEYS = {
3 USERNAME: 'username'
4 };
5
6 username: string;
7 tokens: Tokens;
8
9 static load() {
10 const usernameLocalStorage = localStorage.getItem(this.KEYS.USERNAME);
11 if (usernameLocalStorage) {
12 return new User(localStorage.getItem(this.KEYS.USERNAME), Tokens.load());
13 }
14
15 return null;
16 }
17
18 static flush() {
19 localStorage.removeItem(this.KEYS.USERNAME);
20 Tokens.flush();
21 }
22
23 constructor(username: string, hash_tokens: any) {
24 this.username = username;
25 this.tokens = new Tokens(hash_tokens);
26 }
27
28 getAccessToken() {
29 return this.tokens.access_token;
30 }
31
32 getRefreshToken() {
33 return this.tokens.refresh_token;
34 }
35
36 getTokenType() {
37 return this.tokens.token_type;
38 }
39
40 refreshTokens(access_token: string, refresh_token: string) {
41 this.tokens.access_token = access_token;
42 this.tokens.refresh_token = refresh_token;
43 }
44
45 save() {
46 localStorage.setItem('username', this.username);
47 this.tokens.save();
48 }
49 }
50
51 // Private class used only by User
52 class Tokens {
53 private static KEYS = {
54 ACCESS_TOKEN: 'access_token',
55 REFRESH_TOKEN: 'refresh_token',
56 TOKEN_TYPE: 'token_type',
57 };
58
59 access_token: string;
60 refresh_token: string;
61 token_type: string;
62
63 static load() {
64 const accessTokenLocalStorage = localStorage.getItem(this.KEYS.ACCESS_TOKEN);
65 const refreshTokenLocalStorage = localStorage.getItem(this.KEYS.REFRESH_TOKEN);
66 const tokenTypeLocalStorage = localStorage.getItem(this.KEYS.TOKEN_TYPE);
67
68 if (accessTokenLocalStorage && refreshTokenLocalStorage && tokenTypeLocalStorage) {
69 return new Tokens({
70 access_token: accessTokenLocalStorage,
71 refresh_token: refreshTokenLocalStorage,
72 token_type: tokenTypeLocalStorage
73 });
74 }
75
76 return null;
77 }
78
79 static flush() {
80 localStorage.removeItem(this.KEYS.ACCESS_TOKEN);
81 localStorage.removeItem(this.KEYS.REFRESH_TOKEN);
82 localStorage.removeItem(this.KEYS.TOKEN_TYPE);
83 }
84
85 constructor(hash?: any) {
86 if (hash) {
87 this.access_token = hash.access_token;
88 this.refresh_token = hash.refresh_token;
89
90 if (hash.token_type === 'bearer') {
91 this.token_type = 'Bearer';
92 } else {
93 this.token_type = hash.token_type;
94 }
95 }
96 }
97
98 save() {
99 localStorage.setItem('access_token', this.access_token);
100 localStorage.setItem('refresh_token', this.refresh_token);
101 localStorage.setItem('token_type', this.token_type);
102 }
103 }