forked from aeharding/voyager
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauthSlice.ts
325 lines (265 loc) · 9.12 KB
/
authSlice.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
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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import { ApplicationContext } from "capacitor-application-context";
import { uniqBy } from "es-toolkit";
import { Register } from "lemmy-js-client";
import { resetComments } from "#/features/comment/commentSlice";
import { resetCommunities } from "#/features/community/communitySlice";
import { resetInbox } from "#/features/inbox/inboxSlice";
import { resetInstances } from "#/features/instances/instancesSlice";
import { resetMod } from "#/features/moderation/modSlice";
import { resetPosts } from "#/features/post/postSlice";
import { resetResolve } from "#/features/resolve/resolveSlice";
import { setDefaultFeed } from "#/features/settings/settingsSlice";
import { resetUsers } from "#/features/user/userSlice";
import { getRemoteHandle, parseLemmyJWT } from "#/helpers/lemmy";
import { getDefaultServer } from "#/services/app";
import { getClient } from "#/services/lemmy";
import { AppDispatch, RootState } from "#/store";
import { getInstanceFromHandle, instanceSelector } from "./authSelectors";
import { receivedSite, resetSite } from "./siteSlice";
const MULTI_ACCOUNT_STORAGE_NAME = "credentials";
/**
* DO NOT CHANGE this type. It is persisted.
*/
export interface Credential {
jwt?: string;
/**
* Can either be user handle or instance url.
*
* e.g. `aeharding@lemmy.world` or `lemmy.world`
*/
handle: string;
}
/**
* DO NOT CHANGE this type. It is persisted.
*/
interface CredentialStoragePayload {
accounts: Credential[];
/**
* Can either be user handle or instance url.
*
* e.g. `aeharding@lemmy.world` or `lemmy.world`
*/
activeHandle: string;
}
interface AuthState {
accountData: CredentialStoragePayload | undefined;
connectedInstance: string;
}
const initialState: (connectedInstance?: string) => AuthState = (
connectedInstance = "",
) => ({
accountData: getCredentialsFromStorage(),
connectedInstance,
});
export const authSlice = createSlice({
name: "auth",
initialState,
reducers: {
addAccount: (state, action: PayloadAction<Credential>) => {
state.accountData ??= {
accounts: [action.payload],
activeHandle: action.payload.handle,
};
let cleanedPreviousAccounts;
if (
state.accountData.accounts.length === 1 &&
!state.accountData.accounts[0]?.handle.includes("@")
) {
// If only one account, and it's a guest, just switch it out
cleanedPreviousAccounts = [action.payload];
} else {
// Remove guest accounts for this instance when logging in
cleanedPreviousAccounts = state.accountData.accounts.filter(
(a) => a.handle !== getInstanceFromHandle(action.payload.handle),
);
}
const accounts = uniqBy(
[action.payload, ...cleanedPreviousAccounts],
(c) => c.handle,
);
state.accountData = {
accounts,
activeHandle: action.payload.handle,
};
updateCredentialsStorage(state.accountData);
},
removeAccount: (state, action: PayloadAction<string>) => {
if (!state.accountData) return;
const accounts = state.accountData.accounts.filter(
(a) => a.handle !== action.payload,
);
const nextAccount = accounts[0];
if (!nextAccount) {
state.accountData = undefined;
updateCredentialsStorage(undefined);
return;
}
state.accountData.accounts = accounts;
if (state.accountData.activeHandle === action.payload) {
state.accountData.activeHandle = nextAccount.handle;
}
updateCredentialsStorage(state.accountData);
},
setPrimaryAccount: (state, action: PayloadAction<string>) => {
if (!state.accountData) return;
state.accountData.activeHandle = action.payload;
updateCredentialsStorage(state.accountData);
},
setAccounts: (state, action: PayloadAction<Credential[]>) => {
if (!state.accountData) return;
state.accountData.accounts = action.payload;
updateCredentialsStorage(state.accountData);
},
updateConnectedInstance(state, action: PayloadAction<string>) {
if (import.meta.env.VITE__TEST_MODE) {
state.connectedInstance = getDefaultServer();
return;
}
state.connectedInstance = action.payload;
},
reset: (state) => {
return initialState(state.connectedInstance);
},
},
});
// Action creators are generated for each case reducer function
export const {
addAccount,
removeAccount,
setPrimaryAccount,
setAccounts,
updateConnectedInstance,
reset,
} = authSlice.actions;
export default authSlice.reducer;
export const login =
(baseUrl: string, username: string, password: string, totp?: string) =>
async (dispatch: AppDispatch) => {
const client = getClient(baseUrl);
const res = await client.login({
username_or_email: username,
// lemmy-ui has maxlength of 60. If we don't clamp too users will complain password won't work
password: password.slice(0, 60),
totp_2fa_token: totp || undefined,
});
if (!res.jwt) {
// todo
throw new Error("broke");
}
await dispatch(addJwt(baseUrl, res.jwt));
};
export const register =
(baseUrl: string, register: Register) => async (dispatch: AppDispatch) => {
const client = getClient(baseUrl);
const res = await client.register(register);
if (!res.jwt) {
return res;
}
await dispatch(addJwt(baseUrl, res.jwt));
return true;
};
export const addGuestInstance =
(url: string) => async (dispatch: AppDispatch) => {
const client = getClient(url);
const site = await client.getSite();
dispatch(resetAccountSpecificStoreData());
dispatch(receivedSite(site));
dispatch(addAccount({ handle: url }));
dispatch(updateConnectedInstance(url));
};
const addJwt =
(baseUrl: string, jwt: string) => async (dispatch: AppDispatch) => {
const authenticatedClient = getClient(baseUrl, jwt);
const site = await authenticatedClient.getSite();
const myUser = site.my_user?.local_user_view?.person;
if (!myUser) throw new Error("broke");
dispatch(resetAccountSpecificStoreData());
dispatch(receivedSite(site));
dispatch(addAccount({ jwt, handle: getRemoteHandle(myUser) }));
dispatch(updateConnectedInstance(parseLemmyJWT(jwt).iss));
};
const resetAccountSpecificStoreData = () => (dispatch: AppDispatch) => {
dispatch(resetPosts());
dispatch(resetComments());
dispatch(resetUsers());
dispatch(resetInbox());
dispatch(resetCommunities());
dispatch(resetResolve());
dispatch(resetInstances());
dispatch(resetMod());
dispatch(resetSite());
dispatch(setDefaultFeed(undefined));
};
export const logoutEverything = () => (dispatch: AppDispatch) => {
dispatch(reset());
dispatch(resetAccountSpecificStoreData());
};
export const changeAccount =
(handle: string) => (dispatch: AppDispatch, getState: () => RootState) => {
dispatch(resetAccountSpecificStoreData());
dispatch(setPrimaryAccount(handle));
const instanceUrl = instanceSelector(getState());
if (instanceUrl) dispatch(updateConnectedInstance(instanceUrl));
};
export const logoutAccount =
(handle: string) => (dispatch: AppDispatch, getState: () => RootState) => {
const accountData = getState().auth.accountData;
const currentAccount = accountData?.accounts?.find(
({ handle: h }) => handle === h,
);
// Going to need to change active accounts
if (handle === accountData?.activeHandle) {
dispatch(resetAccountSpecificStoreData());
}
// revoke token
if (currentAccount && currentAccount.jwt)
getClient(
parseLemmyJWT(currentAccount.jwt).iss,
currentAccount.jwt,
)?.logout();
dispatch(removeAccount(handle));
const instanceUrl = instanceSelector(getState());
if (instanceUrl) dispatch(updateConnectedInstance(instanceUrl));
};
function updateCredentialsStorage(
accounts: CredentialStoragePayload | undefined,
) {
updateApplicationContextIfNeeded(accounts);
if (!accounts) {
localStorage.removeItem(MULTI_ACCOUNT_STORAGE_NAME);
return;
}
localStorage.setItem(MULTI_ACCOUNT_STORAGE_NAME, JSON.stringify(accounts));
}
function getCredentialsFromStorage(): CredentialStoragePayload | undefined {
const serializedCredentials = localStorage.getItem(
MULTI_ACCOUNT_STORAGE_NAME,
);
if (!serializedCredentials) return;
return JSON.parse(serializedCredentials);
}
// Run once on app load to sync state if needed
updateApplicationContextIfNeeded(getCredentialsFromStorage());
/**
* This syncs application state for the Apple Watch App
*/
function updateApplicationContextIfNeeded(
accounts: CredentialStoragePayload | undefined,
) {
const DEFAULT_INSTANCE = "lemm.ee";
const connectedInstance = (() => {
if (!accounts) return DEFAULT_INSTANCE;
if (!accounts.activeHandle.includes("@")) return accounts.activeHandle;
return accounts.activeHandle.slice(
accounts.activeHandle.lastIndexOf("@") + 1,
);
})();
ApplicationContext.updateApplicationContext({
connectedInstance,
authToken: accounts
? (accounts.accounts.find((a) => a.handle === accounts.activeHandle)
?.jwt ?? "")
: "",
});
}