Skip to content
Snippets Groups Projects
Commit b265d450 authored by Defendi Alberto's avatar Defendi Alberto
Browse files

Merge branch 'fix/authorization' into 'dev'

Fix/authorization

See merge request !50
parents bb875367 b7ce3a82
No related branches found
No related tags found
2 merge requests!56Refined auth flow and new website pages.,!50Fix/authorization
Pipeline #12384 passed
......@@ -16,23 +16,22 @@ import { Dashboard } from 'components/AuthUser/Dashboard/Dashboard';
import { isAuthenticated } from 'api/isAuthenticated';
import { muiTheme } from 'App.style';
import { getRole } from 'api/getRole';
import { withAuthorization } from 'components/Authorization/Authorization';
import { useRole } from 'hooks/useRole';
import { useAuth } from 'hooks/useAuth';
const Personal = withAuthorization(Dashboard);
/**
* Entry point of the app.
*/
export const App: FC = () => {
configDjangoCookieName();
const [role, setRole] = useState('');
const [isAuth, setIsAuth] = useState<boolean>(false);
const [role, setRole] = useRole();
const [isAuth, setIsAuth] = useAuth();
const value = { role, setRole, isAuth, setIsAuth };
useEffect(() => {
// Initialize asking the server if this session is already logged in.
isAuthenticated().then((responseState) => setIsAuth(responseState));
getRole().then((responseRole) => setRole(responseRole));
}, [isAuth, role]);
return (
<div data-testid="App">
<ThemeProvider theme={muiTheme}>
......@@ -42,20 +41,13 @@ export const App: FC = () => {
<Route exact path={NonAuthRoutes.home} component={LandingPage} />
<Route path={NonAuthRoutes.auth} component={AuthUser} />
<PrivateRoute
Component={Dashboard}
path={AuthRoutes.dashboard}
requiredRoles={[Roles.admin, Roles.operator, Roles.senior]}
/>
<PrivateRoute
Component={HomePage}
<Route
path={AuthRoutes.dashboard}
requiredRoles={[Roles.admin, Roles.operator, Roles.senior]}
/>
<PrivateRoute
Component={ProfilePage}
path={AuthRoutes.profile}
requiredRoles={[Roles.admin, Roles.operator, Roles.senior]}
render={() => (
<Personal
allowedRoles={['admin', 'driver', 'senior', 'operator']}
/>
)}
/>
<Route
path={NonAuthRoutes.unauthorized}
......
import React, { FC } from 'react';
import Container from '@material-ui/core/Container';
import { Route, useRouteMatch } from 'react-router-dom';
import { Redirect, Route, useRouteMatch } from 'react-router-dom';
import { AuthRoutes, NonAuthRoutes } from 'api/routes';
import { SignInForm } from 'components/AuthUser/SignInForm/SignInForm';
import { SignUpForm } from 'components/AuthUser/SignUpForm/SignUpForm';
......@@ -14,10 +14,7 @@ export const AuthUser: FC = () => {
const { path } = useRouteMatch();
return (
<Container maxWidth="sm">
<RestrictedRoute
path={`${path}${NonAuthRoutes.signIn}`}
Component={SignInForm}
/>
<Route path={`${path}${NonAuthRoutes.signIn}`} component={SignInForm} />
<Route path={`${path}${NonAuthRoutes.signUp}`} component={SignUpForm} />
<Route path={`${path}${AuthRoutes.choseRole}`} component={ChoseRole} />
</Container>
......
Chose role.
```
const role = ["operator", "driver",];
<ChoseRole role={role} />
```
\ No newline at end of file
......@@ -12,7 +12,7 @@ import { AuthRoutes } from 'api/routes';
*/
export const ChoseRole: FC = () => {
const history = useHistory();
const [userRoles, setUserRoles] = useState<string[]>(['hello', 'world']);
const [userRoles, setUserRoles] = useState<string[]>(['']);
const choseAndForward = (role: string): void => {
// Set role in the server.
......
......@@ -64,8 +64,6 @@ export const SignInForm: FC = () => {
} else if (response.data.status === 'role-choice-needed') {
history.replace(`${NonAuthRoutes.auth}${AuthRoutes.choseRole}`);
} else if (response.data.status === 'success') {
setRole(response.data.role);
setIsAuth(true);
history.replace(`${AuthRoutes.dashboard}${AuthRoutes.home}`);
}
});
......
import React, { ComponentType, FC, useContext } from 'react';
import { BlurCircular } from '@material-ui/icons';
import { NonAuthRoutes } from 'api/routes';
import { AuthContext } from 'components/AuthUser/AuthContext';
import { Unauthorized } from 'components/NonAuthUser/Unauthorized/Unauthorized';
import React, { ComponentType, FC } from 'react';
import { useAuth } from 'hooks/useAuth';
import { useRole } from 'hooks/useRole';
import { Redirect } from 'react-router-dom';
const HandleIsAuth: FC<{ isAuth: boolean }> = ({ isAuth }) =>
isAuth ? (
<Unauthorized />
) : (
<Redirect
to={{ pathname: `${NonAuthRoutes.auth}${NonAuthRoutes.signIn}` }}
/>
);
interface WithAuthProps {
allowedRoles: string[];
......@@ -25,14 +40,15 @@ export const withAuthorization = <T extends WithAuthProps = WithAuthProps>(
) => {
const { allowedRoles } = props as T;
const role = 'admin';
const isAuth = true;
const { role, isAuth } = useContext(AuthContext);
console.log(`ROLE ${role} AUTH ${isAuth}`);
// props comes afterwards so the can override the default ones.
return allowedRoles.includes(role) && isAuth ? (
<WrappedComponent {...(props as T)} />
) : (
<Unauthorized />
<HandleIsAuth isAuth={isAuth} />
);
};
......
import { isAuthenticated } from 'api/isAuthenticated';
import { useEffect, useState } from 'react';
/**
* Custom hook that uses the call is_authenticated.
* {@link isAuthenticated}
*
* @returns {boolean | null} isAuth: true if user is authenticated, false otherwise or null if the request has not finished.
*/
export const useAuth = (): [
boolean,
React.Dispatch<React.SetStateAction<boolean>>,
] => {
let isMounted = true;
const [isAuth, setIsAuth] = useState<boolean>(false);
useEffect(() => {
isAuthenticated().then((state) => {
if (isMounted) {
setIsAuth(state);
}
});
return () => {
isMounted = false;
};
}, []);
return [isAuth, setIsAuth];
};
import { fetchCookie } from 'api/fetchCookie';
import { useCallback, useEffect, useState } from 'react';
/**
* Custom hook that return csrf cookie fetched from server.
*
* @return cookie
*/
export const useCookie = (): string => {
const [cookie, setCookie] = useState('');
const askCookie = useCallback(() => {
let isMounted = true;
if (isMounted)
fetchCookie().then((cookieResponse) => setCookie(cookieResponse));
return () => {
isMounted = false;
};
}, []);
useEffect(() => {
askCookie();
}, [askCookie]);
return cookie;
};
import { getRole } from 'api/getRole';
import { useEffect, useState } from 'react';
export const useRole = (): [
string,
React.Dispatch<React.SetStateAction<string>>,
] => {
const [role, setRole] = useState('');
useEffect(() => {
let isMounted = true;
// Initialize asking the server if this session is already logged in.
getRole().then((responseRole) => {
if (isMounted) {
setRole(responseRole);
}
});
return () => {
isMounted = false;
};
}, []);
return [role, setRole];
};
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment