From 64dc43daa7b40103b153e8a0f5d155a2f4fed0be Mon Sep 17 00:00:00 2001 From: Potenz Date: Thu, 3 Jul 2025 23:21:40 +0530 Subject: [PATCH] auth - when creds were wrong, fixed --- apps/Backend/src/routes/auth.ts | 106 ++++++++++++++------------ apps/Frontend/src/hooks/use-auth.tsx | 34 +++++++-- apps/Frontend/src/lib/queryClient.ts | 5 +- apps/Frontend/src/pages/auth-page.tsx | 37 +++++---- 4 files changed, 113 insertions(+), 69 deletions(-) diff --git a/apps/Backend/src/routes/auth.ts b/apps/Backend/src/routes/auth.ts index 3b628f0..8be85b0 100644 --- a/apps/Backend/src/routes/auth.ts +++ b/apps/Backend/src/routes/auth.ts @@ -1,18 +1,18 @@ -import express, { Request, Response, NextFunction } from 'express'; -import jwt from 'jsonwebtoken'; -import bcrypt from 'bcrypt'; -import { storage } from '../storage'; -import { UserUncheckedCreateInputObjectSchema } from '@repo/db/usedSchemas'; -import { z } from 'zod'; +import express, { Request, Response, NextFunction } from "express"; +import jwt from "jsonwebtoken"; +import bcrypt from "bcrypt"; +import { storage } from "../storage"; +import { UserUncheckedCreateInputObjectSchema } from "@repo/db/usedSchemas"; +import { z } from "zod"; type SelectUser = z.infer; -const JWT_SECRET = process.env.JWT_SECRET || 'your-jwt-secret'; -const JWT_EXPIRATION = '24h'; // JWT expiration time (1 day) +const JWT_SECRET = process.env.JWT_SECRET || "your-jwt-secret"; +const JWT_EXPIRATION = "24h"; // JWT expiration time (1 day) // Function to hash password using bcrypt async function hashPassword(password: string) { - const saltRounds = 10; // Salt rounds for bcrypt + const saltRounds = 10; // Salt rounds for bcrypt const hashedPassword = await bcrypt.hash(password, saltRounds); return hashedPassword; } @@ -32,50 +32,63 @@ function generateToken(user: SelectUser) { const router = express.Router(); - // User registration route -router.post("/register", async (req: Request, res: Response, next: NextFunction): Promise => { +router.post( + "/register", + async (req: Request, res: Response, next: NextFunction): Promise => { + try { + const existingUser = await storage.getUserByUsername(req.body.username); + if (existingUser) { + return res.status(400).send("Username already exists"); + } - try { - const existingUser = await storage.getUserByUsername(req.body.username); - if (existingUser) { - return res.status(400).send("Username already exists"); + const hashedPassword = await hashPassword(req.body.password); + const user = await storage.createUser({ + ...req.body, + password: hashedPassword, + }); + + // Generate a JWT token for the user after successful registration + const token = generateToken(user); + + const { password, ...safeUser } = user; + return res.status(201).json({ user: safeUser, token }); + } catch (error) { + console.error("Registration error:", error); + return res.status(500).json({ error: "Internal server error" }); } - - const hashedPassword = await hashPassword(req.body.password); - const user = await storage.createUser({ - ...req.body, - password: hashedPassword, - }); - - // Generate a JWT token for the user after successful registration - const token = generateToken(user); - - const { password, ...safeUser } = user; - return res.status(201).json({ user: safeUser, token }); - - } catch (error) { - next(error); } -}); +); // User login route -router.post("/login", async (req: Request, res: Response, next: NextFunction): Promise => { - try { - const user = await storage.getUserByUsername(req.body.username); - if (!user || !(await comparePasswords(req.body.password, user.password))) { - return res.status(401).send("Invalid username or password"); +router.post( + "/login", + async (req: Request, res: Response, next: NextFunction): Promise => { + try { + const user = await storage.getUserByUsername(req.body.username); + + if (!user) { + return res.status(401).json({ error: "Invalid username or password" }); + } + + const isPasswordMatch = await comparePasswords( + req.body.password, + user.password + ); + + if (!isPasswordMatch) { + return res.status(401).json({ error: "Invalid password or password" }); + } + + // Generate a JWT token for the user after successful login + const token = generateToken(user); + const { password, ...safeUser } = user; + return res.status(200).json({ user: safeUser, token }); + } catch (error) { + return res.status(500).json({ error: "Internal server error" }); } - - // Generate a JWT token for the user after successful login - const token = generateToken(user); - const { password, ...safeUser } = user; - return res.status(200).json({ user: safeUser, token }); - - } catch (error) { - next(error); } -}); +); // Logout route (client-side action to remove the token) router.post("/logout", (req: Request, res: Response) => { @@ -83,5 +96,4 @@ router.post("/logout", (req: Request, res: Response) => { res.status(200).send("Logged out successfully"); }); - -export default router; \ No newline at end of file +export default router; diff --git a/apps/Frontend/src/hooks/use-auth.tsx b/apps/Frontend/src/hooks/use-auth.tsx index 48a8a4c..46f1d72 100644 --- a/apps/Frontend/src/hooks/use-auth.tsx +++ b/apps/Frontend/src/hooks/use-auth.tsx @@ -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"); }, diff --git a/apps/Frontend/src/lib/queryClient.ts b/apps/Frontend/src/lib/queryClient.ts index 1c62606..3f8634c 100644 --- a/apps/Frontend/src/lib/queryClient.ts +++ b/apps/Frontend/src/lib/queryClient.ts @@ -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}`); diff --git a/apps/Frontend/src/pages/auth-page.tsx b/apps/Frontend/src/pages/auth-page.tsx index b30c523..cf4c98c 100644 --- a/apps/Frontend/src/pages/auth-page.tsx +++ b/apps/Frontend/src/pages/auth-page.tsx @@ -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 @@ -53,7 +54,8 @@ type RegisterFormValues = z.infer; export default function AuthPage() { const [activeTab, setActiveTab] = useState("login"); - const { user, loginMutation, registerMutation } = useAuth(); + const { isLoading, user, loginMutation, registerMutation } = useAuth(); + const [, navigate] = useLocation(); const loginForm = useForm({ 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 ; + if (isLoading) { + return ; } + useEffect(() => { + if (user) { + navigate("/"); + } + }, [user, navigate]); + return (