auth - when creds were wrong, fixed

This commit is contained in:
2025-07-03 23:21:40 +05:30
parent 54f80db08a
commit 64dc43daa7
4 changed files with 113 additions and 69 deletions

View File

@@ -55,15 +55,25 @@ export function AuthProvider({ children }: { children: ReactNode }) {
mutationFn: async (credentials: LoginData) => {
const res = await apiRequest("POST", "/api/auth/login", credentials);
const data = await res.json();
localStorage.setItem("token", data.token);
const contentType = res.headers.get("content-type") || "";
const isJson = contentType.includes("application/json");
const data = isJson ? await res.json() : {};
return data;
if (!res.ok) {
throw new Error(data?.error || "Login failed. Please try again.");
}
if (!data?.token || !data?.user) {
throw new Error("Invalid response from server");
}
localStorage.setItem("token", data.token);
return data.user;
},
onSuccess: (user: SelectUser) => {
queryClient.setQueryData(["/api/users/"], user);
},
onError: (error: Error) => {
console.error("Login error:", error);
toast({
title: "Login failed",
description: error.message,
@@ -75,14 +85,27 @@ export function AuthProvider({ children }: { children: ReactNode }) {
const registerMutation = useMutation({
mutationFn: async (credentials: InsertUser) => {
const res = await apiRequest("POST", "/api/auth/register", credentials);
const data = await res.json();
const contentType = res.headers.get("content-type") || "";
const isJson = contentType.includes("application/json");
const data = isJson ? await res.json() : {};
if (!res.ok) {
throw new Error(data?.error || "Registration failed.");
}
if (!data?.token || !data?.user) {
throw new Error("Invalid response from server");
}
localStorage.setItem("token", data.token);
return data;
return data.user;
},
onSuccess: (user: SelectUser) => {
queryClient.setQueryData(["/api/users/"], user);
},
onError: (error: Error) => {
console.error("Registration error:", error);
toast({
title: "Registration failed",
description: error.message,
@@ -93,7 +116,6 @@ export function AuthProvider({ children }: { children: ReactNode }) {
const logoutMutation = useMutation({
mutationFn: async () => {
// Remove token from localStorage when logging out
localStorage.removeItem("token");
await apiRequest("POST", "/api/auth/logout");
},

View File

@@ -8,7 +8,10 @@ async function throwIfResNotOk(res: Response) {
if (res.status === 401 || res.status === 403) {
localStorage.removeItem("token");
window.location.href = "/auth"; // 👈 Redirect on invalid/expired token
if (!window.location.pathname.startsWith("/auth")) {
window.location.href = "/auth";
throw new Error(`${res.status}: Unauthorized`);
}
return;
}
throw new Error(`${res.status}: ${text}`);

View File

@@ -2,9 +2,8 @@ import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { UserUncheckedCreateInputObjectSchema } from "@repo/db/usedSchemas";
import { useState } from "react";
import { useEffect, useState } from "react";
import { useAuth } from "@/hooks/use-auth";
import { Redirect } from "wouter";
import { Button } from "@/components/ui/button";
import {
Form,
@@ -17,9 +16,11 @@ import {
import { Input } from "@/components/ui/input";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Checkbox } from "@/components/ui/checkbox";
import { Card, CardContent } from "@/components/ui/card";
import { BriefcaseMedical, CheckCircle, Torus } from "lucide-react";
import { Card} from "@/components/ui/card";
import { CheckCircle, Torus } from "lucide-react";
import { CheckedState } from "@radix-ui/react-checkbox";
import LoadingScreen from "@/components/ui/LoadingScreen";
import { useLocation } from "wouter";
const insertUserSchema = (
UserUncheckedCreateInputObjectSchema as unknown as z.ZodObject<any>
@@ -53,7 +54,8 @@ type RegisterFormValues = z.infer<typeof registerSchema>;
export default function AuthPage() {
const [activeTab, setActiveTab] = useState<string>("login");
const { user, loginMutation, registerMutation } = useAuth();
const { isLoading, user, loginMutation, registerMutation } = useAuth();
const [, navigate] = useLocation();
const loginForm = useForm<LoginFormValues>({
resolver: zodResolver(loginSchema),
@@ -75,10 +77,7 @@ export default function AuthPage() {
});
const onLoginSubmit = (data: LoginFormValues) => {
loginMutation.mutate({
username: data.username,
password: data.password,
});
loginMutation.mutate({ username: data.username, password: data.password });
};
const onRegisterSubmit = (data: RegisterFormValues) => {
@@ -88,11 +87,16 @@ export default function AuthPage() {
});
};
// Redirect if already logged in
if (user) {
return <Redirect to="/" />;
if (isLoading) {
return <LoadingScreen />;
}
useEffect(() => {
if (user) {
navigate("/");
}
}, [user, navigate]);
return (
<div className="min-h-screen bg-gray-100 flex items-center justify-center">
<div className="w-full max-w-4xl grid grid-cols-1 md:grid-cols-2 shadow-lg rounded-lg overflow-hidden">
@@ -173,12 +177,15 @@ export default function AuthPage() {
</div>
)}
/>
<a
href="#"
<button
type="button"
onClick={() => {
// do something if needed
}}
className="text-sm font-medium text-primary hover:text-primary/80"
>
Forgot password?
</a>
</button>
</div>
<Button