1

I'm a little confused and don't know why my function isn't working. In fact I want to redirect the user to the login page if a token is not in LocalStorage. I use Redux, so a authReducer and a userActions". My application don't redirect the user! Thank you in advance

My authReducer...

import { authConstants } from "../../constants/userConstants"; 

export const authReducer = (state = { user: {}, token: null, roles:{}, isAuthenticated: false, 
isRegistered: true }, action) => {
switch (action.type) {

    case authConstants.REGISTER_USER_REQUEST:
        return {
            loading: true,
            isRegistered: false
        }
        
    case authConstants.LOGIN_REQUEST:
    case authConstants.LOAD_USER_REQUEST:
        return {
            loading: true,
            isAuthenticated: false,
        } 

    case authConstants.LOGIN_SUCCESS:
    case authConstants.LOAD_USER_SUCCESS:
        return {
            ...state,
            loading: false,
            isAuthenticated: true,
            user: action.payload.user.username,
            token: action.payload.token,
            roles: action.payload.roles
        }

    case authConstants.REGISTER_USER_SUCCESS:
        return {
            ...state,
            loading: false,
            isRegistered: true,
            
        }

    case authConstants.LOGOUT_SUCCESS:
        return {
            loading: false,
            isAuthenticated: false,
            user: null
        }

    case authConstants.LOAD_USER_FAIL:
        return {
            loading: false,
            isAuthenticated: false,
            user: null,
            error: action.payload
        }

    case authConstants.LOGOUT_FAIL:
        return {
            ...state,
            error: action.payload
        }

    case authConstants.LOGIN_FAIL:
    case authConstants.REGISTER_USER_FAIL:
        return {
            ...state,
            loading: false,
            isAuthenticated: false,
            user: null,
            message: action.payload
        }

    case CLEAR_ERRORS:
        return {
            ...state,
            error: null
        }

    default:
        return state
  }
 }

My authActions

import { authConstants } from "../../constants/userConstants"
import axios from "axios";
import { toast } from 'react-toastify';

export const login = (user) => {
console.log("test ", user);

return (dispatch) => {
    dispatch({
        type: authConstants.LOGIN_REQUEST
    });

    axios.post('/login', {
        ...user,
    })
    .then((response) => {
        if(response.data.success === true){
            const { token, user, roles } = response.data;
            // console.log(response.data.user.token)
            localStorage.setItem('token', user.token);
            localStorage.setItem('user', JSON.stringify(user.username));
            localStorage.setItem('roles', user.roles);
            toast.success("Successfully Connected !");
            dispatch({
                type: authConstants.LOGIN_SUCCESS,
                payload: { token, user, roles }
            });
        }else{
            if (response.data.success === false) {
                // console.log(response.data.full_messages[0])
                toast.error(response.data.full_messages[0]);

                dispatch({
                    type: authConstants.LOGIN_FAIL,
                    payload: { message: response.data.full_messages[0] }
                });
            } 
        }
    })
    .catch((error) => {
        console.log("Oops, Request failed!");
    });
    }
    }

a part of my root file. this is my login page and dashboard route, my logic for verify the token to redirect

class Root extends Component {
render() {
    return (
        <Provider store={store}>
            <BrowserRouter basename={'/'}>
                <ScrollContext>
                    <Switch>
                        <Route path='/login' component={Login} />
                        {/* <Route exact path='/login' component={Login} /> */}
                        <App>
                            <Route exact path='/' component={Dashboard} />
                                         .
                                         .
                                         .
                                         
          if (token) {

               console.log(token);
               store.dispatch(login)

          }else{
             store.dispatch({ type: authConstants.LOGIN_FAIL });
          }
    ReactDOM.render(<Root />, document.getElementById('root'));

I would really appreciate an answer from you. Thank you!

NSK17039
  • 13
  • 1
  • 2

1 Answers1

0

You could check this answer: How to restrict access to routes in react-router?

Basically, You would create a wrapper component to check for the login status.

NvN
  • 89
  • 1