source: frontend/src/configurations/AuthContext.jsx@ badbc79

Last change on this file since badbc79 was badbc79, checked in by Luka Cheshlarov <luka.cheshlarov@…>, 20 months ago

Initial commit

  • Property mode set to 100644
File size: 2.7 KB
Line 
1import {createContext, useContext, useEffect, useState} from 'react'
2import {Navigate, useLocation} from "react-router-dom";
3import {toast} from "react-toastify";
4import axios from "axios";
5
6const AuthContext = createContext(null);
7
8const AuthProvider = props => {
9 const [loggedUser, setLoggedUser] = useState(null);
10 const [loggedUserRole, setLoggedUserRole] = useState(null);
11
12 useEffect(() => {
13 let authData = JSON.parse(sessionStorage.getItem("authData"));
14 if (authData) {
15 let roleUser = {
16 roleId: authData.userRoleId,
17 role: authData.userRole,
18 activeOwnershipId: authData.activeOwnershipId
19 }
20
21 login(authData.userId, roleUser);
22 }
23 }, [])
24
25 const login = (id, role) => {
26 setLoggedUser(id);
27 setLoggedUserRole(role);
28 }
29
30 const ownershipChanges = (value) => {
31 let authData = JSON.parse(sessionStorage.getItem("authData"));
32 authData.activeOwnershipId = value;
33 sessionStorage.setItem("authData", JSON.stringify(authData));
34
35 setLoggedUserRole({...loggedUserRole, value})
36 }
37
38 const logout = () => {
39 sessionStorage.removeItem("authData");
40 toast.success('Logged out');
41
42 setLoggedUser(null);
43 setLoggedUserRole(null);
44 axios.defaults.headers.common['Authorization'] = null;
45
46 window.location.reload();
47 }
48
49 const isAuthorized = (id) => {
50 if (!loggedUserRole) {
51 return false;
52 }
53
54 return id === loggedUserRole.roleId;
55 }
56
57 return (
58 <AuthContext.Provider
59 value={{
60 loggedUser: loggedUser,
61 loggedUserRole: loggedUserRole,
62 setLoggedUser: setLoggedUser,
63 setLoggedUserRole: setLoggedUserRole,
64 login: login,
65 logout: logout,
66 ownershipChanges,
67 isAuthorized: isAuthorized,
68 }}
69 >
70 {props.children}
71 </AuthContext.Provider>
72 )
73}
74
75const AuthConsumer = AuthContext.Consumer
76
77const useAuthContext = () => {
78 const context = useContext(AuthContext)
79 if (!context) {
80 throw new Error('authContext must be used within a AuthProvider')
81 }
82 return context
83}
84
85const RequireAuth = ({children}) => {
86 let auth = useAuthContext();
87 let location = useLocation();
88
89 if (!auth.user) {
90 return <Navigate to="/login" state={{from: location}} replace/>;
91 }
92
93 return children;
94}
95
96const SkipAuth = ({children}) => {
97 let auth = useAuthContext();
98
99 if (auth.loggedUser) {
100 return <Navigate to={"/"} replace/>;
101 }
102
103 return children;
104}
105
106export {AuthProvider, useAuthContext, RequireAuth, SkipAuth, AuthConsumer}
Note: See TracBrowser for help on using the repository browser.