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

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

View File

@@ -16,6 +16,7 @@
"dotenv": "^17.2.0", "dotenv": "^17.2.0",
"express": "^5.1.0", "express": "^5.1.0",
"express-rate-limit": "^8.1.0", "express-rate-limit": "^8.1.0",
"google-auth-library": "^10.3.0",
"jsonwebtoken": "^9.0.2", "jsonwebtoken": "^9.0.2",
"multer": "^2.0.2", "multer": "^2.0.2",
"node-cron": "^3.0.3", "node-cron": "^3.0.3",
@@ -127,6 +128,15 @@
"node": ">= 0.6" "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": { "node_modules/agentkeepalive": {
"version": "4.6.0", "version": "4.6.0",
"resolved": "https://registry.npmjs.org/agentkeepalive/-/agentkeepalive-4.6.0.tgz", "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", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
"integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==" "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": { "node_modules/bcryptjs": {
"version": "3.0.2", "version": "3.0.2",
"resolved": "https://registry.npmjs.org/bcryptjs/-/bcryptjs-3.0.2.tgz", "resolved": "https://registry.npmjs.org/bcryptjs/-/bcryptjs-3.0.2.tgz",
@@ -218,6 +248,15 @@
"bcrypt": "bin/bcrypt" "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": { "node_modules/binary-extensions": {
"version": "2.3.0", "version": "2.3.0",
"resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz", "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==", "integrity": "sha512-KALDyEYgpY+Rlob/iriUtjV6d5Eq+Y191A5g4UqLAi8CyGP9N1+FdVbkc1SxKc2r4YAYqG8JzO2KGL+AizD70Q==",
"license": "MIT" "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": { "node_modules/debug": {
"version": "4.4.1", "version": "4.4.1",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.1.tgz", "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.1.tgz",
@@ -805,6 +853,35 @@
"express": ">= 4.11" "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": { "node_modules/fill-range": {
"version": "7.1.1", "version": "7.1.1",
"resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz",
@@ -914,6 +991,18 @@
"node": ">= 0.6" "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": { "node_modules/forwarded": {
"version": "0.2.0", "version": "0.2.0",
"resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz",
@@ -966,6 +1055,34 @@
"url": "https://github.com/sponsors/ljharb" "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": { "node_modules/get-caller-file": {
"version": "2.0.5", "version": "2.0.5",
"resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", "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" "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": { "node_modules/gopd": {
"version": "1.2.0", "version": "1.2.0",
"resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", "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", "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz",
"integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==" "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": { "node_modules/has-flag": {
"version": "3.0.0", "version": "3.0.0",
"resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz",
@@ -1139,6 +1338,19 @@
"node": ">= 0.8" "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": { "node_modules/humanize-ms": {
"version": "1.2.1", "version": "1.2.1",
"resolved": "https://registry.npmjs.org/humanize-ms/-/humanize-ms-1.2.1.tgz", "resolved": "https://registry.npmjs.org/humanize-ms/-/humanize-ms-1.2.1.tgz",
@@ -1316,6 +1528,15 @@
"node": ">=14" "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": { "node_modules/jsonfile": {
"version": "6.1.0", "version": "6.1.0",
"resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.1.0.tgz", "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.1.0.tgz",
@@ -1615,6 +1836,44 @@
"uuid": "dist/bin/uuid" "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": { "node_modules/nodemon": {
"version": "3.1.10", "version": "3.1.10",
"resolved": "https://registry.npmjs.org/nodemon/-/nodemon-3.1.10.tgz", "resolved": "https://registry.npmjs.org/nodemon/-/nodemon-3.1.10.tgz",
@@ -2668,6 +2927,15 @@
"node": ">= 0.8" "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": { "node_modules/which": {
"version": "2.0.2", "version": "2.0.2",
"resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",

View File

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

View File

@@ -1,8 +1,11 @@
const express = require("express"); const express = require("express");
const jwt = require("jsonwebtoken"); 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 { User } = require("../models"); // Import from models/index.js to get models with associations
const router = express.Router(); const router = express.Router();
const googleClient = new OAuth2Client(process.env.GOOGLE_CLIENT_ID);
router.post("/register", async (req, res) => { router.post("/register", async (req, res) => {
try { try {
const { username, email, password, firstName, lastName, phone } = req.body; 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; 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 { sequelize } = require("./models"); // Import from models/index.js to ensure associations are loaded
const authRoutes = require("./routes/auth"); const authRoutes = require("./routes/auth");
const phoneAuthRoutes = require("./routes/phone-auth");
const userRoutes = require("./routes/users"); const userRoutes = require("./routes/users");
const itemRoutes = require("./routes/items"); const itemRoutes = require("./routes/items");
const rentalRoutes = require("./routes/rentals"); 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/beta", betaRoutes);
app.use("/api/auth", authRoutes); app.use("/api/auth", authRoutes);
app.use("/api/auth/phone", phoneAuthRoutes);
app.use("/api/users", userRoutes); app.use("/api/users", userRoutes);
app.use("/api/items", itemRoutes); app.use("/api/items", itemRoutes);
app.use("/api/rentals", rentalRoutes); app.use("/api/rentals", rentalRoutes);

View File

@@ -14,6 +14,7 @@
<title>CommunityRentals.App - 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 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"> <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> </head>
<body> <body>
<noscript>You need to enable JavaScript to run this app.</noscript> <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"; import { useAuth } from "../contexts/AuthContext";
interface AuthModalProps { interface AuthModalProps {
@@ -13,18 +13,15 @@ const AuthModal: React.FC<AuthModalProps> = ({
initialMode = "login", initialMode = "login",
}) => { }) => {
const [mode, setMode] = useState<"login" | "signup">(initialMode); const [mode, setMode] = useState<"login" | "signup">(initialMode);
const [authMethod, setAuthMethod] = useState<"phone" | "email" | null>(null);
const [phoneNumber, setPhoneNumber] = useState("");
const [email, setEmail] = useState(""); const [email, setEmail] = useState("");
const [password, setPassword] = useState(""); const [password, setPassword] = useState("");
const [firstName, setFirstName] = useState(""); const [firstName, setFirstName] = useState("");
const [lastName, setLastName] = useState(""); const [lastName, setLastName] = useState("");
const [verificationCode, setVerificationCode] = useState("");
const [showVerification, setShowVerification] = useState(false);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [error, setError] = useState(""); 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 // Update mode when modal is opened with different initialMode
useEffect(() => { useEffect(() => {
@@ -33,165 +30,40 @@ const AuthModal: React.FC<AuthModalProps> = ({
} }
}, [show, initialMode]); }, [show, initialMode]);
// Format phone number as user types // Initialize Google Sign-In
const formatPhoneNumber = (value: string) => { useEffect(() => {
// Remove all non-numeric characters if (show && window.google && process.env.REACT_APP_GOOGLE_CLIENT_ID) {
let phoneNumber = value.replace(/\D/g, ""); try {
window.google.accounts.id.initialize({
// Remove leading 1 if present (US country code) client_id: process.env.REACT_APP_GOOGLE_CLIENT_ID,
if (phoneNumber.length > 10 && phoneNumber.startsWith("1")) { callback: handleGoogleResponse,
phoneNumber = phoneNumber.substring(1); auto_select: false,
cancel_on_tap_outside: false,
});
} catch (error) {
console.error("Error initializing Google Sign-In:", error);
}
} }
}, [show]);
// Limit to 10 digits const handleGoogleResponse = async (response: any) => {
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 { try {
// Clean the phone number setLoading(true);
let cleanedNumber = phoneNumber.replace(/\D/g, ""); setError("");
// Remove leading 1 if we have 11 digits if (!response?.credential) {
if (cleanedNumber.length === 11 && cleanedNumber.startsWith("1")) { throw new Error("No credential received from Google");
cleanedNumber = cleanedNumber.substring(1);
} }
const fullPhoneNumber = `+1${cleanedNumber}`; await googleLogin(response.credential);
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(); onHide();
resetModal(); 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) { } catch (err: any) {
console.error("Verification error:", err); setError(
setError(err.message || "Failed to verify code"); err.response?.data?.error ||
err.message ||
"Failed to sign in with Google"
);
} finally { } finally {
setLoading(false); setLoading(false);
} }
@@ -224,20 +96,25 @@ const AuthModal: React.FC<AuthModalProps> = ({
}; };
const handleSocialLogin = (provider: string) => { const handleSocialLogin = (provider: string) => {
// TODO: Implement social login if (provider === "google") {
console.log(`Login with ${provider}`); 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 = () => { const resetModal = () => {
setAuthMethod(null);
setShowVerification(false);
setError(""); setError("");
setPhoneNumber("");
setEmail(""); setEmail("");
setPassword(""); setPassword("");
setFirstName(""); setFirstName("");
setLastName(""); setLastName("");
setVerificationCode("");
}; };
if (!show) return null; if (!show) return null;
@@ -262,7 +139,7 @@ const AuthModal: React.FC<AuthModalProps> = ({
></button> ></button>
</div> </div>
<div className="modal-body px-4 pb-4"> <div className="modal-body px-4 pb-4">
<h4 className="text-center mb-4"> <h4 className="text-center mb-2">
Welcome to CommunityRentals.App Welcome to CommunityRentals.App
</h4> </h4>
@@ -272,234 +149,112 @@ const AuthModal: React.FC<AuthModalProps> = ({
</div> </div>
)} )}
{!authMethod && !showVerification && ( {/* Email Form */}
<div> <form onSubmit={handleEmailSubmit}>
{/* Phone Number Input */} {mode === "signup" && (
<form onSubmit={handlePhoneSubmit}> <>
{mode === "signup" && ( <div className="row mb-3">
<> <div className="col">
<div className="row mb-3"> <label className="form-label">First Name</label>
<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 <input
type="tel" type="text"
className="form-control" className="form-control"
placeholder="(123) 456-7890" value={firstName}
value={phoneNumber} onChange={(e) => setFirstName(e.target.value)}
onChange={handlePhoneChange} 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 required
/> />
</div> </div>
</div> </div>
</>
)}
<button <div className="mb-3">
type="submit" <label className="form-label">Email</label>
className="btn btn-primary w-100 py-3 mb-3" <input
disabled={loading} type="email"
> className="form-control"
{loading ? "Sending..." : "Continue"} value={email}
</button> onChange={(e) => setEmail(e.target.value)}
required
<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> </div>
)}
{showVerification && ( <div className="mb-3">
<form onSubmit={handleVerificationSubmit}> <label className="form-label">Password</label>
<button <input
type="button" type="password"
className="btn btn-link p-0 mb-3" className="form-control"
onClick={() => setShowVerification(false)} 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 {mode === "login" ? "Sign up" : "Log in"}
</button> </a>
</small>
<div className="mb-3"> </div>
<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"> <p className="text-center text-muted small mt-4 mb-0">
By continuing, you agree to CommunityRentals.App's{" "} By continuing, you agree to CommunityRentals.App's{" "}

View File

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

View File

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