authSlice.ts
1.16 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
import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import type { UserBrief } from "@/api/auth";
import { getToken, setToken, clearToken } from "@/api/client";
interface AuthState {
token: string | null;
user: UserBrief | null;
companyId: string | null; // "std" / "ent" / "trial"
companyName: string | null;
}
const initialState: AuthState = {
token: getToken(),
user: null,
companyId: null,
companyName: null,
};
const slice = createSlice({
name: "auth",
initialState,
reducers: {
loginSucceeded(
state,
action: PayloadAction<{
token: string;
user: UserBrief;
companyId: string;
companyName: string;
}>
) {
state.token = action.payload.token;
state.user = action.payload.user;
state.companyId = action.payload.companyId;
state.companyName = action.payload.companyName;
setToken(action.payload.token);
},
logout(state) {
state.token = null;
state.user = null;
state.companyId = null;
state.companyName = null;
clearToken();
},
},
});
export const { loginSucceeded, logout } = slice.actions;
export default slice.reducer;