refactor: implement new login logic and verify context.api status

This commit is contained in:
Prayag Prajapati committed 2024-05-29 18:10:22 +05:30
1 parent b1737b82e8
commit b8552ac35d
25 files changed
+589 -513

No files matched your search

+225 -251
View File
@@ -1,5 +1,5 @@
import { queryOptions, useQuery } from "@tanstack/react-query";
import React, { useLayoutEffect, useState } from "react";
import { queryOptions, useMutation, useQuery } from "@tanstack/react-query";
import React, { type FormEvent, useLayoutEffect, useState } from "react";
import { saveUser } from "@/utils/storage/user.js";
@@ -9,9 +9,11 @@ import {
DialogActions,
DialogContent,
DialogContentText,
FilledInput,
Grid,
OutlinedInput,
Paper,
TextField,
Tooltip,
Typography,
} from "@mui/material";
@@ -28,16 +30,21 @@ import InputLabel from "@mui/material/InputLabel";
import { useSnackbar } from "notistack";
import { AppBarBackOnly } from "@/components/appBar/backOnly.jsx";
import { createApi, useApiInContext } from "@/utils/store/api.js";
import { useApiInContext } from "@/utils/store/api.js";
import { getBrandingApi } from "@jellyfin/sdk/lib/utils/api/branding-api";
import { getQuickConnectApi } from "@jellyfin/sdk/lib/utils/api/quick-connect-api";
import { getUserApi } from "@jellyfin/sdk/lib/utils/api/user-api";
import "./login.scss";
import { queryClient } from "@/main.js";
import { setBackdrop } from "@/utils/store/backdrop.js";
import { blue } from "@mui/material/colors";
import { createFileRoute, useNavigate } from "@tanstack/react-router";
import {
createFileRoute,
useNavigate,
useRouteContext,
useRouter,
useRouterState,
} from "@tanstack/react-router";
import { redirect } from "@tanstack/react-router";
export const Route = createFileRoute("/_api/login/manual")({
@@ -49,7 +56,11 @@ function UserLoginManual() {
const [quickConnectLoading, setQuickConnectLoading] = useState(-1);
const [quickConnectCode, setQuickConnectCode] = useState("");
const [rememberMe, setRememberMe] = useState(true);
const api = Route.useRouteContext().api;
// console.log(Route.useRouteContext());
const api = useApiInContext((s) => s.api);
const createApi = useApiInContext((s) => s.createApi);
const router = useRouter();
const searchParams = Route.useSearch();
const server = useQuery({
queryKey: ["login", "manual", "serverInfo"],
@@ -61,14 +72,14 @@ function UserLoginManual() {
const navigate = useNavigate();
const { enqueueSnackbar } = useSnackbar();
const [password, setPassword] = useState({
const [username, setUsername] = useState("");
const [password, setPassword] = useState<{
password: string | undefined;
showpass: boolean;
}>({
showpass: false,
password: "",
});
const [userName, setUserName] = useState("");
const handleUsername = (event) => {
setUserName(event.target.value);
};
const handlePassword = (prop) => (event) => {
setPassword({
@@ -84,33 +95,34 @@ function UserLoginManual() {
});
};
const authUser = async () => {
const handleLoginFn = async (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
try {
const auth = await api.authenticateUserByName(
userName,
const authenticate = await api.authenticateUserByName(
username,
password.password,
);
return auth;
} catch (error) {
enqueueSnackbar("Incorrect Username or Password!", {
variant: "error",
createApi(api.basePath, authenticate.data?.AccessToken);
if (rememberMe) await saveUser(username, authenticate.data.AccessToken);
router.invalidate().finally(() => {
navigate({ to: searchParams.redirect || "/home", replace: true });
});
setLoading(false);
console.error(error);
} catch (err) {
console.error(err);
enqueueSnackbar(
"Unable to authenticate. Please check your username and password",
{ variant: "error" },
);
}
return;
};
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);
}
setLoading(false);
navigate("/home");
};
const handleLogin = useMutation({
mutationKey: ["login", "authenticate"],
mutationFn: handleLoginFn,
});
const handleCheckRememberMe = (event) => {
setRememberMe(event.target.checked);
@@ -211,238 +223,200 @@ function UserLoginManual() {
return (
<>
<AppBarBackOnly />
<Container
maxWidth="xs"
sx={{
height: "100vh",
display: "flex",
justifyContent: "center",
alignItems: "center",
}}
>
<Grid
container
spacing={2}
direction="column"
justifyContent="center"
alignItems="center"
sx={{
transition: "opacity 200ms",
width: "100%",
}}
<div className="login scrollY">
<div
className={`login-form-container ${
server.data?.LoginDisclaimer && "padded-top"
}`}
>
<Grid sx={{ marginBottom: "1em" }}>
<Typography variant="h3" color="textPrimary">
Login
</Typography>
</Grid>
<Grid sx={{ width: "100%", mb: 1 }}>
<Typography variant="h3" color="textPrimary">
Login
</Typography>
<form className="login-form" onSubmit={(e) => handleLogin.mutate(e)}>
<TextField
variant="outlined"
label="Username"
onChange={(e) => setUsername(e.currentTarget.value)}
/>
<FormControl sx={{ width: "100%" }} variant="outlined">
<InputLabel htmlFor="user-name">Username:</InputLabel>
<InputLabel htmlFor="user-password">Password:</InputLabel>
<OutlinedInput
fullWidth
id="user-name"
type="text"
variant="outlined"
label="Username:"
onChange={handleUsername}
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>
}
/>
</FormControl>
</Grid>
<Grid sx={{ width: "100%" }}>
<FormGroup>
<FormControl sx={{ width: "100%" }} variant="outlined">
<InputLabel htmlFor="user-password">Password:</InputLabel>
<OutlinedInput
fullWidth
id="user-password"
type={password.showpass ? "text" : "password"}
variant="outlined"
onChange={handlePassword("password")}
onKeyUp={(event) => {
if (event.key === "Enter") {
handleLogin();
}
}}
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>
}
<FormControlLabel
control={
<Checkbox
checked={rememberMe}
onChange={handleCheckRememberMe}
/>
</FormControl>
<FormControlLabel
control={
<Checkbox
checked={rememberMe}
onChange={handleCheckRememberMe}
/>
}
label="Remember me"
/>
</FormGroup>
</Grid>
<div
className="flex flex-column"
style={{ width: "100%", gap: "0.4em" }}
>
<LoadingButton
variant="contained"
endIcon={
<span className="material-symbols-rounded">chevron_right</span>
}
onClick={handleLogin}
loading={loading}
loadingPosition="end"
size="large"
sx={{ width: "100%" }}
>
Login
</LoadingButton>
<LoadingButton
onClick={handleQuickConnect}
variant="contained"
className="userEventButton"
sx={{ width: "100%" }}
loading={quickConnectLoading === 1}
// size="large"
>
Quick Connect
</LoadingButton>
<Button
color="secondary"
variant="contained"
className="userEventButton"
// size="large"
sx={{ width: "100%" }}
onClick={() => navigate("/servers/list")}
>
Change Server
</Button>
</div>
<Dialog open={Boolean(quickConnectCode)} fullWidth maxWidth="xs">
<DialogContent
style={{
display: "flex",
flexDirection: "column",
alignItems: "center",
}}
>
<Typography
variant="h5"
mb={2}
style={{
width: "100%",
}}
>
Quick Connect Code:
</Typography>
<DialogContentText>
Use this code in the Quick Connect tab in your server to login.
</DialogContentText>
<div
className="flex flex-row"
style={{ gap: "1em", alignItems: "center", marginTop: "1em" }}
>
<Tooltip title="Click to copy" arrow placement="top">
<Typography
variant="h3"
color="textPrimary"
textAlign="center"
sx={{
background: "rgb(255 255 255 / 0.1)",
width: "fit-content",
padding: "0.4em",
borderRadius: "10px",
cursor: "pointer",
}}
onClick={(e) => {
navigator.clipboard.writeText(quickConnectCode);
enqueueSnackbar("Quick Connect Code copied!", {
variant: "info",
key: "copiedText",
});
}}
>
{quickConnectCode}
</Typography>
</Tooltip>
</div>
</DialogContent>
<DialogActions
label="Remember me"
/>
<div
className="flex flex-row"
sx={{
padding: "0em 1em 1em 1em",
justifyContent: "space-between",
style={{ width: "100%", gap: "0.8em", flexWrap: "wrap" }}
>
<LoadingButton
variant="contained"
type="submit"
loading={handleLogin.isPending}
sx={{ width: "100%" }}
>
Login
</LoadingButton>
<LoadingButton
onClick={handleQuickConnect}
variant="contained"
className="userEventButton"
style={{ flex: 1 }}
loading={quickConnectLoading === 1}
// size="large"
>
Quick Connect
</LoadingButton>
<Button
color="secondary"
variant="contained"
className="userEventButton"
// size="large"
style={{ flex: 1 }}
onClick={() => navigate("/servers/list")}
>
Change Server
</Button>
</div>
</form>
</div>
{server.isSuccess && server.data.LoginDisclaimer && (
<Paper
elevation={5}
style={{
marginTop: "1em",
padding: "1em",
borderRadius: "15px",
width: "32em",
}}
>
<div
className="flex flex-row flex-align-center"
style={{ gap: "0.5em", marginBottom: "0.5em" }}
>
<span
className="material-symbols-rounded"
style={{
color: blue[700],
"--fill": 1,
}}
>
info
</span>
Notice
</div>
<Typography variant="subtitle2" style={{ opacity: 0.8 }}>
{server.data.LoginDisclaimer}
</Typography>
</Paper>
)}
<Dialog open={Boolean(quickConnectCode)} fullWidth maxWidth="xs">
<DialogContent
style={{
display: "flex",
flexDirection: "column",
alignItems: "center",
}}
>
<Typography
variant="h5"
mb={2}
style={{
width: "100%",
}}
>
<FormControlLabel
control={
<Checkbox
checked={rememberMe}
onChange={handleCheckRememberMe}
/>
}
label="Remember device"
/>
<Button
variant="contained"
onClick={() => {
setQuickConnectCode("");
setQuickConnectLoading(-1);
}}
>
Close
</Button>
</DialogActions>
</Dialog>
<Grid sx={{ width: "100%" }}>
{server.isSuccess && server.data.LoginDisclaimer && (
<Paper
elevation={5}
style={{
marginTop: "1em",
padding: "1em",
borderRadius: "15px",
}}
>
<div
className="flex flex-row flex-align-center"
style={{ gap: "0.5em", marginBottom: "0.5em" }}
Quick Connect Code:
</Typography>
<DialogContentText>
Use this code in the Quick Connect tab in your server to login.
</DialogContentText>
<div
className="flex flex-row"
style={{ gap: "1em", alignItems: "center", marginTop: "1em" }}
>
<Tooltip title="Click to copy" arrow placement="top">
<Typography
variant="h3"
color="textPrimary"
textAlign="center"
sx={{
background: "rgb(255 255 255 / 0.1)",
width: "fit-content",
padding: "0.4em",
borderRadius: "10px",
cursor: "pointer",
}}
onClick={(e) => {
navigator.clipboard.writeText(quickConnectCode);
enqueueSnackbar("Quick Connect Code copied!", {
variant: "info",
key: "copiedText",
});
}}
>
<span
className="material-symbols-rounded"
style={{
color: blue[700],
"--fill": 1,
}}
>
info
</span>
Notice
</div>
<Typography variant="subtitle2" style={{ opacity: 0.8 }}>
{server.data.LoginDisclaimer}
{quickConnectCode}
</Typography>
</Paper>
)}
</Grid>
</Grid>
</Container>
</Tooltip>
</div>
</DialogContent>
<DialogActions
className="flex flex-row"
sx={{
padding: "0em 1em 1em 1em",
justifyContent: "space-between",
}}
>
<FormControlLabel
control={
<Checkbox
checked={rememberMe}
onChange={handleCheckRememberMe}
/>
}
label="Remember device"
/>
<Button
variant="contained"
onClick={() => {
setQuickConnectCode("");
setQuickConnectLoading(-1);
}}
>
Close
</Button>
</DialogActions>
</Dialog>
</div>
</>
);
}