import { defineStore } from 'pinia';
|
import { store } from '@/stores';
|
import {
|
getToken as getCacheToken,
|
getUserInfo as getCacheUserInfo,
|
setUserInfo,
|
removeUserInfo,
|
setUserDetail,
|
getUserDetail,
|
removeUserDetail,
|
removeMatchMakingIdentity,
|
getMatchMakingIdentity,
|
setMatchMakingIdentity,
|
} from '@/utils/storage/auth';
|
import * as accountServices from '@12333/services/api/Account';
|
import * as userServices from '@12333/services/api/User';
|
import Taro, { useRouter } from '@tarojs/taro';
|
import { ButtonProps } from '@tarojs/components';
|
import { debounce } from 'lodash';
|
import { goHome, getStorageLocationCity, setStorageLocationCity } from '@/utils';
|
import {
|
getAccountInfoFromAccessToken,
|
AccountInfo,
|
setOSSLink,
|
getUserCertificationFrontStatusAdapter,
|
LocationUtils,
|
} from '@12333/utils';
|
import DefaultAvatar from '@/assets/components/icon-default-avatar.png';
|
import { WxMiniAppEnum } from '@12333/constants';
|
import { myClient } from '@/constants/query';
|
import { globalEventEmitter } from '@12333/hooks';
|
|
interface UserState {
|
userInfo?: Nullable<API.IdentityModelTokenCacheItem>;
|
token?: Nullable<string>;
|
refreshToken?: Nullable<string>;
|
userDetail?: Nullable<API.UserInfoV2>;
|
firstGetUserDetail?: boolean;
|
|
locationCity?: string;
|
locationProvince?: string;
|
firstSetLocation?: boolean;
|
}
|
|
const goAuthorization = debounce(
|
() => {
|
const route = Taro.getCurrentInstance().router;
|
if (route.path !== RouterPath.authorization) {
|
Taro.navigateTo({
|
url: RouterPath.authorization,
|
});
|
}
|
},
|
300,
|
{
|
leading: true,
|
trailing: false,
|
}
|
);
|
|
export const useUserStore = defineStore({
|
id: 'app-user',
|
state: (): UserState => {
|
const userInfo = getCacheUserInfo();
|
const userDetail = getUserDetail();
|
const storageLocation = getStorageLocationCity();
|
|
return {
|
// user info
|
userInfo: userInfo,
|
// token
|
token: userInfo?.accessToken ?? '',
|
|
refreshToken: userInfo?.refreshToken ?? '',
|
userDetail: userDetail,
|
firstGetUserDetail: true,
|
locationCity: storageLocation?.city ?? '北京市',
|
locationProvince: storageLocation?.province ?? '北京',
|
firstSetLocation: true,
|
};
|
},
|
getters: {
|
cacheToken: (state) => {
|
if (!state.token) {
|
const storageToken = getCacheToken() as API.IdentityModelTokenCacheItem;
|
|
state.token = storageToken.accessToken;
|
}
|
return state.token || null;
|
},
|
|
cacheRefreshToken: (state) => {
|
return state.refreshToken;
|
},
|
|
accountInfo(): Partial<AccountInfo> {
|
return getAccountInfoFromAccessToken(this.userInfo?.accessToken);
|
},
|
|
// matchMakingIdentity(state): MatchMakingIdentityEnum {
|
|
// },
|
},
|
actions: {
|
// 手机号授权Code登录
|
async getTokenByPhone(
|
detail: ButtonProps.onGetPhoneNumberEventDetail,
|
wxMiniAppUserLoginRes: any
|
) {
|
try {
|
let res: API.IdentityModelTokenCacheItem;
|
if (!wxMiniAppUserLoginRes.accessToken) {
|
let params: API.WxMiniAppPhoneLoginInput = {
|
openId: wxMiniAppUserLoginRes.openId,
|
sessionKey: wxMiniAppUserLoginRes.sessionKey,
|
encryptedData: detail.encryptedData,
|
iv: detail.iv,
|
wxMiniApp: WxMiniAppEnum.C端小程序,
|
};
|
res = await accountServices.wxMiniAppPhoneAuthLogin(params);
|
this.loginSuccess(res);
|
}
|
return res;
|
} catch (error) {
|
console.log('error3: ', error);
|
}
|
},
|
|
// 用户手机验证码登入
|
async loginByUsername(data: API.PhoneMesssageCodeLoginInput) {
|
let res = await accountServices.phoneMesssageCodeLogin(
|
{
|
phoneNumber: data.phoneNumber,
|
code: data.code,
|
},
|
{ showLoading: false }
|
);
|
|
if (res) {
|
this.loginSuccess(res);
|
}
|
return res;
|
},
|
|
// 用户账号密码登入
|
async loginByPassword(data: API.AccessRequestDto) {
|
let res = await accountServices.passwordLogin(
|
{
|
loginName: data.userName,
|
password: data.userPassword,
|
},
|
{ showLoading: false }
|
);
|
if (res) {
|
this.loginSuccess(res);
|
}
|
return res;
|
},
|
|
async loginSuccess(res: API.IdentityModelTokenCacheItem) {
|
try {
|
this.setUserInfoAction(res);
|
this.setTokenAction(res);
|
await this.getCurrentUserInfo();
|
} catch (error) {}
|
},
|
|
async wxMiniAppUserLoginFromScan(wxIndentityRes: API.WxMiniAppIndentityInfo, uuid: string) {
|
try {
|
let res = await accountServices.wxMiniAppUserLoginFromScan({
|
uId: uuid,
|
userName: wxIndentityRes.userName,
|
openId: wxIndentityRes.openId,
|
});
|
this.loginSuccess(res);
|
return res;
|
} catch (error) {}
|
},
|
|
async wxMiniAppPhoneAuthLoginFromScan(
|
detail: ButtonProps.onGetPhoneNumberEventDetail,
|
wxIndentityRes: API.WxMiniAppIndentityInfo,
|
uuid: string
|
) {
|
try {
|
let res = await accountServices.wxMiniAppPhoneAuthLoginFromScan({
|
uId: uuid,
|
openId: wxIndentityRes.openId,
|
sessionKey: wxIndentityRes.sessionKey,
|
encryptedData: detail.encryptedData,
|
iv: detail.iv,
|
wxMiniApp: WxMiniAppEnum.C端小程序,
|
});
|
this.loginSuccess(res);
|
return res;
|
} catch (error) {}
|
},
|
|
async getCurrentUserInfo() {
|
try {
|
let res = await userServices.getUserInfo({ showLoading: false });
|
if (res) {
|
res.frontStatus = getUserCertificationFrontStatusAdapter(
|
res.userCertificationStatus,
|
res.userCertificationAuditStatus
|
);
|
res.originalAvatarUrl = res.avatarUrl;
|
res.avatarUrl = res.avatarUrl ? setOSSLink(res.avatarUrl) : DefaultAvatar;
|
this.setUserDetail(res);
|
this.firstGetUserDetail = false;
|
}
|
} catch (error) {}
|
},
|
|
setTokenAction(tokenInfo: API.IdentityModelTokenCacheItem) {
|
this.token = tokenInfo?.accessToken;
|
this.refreshToken = tokenInfo.refreshToken ?? '';
|
},
|
|
setUserInfoAction(info: API.IdentityModelTokenCacheItem) {
|
this.userInfo = info;
|
setUserInfo(info);
|
},
|
|
setUserDetail(detail: API.UserInfoV2) {
|
this.userDetail = detail;
|
setUserDetail(detail);
|
},
|
|
resetState() {
|
this.userInfo = null;
|
this.token = '';
|
this.refreshToken = '';
|
this.userDetail = null;
|
removeUserInfo();
|
removeUserDetail();
|
removeMatchMakingIdentity();
|
},
|
|
/**
|
* @description: logout
|
*/
|
logout() {
|
this.resetState();
|
myClient.removeQueries();
|
goAuthorization();
|
},
|
|
logoutAndToHome() {
|
this.resetState();
|
goHome();
|
},
|
|
toLoginPage(targetUrl?: string) {
|
// 存 登录后跳转目标页
|
if (targetUrl) {
|
// tabbar 跳转:不是在具体页面判断用户是否登录
|
} else {
|
// 页面里 跳转登录页 存当前页面路径 已供登陆后
|
const currentPage = useRouter();
|
|
// const params = omit(currentPage.params, '$taroTimestamp');
|
|
console.log(currentPage.params);
|
|
// 直接用currentPage.path,params 会丢失
|
|
Taro.redirectTo({
|
url: `/packageLogin/authLogin/index`,
|
});
|
}
|
},
|
|
async getTokenByRefreshToken(params: API.AccessRefreshToken) {
|
try {
|
const res = await accountServices.getTokenByRefreshToken(params, {
|
showLoading: false,
|
});
|
if (res) {
|
this.setTokenAction(res);
|
this.setUserInfoAction(res);
|
return res;
|
} else {
|
throw new Error('刷新token失败');
|
}
|
} catch (error) {
|
throw new Error('error');
|
}
|
},
|
|
setLocationCity(cityName: string, provinceName: string) {
|
this.locationCity = cityName;
|
this.locationProvince = provinceName;
|
this.firstSetLocation = false;
|
setStorageLocationCity({ city: cityName, province: provinceName });
|
// if (LocationUtils.isProvinceChange(provinceName)) {
|
// this.resetState();
|
// myClient.removeQueries();
|
// globalEventEmitter.trigger('logout/refresh');
|
// }
|
LocationUtils.currentProvinceName = provinceName;
|
},
|
},
|
});
|
|
// Need to be used outside the setup
|
export function useUserStoreWithOut() {
|
return useUserStore(store);
|
}
|