65 lines
1.9 KiB
TypeScript
65 lines
1.9 KiB
TypeScript
import { createSlice, PayloadAction } from "@reduxjs/toolkit";
|
|
import { jwtDecode, JwtPayload as JwtPayloadBase } from "jwt-decode";
|
|
import { OpenAPI } from "../client";
|
|
|
|
interface AuthState {
|
|
isAuthorized: boolean;
|
|
accessToken: string;
|
|
isDealEditor: boolean;
|
|
isDealsViewer: boolean;
|
|
isGuest: boolean;
|
|
role: string;
|
|
}
|
|
|
|
const initialState = (): AuthState => {
|
|
const localStorageState = localStorage.getItem("authState");
|
|
if (localStorageState !== null) {
|
|
return JSON.parse(localStorageState);
|
|
}
|
|
return {
|
|
accessToken: "",
|
|
isAuthorized: false,
|
|
isDealEditor: false,
|
|
isDealsViewer: false,
|
|
isGuest: false,
|
|
role: "user",
|
|
};
|
|
};
|
|
|
|
interface JwtPayload extends JwtPayloadBase {
|
|
role: string;
|
|
}
|
|
|
|
const authSlice = createSlice({
|
|
name: "auth",
|
|
initialState,
|
|
reducers: {
|
|
login: (state, action: PayloadAction<{ accessToken: string }>) => {
|
|
try {
|
|
const { sub, role } = jwtDecode<JwtPayload>(
|
|
action.payload.accessToken,
|
|
);
|
|
OpenAPI.TOKEN = action.payload.accessToken;
|
|
state.accessToken = action.payload.accessToken;
|
|
state.isAuthorized = true;
|
|
state.role = role;
|
|
state.isDealEditor = sub === "deal_editor";
|
|
state.isDealsViewer = sub === "deals_viewer";
|
|
state.isGuest = state.isDealEditor || state.isDealsViewer;
|
|
} catch (_) {
|
|
const url = window.location.href;
|
|
const urlObj = new URL(url);
|
|
urlObj.search = "";
|
|
history.replaceState(null, "", urlObj);
|
|
window.location.reload();
|
|
}
|
|
},
|
|
logout: state => {
|
|
state.isAuthorized = false;
|
|
state.accessToken = "";
|
|
},
|
|
},
|
|
});
|
|
export const { login, logout } = authSlice.actions;
|
|
export default authSlice.reducer;
|