AuthService.ts 2.65 KB
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);
    }
}