Skip to main content

Overview

DADDO uses a secure token-based authentication system built with JWT tokens. The authentication flow includes user registration, login with remember me functionality, password recovery, and protected routes.

Login Flow

Redux Action: LoginUser

The login system is implemented in src/Redux/actions/Auth/login.js and handles authentication with token storage:
export const LoginUser = (credentials, rememberMe) => async (dispatch) => {
  try {
    dispatch({ type: LOGIN_REQUEST });

    const { data } = await api.post("/user/login", credentials);

    const storage = rememberMe ? localStorage : sessionStorage;
    storage.setItem("token", data.token);
    storage.setItem("user", JSON.stringify(data.userdata));

    dispatch({
      type: LOGIN_SUCCESS,
      payload: { token: data.token, user: data.userdata },
    });
  } catch (error) {
    dispatch({
      type: LOGIN_FAILURE,
      payload: error.response?.data?.message || error.message,
    });
  }
};
The rememberMe parameter determines whether credentials are stored in localStorage (persistent) or sessionStorage (session-only).

Login Component

The login page (src/Views/LoginPage.jsx) provides a modern UI with:
  • Email and password input fields
  • Password visibility toggle
  • “Remember me” checkbox
  • Error message display
  • Loading states
  • Links to registration and public catalogs
Key Features:
  • Real-time form validation
  • Animated UI with fade-in effects
  • Responsive design with gradient backgrounds
  • Auto-navigation on successful login
const handleSubmit = (e) => {
  e.preventDefault();
  dispatch(LoginUser({ email: useremail, password: userpassword }, rememberMe));
};

useEffect(() => {
  if (token && !error) {
    navigateRef.current('/home');
  }
}, [token, error]);

User Registration

Create User Action

New users are registered through the createUser action in src/Redux/actions/Auth/create_user.js:
export const createUser = (userData) => {
  return async dispatch => {
    dispatch ({type: CREATE_USER});

    try{
      const response = await api.post("/user", userData);
      
      dispatch({type: CREATE_USER, payload: response.data});
    }catch(error){
      return ({error: error.message});
    }
  }
}

Registration Page

Access the registration form at /create to create a new account with business details.

User Profile

After registration, users can update their profile information including business name and phone.

Password Recovery

Request Password Reset

The password recovery system uses a two-step verification process: Step 1: Request Reset Email Implemented in src/Redux/actions/Auth/requestPassword.js:
export const requestPasswordReset = (email) => async () => {
  try {
    const { data } = await api.post("/user/request-reset", { email });
    toast.success(data.message || "Correo enviado con instrucciones");
  } catch (error) {
    toast.error(error?.response?.data?.error || "No se pudo enviar el correo");
  }
};
Step 2: Verify Token and Reset The system verifies the reset token before allowing password changes:
export const verifyResetToken = (token) => async () => {
  try {
    const { data } = await api.get(`/user/reset/${token}`);
    return data.valid;
  } catch (error) {
    toast.error("Token inválido o expirado");
    return false;
  }
};

Password Reset Component

The ForgotPassword component (src/components/ForgotPassword.jsx) provides:
  • Token validation on page load
  • New password input with confirmation
  • Password strength requirements (minimum 6 characters)
  • Success/error notifications
  • Auto-redirect to login after successful reset
  1. User requests password reset by providing email
  2. System sends email with unique reset token
  3. User clicks link in email with token parameter
  4. Component validates token on load
  5. If valid, user can enter new password
  6. System updates password and redirects to login

Protected Routes

Route Protection Component

All authenticated routes are protected using the Protected_Route component (src/components/Protected_Route.jsx):
import { Navigate, Outlet } from "react-router-dom";
import { useSelector } from "react-redux";

const Protected_Route = () => {
  const token = useSelector(state => state.auth.token);
  return token ? <Outlet /> : <Navigate to="/" />;
};

Protected Routes List

The following routes require authentication (src/App.jsx):

/home

Main dashboard homepage

/createProd

Create new products

/my-catalog

Generate catalog links and QR codes

/createSell

Record new sales

/dash

Analytics dashboard

/Sells

View sales history

/products

Manage all products

/profile

User profile settings

Logout Functionality

Users can logout using the logout action that clears all stored credentials:
export const logout = () => (dispatch) => {
  localStorage.removeItem('token');
  localStorage.removeItem('user');
  dispatch({ type: LOGOUT });
};
Logging out removes both the JWT token and user data from storage, requiring a fresh login to access protected routes.

Security Features

  • JWT tokens stored securely in browser storage
  • Automatic token validation on protected routes
  • Token included in API request headers
  • Session vs. persistent storage based on user preference
  • User-friendly error messages
  • Automatic redirect on invalid/expired tokens
  • Storage cleanup on authentication failures
  • Toast notifications for all auth events
  • Loading states during authentication
  • Animated transitions
  • Password visibility toggle
  • Auto-navigation on success
  • Remember me functionality

API Integration

All authentication requests use the centralized API instance configured in src/Redux/api.js with:
  • Base URL configuration
  • Automatic token injection in headers
  • Error interceptors
  • Response transformers
const { data } = await api.post("/user/login", credentials);
The authentication system automatically handles token refresh and maintains user session across page reloads when “Remember me” is enabled.

Build docs developers (and LLMs) love