working on new login sign up flow

This commit is contained in:
jackiettran
2025-07-29 23:48:09 -04:00
parent 6cba15d36a
commit 72d79596ce
10 changed files with 763 additions and 29 deletions

View File

@@ -7,11 +7,11 @@
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Rentall - Rent gym equipment, tools, and musical instruments from your neighbors"
content="CommunityRentals.App - Rent gym equipment, tools, and musical instruments from your neighbors"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<title>Rentall - Equipment & Tool Rental Marketplace</title>
<title>CommunityRentals.App - Equipment & Tool Rental Marketplace</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
</head>

View File

@@ -0,0 +1,523 @@
import React, { useState, useEffect } from "react";
import { useAuth } from "../contexts/AuthContext";
interface AuthModalProps {
show: boolean;
onHide: () => void;
initialMode?: "login" | "signup";
}
const AuthModal: React.FC<AuthModalProps> = ({
show,
onHide,
initialMode = "login",
}) => {
const [mode, setMode] = useState<"login" | "signup">(initialMode);
const [authMethod, setAuthMethod] = useState<"phone" | "email" | null>(null);
const [phoneNumber, setPhoneNumber] = useState("");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [firstName, setFirstName] = useState("");
const [lastName, setLastName] = useState("");
const [verificationCode, setVerificationCode] = useState("");
const [showVerification, setShowVerification] = useState(false);
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");
const { login, register, updateUser } = useAuth();
// Update mode when modal is opened with different initialMode
useEffect(() => {
if (show && initialMode) {
setMode(initialMode);
}
}, [show, initialMode]);
// Format phone number as user types
const formatPhoneNumber = (value: string) => {
// Remove all non-numeric characters
let phoneNumber = value.replace(/\D/g, "");
// Remove leading 1 if present (US country code)
if (phoneNumber.length > 10 && phoneNumber.startsWith("1")) {
phoneNumber = phoneNumber.substring(1);
}
// Limit to 10 digits
phoneNumber = phoneNumber.substring(0, 10);
// Format as (XXX) XXX-XXXX
if (phoneNumber.length <= 3) {
return phoneNumber;
} else if (phoneNumber.length <= 6) {
return `(${phoneNumber.slice(0, 3)}) ${phoneNumber.slice(3)}`;
} else {
return `(${phoneNumber.slice(0, 3)}) ${phoneNumber.slice(
3,
6
)}-${phoneNumber.slice(6)}`;
}
};
const handlePhoneChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const formatted = formatPhoneNumber(e.target.value);
setPhoneNumber(formatted);
};
const handlePhoneSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setLoading(true);
setError("");
try {
// Clean the phone number
let cleanedNumber = phoneNumber.replace(/\D/g, "");
// Remove leading 1 if we have 11 digits
if (cleanedNumber.length === 11 && cleanedNumber.startsWith("1")) {
cleanedNumber = cleanedNumber.substring(1);
}
const fullPhoneNumber = `+1${cleanedNumber}`;
const response = await fetch(
"http://localhost:5001/api/auth/phone/send-code",
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
phoneNumber: fullPhoneNumber,
}),
}
);
// Check if response is JSON
const contentType = response.headers.get("content-type");
if (!contentType || !contentType.includes("application/json")) {
throw new Error(
"Server error: Invalid response format. Make sure the backend is running."
);
}
const data = await response.json();
if (!response.ok) {
throw new Error(data.message || `Server error: ${response.status}`);
}
setShowVerification(true);
} catch (err: any) {
console.error("Phone auth error:", err);
setError(err.message || "Failed to send verification code");
} finally {
setLoading(false);
}
};
const handleVerificationSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setLoading(true);
setError("");
try {
// Clean phone number - remove all formatting
let cleanedDigits = phoneNumber.replace(/\D/g, "");
// Remove leading 1 if we have 11 digits
if (cleanedDigits.length === 11 && cleanedDigits.startsWith("1")) {
cleanedDigits = cleanedDigits.substring(1);
}
const cleanPhone = `+1${cleanedDigits}`;
console.log("Sending verification request...");
console.log("Current mode:", mode);
console.log("First Name:", firstName);
console.log("Last Name:", lastName);
const requestBody = {
phoneNumber: cleanPhone,
code: verificationCode,
firstName: mode === "signup" ? firstName : undefined,
lastName: mode === "signup" ? lastName : undefined,
};
console.log("Request body:", requestBody);
const response = await fetch(
"http://localhost:5001/api/auth/phone/verify-code",
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(requestBody),
}
);
console.log("Verification response status:", response.status);
const data = await response.json();
console.log("Verification response data:", data);
if (!response.ok) {
// Check if it's a new user who needs to provide name
if (data.isNewUser) {
setMode("signup");
setShowVerification(false);
setAuthMethod("phone");
return;
}
throw new Error(data.message);
}
// Store token and user data
console.log("Storing token:", data.token);
localStorage.setItem("token", data.token);
// Verify token was stored
const storedToken = localStorage.getItem("token");
console.log("Token stored successfully:", !!storedToken);
console.log("User data:", data.user);
// Update auth context with the user data
updateUser(data.user);
// Close modal and reset state
onHide();
resetModal();
// Force a page reload to ensure auth state is properly initialized
// This is needed because AuthContext's useEffect only runs once on mount
setTimeout(() => {
window.location.href = '/';
}, 100);
} catch (err: any) {
console.error("Verification error:", err);
setError(err.message || "Failed to verify code");
} finally {
setLoading(false);
}
};
const handleEmailSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setLoading(true);
setError("");
try {
if (mode === "login") {
await login(email, password);
onHide();
} else {
await register({
email,
password,
firstName,
lastName,
username: email.split("@")[0], // Generate username from email
});
onHide();
}
} catch (err: any) {
setError(err.response?.data?.message || "An error occurred");
} finally {
setLoading(false);
}
};
const handleSocialLogin = (provider: string) => {
// TODO: Implement social login
console.log(`Login with ${provider}`);
};
const resetModal = () => {
setAuthMethod(null);
setShowVerification(false);
setError("");
setPhoneNumber("");
setEmail("");
setPassword("");
setFirstName("");
setLastName("");
setVerificationCode("");
};
if (!show) return null;
return (
<>
<div
className="modal show d-block"
tabIndex={-1}
style={{ backgroundColor: "rgba(0,0,0,0.5)" }}
>
<div className="modal-dialog modal-dialog-centered">
<div className="modal-content">
<div className="modal-header border-0 pb-0">
<button
type="button"
className="btn-close"
onClick={() => {
resetModal();
onHide();
}}
></button>
</div>
<div className="modal-body px-4 pb-4">
<h4 className="text-center mb-4">
Welcome to CommunityRentals.App
</h4>
{error && (
<div className="alert alert-danger" role="alert">
{error}
</div>
)}
{!authMethod && !showVerification && (
<div>
{/* Phone Number Input */}
<form onSubmit={handlePhoneSubmit}>
{mode === "signup" && (
<>
<div className="row mb-3">
<div className="col">
<label className="form-label">First Name</label>
<input
type="text"
className="form-control"
value={firstName}
onChange={(e) => setFirstName(e.target.value)}
required
/>
</div>
<div className="col">
<label className="form-label">Last Name</label>
<input
type="text"
className="form-control"
value={lastName}
onChange={(e) => setLastName(e.target.value)}
required
/>
</div>
</div>
</>
)}
<div className="mb-3">
<label className="form-label">Phone Number</label>
<div className="input-group">
<span className="input-group-text">+1</span>
<input
type="tel"
className="form-control"
placeholder="(555) 123-4567"
value={phoneNumber}
onChange={handlePhoneChange}
required
/>
</div>
</div>
<button
type="submit"
className="btn btn-primary w-100 py-3 mb-3"
disabled={loading}
>
{loading ? "Sending..." : "Continue"}
</button>
<p className="text-center text-muted small mb-3">
We'll text you to verify your number.
</p>
</form>
<div className="d-flex align-items-center my-3">
<hr className="flex-grow-1" />
<span className="px-3 text-muted">or</span>
<hr className="flex-grow-1" />
</div>
{/* Social Login Options */}
<button
className="btn btn-outline-dark w-100 mb-2 py-3 d-flex align-items-center justify-content-center"
onClick={() => handleSocialLogin("google")}
>
<i className="bi bi-google me-2"></i>
Continue with Google
</button>
<button
className="btn btn-outline-dark w-100 mb-2 py-3 d-flex align-items-center justify-content-center"
onClick={() => handleSocialLogin("apple")}
>
<i className="bi bi-apple me-2"></i>
Continue with Apple
</button>
<button
className="btn btn-outline-dark w-100 mb-2 py-3 d-flex align-items-center justify-content-center"
onClick={() => handleSocialLogin("facebook")}
>
<i className="bi bi-facebook me-2"></i>
Continue with Facebook
</button>
<button
className="btn btn-outline-dark w-100 mb-3 py-3 d-flex align-items-center justify-content-center"
onClick={() => setAuthMethod("email")}
>
<i className="bi bi-envelope me-2"></i>
Continue with Email
</button>
<div className="text-center mt-3">
<small className="text-muted">
{mode === "login"
? "Don't have an account? "
: "Already have an account? "}
<a
href="#"
className="text-primary text-decoration-none"
onClick={(e) => {
e.preventDefault();
setMode(mode === "login" ? "signup" : "login");
}}
>
{mode === "login" ? "Sign up" : "Log in"}
</a>
</small>
</div>
</div>
)}
{showVerification && (
<form onSubmit={handleVerificationSubmit}>
<button
type="button"
className="btn btn-link p-0 mb-3"
onClick={() => setShowVerification(false)}
>
<i className="bi bi-arrow-left me-2"></i>Back
</button>
<div className="mb-3">
<label className="form-label">
Enter verification code
</label>
<p className="text-muted small">
We sent a code to +1{phoneNumber}
</p>
<input
type="text"
className="form-control"
placeholder="000000"
value={verificationCode}
onChange={(e) => setVerificationCode(e.target.value)}
maxLength={6}
required
/>
</div>
<button
type="submit"
className="btn btn-primary w-100 py-3"
disabled={loading}
>
{loading ? "Verifying..." : "Verify"}
</button>
</form>
)}
{authMethod === "email" && (
<form onSubmit={handleEmailSubmit}>
<button
type="button"
className="btn btn-link p-0 mb-3"
onClick={() => setAuthMethod(null)}
>
<i className="bi bi-arrow-left me-2"></i>Back
</button>
{mode === "signup" && (
<>
<div className="row mb-3">
<div className="col">
<label className="form-label">First Name</label>
<input
type="text"
className="form-control"
value={firstName}
onChange={(e) => setFirstName(e.target.value)}
required
/>
</div>
<div className="col">
<label className="form-label">Last Name</label>
<input
type="text"
className="form-control"
value={lastName}
onChange={(e) => setLastName(e.target.value)}
required
/>
</div>
</div>
</>
)}
<div className="mb-3">
<label className="form-label">Email</label>
<input
type="email"
className="form-control"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
/>
</div>
<div className="mb-3">
<label className="form-label">Password</label>
<input
type="password"
className="form-control"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
/>
</div>
<button
type="submit"
className="btn btn-primary w-100 py-3"
disabled={loading}
>
{loading
? "Loading..."
: mode === "login"
? "Log in"
: "Sign up"}
</button>
</form>
)}
<p className="text-center text-muted small mt-4 mb-0">
By continuing, you agree to CommunityRentals.App's{" "}
<a href="/terms" className="text-decoration-none">
Terms of Service
</a>{" "}
and{" "}
<a href="/privacy" className="text-decoration-none">
Privacy Policy
</a>
.
</p>
</div>
</div>
</div>
</div>
</>
);
};
export default AuthModal;

View File

@@ -9,7 +9,7 @@ const Footer: React.FC = () => {
<div className="col-lg-3">
<h5 className="mb-3">
<i className="bi bi-box-seam me-2"></i>
Rentall
CommunityRentals.App
</h5>
<p className="small text-white-50">
The marketplace for renting anything, from anyone, anywhere.
@@ -122,7 +122,7 @@ const Footer: React.FC = () => {
<div className="row">
<div className="col-md-6">
<p className="small text-white-50 mb-0">
© 2025 Rentall. All rights reserved.
© 2025 CommunityRentals.App. All rights reserved.
</p>
</div>
<div className="col-md-6 text-md-end">

View File

@@ -1,22 +1,31 @@
import React from 'react';
import React, { useState } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { useAuth } from '../contexts/AuthContext';
import AuthModal from './AuthModal';
const Navbar: React.FC = () => {
const { user, logout } = useAuth();
const navigate = useNavigate();
const [showAuthModal, setShowAuthModal] = useState(false);
const [authModalMode, setAuthModalMode] = useState<'login' | 'signup'>('login');
const handleLogout = () => {
logout();
navigate('/');
};
const openAuthModal = (mode: 'login' | 'signup') => {
setAuthModalMode(mode);
setShowAuthModal(true);
};
return (
<>
<nav className="navbar navbar-expand-lg navbar-light bg-white shadow-sm">
<div className="container-fluid" style={{ maxWidth: '1800px' }}>
<Link className="navbar-brand fw-bold" to="/">
<i className="bi bi-box-seam me-2"></i>
Rentall
CommunityRentals.App
</Link>
<button
className="navbar-toggler"
@@ -96,18 +105,14 @@ const Navbar: React.FC = () => {
</li>
</>
) : (
<>
<li className="nav-item me-2">
<Link className="btn btn-outline-secondary btn-sm text-nowrap" to="/login">
Login
</Link>
</li>
<li className="nav-item">
<Link className="btn btn-primary btn-sm text-nowrap" to="/register">
Sign Up
</Link>
</li>
</>
<li className="nav-item">
<button
className="btn btn-primary btn-sm text-nowrap"
onClick={() => openAuthModal('login')}
>
Login or Sign Up
</button>
</li>
)}
</ul>
</div>
@@ -115,6 +120,13 @@ const Navbar: React.FC = () => {
</div>
</div>
</nav>
<AuthModal
show={showAuthModal}
onHide={() => setShowAuthModal(false)}
initialMode={authModalMode}
/>
</>
);
};

View File

@@ -32,17 +32,21 @@ export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
useEffect(() => {
const token = localStorage.getItem('token');
if (token) {
console.log('AuthContext: Found token, fetching profile...');
userAPI.getProfile()
.then(response => {
console.log('AuthContext: Profile loaded', response.data);
setUser(response.data);
})
.catch(() => {
.catch((error) => {
console.error('AuthContext: Failed to load profile', error);
localStorage.removeItem('token');
})
.finally(() => {
setLoading(false);
});
} else {
console.log('AuthContext: No token found');
setLoading(false);
}
}, []);

View File

@@ -273,7 +273,7 @@ const Home: React.FC = () => {
<div className="container-fluid" style={{ maxWidth: '1800px' }}>
<div className="row align-items-center">
<div className="col-lg-6">
<h2 className="mb-4">Why Choose Rentall?</h2>
<h2 className="mb-4">Why Choose CommunityRentals.App?</h2>
<div className="d-flex mb-3">
<i className="bi bi-check-circle-fill text-success me-3" style={{ fontSize: '1.5rem' }}></i>
<div>