-
Notifications
You must be signed in to change notification settings - Fork 54
Expand file tree
/
Copy pathauth.tsx
More file actions
219 lines (200 loc) · 5.93 KB
/
auth.tsx
File metadata and controls
219 lines (200 loc) · 5.93 KB
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
import { makePersisted } from "@solid-primitives/storage";
import { createStore, produce, reconcile } from "solid-js/store";
import { createEffect, createMemo, onMount } from "solid-js";
import { useLocation, useNavigate } from "@solidjs/router";
import { createClient } from "@openauthjs/openauth/client";
import { createInitializedContext } from "../common/context";
import { type Workspace } from "@console/core/workspace/index";
import { useCommandBar } from "../pages/workspace/command-bar";
import { IconLogout, IconUser, IconUserAdd } from "../ui/icons/custom";
interface AccountInfo {
id: string;
email: string;
workspaces: Workspace.Info[];
access: string;
refresh: string;
}
interface Storage {
accounts: Record<string, AccountInfo>;
current?: string;
}
export const client = createClient({
issuer: import.meta.env.VITE_AUTH_URL,
clientID: "web",
});
export const { use: useAuth, provider: AuthProvider } =
createInitializedContext("AuthContext", () => {
const [store, setStore] = makePersisted(
createStore<Storage>({
accounts: {},
}),
{
name: "sst.auth",
},
);
const location = useLocation();
const params = createMemo(
() => new URLSearchParams(location.hash.substring(1)),
);
const accessToken = createMemo(() => params().get("access_token"));
const refreshToken = createMemo(() => params().get("refresh_token"));
createEffect(async () => {
// if (!result.current && Object.keys(store.accounts).length) {
// result.switch(Object.keys(store.accounts)[0])
// navigate("/")
// }
})
createEffect(async () => {
if (accessToken()) return;
if (Object.keys(store.accounts).length) return;
const redir = await client.authorize(window.location.origin, "token");
window.location.href = redir.url
});
createEffect(async () => {
const current = store.current;
const accounts = store.accounts;
if (!current) return;
const match = accounts[current];
if (match) return;
const keys = Object.keys(accounts);
if (keys.length) {
setStore("current", keys[0]);
navigate("/");
return
}
const redir = await client.authorize(window.location.origin, "token");
window.location.href = redir.url
});
async function refresh() {
for (const account of [...Object.values(store.accounts)]) {
if (!account.refresh) continue;
const result = await client.refresh(account.refresh, {
access: account.access,
})
if (result.err) {
if ("id" in account)
setStore(produce((state) => {
delete state.accounts[account.id];
}))
continue
};
const tokens = result.tokens || {
access: account.access,
refresh: account.refresh,
}
fetch(import.meta.env.VITE_API_URL + "/account", {
headers: {
authorization: `Bearer ${tokens.access}`,
},
}).then(async (response) => {
await new Promise((resolve) => setTimeout(resolve, 5000));
if (response.ok) {
const info = await response.json();
setStore(
"accounts",
info.id,
reconcile({
...info,
...tokens,
}),
);
}
if (!response.ok)
setStore(
produce((state) => {
delete state.accounts[account.id];
}),
);
})
}
}
onMount(async () => {
if (refreshToken() && accessToken()) {
const result = await fetch(import.meta.env.VITE_API_URL + "/account", {
headers: {
authorization: `Bearer ${accessToken()}`,
},
}).catch(() => { })
if (result?.ok) {
const info = await result.json();
setStore(
"accounts",
info.id,
reconcile({
...info,
access: accessToken(),
refresh: refreshToken(),
}),
);
setStore("current", info.id);
}
window.location.hash = "";
}
await refresh();
})
const navigate = useNavigate();
const bar = useCommandBar()
bar.register("auth", async () => {
console.log("bar", bar)
return [
{
category: "Account",
title: "Logout",
icon: IconLogout,
run: async (bar) => {
result.logout();
setStore("current", undefined);
navigate("/");
bar.hide()
},
},
{
category: "Add Account",
title: "Add Account",
icon: IconUserAdd,
run: async () => {
const redir = await client.authorize(window.location.origin, "token");
window.location.href = redir.url
bar.hide()
},
},
...result.all()
.filter((item) => item.id !== result.current.id)
.map((item) => ({
category: "Account",
title: "Switch to " + item.email,
icon: IconUser,
run: async () => {
result.switch(item.id);
navigate("/");
bar.hide()
},
})),
]
})
const result = {
get current() {
return store.accounts[store.current!]!;
},
switch(accountID: string) {
setStore("current", accountID);
},
all() {
return Object.values(store.accounts);
},
refresh,
logout() {
setStore(
produce((state) => {
if (!state.current) return;
delete state.accounts[state.current];
state.current = Object.keys(state.accounts)[0];
}),
);
},
get ready() {
return Boolean(!accessToken() && store.current);
},
};
return result;
});