refactor: improve login page UI #338 #202

This commit is contained in:
Prayag Prajapati committed 2024-11-20 21:51:42 +05:30
1 parent 19343b4ea3
commit 45f67aac40
9 files changed
+314 -316

No files matched your search

+149 -152
View File
@@ -1,51 +1,68 @@
import LoadingButton from "@mui/lab/LoadingButton";
import { OutlinedInput, Paper, Typography } from "@mui/material";
import { OutlinedInput, Typography } from "@mui/material";
import Checkbox from "@mui/material/Checkbox";
import FormControl from "@mui/material/FormControl";
import FormControlLabel from "@mui/material/FormControlLabel";
import FormGroup from "@mui/material/FormGroup";
import IconButton from "@mui/material/IconButton";
import InputAdornment from "@mui/material/InputAdornment";
import InputLabel from "@mui/material/InputLabel";
import { useSnackbar } from "notistack";
import { AppBarBackOnly } from "@/components/appBar/backOnly.jsx";
import { AvatarImage } from "@/components/avatar/avatar.jsx";
import "./login.scss";
import { saveUser } from "@/utils/storage/user";
import { useApiInContext } from "@/utils/store/api";
import { setBackdrop } from "@/utils/store/backdrop.js";
import { createFileRoute, useNavigate } from "@tanstack/react-router";
import React, { useLayoutEffect, useState } from "react";
import { useBackdropStore } from "@/utils/store/backdrop.js";
import { useMutation } from "@tanstack/react-query";
import {
createFileRoute,
useNavigate,
useRouter,
} from "@tanstack/react-router";
import React, {
type ChangeEvent,
type FormEvent,
useEffect,
useState,
} from "react";
export const Route = createFileRoute("/_api/login/$userId/$userName")({
component: LoginUser,
});
type PasswordState = {
showpass: boolean;
password: string | undefined;
};
function LoginUser() {
const { userName, userId } = Route.useParams();
const router = useRouter();
const api = useApiInContext((s) => s.api);
const createApi = useApiInContext((s) => s.createApi);
const [password, setPassword] = useState({
const [password, setPassword] = useState<PasswordState>({
showpass: false,
password: undefined,
});
const [loading, setLoading] = useState(false);
const [rememberMe, setRememberMe] = useState(true);
const navigate = useNavigate({ from: "/login/$userId/$userName" });
const { enqueueSnackbar } = useSnackbar();
const handlePassword = (prop) => (event) => {
setPassword({
...password,
[prop]: event.target.value,
});
};
const handlePassword =
(prop: "password" | "showPassord") =>
(event: ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
setPassword({
...password,
[prop]: event.target.value,
});
};
const handleShowPassword = () => {
setPassword({
@@ -54,159 +71,139 @@ function LoginUser() {
});
};
const authUser = async () => {
try {
const auth = await api.authenticateUserByName(
userName,
password.password,
);
return auth;
} catch (error) {
if (error.response?.status === 500) {
enqueueSnackbar(
"Unable to connect to server. Please try again after some time.",
{ variant: "error" },
);
} else {
enqueueSnackbar("Incorrect Password.", { variant: "error" });
}
setLoading(false);
console.error(error);
}
};
const setBackdrop = useBackdropStore((state) => state.setBackdrop);
const handleLogin = async () => {
setLoading(true);
const user = await authUser();
sessionStorage.setItem("accessToken", user.data.AccessToken);
createApi(api.basePath, user.data.AccessToken);
if (rememberMe === true) {
await saveUser(userName, user.data.AccessToken);
useEffect(() => {
if (!api) {
return;
}
setLoading(false);
navigate({ to: "/home" });
};
useLayoutEffect(() => {
setBackdrop("", "");
}, []);
const handleCheckRememberMe = (event) => {
setRememberMe(event.target.checked);
const handleCheckRememberMe = (
_: ChangeEvent<HTMLInputElement>,
checked: boolean,
) => {
setRememberMe(checked);
};
const handleLoginFn = async (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
try {
if (!api) {
throw new Error("API not initialized");
}
const authenticate = await api.authenticateUserByName(
userName,
password.password,
);
if (!authenticate.data.AccessToken) {
throw new Error("No access token received");
}
createApi(api.basePath, authenticate.data?.AccessToken);
if (rememberMe) await saveUser(userName, authenticate.data.AccessToken);
router.invalidate().finally(() => {
navigate({ to: "/home", replace: true });
});
} catch (err) {
console.error(err);
enqueueSnackbar("Unable to authenticate! Please check your password", {
variant: "error",
});
}
return;
};
const handleLogin = useMutation({
mutationKey: ["login", "authenticate"],
mutationFn: handleLoginFn,
});
return (
<>
<AppBarBackOnly />
<div
style={{
height: "100vh",
display: "flex",
justifyContent: "center",
alignItems: "center",
flexDirection: "column",
width: "30vw",
margin: "auto",
}}
<div
style={{
height: "100vh",
display: "flex",
justifyContent: "center",
alignItems: "center",
flexDirection: "column",
width: "30vw",
margin: "auto",
}}
>
<AvatarImage userId={userId} />
<Typography
textAlign="center"
variant="h5"
sx={{ opacity: 0.8 }}
mb={2}
mt={2}
>
<div
Login as{" "}
<Typography
variant="h5"
style={{
marginBottom: "-4em",
boxShadow: "1em 0 hsl(256, 100%, 6%)",
display: "inline",
}}
fontWeight={700}
className="gradient-text"
>
<AvatarImage userId={userId} />
</div>
<Paper
sx={{
{userName}
</Typography>
</Typography>
<form onSubmit={(e) => handleLogin.mutate(e)}>
<FormControl
variant="outlined"
style={{
width: "100%",
padding: "1em",
paddingTop: "5em",
borderRadius: "10px",
}}
elevation={2}
>
<Typography
textAlign="center"
variant="h5"
sx={{ opacity: 0.8 }}
mb={2}
>
Login as{" "}
<Typography
variant="h5"
style={{
display: "inline",
}}
fontWeight={700}
className="gradient-text"
>
{userName}
</Typography>
</Typography>
<FormGroup
sx={{
width: "100%",
}}
>
<FormControl
variant="outlined"
style={{
width: "100%",
}}
>
<InputLabel htmlFor="user-password">Password:</InputLabel>
<OutlinedInput
id="user-password"
type={password.showpass ? "text" : "password"}
variant="outlined"
onChange={handlePassword("password")}
label="Password:"
endAdornment={
<InputAdornment position="end">
<IconButton
onClick={handleShowPassword}
aria-label="toggle password visibility"
>
{password.showpass ? (
<span className="material-symbols-rounded">
visibility
</span>
) : (
<span className="material-symbols-rounded">
visibility_off
</span>
)}
</IconButton>
</InputAdornment>
}
/>
</FormControl>
<FormControlLabel
control={
<Checkbox
checked={rememberMe}
onChange={handleCheckRememberMe}
/>
}
label="Remember me"
/>
</FormGroup>
<LoadingButton
variant="contained"
endIcon={
<span className="material-symbols-rounded">chevron_right</span>
<InputLabel htmlFor="user-password">Password:</InputLabel>
<OutlinedInput
id="user-password"
type={password.showpass ? "text" : "password"}
onChange={handlePassword("password")}
label="Password:"
endAdornment={
<InputAdornment position="end">
<IconButton
onClick={handleShowPassword}
aria-label="toggle password visibility"
>
{password.showpass ? (
<span className="material-symbols-rounded">visibility</span>
) : (
<span className="material-symbols-rounded">
visibility_off
</span>
)}
</IconButton>
</InputAdornment>
}
onClick={handleLogin}
loading={loading}
loadingPosition="end"
size="large"
fullWidth
>
Login
</LoadingButton>
</Paper>
</div>
</>
/>
</FormControl>
<FormControlLabel
control={
<Checkbox checked={rememberMe} onChange={handleCheckRememberMe} />
}
label="Remember me"
/>
<LoadingButton
variant="contained"
endIcon={
<span className="material-symbols-rounded">chevron_right</span>
}
type="submit"
loading={handleLogin.isPending}
loadingPosition="end"
size="large"
fullWidth
>
Login
</LoadingButton>
</form>
</div>
);
}