-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy pathauth.ts
86 lines (82 loc) · 1.94 KB
/
auth.ts
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
82
83
84
85
86
import { defineStore } from "pinia";
import useMe, { Me } from "~/composables/api/auth/useMe";
import { HTTP_UNAUTHORIZED, POST } from "~/constants/http";
import { User } from "~/types/user";
import { AppFetch } from "~/types/AppFetch";
type AuthState = {
authUser: Me | null;
isPending: boolean;
authUrl: string;
};
const login = async (
fetcher: AppFetch<any>,
username: string,
password: string
) => {
return fetcher("/login", {
method: POST,
body: {
username,
password,
},
}) as Promise<User>;
};
export const useAuthUser = defineStore({
id: "auth-store",
state: (): AuthState => ({
authUser: null,
isPending: false,
authUrl: "",
//authUrl: ""
}),
actions: {
async authenticateUser(
username: string,
password: string,
fetch: AppFetch<any>
) {
return login(fetch, username, password);
},
resetAuth() {
this.authUser = null;
},
setAuthUser(authUser: Me) {
this.authUser = authUser;
},
startPending() {
this.isPending = true;
},
endPending() {
this.isPending = false;
},
async syncMe() {
if (this.isPending) {
return;
}
this.startPending();
// Our session is based on the PHPSESSID cookie
const me = useMe();
try {
const authUser = await me();
this.setAuthUser(authUser);
this.endPending();
return;
} catch (exception: any) {
this.endPending();
const is401 = exception?.response?.status === HTTP_UNAUTHORIZED;
if (!is401) {
// TODO error store in appFetch
throw exception;
}
const ret = await exception.response._data;
this.authUrl = ret?.url || "/auth/login";
return;
}
},
},
getters: {
isAuthenticated: (state) => !!state.authUser,
isAuthUser: (state) => (user: User) => state.authUser?.id === user.id,
},
});
export default useAuthUser;