Compare commits

...

2 Commits

Author SHA1 Message Date
jackiettran
ce0b7bd0cc google sign in 2025-09-15 12:38:18 -04:00
jackiettran
688f5ac8d6 map search 2025-09-10 16:41:05 -04:00
15 changed files with 1264 additions and 665 deletions

View File

@@ -1,132 +1,131 @@
const { DataTypes } = require('sequelize');
const sequelize = require('../config/database');
const bcrypt = require('bcryptjs');
const { DataTypes } = require("sequelize");
const sequelize = require("../config/database");
const bcrypt = require("bcryptjs");
const User = sequelize.define('User', {
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true
},
username: {
type: DataTypes.STRING,
unique: true,
allowNull: true
},
email: {
type: DataTypes.STRING,
unique: true,
allowNull: true,
validate: {
isEmail: true
}
},
password: {
type: DataTypes.STRING,
allowNull: true
},
firstName: {
type: DataTypes.STRING,
allowNull: false
},
lastName: {
type: DataTypes.STRING,
allowNull: false
},
phone: {
type: DataTypes.STRING,
unique: true,
allowNull: true
},
phoneVerified: {
type: DataTypes.BOOLEAN,
defaultValue: false
},
authProvider: {
type: DataTypes.ENUM('local', 'phone', 'google', 'apple', 'facebook'),
defaultValue: 'local'
},
providerId: {
type: DataTypes.STRING,
allowNull: true
},
address1: {
type: DataTypes.STRING
},
address2: {
type: DataTypes.STRING
},
city: {
type: DataTypes.STRING
},
state: {
type: DataTypes.STRING
},
zipCode: {
type: DataTypes.STRING
},
country: {
type: DataTypes.STRING
},
profileImage: {
type: DataTypes.STRING
},
isVerified: {
type: DataTypes.BOOLEAN,
defaultValue: false
},
defaultAvailableAfter: {
type: DataTypes.STRING,
defaultValue: '09:00'
},
defaultAvailableBefore: {
type: DataTypes.STRING,
defaultValue: '17:00'
},
defaultSpecifyTimesPerDay: {
type: DataTypes.BOOLEAN,
defaultValue: false
},
defaultWeeklyTimes: {
type: DataTypes.JSONB,
defaultValue: {
sunday: { availableAfter: "09:00", availableBefore: "17:00" },
monday: { availableAfter: "09:00", availableBefore: "17:00" },
tuesday: { availableAfter: "09:00", availableBefore: "17:00" },
wednesday: { availableAfter: "09:00", availableBefore: "17:00" },
thursday: { availableAfter: "09:00", availableBefore: "17:00" },
friday: { availableAfter: "09:00", availableBefore: "17:00" },
saturday: { availableAfter: "09:00", availableBefore: "17:00" }
}
},
stripeConnectedAccountId: {
type: DataTypes.STRING,
allowNull: true
},
stripeCustomerId: {
type: DataTypes.STRING,
allowNull: true
}
}, {
hooks: {
beforeCreate: async (user) => {
if (user.password) {
user.password = await bcrypt.hash(user.password, 10);
}
const User = sequelize.define(
"User",
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
username: {
type: DataTypes.STRING,
unique: true,
allowNull: true,
},
email: {
type: DataTypes.STRING,
unique: true,
allowNull: true,
validate: {
isEmail: true,
},
},
password: {
type: DataTypes.STRING,
allowNull: true,
},
firstName: {
type: DataTypes.STRING,
allowNull: false,
},
lastName: {
type: DataTypes.STRING,
allowNull: false,
},
phone: {
type: DataTypes.STRING,
allowNull: true,
},
authProvider: {
type: DataTypes.ENUM("local", "google", "apple"),
defaultValue: "local",
},
providerId: {
type: DataTypes.STRING,
allowNull: true,
},
address1: {
type: DataTypes.STRING,
},
address2: {
type: DataTypes.STRING,
},
city: {
type: DataTypes.STRING,
},
state: {
type: DataTypes.STRING,
},
zipCode: {
type: DataTypes.STRING,
},
country: {
type: DataTypes.STRING,
},
profileImage: {
type: DataTypes.STRING,
},
isVerified: {
type: DataTypes.BOOLEAN,
defaultValue: false,
},
defaultAvailableAfter: {
type: DataTypes.STRING,
defaultValue: "09:00",
},
defaultAvailableBefore: {
type: DataTypes.STRING,
defaultValue: "17:00",
},
defaultSpecifyTimesPerDay: {
type: DataTypes.BOOLEAN,
defaultValue: false,
},
defaultWeeklyTimes: {
type: DataTypes.JSONB,
defaultValue: {
sunday: { availableAfter: "09:00", availableBefore: "17:00" },
monday: { availableAfter: "09:00", availableBefore: "17:00" },
tuesday: { availableAfter: "09:00", availableBefore: "17:00" },
wednesday: { availableAfter: "09:00", availableBefore: "17:00" },
thursday: { availableAfter: "09:00", availableBefore: "17:00" },
friday: { availableAfter: "09:00", availableBefore: "17:00" },
saturday: { availableAfter: "09:00", availableBefore: "17:00" },
},
},
stripeConnectedAccountId: {
type: DataTypes.STRING,
allowNull: true,
},
stripeCustomerId: {
type: DataTypes.STRING,
allowNull: true,
},
},
{
hooks: {
beforeCreate: async (user) => {
if (user.password) {
user.password = await bcrypt.hash(user.password, 10);
}
},
beforeUpdate: async (user) => {
if (user.changed("password") && user.password) {
user.password = await bcrypt.hash(user.password, 10);
}
},
},
beforeUpdate: async (user) => {
if (user.changed('password') && user.password) {
user.password = await bcrypt.hash(user.password, 10);
}
}
}
});
);
User.prototype.comparePassword = async function(password) {
User.prototype.comparePassword = async function (password) {
if (!this.password) {
return false;
}
return bcrypt.compare(password, this.password);
};
module.exports = User;
module.exports = User;

View File

@@ -16,6 +16,7 @@
"dotenv": "^17.2.0",
"express": "^5.1.0",
"express-rate-limit": "^8.1.0",
"google-auth-library": "^10.3.0",
"jsonwebtoken": "^9.0.2",
"multer": "^2.0.2",
"node-cron": "^3.0.3",
@@ -127,6 +128,15 @@
"node": ">= 0.6"
}
},
"node_modules/agent-base": {
"version": "7.1.4",
"resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz",
"integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==",
"license": "MIT",
"engines": {
"node": ">= 14"
}
},
"node_modules/agentkeepalive": {
"version": "4.6.0",
"resolved": "https://registry.npmjs.org/agentkeepalive/-/agentkeepalive-4.6.0.tgz",
@@ -210,6 +220,26 @@
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
"integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw=="
},
"node_modules/base64-js": {
"version": "1.5.1",
"resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
"integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/feross"
},
{
"type": "patreon",
"url": "https://www.patreon.com/feross"
},
{
"type": "consulting",
"url": "https://feross.org/support"
}
],
"license": "MIT"
},
"node_modules/bcryptjs": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/bcryptjs/-/bcryptjs-3.0.2.tgz",
@@ -218,6 +248,15 @@
"bcrypt": "bin/bcrypt"
}
},
"node_modules/bignumber.js": {
"version": "9.3.1",
"resolved": "https://registry.npmjs.org/bignumber.js/-/bignumber.js-9.3.1.tgz",
"integrity": "sha512-Ko0uX15oIUS7wJ3Rb30Fs6SkVbLmPBAKdlm7q9+ak9bbIeFf0MwuBsQV6z7+X768/cHsfg+WlysDWJcmthjsjQ==",
"license": "MIT",
"engines": {
"node": "*"
}
},
"node_modules/binary-extensions": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz",
@@ -564,6 +603,15 @@
"integrity": "sha512-KALDyEYgpY+Rlob/iriUtjV6d5Eq+Y191A5g4UqLAi8CyGP9N1+FdVbkc1SxKc2r4YAYqG8JzO2KGL+AizD70Q==",
"license": "MIT"
},
"node_modules/data-uri-to-buffer": {
"version": "4.0.1",
"resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-4.0.1.tgz",
"integrity": "sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A==",
"license": "MIT",
"engines": {
"node": ">= 12"
}
},
"node_modules/debug": {
"version": "4.4.1",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.1.tgz",
@@ -805,6 +853,35 @@
"express": ">= 4.11"
}
},
"node_modules/extend": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz",
"integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==",
"license": "MIT"
},
"node_modules/fetch-blob": {
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/fetch-blob/-/fetch-blob-3.2.0.tgz",
"integrity": "sha512-7yAQpD2UMJzLi1Dqv7qFYnPbaPx7ZfFK6PiIxQ4PfkGPyNyl2Ugx+a/umUonmKqjhM4DnfbMvdX6otXq83soQQ==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/jimmywarting"
},
{
"type": "paypal",
"url": "https://paypal.me/jimmywarting"
}
],
"license": "MIT",
"dependencies": {
"node-domexception": "^1.0.0",
"web-streams-polyfill": "^3.0.3"
},
"engines": {
"node": "^12.20 || >= 14.13"
}
},
"node_modules/fill-range": {
"version": "7.1.1",
"resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz",
@@ -914,6 +991,18 @@
"node": ">= 0.6"
}
},
"node_modules/formdata-polyfill": {
"version": "4.0.10",
"resolved": "https://registry.npmjs.org/formdata-polyfill/-/formdata-polyfill-4.0.10.tgz",
"integrity": "sha512-buewHzMvYL29jdeQTVILecSaZKnt/RJWjoZCF5OW60Z67/GmSLBkOFM7qh1PI3zFNtJbaZL5eQu1vLfazOwj4g==",
"license": "MIT",
"dependencies": {
"fetch-blob": "^3.1.2"
},
"engines": {
"node": ">=12.20.0"
}
},
"node_modules/forwarded": {
"version": "0.2.0",
"resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz",
@@ -966,6 +1055,34 @@
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/gaxios": {
"version": "7.1.1",
"resolved": "https://registry.npmjs.org/gaxios/-/gaxios-7.1.1.tgz",
"integrity": "sha512-Odju3uBUJyVCkW64nLD4wKLhbh93bh6vIg/ZIXkWiLPBrdgtc65+tls/qml+un3pr6JqYVFDZbbmLDQT68rTOQ==",
"license": "Apache-2.0",
"dependencies": {
"extend": "^3.0.2",
"https-proxy-agent": "^7.0.1",
"node-fetch": "^3.3.2"
},
"engines": {
"node": ">=18"
}
},
"node_modules/gcp-metadata": {
"version": "7.0.1",
"resolved": "https://registry.npmjs.org/gcp-metadata/-/gcp-metadata-7.0.1.tgz",
"integrity": "sha512-UcO3kefx6dCcZkgcTGgVOTFb7b1LlQ02hY1omMjjrrBzkajRMCFgYOjs7J71WqnuG1k2b+9ppGL7FsOfhZMQKQ==",
"license": "Apache-2.0",
"dependencies": {
"gaxios": "^7.0.0",
"google-logging-utils": "^1.0.0",
"json-bigint": "^1.0.0"
},
"engines": {
"node": ">=18"
}
},
"node_modules/get-caller-file": {
"version": "2.0.5",
"resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz",
@@ -1054,6 +1171,54 @@
"url": "https://github.com/sponsors/isaacs"
}
},
"node_modules/google-auth-library": {
"version": "10.3.0",
"resolved": "https://registry.npmjs.org/google-auth-library/-/google-auth-library-10.3.0.tgz",
"integrity": "sha512-ylSE3RlCRZfZB56PFJSfUCuiuPq83Fx8hqu1KPWGK8FVdSaxlp/qkeMMX/DT/18xkwXIHvXEXkZsljRwfrdEfQ==",
"license": "Apache-2.0",
"dependencies": {
"base64-js": "^1.3.0",
"ecdsa-sig-formatter": "^1.0.11",
"gaxios": "^7.0.0",
"gcp-metadata": "^7.0.0",
"google-logging-utils": "^1.0.0",
"gtoken": "^8.0.0",
"jws": "^4.0.0"
},
"engines": {
"node": ">=18"
}
},
"node_modules/google-auth-library/node_modules/jwa": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/jwa/-/jwa-2.0.1.tgz",
"integrity": "sha512-hRF04fqJIP8Abbkq5NKGN0Bbr3JxlQ+qhZufXVr0DvujKy93ZCbXZMHDL4EOtodSbCWxOqR8MS1tXA5hwqCXDg==",
"license": "MIT",
"dependencies": {
"buffer-equal-constant-time": "^1.0.1",
"ecdsa-sig-formatter": "1.0.11",
"safe-buffer": "^5.0.1"
}
},
"node_modules/google-auth-library/node_modules/jws": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/jws/-/jws-4.0.0.tgz",
"integrity": "sha512-KDncfTmOZoOMTFG4mBlG0qUIOlc03fmzH+ru6RgYVZhPkyiy/92Owlt/8UEN+a4TXR1FQetfIpJE8ApdvdVxTg==",
"license": "MIT",
"dependencies": {
"jwa": "^2.0.0",
"safe-buffer": "^5.0.1"
}
},
"node_modules/google-logging-utils": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/google-logging-utils/-/google-logging-utils-1.1.1.tgz",
"integrity": "sha512-rcX58I7nqpu4mbKztFeOAObbomBbHU2oIb/d3tJfF3dizGSApqtSwYJigGCooHdnMyQBIw8BrWyK96w3YXgr6A==",
"license": "Apache-2.0",
"engines": {
"node": ">=14"
}
},
"node_modules/gopd": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",
@@ -1070,6 +1235,40 @@
"resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz",
"integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ=="
},
"node_modules/gtoken": {
"version": "8.0.0",
"resolved": "https://registry.npmjs.org/gtoken/-/gtoken-8.0.0.tgz",
"integrity": "sha512-+CqsMbHPiSTdtSO14O51eMNlrp9N79gmeqmXeouJOhfucAedHw9noVe/n5uJk3tbKE6a+6ZCQg3RPhVhHByAIw==",
"license": "MIT",
"dependencies": {
"gaxios": "^7.0.0",
"jws": "^4.0.0"
},
"engines": {
"node": ">=18"
}
},
"node_modules/gtoken/node_modules/jwa": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/jwa/-/jwa-2.0.1.tgz",
"integrity": "sha512-hRF04fqJIP8Abbkq5NKGN0Bbr3JxlQ+qhZufXVr0DvujKy93ZCbXZMHDL4EOtodSbCWxOqR8MS1tXA5hwqCXDg==",
"license": "MIT",
"dependencies": {
"buffer-equal-constant-time": "^1.0.1",
"ecdsa-sig-formatter": "1.0.11",
"safe-buffer": "^5.0.1"
}
},
"node_modules/gtoken/node_modules/jws": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/jws/-/jws-4.0.0.tgz",
"integrity": "sha512-KDncfTmOZoOMTFG4mBlG0qUIOlc03fmzH+ru6RgYVZhPkyiy/92Owlt/8UEN+a4TXR1FQetfIpJE8ApdvdVxTg==",
"license": "MIT",
"dependencies": {
"jwa": "^2.0.0",
"safe-buffer": "^5.0.1"
}
},
"node_modules/has-flag": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz",
@@ -1139,6 +1338,19 @@
"node": ">= 0.8"
}
},
"node_modules/https-proxy-agent": {
"version": "7.0.6",
"resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz",
"integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==",
"license": "MIT",
"dependencies": {
"agent-base": "^7.1.2",
"debug": "4"
},
"engines": {
"node": ">= 14"
}
},
"node_modules/humanize-ms": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/humanize-ms/-/humanize-ms-1.2.1.tgz",
@@ -1316,6 +1528,15 @@
"node": ">=14"
}
},
"node_modules/json-bigint": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/json-bigint/-/json-bigint-1.0.0.tgz",
"integrity": "sha512-SiPv/8VpZuWbvLSMtTDU8hEfrZWg/mH/nV/b4o0CYbSxu1UIQPLdwKOCIyLQX+VIPO5vrLX3i8qtqFyhdPSUSQ==",
"license": "MIT",
"dependencies": {
"bignumber.js": "^9.0.0"
}
},
"node_modules/jsonfile": {
"version": "6.1.0",
"resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.1.0.tgz",
@@ -1615,6 +1836,44 @@
"uuid": "dist/bin/uuid"
}
},
"node_modules/node-domexception": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/node-domexception/-/node-domexception-1.0.0.tgz",
"integrity": "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==",
"deprecated": "Use your platform's native DOMException instead",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/jimmywarting"
},
{
"type": "github",
"url": "https://paypal.me/jimmywarting"
}
],
"license": "MIT",
"engines": {
"node": ">=10.5.0"
}
},
"node_modules/node-fetch": {
"version": "3.3.2",
"resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-3.3.2.tgz",
"integrity": "sha512-dRB78srN/l6gqWulah9SrxeYnxeddIG30+GOqK/9OlLVyLg3HPnr6SqOWTWOXKRwC2eGYCkZ59NNuSgvSrpgOA==",
"license": "MIT",
"dependencies": {
"data-uri-to-buffer": "^4.0.0",
"fetch-blob": "^3.1.4",
"formdata-polyfill": "^4.0.10"
},
"engines": {
"node": "^12.20.0 || ^14.13.1 || >=16.0.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/node-fetch"
}
},
"node_modules/nodemon": {
"version": "3.1.10",
"resolved": "https://registry.npmjs.org/nodemon/-/nodemon-3.1.10.tgz",
@@ -2668,6 +2927,15 @@
"node": ">= 0.8"
}
},
"node_modules/web-streams-polyfill": {
"version": "3.3.3",
"resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-3.3.3.tgz",
"integrity": "sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw==",
"license": "MIT",
"engines": {
"node": ">= 8"
}
},
"node_modules/which": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",

View File

@@ -23,6 +23,7 @@
"dotenv": "^17.2.0",
"express": "^5.1.0",
"express-rate-limit": "^8.1.0",
"google-auth-library": "^10.3.0",
"jsonwebtoken": "^9.0.2",
"multer": "^2.0.2",
"node-cron": "^3.0.3",

View File

@@ -1,8 +1,11 @@
const express = require("express");
const jwt = require("jsonwebtoken");
const { OAuth2Client } = require("google-auth-library");
const { User } = require("../models"); // Import from models/index.js to get models with associations
const router = express.Router();
const googleClient = new OAuth2Client(process.env.GOOGLE_CLIENT_ID);
router.post("/register", async (req, res) => {
try {
const { username, email, password, firstName, lastName, phone } = req.body;
@@ -74,4 +77,98 @@ router.post("/login", async (req, res) => {
}
});
router.post("/google", async (req, res) => {
try {
const { idToken } = req.body;
if (!idToken) {
return res.status(400).json({ error: "ID token is required" });
}
// Verify the Google ID token
const ticket = await googleClient.verifyIdToken({
idToken,
audience: process.env.GOOGLE_CLIENT_ID,
});
const payload = ticket.getPayload();
const {
sub: googleId,
email,
given_name: firstName,
family_name: lastName,
picture,
} = payload;
if (!email || !firstName || !lastName) {
return res
.status(400)
.json({ error: "Required user information not provided by Google" });
}
// Check if user exists by Google ID first
let user = await User.findOne({
where: { providerId: googleId, authProvider: "google" },
});
if (!user) {
// Check if user exists with same email but different auth provider
const existingUser = await User.findOne({ where: { email } });
if (existingUser) {
return res.status(409).json({
error:
"An account with this email already exists. Please use email/password login.",
});
}
// Create new user
user = await User.create({
email,
firstName,
lastName,
authProvider: "google",
providerId: googleId,
profileImage: picture,
username: email.split("@")[0] + "_" + googleId.slice(-6), // Generate unique username
});
}
// Generate JWT token
const token = jwt.sign({ id: user.id }, process.env.JWT_SECRET, {
expiresIn: "7d",
});
res.json({
user: {
id: user.id,
username: user.username,
email: user.email,
firstName: user.firstName,
lastName: user.lastName,
profileImage: user.profileImage,
},
token,
});
} catch (error) {
if (error.message && error.message.includes("Token used too late")) {
return res
.status(401)
.json({ error: "Google token has expired. Please try again." });
}
if (error.message && error.message.includes("Invalid token")) {
return res
.status(401)
.json({ error: "Invalid Google token. Please try again." });
}
if (error.message && error.message.includes("Wrong number of segments")) {
return res
.status(400)
.json({ error: "Malformed Google token. Please try again." });
}
res
.status(500)
.json({ error: "Failed to authenticate with Google: " + error.message });
}
});
module.exports = router;

View File

@@ -1,145 +0,0 @@
const express = require("express");
const router = express.Router();
const jwt = require("jsonwebtoken");
const { User } = require("../models");
// Temporary in-memory storage for verification codes
// In production, use Redis or a database
const verificationCodes = new Map();
// Generate random 6-digit code
const generateVerificationCode = () => {
return Math.floor(100000 + Math.random() * 900000).toString();
};
// Send verification code
router.post("/send-code", async (req, res) => {
try {
const { phoneNumber } = req.body;
if (!phoneNumber) {
return res.status(400).json({ message: "Phone number is required" });
}
// Generate and store verification code
const code = generateVerificationCode();
verificationCodes.set(phoneNumber, {
code,
createdAt: Date.now(),
attempts: 0,
});
// TODO: Integrate with SMS service (Twilio, AWS SNS, etc.)
// For development, log the code
console.log(`Verification code for ${phoneNumber}: ${code}`);
res.json({
message: "Verification code sent",
// Remove this in production - only for development
devCode: code,
});
} catch (error) {
console.error("Error sending verification code:", error);
res.status(500).json({ message: "Failed to send verification code" });
}
});
// Verify code and create/login user
router.post("/verify-code", async (req, res) => {
try {
const { phoneNumber, code, firstName, lastName } = req.body;
if (!phoneNumber || !code) {
return res
.status(400)
.json({ message: "Phone number and code are required" });
}
// Check verification code
const storedData = verificationCodes.get(phoneNumber);
if (!storedData) {
return res.status(400).json({
message: "No verification code found. Please request a new one.",
});
}
// Check if code expired (10 minutes)
if (Date.now() - storedData.createdAt > 10 * 60 * 1000) {
verificationCodes.delete(phoneNumber);
return res.status(400).json({
message: "Verification code expired. Please request a new one.",
});
}
// Check attempts
if (storedData.attempts >= 3) {
verificationCodes.delete(phoneNumber);
return res.status(400).json({
message: "Too many failed attempts. Please request a new code.",
});
}
if (storedData.code !== code) {
storedData.attempts++;
return res.status(400).json({ message: "Invalid verification code" });
}
// Code is valid, remove it
verificationCodes.delete(phoneNumber);
// Find or create user
let user = await User.findOne({ where: { phone: phoneNumber } });
if (!user) {
// New user - require firstName and lastName
if (!firstName || !lastName) {
return res.status(400).json({
message: "First name and last name are required for new users",
isNewUser: true,
});
}
user = await User.create({
phone: phoneNumber,
phoneVerified: true,
firstName,
lastName,
authProvider: "phone",
// Generate a unique username from phone
username: `user_${phoneNumber
.replace(/\D/g, "")
.slice(-6)}_${Date.now().toString(36)}`,
});
} else {
// Existing user - update phone verification
await user.update({ phoneVerified: true });
}
// Generate JWT token
const token = jwt.sign(
{ id: user.id, phone: user.phone },
process.env.JWT_SECRET,
{ expiresIn: "7d" }
);
res.json({
message: "Phone verified successfully",
token,
user: {
id: user.id,
username: user.username,
firstName: user.firstName,
lastName: user.lastName,
phone: user.phone,
email: user.email,
phoneVerified: user.phoneVerified,
},
});
} catch (error) {
console.error("Error verifying code:", error);
res.status(500).json({ message: "Failed to verify code" });
}
});
module.exports = router;

View File

@@ -12,7 +12,6 @@ const path = require("path");
const { sequelize } = require("./models"); // Import from models/index.js to ensure associations are loaded
const authRoutes = require("./routes/auth");
const phoneAuthRoutes = require("./routes/phone-auth");
const userRoutes = require("./routes/users");
const itemRoutes = require("./routes/items");
const rentalRoutes = require("./routes/rentals");
@@ -37,7 +36,6 @@ app.use("/uploads", express.static(path.join(__dirname, "uploads")));
app.use("/api/beta", betaRoutes);
app.use("/api/auth", authRoutes);
app.use("/api/auth/phone", phoneAuthRoutes);
app.use("/api/users", userRoutes);
app.use("/api/items", itemRoutes);
app.use("/api/rentals", rentalRoutes);

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

@@ -31,8 +31,9 @@ const GoogleMapWithRadius: React.FC<GoogleMapWithRadiusProps> = ({
// Destructure mapOptions to create stable references
const { zoom = 12 } = mapOptions;
// Get API key from environment
// Get API key and Map ID from environment
const apiKey = process.env.REACT_APP_GOOGLE_MAPS_PUBLIC_API_KEY;
const mapId = process.env.REACT_APP_GOOGLE_MAPS_MAP_ID;
// Refs for map container and instances
const mapRef = useRef<HTMLDivElement>(null);
@@ -60,17 +61,21 @@ const GoogleMapWithRadius: React.FC<GoogleMapWithRadiusProps> = ({
if (!mapRef.current) return;
// Create map
const map = new google.maps.Map(mapRef.current, {
// Create map configuration
const mapConfig: google.maps.MapOptions = {
mapId: mapId,
center: mapCenter,
zoom: zoom,
maxZoom: 15, // Prevent users from zooming too close
zoomControl: true,
mapTypeControl: false,
scaleControl: true,
streetViewControl: false,
rotateControl: false,
fullscreenControl: false,
});
};
const map = new google.maps.Map(mapRef.current, mapConfig);
mapInstanceRef.current = map;
@@ -101,7 +106,7 @@ const GoogleMapWithRadius: React.FC<GoogleMapWithRadiusProps> = ({
}
mapInstanceRef.current = null;
};
}, [apiKey, mapCenter, zoom]);
}, [apiKey, mapId, mapCenter, zoom]);
// Update map center and circle when coordinates change
useEffect(() => {

View File

@@ -0,0 +1,98 @@
import React from 'react';
import { Item } from '../types';
interface ItemMarkerInfoProps {
item: Item;
onViewDetails?: () => void;
}
const ItemMarkerInfo: React.FC<ItemMarkerInfoProps> = ({ item, onViewDetails }) => {
const getPriceDisplay = () => {
if (item.pricePerDay !== undefined) {
return Number(item.pricePerDay) === 0
? "Free to Borrow"
: `$${Math.floor(Number(item.pricePerDay))}/Day`;
} else if (item.pricePerHour !== undefined) {
return Number(item.pricePerHour) === 0
? "Free to Borrow"
: `$${Math.floor(Number(item.pricePerHour))}/Hour`;
}
return 'Contact for pricing';
};
const getLocationDisplay = () => {
return item.city && item.state
? `${item.city}, ${item.state}`
: 'Location not specified';
};
return (
<div style={{ width: 'min(280px, 90vw)', maxWidth: '280px' }}>
<div className="card border-0">
{item.images && item.images[0] ? (
<img
src={item.images[0]}
className="card-img-top"
alt={item.name}
style={{
height: '120px',
objectFit: 'cover',
borderRadius: '8px 8px 0 0'
}}
/>
) : (
<div
className="bg-light d-flex align-items-center justify-content-center"
style={{
height: '120px',
borderRadius: '8px 8px 0 0'
}}
>
<i className="bi bi-image text-muted" style={{ fontSize: '1.5rem' }}></i>
</div>
)}
<div className="card-body p-3">
<h6 className="card-title mb-2 text-dark fw-bold text-truncate">
{item.name}
</h6>
<div className="mb-2">
<span className="text-primary fw-bold">
{getPriceDisplay()}
</span>
</div>
<div className="text-muted small mb-2">
<i className="bi bi-geo-alt"></i> {getLocationDisplay()}
</div>
{item.description && (
<p className="card-text text-muted small mb-3"
style={{
display: '-webkit-box',
WebkitLineClamp: 2,
WebkitBoxOrient: 'vertical',
overflow: 'hidden',
lineHeight: '1.2em',
maxHeight: '2.4em'
}}>
{item.description}
</p>
)}
<div className="d-grid">
<button
className="btn btn-primary btn-sm"
onClick={onViewDetails}
>
View Details
</button>
</div>
</div>
</div>
</div>
);
};
export default ItemMarkerInfo;

View File

@@ -0,0 +1,432 @@
import React, {
useEffect,
useRef,
useState,
useCallback,
useMemo,
} from "react";
import { Loader } from "@googlemaps/js-api-loader";
import { createRoot } from "react-dom/client";
import { Item } from "../types";
import ItemMarkerInfo from "./ItemMarkerInfo";
// Debounce utility function
function debounce<T extends (...args: any[]) => any>(
func: T,
wait: number
): (...args: Parameters<T>) => void {
let timeout: NodeJS.Timeout;
return (...args: Parameters<T>) => {
clearTimeout(timeout);
timeout = setTimeout(() => func(...args), wait);
};
}
interface SearchResultsMapProps {
items: Item[];
searchLocation?: string;
className?: string;
style?: React.CSSProperties;
onItemSelect?: (item: Item) => void;
}
const SearchResultsMap: React.FC<SearchResultsMapProps> = ({
items,
searchLocation,
className,
style,
onItemSelect,
}) => {
const mapRef = useRef<HTMLDivElement>(null);
const mapInstanceRef = useRef<google.maps.Map | null>(null);
const markersRef = useRef<google.maps.marker.AdvancedMarkerElement[]>([]);
const infoWindowRef = useRef<google.maps.InfoWindow | null>(null);
const mapInitializedRef = useRef<boolean>(false);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const apiKey = process.env.REACT_APP_GOOGLE_MAPS_PUBLIC_API_KEY;
const mapId = process.env.REACT_APP_GOOGLE_MAPS_MAP_ID;
// Clean up markers
const clearMarkers = useCallback(() => {
markersRef.current.forEach((marker) => {
marker.map = null;
});
markersRef.current = [];
if (infoWindowRef.current) {
infoWindowRef.current.close();
}
}, []);
// Create marker for an item
const createItemMarker = useCallback(
async (item: Item, map: google.maps.Map) => {
if (!item.latitude || !item.longitude) return null;
const { AdvancedMarkerElement } = (await google.maps.importLibrary(
"marker"
)) as google.maps.MarkerLibrary;
// Create marker element
const isMobile = window.innerWidth < 768;
const markerSize = isMobile ? 48 : 40;
const markerElement = document.createElement("div");
markerElement.className =
"d-flex align-items-center justify-content-center";
markerElement.style.cssText = `
width: ${markerSize}px;
height: ${markerSize}px;
background-color: #0d6efd;
border: 3px solid white;
border-radius: 50%;
cursor: pointer;
box-shadow: 0 2px 8px rgba(0,0,0,0.3);
transition: transform 0.2s ease;
touch-action: manipulation;
`;
// Add icon
const icon = document.createElement("i");
icon.className = "bi bi-geo-fill text-white";
icon.style.fontSize = "16px";
markerElement.appendChild(icon);
// Hover effects
markerElement.addEventListener("mouseenter", () => {
markerElement.style.transform = "scale(1.1)";
});
markerElement.addEventListener("mouseleave", () => {
markerElement.style.transform = "scale(1)";
});
const marker = new AdvancedMarkerElement({
position: { lat: item.latitude, lng: item.longitude },
map: map,
content: markerElement,
title: item.name,
});
// Add click listener
marker.addListener("click", () => {
if (infoWindowRef.current) {
infoWindowRef.current.close();
}
const infoWindow = new google.maps.InfoWindow({
headerDisabled: true,
maxWidth:
window.innerWidth < 768
? Math.min(300, window.innerWidth - 40)
: 300,
});
// Create React container for info window content
const infoContainer = document.createElement("div");
const root = createRoot(infoContainer);
root.render(
<ItemMarkerInfo
item={item}
onViewDetails={() => {
infoWindow.close();
if (onItemSelect) {
onItemSelect(item);
} else {
window.location.href = `/items/${item.id}`;
}
}}
/>
);
infoWindow.setContent(infoContainer);
infoWindow.open(map, marker);
infoWindowRef.current = infoWindow;
});
return marker;
},
[onItemSelect]
);
// Add markers for all items
const addMarkersToMap = useCallback(
async (map: google.maps.Map, items: Item[]) => {
clearMarkers();
const validItems = items.filter(
(item) => item.latitude && item.longitude
);
for (const item of validItems) {
const marker = await createItemMarker(item, map);
if (marker) {
markersRef.current.push(marker);
}
}
},
[createItemMarker, clearMarkers]
);
// Calculate map bounds to fit all markers with appropriate zoom levels
const fitMapToMarkers = useCallback((map: google.maps.Map, items: Item[]) => {
const validItems = items.filter((item) => item.latitude && item.longitude);
if (validItems.length === 0) return;
const bounds = new google.maps.LatLngBounds();
validItems.forEach((item) => {
if (item.latitude && item.longitude) {
bounds.extend(new google.maps.LatLng(item.latitude, item.longitude));
}
});
if (validItems.length === 1) {
// Single marker - center and set neighborhood-level zoom (not street-level)
map.setCenter(bounds.getCenter());
map.setZoom(10); // Changed from 12 to 10 for better context
} else {
// Multiple markers - calculate distance to determine zoom strategy
const northeast = bounds.getNorthEast();
const southwest = bounds.getSouthWest();
// Calculate approximate distance between bounds corners in miles
const distance =
google.maps.geometry.spherical.computeDistanceBetween(
southwest,
northeast
) / 1609.34; // Convert meters to miles
if (distance < 0.5) {
// Very close items - show broader neighborhood context
const center = bounds.getCenter();
map.setCenter(center);
map.setZoom(11); // Neighborhood level for very close items
} else if (distance < 5) {
// Moderate spread - use fitBounds with generous padding and min zoom
map.fitBounds(bounds, 120); // Increased padding from 50 to 120
// Ensure we don't zoom too close
const currentZoom = map.getZoom();
if (currentZoom && currentZoom > 12) {
map.setZoom(12);
}
} else {
// Wide spread - use fitBounds with standard padding
map.fitBounds(bounds, 80);
// Ensure minimum zoom for very spread out items
const currentZoom = map.getZoom();
if (currentZoom && currentZoom < 6) {
map.setZoom(6);
}
}
}
}, []);
// Check if any items have coordinates before initializing map
const hasMappableItems = items.some(
(item) => item.latitude && item.longitude
);
// Debounced function to update map markers (prevents excessive API calls during rapid updates)
const debouncedUpdateMap = useMemo(
() =>
debounce(async (map: google.maps.Map, items: Item[]) => {
try {
setIsLoading(true);
await addMarkersToMap(map, items);
fitMapToMarkers(map, items);
} catch (err) {
console.error("Error updating map:", err);
} finally {
setIsLoading(false);
}
}, 300), // 300ms debounce delay
[addMarkersToMap, fitMapToMarkers]
);
// Initialize map
useEffect(() => {
if (!apiKey || !mapRef.current || !hasMappableItems) return;
// If map is already initialized, just update markers using debounced function
if (mapInitializedRef.current && mapInstanceRef.current) {
debouncedUpdateMap(mapInstanceRef.current, items);
return;
}
let mounted = true;
const initializeMap = async () => {
try {
setIsLoading(true);
setError(null);
const loader = new Loader({
apiKey,
version: "weekly",
});
await loader.importLibrary("maps");
await loader.importLibrary("marker");
await loader.importLibrary("geometry");
if (!mounted || !mapRef.current) return;
// Default map center (will be updated based on search results)
const defaultCenter = { lat: 39.8283, lng: -98.5795 }; // Geographic center of US
const mapConfig: google.maps.MapOptions = {
mapId: mapId,
center: defaultCenter,
zoom: 4,
maxZoom: 15, // Prevent users from zooming too close
zoomControl: true,
mapTypeControl: false,
scaleControl: false,
streetViewControl: false,
rotateControl: false,
fullscreenControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP,
};
const map = new google.maps.Map(mapRef.current, mapConfig);
mapInstanceRef.current = map;
mapInitializedRef.current = true;
// Add markers if items exist
if (items.length > 0) {
await addMarkersToMap(map, items);
fitMapToMarkers(map, items);
}
} catch (err) {
console.error("Failed to load Google Maps:", err);
if (mounted) {
setError("Failed to load map. Please try again later.");
}
} finally {
if (mounted) {
setIsLoading(false);
}
}
};
initializeMap();
return () => {
mounted = false;
// Don't clear markers on cleanup - preserve for next use
};
}, [
apiKey,
mapId,
hasMappableItems,
items,
addMarkersToMap,
fitMapToMarkers,
clearMarkers,
debouncedUpdateMap,
]);
// This useEffect is now handled by the main initialization effect above
const defaultStyle = {
height: "600px",
width: "100%",
borderRadius: "8px",
backgroundColor: "#f8f9fa",
};
// Show message when no items have location data
if (!hasMappableItems) {
return (
<div className={className} style={{ ...defaultStyle, ...style }}>
<div className="d-flex align-items-center justify-content-center h-100">
<div className="text-center">
<i
className="bi bi-geo-alt text-muted mb-3"
style={{ fontSize: "3rem" }}
></i>
<h5 className="text-muted">No Location Data</h5>
<p className="text-muted small mb-0">
None of the search results have location information available for
mapping.
</p>
</div>
</div>
</div>
);
}
if (error) {
return (
<div className={className} style={{ ...defaultStyle, ...style }}>
<div className="d-flex align-items-center justify-content-center h-100">
<div className="text-center">
<i
className="bi bi-exclamation-triangle text-warning mb-2"
style={{ fontSize: "3rem" }}
></i>
<p className="text-muted">{error}</p>
<button
className="btn btn-outline-primary btn-sm"
onClick={() => window.location.reload()}
>
Retry
</button>
</div>
</div>
</div>
);
}
return (
<div
className={className}
style={{ ...defaultStyle, ...style, position: "relative" }}
>
{isLoading && (
<div
className="position-absolute d-flex align-items-center justify-content-center w-100 h-100"
style={{
backgroundColor: "rgba(248, 249, 250, 0.8)",
borderRadius: "8px",
zIndex: 1000,
}}
>
<div className="text-center">
<div className="spinner-border text-primary mb-2" role="status">
<span className="visually-hidden">Loading map...</span>
</div>
<p className="text-muted small">Loading map...</p>
</div>
</div>
)}
<div
ref={mapRef}
style={{ width: "100%", height: "100%", borderRadius: "8px" }}
/>
{!isLoading && items.length > 0 && (
<div
className="position-absolute bottom-0 start-0 bg-white px-3 py-2 rounded-top-2 shadow-sm"
style={{ margin: "0 0 10px 10px", zIndex: 500 }}
>
<small className="text-muted">
<i className="bi bi-geo-alt-fill text-primary me-1"></i>
{
items.filter((item) => item.latitude && item.longitude).length
}{" "}
items shown
</small>
</div>
)}
</div>
);
};
export default SearchResultsMap;

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

@@ -1,14 +1,17 @@
import React, { useState, useEffect } from "react";
import { useSearchParams } from "react-router-dom";
import { useSearchParams, useNavigate } from "react-router-dom";
import { Item } from "../types";
import { itemAPI } from "../services/api";
import ItemCard from "../components/ItemCard";
import SearchResultsMap from "../components/SearchResultsMap";
const ItemList: React.FC = () => {
const [searchParams] = useSearchParams();
const navigate = useNavigate();
const [items, setItems] = useState<Item[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [viewMode, setViewMode] = useState<'list' | 'map'>('list');
const [filters, setFilters] = useState({
search: searchParams.get("search") || "",
city: searchParams.get("city") || "",
@@ -58,6 +61,16 @@ const ItemList: React.FC = () => {
}
};
const handleItemSelect = (item: Item) => {
navigate(`/items/${item.id}`);
};
const getSearchLocationString = () => {
if (filters.city) return filters.city;
if (filters.zipCode) return filters.zipCode;
return '';
};
if (loading) {
return (
<div className="container mt-5">
@@ -81,23 +94,63 @@ const ItemList: React.FC = () => {
}
return (
<div className="container mt-4">
<h1>Browse Items</h1>
<div className="mb-4">
<span className="text-muted">{items.length} items found</span>
<div className="container-fluid mt-4" style={{ maxWidth: '1800px' }}>
<div className="d-flex flex-column flex-md-row justify-content-between align-items-start align-items-md-center mb-4 gap-3">
<div>
<h1 className="mb-1">Browse Items</h1>
<span className="text-muted">{items.length} items found</span>
</div>
{items.length > 0 && (
<div className="btn-group" role="group" aria-label="View toggle">
<button
type="button"
className={`btn btn-outline-secondary ${viewMode === 'list' ? 'active' : ''}`}
onClick={() => setViewMode('list')}
>
<i className="bi bi-list-ul me-1 me-md-2"></i>
<span className="d-none d-md-inline">List</span>
</button>
<button
type="button"
className={`btn btn-outline-secondary ${viewMode === 'map' ? 'active' : ''}`}
onClick={() => setViewMode('map')}
>
<i className="bi bi-geo-alt-fill me-1 me-md-2"></i>
<span className="d-none d-md-inline">Map</span>
</button>
</div>
)}
</div>
{items.length === 0 ? (
<p className="text-center text-muted">No items available for rent.</p>
) : (
<div className="text-center py-5">
<i className="bi bi-search text-muted mb-3" style={{ fontSize: '4rem' }}></i>
<h3 className="text-muted">No items found</h3>
<p className="text-muted">
Try adjusting your search criteria or browse all available items.
</p>
</div>
) : viewMode === 'list' ? (
<div className="row">
{items.map((item) => (
<div key={item.id} className="col-md-6 col-lg-4 mb-4">
<div key={item.id} className="col-md-6 col-lg-4 col-xl-3 mb-4">
<ItemCard item={item} variant="standard" />
</div>
))}
</div>
) : (
<div className="mb-4">
<SearchResultsMap
items={items}
searchLocation={getSearchLocationString()}
onItemSelect={handleItemSelect}
style={{
height: window.innerWidth < 768 ? '60vh' : '70vh',
minHeight: window.innerWidth < 768 ? '400px' : '500px'
}}
/>
</div>
)}
</div>
);

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 {};