Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
2.7 kB
1
Indexable
Never
import React, { useState, useEffect } from "react";
import { useFormik } from "formik";
import { useNavigate } from "react-router-dom";
import Button from '@mui/material/Button';
import './Login.css';

const pre_username = "DebashisSahoo@gmail.com";
const pre_password = "Ds@123456";

sessionStorage.setItem("name", pre_username);
sessionStorage.setItem("password", pre_password);

const Login = () => {
  const navi = useNavigate();
  const [errorMessage, setErrorMessage] = useState("");

  useEffect(() => {
    // If user is already authenticated, log them out
    if (sessionStorage.getItem("isAuthenticated") === "true") {
      sessionStorage.removeItem("isAuthenticated");
      sessionStorage.removeItem("name");
      sessionStorage.removeItem("password");
    }
  }, []);

  const formik = useFormik({
    initialValues: {
      'name': "",
      'password': ""
    },
    onSubmit: values => {
      if (values.name === sessionStorage.getItem("name") && values.password === sessionStorage.getItem("password")) {
        // Set authentication flag upon successful login
        sessionStorage.setItem("isAuthenticated", "true");
        navi('/Dashboard');
      } else if (values.name === "" || values.password === "") {
        setErrorMessage("Please enter both Username and Password.");
      } else {
        setErrorMessage("Invalid login credentials.");
      }
    }
  });

  return (
    <>
    <body className="login-body">
    <h1 className="login-title">WEATHER APP</h1><br /><br />
   
   <div className="login-container">
  
     
     
     
     <form className="login-form" onSubmit={formik.handleSubmit}>
       <label className="login-label" htmlFor="name">User_Name: 
         <input
           className="login-input"
           type="text"
           name="name"
           id="name"
           onChange={formik.handleChange}
           onBlur={formik.onBlur}
           value={formik.values.name}
           required
         />
       </label>
       <br /><br />
       <label className="login-label" htmlFor="password">Password: 
         <input
           className="login-input"
           type="password"
           name="password"
           id="password"
           onChange={formik.handleChange}
           onBlur={formik.onBlur}
           value={formik.values.password}
           required
         />
       </label>
       <br /><br /><br />
       {errorMessage && <p className="login-error">{errorMessage}</p>}
       <Button className="login-button" type="submit" variant="contained" onClick={formik.handleSubmit}>Login</Button>
     </form>
   </div>
    </body>
    </>
  );
}

export default Login;
Leave a Comment