wangrong
21 小时以前 db685b04e52efd75213ef7540fdc0bed7dccfd9e
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
import { reactive } from "vue";
import { BaseService } from "./service/base";
import { useUserStore } from "./store/user";
import { storage } from "./utils";
 
export type PhoneAuthState = {
    dismissed: boolean;
    ready: boolean;
};
 
export function phoneAuthState(): PhoneAuthState {
    const host = globalThis as any;
    if (!host.__phoneAuthState) {
        host.__phoneAuthState = reactive({
            dismissed: false,
            ready: false,
        });
    }
    return host.__phoneAuthState;
}
 
function wxLoginCode() {
    return new Promise<string>((resolve) => {
        uni.login({
            provider: "weixin",
            success: (res) => resolve(res.code || ""),
            fail: () => resolve(""),
        });
    });
}
 
let pending: Promise<boolean> | null = null;
 
/**
 * 已授权过手机号的微信用户,再次打开时用 openid 换回登录态。
 */
export function miniAutoLogin(force = false) {
    if (pending && !force) {
        return pending;
    }
    const task = runMiniAutoLogin(force).finally(() => {
        if (pending === task) {
            pending = null;
        }
    });
    pending = task;
    return task;
}
 
async function runMiniAutoLogin(force = false) {
    const user = useUserStore();
    if (!force && user.token && user.info?.phone && !storage.isExpired("token")) {
        return true;
    }
 
    const code = await wxLoginCode();
    if (!code) {
        return false;
    }
 
    const res = await new BaseService("app/user/login").request({
        url: "/miniAuto",
        method: "POST",
        data: { code },
    });
 
    if (!res?.token) {
        return false;
    }
 
    user.setToken(res);
    user.set({
        ...(user.info || {}),
        id: res.id,
        unionid: res.unionid,
        phone: res.phone,
        nickName: res.nickName || user.info?.nickName,
        avatarUrl: res.avatarUrl || user.info?.avatarUrl,
    });
    return true;
}