Files
Fulfillment-Frontend/src/features/authSlice.ts

57 lines
1.6 KiB
TypeScript

import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import { jwtDecode, JwtPayload as JwtPayloadBase } from "jwt-decode";
interface AuthState {
isAuthorized: boolean;
accessToken: string;
isGuest: boolean;
role: string;
}
const initialState = (): AuthState => {
const localStorageState = localStorage.getItem("authState");
if (localStorageState !== null) {
return JSON.parse(localStorageState);
}
return {
accessToken: "",
isAuthorized: 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,
);
state.accessToken = action.payload.accessToken;
state.isAuthorized = true;
state.role = role;
if (sub === "guest") state.isGuest = true;
} 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;