AuthService.ts
2.65 KB
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import {AuthenticationManager} from "lib/src/core/security/AuthenticationManager";
// import {DefaultTokenInterceptor} from "lib/src/core/http/DefaultTokenInterceptor";
import {AccountInfo} from "lib/src/entity/account/domain/AccountInfo";
import {DefaultTokenInterceptor} from "lib/src/core/http/DefaultTokenInterceptor";
export class AuthService {
/**
* TOKEN存储KEY
*/
public static readonly TOKEN = 'token';
private token: string;
private accountInfo: AccountInfo = null;
constructor() {
this.loadStorageToken();
this.loadStorageAuthentication();
}
/**
* 更新TOKEN
*/
updateToken(token: string): void {
this.token = token;
uni.setStorageSync(AuthenticationManager.TOKEN, token);
}
/**
* 删除TOKEN
*/
removeToken() {
this.token = null;
uni.removeStorageSync(AuthenticationManager.TOKEN);
}
/**
* 判断是否登录
*/
isLogin(): boolean {
if (this.token) {
return this.getAuthentication() != null;
} else {
return false;
}
}
getAuthentication(): AccountInfo | null {
return this.accountInfo;
}
/**
* 获取TOKEN
*/
getStorageToken(): string {
return uni.getStorageSync(AuthenticationManager.TOKEN);
}
deleteAuthentication(): void {
this.accountInfo = null;
uni.removeStorageSync(DefaultTokenInterceptor.AUTHORIZATION);
}
/**
* 获取TOKEN
*/
getToken() {
return this.token;
}
saveAuthentication(authentication: AccountInfo): void {
this.accountInfo = authentication;
uni.setStorageSync(DefaultTokenInterceptor.AUTHORIZATION, JSON.stringify(authentication));
}
loadStorageAuthentication(): Promise<any> {
if (uni.getStorageSync(DefaultTokenInterceptor.AUTHORIZATION)) {
const authString = uni.getStorageSync(DefaultTokenInterceptor.AUTHORIZATION);
// console.log('本地存储的authString : ' + authString);
if (authString && authString.length > 0) {
this.accountInfo = JSON.parse(authString);
this.token = this.accountInfo.token;
}
} else {
this.accountInfo = null;
}
// console.log('本地存储的authentication : ' + JSON.stringify(this.accountInfo))
return Promise.resolve(this.accountInfo);
}
loadStorageToken(): Promise<any> {
this.token = uni.getStorageSync(AuthenticationManager.TOKEN);
// console.log('本地存储的token : ' + this.token);
return Promise.resolve(this.token);
}
}