duclayan / ai-questionnaire

Questionnaire Application for Consultants
0 stars 0 forks source link

When the user login, it should be authenticated and redirected to the forms #25

Closed duclayan closed 2 weeks ago

duclayan commented 2 weeks ago

To implement user authentication in your React application, you can use a combination of React Router for routing and a context or state management solution (like React Context API or Redux) to manage user authentication status. Below is a step-by-step guide to achieve the desired functionality:

Step 1: Set Up Authentication Context

Create a context to manage authentication state. This will allow you to share the authentication status across your application.

Create AuthContext.js

import React, { createContext, useContext, useState } from 'react';

// Create AuthContext
const AuthContext = createContext();

// Create a provider component
export const AuthProvider = ({ children }) => {
  const [isAuthenticated, setIsAuthenticated] = useState(false);

  const login = () => setIsAuthenticated(true);
  const logout = () => setIsAuthenticated(false);

  return (
    <AuthContext.Provider value={{ isAuthenticated, login, logout }}>
      {children}
    </AuthContext.Provider>
  );
};

// Custom hook to use auth context
export const useAuth = () => useContext(AuthContext);

Step 2: Protect Routes

Now, create a component to handle protected routes. This component will check if the user is authenticated and redirect them to the login page if they are not.

Create ProtectedRoute.js

import React from 'react';
import { Navigate } from 'react-router-dom';
import { useAuth } from './AuthContext';

const ProtectedRoute = ({ element }) => {
  const { isAuthenticated } = useAuth();

  return isAuthenticated ? element : <Navigate to="/" />;
};

export default ProtectedRoute;

Step 3: Update App.js

Now, integrate the AuthProvider and ProtectedRoute into your App.js file.

import React from 'react';
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
import { AuthProvider } from './AuthContext'; // Import AuthProvider
import Form from './views/Form/Form';
import Login from './views/Login/Login';
import Dashboard from './views/Dashboard/Dashboard';
import ProtectedRoute from './ProtectedRoute'; // Import ProtectedRoute

function App() {
  return (
    <AuthProvider>
      <Router>
        <Routes>
          <Route path="/" element={<Login />} />
          <Route path="/form" element={<Form />} />
          <Route path="/dashboard" element={<ProtectedRoute element={<Dashboard />} />} />
        </Routes>
      </Router>
    </AuthProvider>
  );
}

export default App;

Step 4: Implement Login Logic

In your Login component, you need to handle the login logic to update the authentication state.

Update Login.js

import React from 'react';
import { useAuth } from '../../AuthContext'; // Import useAuth
import { useNavigate } from 'react-router-dom';

const Login = () => {
  const { login } = useAuth();
  const navigate = useNavigate();

  const handleLogin = () => {
    // Perform login logic (e.g., API call)
    login(); // Update authentication state
    navigate('/dashboard'); // Redirect to dashboard after login
  };

  return (
    <div>
      <h2>Login Page</h2>
      <button onClick={handleLogin}>Login</button>
    </div>
  );
};

export default Login;

Step 5: Logout Functionality

You may also want to implement a logout functionality to allow users to log out and be redirected back to the login page.

Update Dashboard.js

import React from 'react';
import { useAuth } from '../../AuthContext'; // Import useAuth
import { useNavigate } from 'react-router-dom';

const Dashboard = () => {
  const { logout } = useAuth();
  const navigate = useNavigate();

  const handleLogout = () => {
    logout(); // Update authentication state
    navigate('/'); // Redirect to login page
  };

  return (
    <div>
      <h2>Dashboard</h2>
      <button onClick={handleLogout}>Logout</button>
    </div>
  );
};

export default Dashboard;

Summary

With these steps, you have implemented a simple authentication flow in your React application. Users will be redirected to the login page if they attempt to access the dashboard without being logged in. Once logged in, they can navigate freely without being redirected back to the login page unless they log out.

Feel free to enhance the login logic with actual authentication mechanisms, such as API calls to validate user credentials!

duclayan commented 2 weeks ago

Note: Adjustments has been added and material ui is used