Add: redirect back to where the user was

This commit is contained in:
Aroy-Art 2025-02-27 22:15:43 +01:00
parent 4c094920fd
commit 6be77a6859
Signed by: Aroy
GPG key ID: 583642324A1D2070

View file

@ -1,10 +1,12 @@
import React, { useState } from "react";
import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button"
import { Card, CardContent } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { CircleAlert } from "lucide-react";
import { login } from "@/services/auth";
@ -17,13 +19,28 @@ export function LoginForm({
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const handelSubmit = async (e) => {
const navigate = useNavigate();
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const handelLogin = async (e) => {
e.preventDefault();
try {
setLoading(true)
await login(username, password);
window.location.href = "/";
} catch (error) {
alert("Login failed!");
// Get the stored redirect path from localStorage
const redirectPath = localStorage.getItem("redirect_after_login") || "/";
localStorage.removeItem("redirect_after_login"); // clear the redirect path after use
// Redirect to the stored path
navigate(redirectPath, { replace: true });
} catch (err) {
setError("Invalid credentials. Please try again.");
console.log(err)
} finally {
setLoading(false);
}
};
@ -31,14 +48,18 @@ export function LoginForm({
<div className={cn("flex flex-col gap-6", className)} {...props}>
<Card className="overflow-hidden border-2 border-fuchsia-800">
<CardContent className="grid p-0 md:grid-cols-2">
<form onSubmit={handelSubmit} className="p-6 md:p-8">
<form onSubmit={handelLogin} className="p-6 md:p-8">
<div className="flex flex-col gap-6">
<div className="flex flex-col items-center text-center">
<h1 className="text-2xl font-bold">Welcome back</h1>
<p className="text-balance text-muted-foreground">
Login to your Gallery Archive account
Login to your {__SITE_NAME__} account
</p>
</div>
{error && <div className="flex flex-row border-2 border-red-600 p-6 bg-red-400 bg-opacity-40 rounded-md">
<CircleAlert />
<p className="ps-4">{error}</p>
</div>}
<div className="grid gap-2">
<Label htmlFor="username">Username</Label>
<Input
@ -68,7 +89,7 @@ export function LoginForm({
/>
</div>
<Button type="submit" className="w-full bg-primary">
Login
{loading ? "Logging in..." : "Login"}
</Button>
{/* <div className="relative text-center text-sm after:absolute after:inset-0 after:top-1/2 after:z-0 after:flex after:items-center after:border-t after:border-border">
<span className="relative z-10 bg-background px-2 text-muted-foreground">