import { Injectable } from '@kaokei/use-vue-service'; import { DaoService } from './dao.service'; import { domains } from '@/utils'; @Injectable() export class UserService { public token = ''; public user?: any; constructor(public daoService: DaoService) {} public init() { return this.daoService .getCurrentUserInfoIgnoreError() .then(user => { this.token = localStorage.getItem('token') || ''; this.user = user; }) .catch(() => { // ignore error // we think current user is not logged in }); } public setUser(user: any) { this.user = user; } public login(user: any) { this.token = user.token; this.user = user; localStorage.setItem('token', user.token); } public logout() { this.token = ''; this.user = undefined; localStorage.removeItem('token'); } public tryLogin(pathParam?: string) { if (!(this.user && this.user.id)) { const pathname = pathParam || '/' + location.pathname.split('/').slice(2).join('/'); const path = `${domains.apiDomain}/redirect?path=${pathname}`; this.daoService.getMobileAuthUrl(path).then(res => { window.location.href = res.redirectUrl; }); } } }