google sign in

This commit is contained in:
jackiettran
2025-09-15 12:38:18 -04:00
parent 688f5ac8d6
commit ce0b7bd0cc
11 changed files with 662 additions and 651 deletions

View File

@@ -14,6 +14,7 @@
<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">
<script src="https://accounts.google.com/gsi/client" async defer></script>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>

View File

@@ -1,4 +1,4 @@
import React, { useState, useEffect } from "react";
import React, { useState, useEffect, useRef } from "react";
import { useAuth } from "../contexts/AuthContext";
interface AuthModalProps {
@@ -13,18 +13,15 @@ const AuthModal: React.FC<AuthModalProps> = ({
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 googleButtonRef = useRef<HTMLDivElement>(null);
const { login, register, updateUser } = useAuth();
const { login, register, googleLogin, updateUser } = useAuth();
// Update mode when modal is opened with different initialMode
useEffect(() => {
@@ -33,165 +30,40 @@ const AuthModal: React.FC<AuthModalProps> = ({
}
}, [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);
// Initialize Google Sign-In
useEffect(() => {
if (show && window.google && process.env.REACT_APP_GOOGLE_CLIENT_ID) {
try {
window.google.accounts.id.initialize({
client_id: process.env.REACT_APP_GOOGLE_CLIENT_ID,
callback: handleGoogleResponse,
auto_select: false,
cancel_on_tap_outside: false,
});
} catch (error) {
console.error("Error initializing Google Sign-In:", error);
}
}
}, [show]);
// 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("");
const handleGoogleResponse = async (response: any) => {
try {
// Clean the phone number
let cleanedNumber = phoneNumber.replace(/\D/g, "");
setLoading(true);
setError("");
// Remove leading 1 if we have 11 digits
if (cleanedNumber.length === 11 && cleanedNumber.startsWith("1")) {
cleanedNumber = cleanedNumber.substring(1);
if (!response?.credential) {
throw new Error("No credential received from Google");
}
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
await googleLogin(response.credential);
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");
setError(
err.response?.data?.error ||
err.message ||
"Failed to sign in with Google"
);
} finally {
setLoading(false);
}
@@ -224,20 +96,25 @@ const AuthModal: React.FC<AuthModalProps> = ({
};
const handleSocialLogin = (provider: string) => {
// TODO: Implement social login
console.log(`Login with ${provider}`);
if (provider === "google") {
if (window.google) {
try {
window.google.accounts.id.prompt();
} catch (error) {
setError("Failed to open Google Sign-In. Please try again.");
}
} else {
setError("Google Sign-In is not available. Please try again later.");
}
}
};
const resetModal = () => {
setAuthMethod(null);
setShowVerification(false);
setError("");
setPhoneNumber("");
setEmail("");
setPassword("");
setFirstName("");
setLastName("");
setVerificationCode("");
};
if (!show) return null;
@@ -262,7 +139,7 @@ const AuthModal: React.FC<AuthModalProps> = ({
></button>
</div>
<div className="modal-body px-4 pb-4">
<h4 className="text-center mb-4">
<h4 className="text-center mb-2">
Welcome to CommunityRentals.App
</h4>
@@ -272,234 +149,112 @@ const AuthModal: React.FC<AuthModalProps> = ({
</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>
{/* Email Form */}
<form onSubmit={handleEmailSubmit}>
{mode === "signup" && (
<>
<div className="row mb-3">
<div className="col">
<label className="form-label">First Name</label>
<input
type="tel"
type="text"
className="form-control"
placeholder="(123) 456-7890"
value={phoneNumber}
onChange={handlePhoneChange}
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>
</>
)}
<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 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>
)}
{showVerification && (
<form onSubmit={handleVerificationSubmit}>
<button
type="button"
className="btn btn-link p-0 mb-3"
onClick={() => setShowVerification(false)}
<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 mb-1"
disabled={loading}
>
{loading
? "Loading..."
: mode === "login"
? "Log in"
: "Sign up"}
</button>
</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")}
disabled={loading}
>
<i className="bi bi-google me-2"></i>
Sign in with Google
</button>
<button
className="btn btn-outline-dark w-100 mb-3 py-3 d-flex align-items-center justify-content-center"
onClick={() => handleSocialLogin("apple")}
disabled={loading}
>
<i className="bi bi-apple me-2"></i>
Sign in with Apple
</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");
}}
>
<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>
)}
{mode === "login" ? "Sign up" : "Log in"}
</a>
</small>
</div>
<p className="text-center text-muted small mt-4 mb-0">
By continuing, you agree to CommunityRentals.App's{" "}

View File

@@ -13,6 +13,7 @@ interface AuthContextType {
loading: boolean;
login: (email: string, password: string) => Promise<void>;
register: (data: any) => Promise<void>;
googleLogin: (idToken: string) => Promise<void>;
logout: () => void;
updateUser: (user: User) => void;
}
@@ -66,6 +67,12 @@ export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
setUser(response.data.user);
};
const googleLogin = async (idToken: string) => {
const response = await authAPI.googleLogin({ idToken });
localStorage.setItem("token", response.data.token);
setUser(response.data.user);
};
const logout = () => {
localStorage.removeItem("token");
setUser(null);
@@ -77,7 +84,7 @@ export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
return (
<AuthContext.Provider
value={{ user, loading, login, register, logout, updateUser }}
value={{ user, loading, login, register, googleLogin, logout, updateUser }}
>
{children}
</AuthContext.Provider>

View File

@@ -39,6 +39,7 @@ api.interceptors.response.use(
export const authAPI = {
register: (data: any) => api.post("/auth/register", data),
login: (data: any) => api.post("/auth/login", data),
googleLogin: (data: any) => api.post("/auth/google", data),
};
export const userAPI = {

29
frontend/src/types/google.d.ts vendored Normal file
View File

@@ -0,0 +1,29 @@
declare global {
interface Window {
google?: {
accounts: {
id: {
initialize: (config: {
client_id: string;
callback: (response: { credential: string }) => void;
auto_select?: boolean;
cancel_on_tap_outside?: boolean;
}) => void;
renderButton: (
element: HTMLElement,
config: {
theme?: "outline" | "filled_blue" | "filled_black";
size?: "large" | "medium" | "small";
width?: string;
text?: "signin_with" | "signup_with" | "continue_with" | "signin";
shape?: "rectangular" | "pill" | "circle" | "square";
}
) => void;
prompt: (momentListener?: (notification: any) => void) => void;
};
};
};
}
}
export {};