auth - when creds were wrong, fixed
This commit is contained in:
@@ -1,18 +1,18 @@
|
|||||||
import express, { Request, Response, NextFunction } from 'express';
|
import express, { Request, Response, NextFunction } from "express";
|
||||||
import jwt from 'jsonwebtoken';
|
import jwt from "jsonwebtoken";
|
||||||
import bcrypt from 'bcrypt';
|
import bcrypt from "bcrypt";
|
||||||
import { storage } from '../storage';
|
import { storage } from "../storage";
|
||||||
import { UserUncheckedCreateInputObjectSchema } from '@repo/db/usedSchemas';
|
import { UserUncheckedCreateInputObjectSchema } from "@repo/db/usedSchemas";
|
||||||
import { z } from 'zod';
|
import { z } from "zod";
|
||||||
|
|
||||||
type SelectUser = z.infer<typeof UserUncheckedCreateInputObjectSchema>;
|
type SelectUser = z.infer<typeof UserUncheckedCreateInputObjectSchema>;
|
||||||
|
|
||||||
const JWT_SECRET = process.env.JWT_SECRET || 'your-jwt-secret';
|
const JWT_SECRET = process.env.JWT_SECRET || "your-jwt-secret";
|
||||||
const JWT_EXPIRATION = '24h'; // JWT expiration time (1 day)
|
const JWT_EXPIRATION = "24h"; // JWT expiration time (1 day)
|
||||||
|
|
||||||
// Function to hash password using bcrypt
|
// Function to hash password using bcrypt
|
||||||
async function hashPassword(password: string) {
|
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);
|
const hashedPassword = await bcrypt.hash(password, saltRounds);
|
||||||
return hashedPassword;
|
return hashedPassword;
|
||||||
}
|
}
|
||||||
@@ -32,50 +32,63 @@ function generateToken(user: SelectUser) {
|
|||||||
|
|
||||||
const router = express.Router();
|
const router = express.Router();
|
||||||
|
|
||||||
|
|
||||||
// User registration route
|
// 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) {
|
||||||
|
return res.status(400).send("Username already exists");
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
const hashedPassword = await hashPassword(req.body.password);
|
||||||
const existingUser = await storage.getUserByUsername(req.body.username);
|
const user = await storage.createUser({
|
||||||
if (existingUser) {
|
...req.body,
|
||||||
return res.status(400).send("Username already exists");
|
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
|
// User login route
|
||||||
router.post("/login", async (req: Request, res: Response, next: NextFunction): Promise<any> => {
|
router.post(
|
||||||
try {
|
"/login",
|
||||||
const user = await storage.getUserByUsername(req.body.username);
|
async (req: Request, res: Response, next: NextFunction): Promise<any> => {
|
||||||
if (!user || !(await comparePasswords(req.body.password, user.password))) {
|
try {
|
||||||
return res.status(401).send("Invalid username or password");
|
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)
|
// Logout route (client-side action to remove the token)
|
||||||
router.post("/logout", (req: Request, res: Response) => {
|
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");
|
res.status(200).send("Logged out successfully");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
export default router;
|
export default router;
|
||||||
@@ -55,15 +55,25 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
|||||||
mutationFn: async (credentials: LoginData) => {
|
mutationFn: async (credentials: LoginData) => {
|
||||||
const res = await apiRequest("POST", "/api/auth/login", credentials);
|
const res = await apiRequest("POST", "/api/auth/login", credentials);
|
||||||
|
|
||||||
const data = await res.json();
|
const contentType = res.headers.get("content-type") || "";
|
||||||
localStorage.setItem("token", data.token);
|
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) => {
|
onSuccess: (user: SelectUser) => {
|
||||||
queryClient.setQueryData(["/api/users/"], user);
|
queryClient.setQueryData(["/api/users/"], user);
|
||||||
},
|
},
|
||||||
onError: (error: Error) => {
|
onError: (error: Error) => {
|
||||||
|
console.error("Login error:", error);
|
||||||
toast({
|
toast({
|
||||||
title: "Login failed",
|
title: "Login failed",
|
||||||
description: error.message,
|
description: error.message,
|
||||||
@@ -75,14 +85,27 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
|||||||
const registerMutation = useMutation({
|
const registerMutation = useMutation({
|
||||||
mutationFn: async (credentials: InsertUser) => {
|
mutationFn: async (credentials: InsertUser) => {
|
||||||
const res = await apiRequest("POST", "/api/auth/register", credentials);
|
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);
|
localStorage.setItem("token", data.token);
|
||||||
return data;
|
return data.user;
|
||||||
},
|
},
|
||||||
onSuccess: (user: SelectUser) => {
|
onSuccess: (user: SelectUser) => {
|
||||||
queryClient.setQueryData(["/api/users/"], user);
|
queryClient.setQueryData(["/api/users/"], user);
|
||||||
},
|
},
|
||||||
onError: (error: Error) => {
|
onError: (error: Error) => {
|
||||||
|
console.error("Registration error:", error);
|
||||||
toast({
|
toast({
|
||||||
title: "Registration failed",
|
title: "Registration failed",
|
||||||
description: error.message,
|
description: error.message,
|
||||||
@@ -93,7 +116,6 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
|||||||
|
|
||||||
const logoutMutation = useMutation({
|
const logoutMutation = useMutation({
|
||||||
mutationFn: async () => {
|
mutationFn: async () => {
|
||||||
// Remove token from localStorage when logging out
|
|
||||||
localStorage.removeItem("token");
|
localStorage.removeItem("token");
|
||||||
await apiRequest("POST", "/api/auth/logout");
|
await apiRequest("POST", "/api/auth/logout");
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -8,7 +8,10 @@ async function throwIfResNotOk(res: Response) {
|
|||||||
|
|
||||||
if (res.status === 401 || res.status === 403) {
|
if (res.status === 401 || res.status === 403) {
|
||||||
localStorage.removeItem("token");
|
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;
|
return;
|
||||||
}
|
}
|
||||||
throw new Error(`${res.status}: ${text}`);
|
throw new Error(`${res.status}: ${text}`);
|
||||||
|
|||||||
@@ -2,9 +2,8 @@ import { useForm } from "react-hook-form";
|
|||||||
import { zodResolver } from "@hookform/resolvers/zod";
|
import { zodResolver } from "@hookform/resolvers/zod";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { UserUncheckedCreateInputObjectSchema } from "@repo/db/usedSchemas";
|
import { UserUncheckedCreateInputObjectSchema } from "@repo/db/usedSchemas";
|
||||||
import { useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import { useAuth } from "@/hooks/use-auth";
|
import { useAuth } from "@/hooks/use-auth";
|
||||||
import { Redirect } from "wouter";
|
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import {
|
import {
|
||||||
Form,
|
Form,
|
||||||
@@ -17,9 +16,11 @@ import {
|
|||||||
import { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||||
import { Checkbox } from "@/components/ui/checkbox";
|
import { Checkbox } from "@/components/ui/checkbox";
|
||||||
import { Card, CardContent } from "@/components/ui/card";
|
import { Card} from "@/components/ui/card";
|
||||||
import { BriefcaseMedical, CheckCircle, Torus } from "lucide-react";
|
import { CheckCircle, Torus } from "lucide-react";
|
||||||
import { CheckedState } from "@radix-ui/react-checkbox";
|
import { CheckedState } from "@radix-ui/react-checkbox";
|
||||||
|
import LoadingScreen from "@/components/ui/LoadingScreen";
|
||||||
|
import { useLocation } from "wouter";
|
||||||
|
|
||||||
const insertUserSchema = (
|
const insertUserSchema = (
|
||||||
UserUncheckedCreateInputObjectSchema as unknown as z.ZodObject<any>
|
UserUncheckedCreateInputObjectSchema as unknown as z.ZodObject<any>
|
||||||
@@ -53,7 +54,8 @@ type RegisterFormValues = z.infer<typeof registerSchema>;
|
|||||||
|
|
||||||
export default function AuthPage() {
|
export default function AuthPage() {
|
||||||
const [activeTab, setActiveTab] = useState<string>("login");
|
const [activeTab, setActiveTab] = useState<string>("login");
|
||||||
const { user, loginMutation, registerMutation } = useAuth();
|
const { isLoading, user, loginMutation, registerMutation } = useAuth();
|
||||||
|
const [, navigate] = useLocation();
|
||||||
|
|
||||||
const loginForm = useForm<LoginFormValues>({
|
const loginForm = useForm<LoginFormValues>({
|
||||||
resolver: zodResolver(loginSchema),
|
resolver: zodResolver(loginSchema),
|
||||||
@@ -75,10 +77,7 @@ export default function AuthPage() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const onLoginSubmit = (data: LoginFormValues) => {
|
const onLoginSubmit = (data: LoginFormValues) => {
|
||||||
loginMutation.mutate({
|
loginMutation.mutate({ username: data.username, password: data.password });
|
||||||
username: data.username,
|
|
||||||
password: data.password,
|
|
||||||
});
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const onRegisterSubmit = (data: RegisterFormValues) => {
|
const onRegisterSubmit = (data: RegisterFormValues) => {
|
||||||
@@ -88,11 +87,16 @@ export default function AuthPage() {
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
// Redirect if already logged in
|
if (isLoading) {
|
||||||
if (user) {
|
return <LoadingScreen />;
|
||||||
return <Redirect to="/" />;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (user) {
|
||||||
|
navigate("/");
|
||||||
|
}
|
||||||
|
}, [user, navigate]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen bg-gray-100 flex items-center justify-center">
|
<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">
|
<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>
|
</div>
|
||||||
)}
|
)}
|
||||||
/>
|
/>
|
||||||
<a
|
<button
|
||||||
href="#"
|
type="button"
|
||||||
|
onClick={() => {
|
||||||
|
// do something if needed
|
||||||
|
}}
|
||||||
className="text-sm font-medium text-primary hover:text-primary/80"
|
className="text-sm font-medium text-primary hover:text-primary/80"
|
||||||
>
|
>
|
||||||
Forgot password?
|
Forgot password?
|
||||||
</a>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<Button
|
<Button
|
||||||
|
|||||||
Reference in New Issue
Block a user