Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
7.1 kB
2
Indexable
Never
import React, { useState } from "react";
import Backdrop from "@mui/material/Backdrop";
import CircularProgress from "@mui/material/CircularProgress";
import Button from "@mui/material/Button";
import TextField from "@mui/material/TextField";
import Visibility from "@mui/icons-material/Visibility";
import VisibilityOff from "@mui/icons-material/VisibilityOff";
import InputAdornment from "@mui/material/InputAdornment";
import IconButton from "@mui/material/IconButton";
import SignupLogo from "../../assets/icons/signup.png";
import buchAssistLogo from "../../assets/icons/buchAssistLogo.png";
import Alert from "../../components/alerts/Alert";
import "../../assets/stylesheets/styles.css";
import { PasswordOutlined } from "@mui/icons-material";
import { useTranslation } from "react-i18next";
import jwt_decode from "jwt-decode";
import { useDispatch } from "react-redux";
import { login } from "../../store/user";
import { useNavigate } from "react-router-dom";

const Login = () => {
  const navigate = useNavigate();

  //redux variables
  let user;
  const dispatch = useDispatch();
  const { t } = useTranslation();

  const [showPassword, setShowPassword] = useState(false);
  const handleClickShowPassword = () => setShowPassword(!showPassword);
  const handleMouseDownPassword = () => setShowPassword(!showPassword);

  //utils
  const [loading, setLoading] = useState(false);
  const [isAlert, setIsAlert] = useState({
    open: false,
    severity: "",
    message: "",
  });

  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");

  const handleSubmit = async (e) => {
    e.preventDefault();

    setLoading(true);

    var myHeaders = new Headers();

    myHeaders.append("Content-Type", "application/json");

    var raw = JSON.stringify({
      user: {
        email: email,
        password: password,
      },
    });

    var requestOptions = {
      method: "POST",
      headers: myHeaders,
      body: raw,
      redirect: "follow",
    };
    const url = process.env.REACT_APP_API_URL + "users/sign_in";
    fetch(url, requestOptions)
      .then((response) => {
        //console.log(response.headers.get("Authorization"));

        let token = response.headers.get("Authorization");

        if (token !== null) {
          //window.localStorage.setItem("rails_token", token);
          user = jwt_decode(token);
          user.rails = token;
          dispatch(login({ ...user }));

          setIsAlert({
            open: true,
            severity: "success",
            message: "You are successfully logged in",
          });

          navigate("/home");
        } else {
          setIsAlert({
            open: true,
            severity: "error",
            message: "You have entered an invalid email or password",
          });
          setLoading(false);
        }
      })

      .catch((error) => console.log("error", error));
  };
  return (
    <>
      <section className="vh-100">
        <div className="container-fluid">
          <div className="row">
            <div className="col-sm-4" style={{ background: "white" }}>
              <div className="mt-5 px-5 text-center">
                <img
                  src={buchAssistLogo}
                  alt="buchAssistLogo"
                  style={{ width: "60px", height: "50px" }}
                />
                <h3 className="fw-bold">BuchAssist</h3>
                <h5 className="fw-bold">Devisen</h5>
                <h5 className="fw-bold">Log in</h5>
              </div>

              <div className="px-5 mt-3 pt-5 pt-xl-0 mt-xl-n5">
                <form onSubmit={handleSubmit}>
                  <div className="row mt-5">
                    <div className="col">
                      <TextField
                        required
                        type="text"
                        value={email}
                        onChange={(e) => setEmail(e.target.value)}
                        placeholder="name@domain.com"
                        style={{ width: "100%" }}
                        label={"Email"}
                      />

                      <br />
                      <br />

                      <TextField
                        required
                        type={showPassword ? "text" : "password"}
                        onChange={(e) => setPassword(e.target.value)}
                        placeholder="At least 6 characters"
                        style={{ width: "100%" }}
                        label={"Password"}
                        InputProps={{
                          endAdornment: (
                            <InputAdornment position="end">
                              <IconButton
                                aria-label="toggle password visibility"
                                onClick={handleClickShowPassword}
                                onMouseDown={handleMouseDownPassword}
                              >
                                {showPassword ? (
                                  <Visibility />
                                ) : (
                                  <VisibilityOff />
                                )}
                              </IconButton>
                            </InputAdornment>
                          ),
                        }}
                      />
                    </div>
                  </div>

                  <Button
                    type="submit"
                    className="mt-3 mb-3 main-button"
                    style={{ width: "100%" }}
                  >
                    Log in
                  </Button>

                  <p className="normal-text text-center">
                    {t("Login.New to BuchAssist? Register")}{" "}
                    <span
                      onClick={() => (window.location.href = "/")}
                      className="main-link"
                      style={{ cursor: "pointer" }}
                    >
                      {t("Login.here")}
                    </span>
                  </p>
                </form>
              </div>
            </div>

            <div
              className="col-sm-8 px-0 d-none d-sm-block"
              style={{ background: "#E0EAFF" }}
            >
              <img
                src={SignupLogo}
                alt="Signup BuchAssist"
                className="w-90 vh-100"
                style={{
                  objectFit: "scale-down",
                  backgroundRepeat: "no-repeat",
                  backgroundSize: "contain",
                }}
              />
            </div>
          </div>
        </div>

        {isAlert.open && (
          <Alert
            isAlert={isAlert}
            setIsAlert={setIsAlert}
            severity={isAlert.severity}
            message={isAlert.message}
          />
        )}
      </section>
      <Backdrop
        sx={{ color: "#fff", zIndex: (theme) => theme.zIndex.drawer + 1 }}
        open={loading}
      >
        <CircularProgress color="inherit" />
      </Backdrop>
    </>
  );
};

export default Login;