auth - when creds were wrong, fixed
This commit is contained in:
@@ -1,14 +1,14 @@
|
||||
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<typeof UserUncheckedCreateInputObjectSchema>;
|
||||
|
||||
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) {
|
||||
@@ -32,10 +32,10 @@ function generateToken(user: SelectUser) {
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
|
||||
// User registration route
|
||||
router.post("/register", async (req: Request, res: Response, next: NextFunction): Promise<any> => {
|
||||
|
||||
router.post(
|
||||
"/register",
|
||||
async (req: Request, res: Response, next: NextFunction): Promise<any> => {
|
||||
try {
|
||||
const existingUser = await storage.getUserByUsername(req.body.username);
|
||||
if (existingUser) {
|
||||
@@ -53,29 +53,42 @@ router.post("/register", async (req: Request, res: Response, next: NextFunction)
|
||||
|
||||
const { password, ...safeUser } = user;
|
||||
return res.status(201).json({ user: safeUser, token });
|
||||
|
||||
} catch (error) {
|
||||
next(error);
|
||||
console.error("Registration error:", error);
|
||||
return res.status(500).json({ error: "Internal server error" });
|
||||
}
|
||||
});
|
||||
}
|
||||
);
|
||||
|
||||
// User login route
|
||||
router.post("/login", async (req: Request, res: Response, next: NextFunction): Promise<any> => {
|
||||
router.post(
|
||||
"/login",
|
||||
async (req: Request, res: Response, next: NextFunction): Promise<any> => {
|
||||
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");
|
||||
|
||||
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) {
|
||||
next(error);
|
||||
return res.status(500).json({ error: "Internal server 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;
|
||||
@@ -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");
|
||||
},
|
||||
|
||||
@@ -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}`);
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user