| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273 |
- import {body, get} from "@/utils/https";
- // const _tokenQueue: {
- // pending: boolean;
- // list: {
- // resolve: (value: string) => void;
- // reject: (err: any) => void;
- // }[];
- // } = {
- // pending: false,
- // list: [],
- // };
- //
- // let _onTokenListener: {
- // cb: (token: string) => void;
- // }[] = [];
- //
- // const _resolveTokenQueue = function (res: any) {
- // _tokenQueue.pending = false;
- // uni.hideLoading();
- // if (res.errMsg) {
- // console.log(res);
- // uni.showModal({
- // title: "登录失败",
- // content: `${res.errMsg}`,
- // });
- // _tokenQueue.list.forEach((item) => {
- // item.reject(res);
- // });
- // } else {
- // uni.showToast({
- // icon: "success",
- // title: "登录成功",
- // });
- // setToken(res as string);
- // _onTokenListener.forEach((item) => {
- // item.cb(res as string);
- // });
- // _tokenQueue.list.forEach((item) => {
- // item.resolve(res as string);
- // });
- // }
- // _onTokenListener = [];
- // _tokenQueue.list = [];
- // };
- export function login(e: any): Promise<string> {
- return new Promise((resolve, reject) => {
- if (/deny|cancel/.test(e.errMsg)) {
- reject(e.errMsg);
- return;
- }
- if (!e.code) {
- uni.showModal({
- title: `${e.errMsg},请重试`,
- });
- reject(e);
- return;
- }
- // _tokenQueue.list.push({
- // resolve,
- // reject,
- // });
- // if (_tokenQueue.pending) {
- // return;
- // }
- // _tokenQueue.pending = true;
- uni.showLoading({
- title: "登录中",
- mask: true,
- });
- uni.login({
- success: (res) => {
- let data = {
- phoneCode: e.code,
- code: res.code,
- avatar: "",
- nickname: "",
- shortId: e.shortId
- }
- body(`/user/wxLogin`, data).then(async (res: any) => {
- let {satoken, userId} = res;
- if (satoken) {
- getApp<any>().globalData.user.id = userId
- // _resolveTokenQueue(satoken);
- setToken(satoken);
- await loadUserInfo();
- resolve(satoken)
- uni.hideLoading();
- } else {
- uni.showModal({
- title: `登录失败`,
- icon: 'none',
- duration: 2000
- });
- uni.hideLoading();
- // _resolveTokenQueue({
- // errMsg: `${JSON.stringify(res)}`,
- // });
- }
- }).catch(e => {
- uni.showModal({
- title: `${e}`,
- icon: 'none',
- duration: 2000
- });
- uni.hideLoading();
- })
- },
- fail: () => {
- uni.showModal({
- title: `登录失败`,
- icon: 'none',
- duration: 2000
- });
- uni.hideLoading();
- },
- });
- });
- }
- export function tryLogin() {
- return new Promise(((resolve, reject) => {
- let ftoken = fetchToken();
- // console.log("ftoken", ftoken)
- if (ftoken) {
- resolve(ftoken)
- return;
- }
- uni.showLoading()
- uni.login({
- success: (res) => {
- let data = {
- phoneCode: "",
- code: res.code,
- avatar: "",
- nickname: "",
- }
- body(`/user/wxLogin`, data).then(async (res: any) => {
- const {satoken, userId} = res;
- if (satoken) {
- getApp<any>().globalData.user.id = userId
- setToken(satoken);
- await loadUserInfo();
- resolve(satoken)
- } else {
- console.error("tryLogin")
- // _resolveTokenQueue({
- // errMsg: `${JSON.stringify(res)}`,
- // });
- }
- uni.hideLoading()
- }).catch(e => {
- reject(e)
- uni.hideLoading()
- })
- },
- fail: function () {
- reject('fail')
- uni.hideLoading()
- },
- });
- }))
- }
- export function checkLogin() {
- return new Promise((resolve, reject) => {
- let user = getApp<any>().globalData.user;
- if (!user || !user.id) {
- uni.showToast({
- icon: "none",
- title: "请先登录",
- });
- reject('未获取到用户登录信息');
- } else {
- resolve(user);
- }
- })
- }
- export async function loadUserInfo() {
- getApp<any>().globalData.manualLogout = false;
- get(`/user/me`).then((res: any) => {
- // getApp<any>().globalData.user = res;
- // getApp<any>().globalData.isLogin = true;
- getApp<any>().globalData = Object.assign({}, {...getApp<any>().globalData},{user:res,isLogin:true,manualLogout:false})
- uni.$emit('login', {isLogin: true})
- })
- }
- export function refresh(): Promise<string> {
- return new Promise((resolve, reject) => {
- uni.getStorage({key: "token"}).then((token) => {
- if (!token) {
- clearToken();
- reject({
- errMsg: "请登录",
- });
- uni.reLaunch({
- url: "/pages/map/index",
- });
- } else {
- getApp<any>().globalData.token = "";
- uni.removeStorageSync("token");
- get(`/user/refresh`).then((res: any) => {
- const {statusCode, data} = res;
- if (
- statusCode === 200 &&
- data &&
- data.msg === "OK" &&
- data.code === 200
- ) {
- resolve(data.data.access_token);
- } else {
- if (data.code === 21005) {
- uni.reLaunch({
- url: "/pages/map/index",
- });
- }
- reject({
- errMsg: `${JSON.stringify(res)}`,
- });
- }
- }).catch(() => {
- reject()
- })
- }
- });
- });
- }
- export function fetchToken() {
- let tk = uni.getStorageSync("token");
- // console.log(tk)
- if (tk.length > 16) {
- return tk;
- }
- return null;
- }
- export function setToken(token: string) {
- if (!token) {
- console.error("empty token")
- return;
- } else {
- console.log("set token", token)
- }
- getApp<any>().globalData = Object.assign({}, {...getApp<any>().globalData},{token,isLogin:true})
- uni.setStorageSync("token", token)
- }
- export function clearToken() {
- let device = uni.getWindowInfo();
- let initGlobalData = {
- token: "",
- user: {},
- isLogin: false,
- last: {},
- device: {
- windowWidth:device.windowWidth,
- windowHeight:device.windowHeight,
- screenTop: device.screenTop,
- windowTop: device.windowTop,
- },
- deviceId: null,
- manualLogout: false
- }
- uni.$emit('logout')
- uni.removeStorageSync("token")
- getApp<any>().globalData = Object.assign({}, initGlobalData)
- }
|