Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Google/o auth #307

Merged
merged 8 commits into from
Oct 16, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion backend/.env.example
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
MONGO_URI=enter_your_mongo_uri
EMAIL_USER=your_gmail
EMAIL_PASS=your_16_digit_pass
JWT_SECRET=secret
JWT_SECRET=secret
GOOGLE_CLIENT_ID=your_google_client_id
GOOGLE_CLIENT_SECRET=your_google_client_secret
FRONTEND_URL=your_frontend_url
38 changes: 38 additions & 0 deletions backend/config/oauth.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
const GoogleStrategy = require("passport-google-oauth20").Strategy;
const passport = require("passport");
const Customer = require("../models/customer.model"); // Adjust the path as needed
const config = require("./secret"); // Import your secrets (client ID, client secret)
RamakrushnaBiswal marked this conversation as resolved.
Show resolved Hide resolved

passport.use(
new GoogleStrategy(
{
clientID: process.env.GOOGLE_CLIENT_ID || config.GOOGLE_CLIENT_ID,
clientSecret:
process.env.GOOGLE_CLIENT_SECRET || config.GOOGLE_CLIENT_SECRET,
callbackURL: "/auth/google/callback",
RamakrushnaBiswal marked this conversation as resolved.
Show resolved Hide resolved
},
async (accessToken, refreshToken, profile, done) => {
try {
// Extract the email from Google profile
const email = profile.emails[0].value;
samar12-rad marked this conversation as resolved.
Show resolved Hide resolved

// Search for the user in the database by email
let user = await Customer.findOne({ email });
if (!user) {
// If user doesn't exist, create a new user
user = new Customer({
name: profile.displayName || "Unamed User",
email: email, // Email from Google profile
});
await user.save();
}
// Return the user if exists or after creation
return done(null, user);
} catch (error) {
return done(error, false);
samar12-rad marked this conversation as resolved.
Show resolved Hide resolved
}
}
)
);

module.exports = passport;
3 changes: 2 additions & 1 deletion backend/config/passport.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,13 @@ const passport = require("passport");
const config = require("./secret");
RamakrushnaBiswal marked this conversation as resolved.
Show resolved Hide resolved
const Customer = require("../models/customer.model");
const Admin = require("../models/admin.model");
require("./oauth.config");

// Secret key to sign the JWT token
const secret = config.JWT_SECRET;
const opts = {
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: secret,
secretOrKey: process.env.JWT_SECRET || secret,
samar12-rad marked this conversation as resolved.
Show resolved Hide resolved
};

passport.use(
Expand Down
4 changes: 4 additions & 0 deletions backend/config/secret.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,14 @@ const JWT_SECRET = process.env.JWT_SECRET;
const MONGO_URI = process.env.MONGO_URI;
const PORT = process.env.PORT;
const CORS_ORIGIN = process.env.CORS_ORIGIN;
const GOOGLE_CLIENT_ID = process.env.GOOGLE_CLIENT_ID;
const GOOGLE_CLIENT_SECRET = process.env.GOOGLE_CLIENT_SECRET;

module.exports = {
JWT_SECRET,
MONGO_URI,
PORT,
CORS_ORIGIN,
GOOGLE_CLIENT_ID,
GOOGLE_CLIENT_SECRET,
};
26 changes: 26 additions & 0 deletions backend/controller/googleOAuth.controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
const secret = require("../config/secret");
const jwt = require("jsonwebtoken");
const jwtSecret = process.env.JWT_SECRET || secret.JWT_SECRET;
samar12-rad marked this conversation as resolved.
Show resolved Hide resolved

const handleGoogleOAuth = async (req, res) => {
const token = jwt.sign(
{
sub: req.user._id,
email: req.user.email,
},
process.env.JWT_SECRET || jwtSecret,
{
expiresIn: "1d",
}
);
samar12-rad marked this conversation as resolved.
Show resolved Hide resolved

res.cookie("authToken", token, {
expire: "1h",
secure: true,
});
samar12-rad marked this conversation as resolved.
Show resolved Hide resolved
res.redirect(process.env.FRONTEND_URL || "http://localhost:3000");
samar12-rad marked this conversation as resolved.
Show resolved Hide resolved
};

module.exports = {
handleGoogleOAuth,
};
9 changes: 9 additions & 0 deletions backend/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ const dotenv = require("dotenv");
const logger = require("./config/logger");
const errorMiddleware = require("./middlewares/errrorMiddleware");
const passport = require("passport");
const { handleGoogleOAuth } = require("./controller/googleOAuth.controller");

dotenv.config();
const app = express();
Expand Down Expand Up @@ -49,6 +50,14 @@ app.use(passport.initialize());

// API routes
app.use("/api", require("./routes/index"));
app.get(
"/auth/google/callback",
passport.authenticate("google", {
failureRedirect: "/login",
session: false,
}),
handleGoogleOAuth
);

app.options("*", cors(corsOptions));

Expand Down
1 change: 1 addition & 0 deletions backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
"mongoose": "^8.7.0",
"nodemailer": "^6.9.15",
"passport": "^0.7.0",
"passport-google-oauth20": "^2.0.0",
"passport-jwt": "^4.0.1",
"validator": "^13.12.0",
"winston": "^3.14.2",
Expand Down
6 changes: 6 additions & 0 deletions backend/routes/customerRouter.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ const {
} = require("../controller/customer.controller");
const authenticateCustomer = require("../middlewares/authCustomer");
const passport = require("../config/passport.config");
const { handleGoogleOAuth } = require("../controller/googleOAuth.controller");
const router = express.Router();
require("dotenv").config();

Expand All @@ -26,6 +27,11 @@ router.get(
);

router.post("/register", createCustomer);
router.get(
"/auth/google",
passport.authenticate("google", { scope: ["email"] })
);

router.post("/login", loginCustomer);
router.post("/reset-password", resetPassword);

Expand Down
9 changes: 8 additions & 1 deletion backend/routes/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
const express = require("express");
const logger = require("../config/logger"); // Import your Winston logger
require("dotenv").config();

const config = {
JWT_SECRET: process.env.JWT_SECRET,
GOOGLE_CLIENT_ID: process.env.GOOGLE_CLIENT_ID,
GOOGLE_CLIENT_SECRET: process.env.GOOGLE_CLIENT_SECRET,
};

const router = express.Router();

Expand Down Expand Up @@ -46,6 +53,6 @@ router.use("/feedback", feedbackRouter);
router.use("/user", require("./customerRouter"));
router.use("/reservation", require("./reservationRouter"));
router.use("/newsletter", require("./newsletterRoute"));
router.use("/forgot", require("./forgotRouter"))
router.use("/forgot", require("./forgotRouter"));
samar12-rad marked this conversation as resolved.
Show resolved Hide resolved

module.exports = router;
53 changes: 33 additions & 20 deletions frontend/src/components/Pages/Login.jsx
Original file line number Diff line number Diff line change
@@ -1,19 +1,18 @@

import React, { useState , useEffect } from "react";
import photo from "../../assets/login.png";
import { Link, useNavigate } from "react-router-dom";
import { message } from "antd";
import Cookies from 'js-cookie'
import { FaEye } from "react-icons/fa";
import { FaEyeSlash } from "react-icons/fa6";
import React, { useState, useEffect } from 'react';
import photo from '../../assets/login.png';
import { Link, useNavigate } from 'react-router-dom';
import { message } from 'antd';
import Cookies from 'js-cookie';
import { FaEye } from 'react-icons/fa';
import { FaEyeSlash } from 'react-icons/fa6';

const Login = () => {
const API_URL = import.meta.env.VITE_BACKEND_URL || 'http://localhost:3000';
const [data, setData] = useState({
email: '',
password: '',
});
const [hidden, setHidden] = useState(true)
const [hidden, setHidden] = useState(true);

const handleChange = (e) => {
setData({ ...data, [e.target.name]: e.target.value });
Expand All @@ -39,9 +38,9 @@ const Login = () => {
throw new Error(result.message || 'Login failed');
}
// Handle successful login (e.g., store token, redirect)
Cookies.set('authToken',result.token,{
expire:'1h',
secure:true
Cookies.set('authToken', result.token, {
expire: '1h',
secure: true,
});
message.success('Login successful');
navigate('/');
Expand Down Expand Up @@ -83,17 +82,20 @@ const Login = () => {
className="input w-full h-10 rounded-md border-2 border-black bg-beige shadow-[4px_4px_0px_0px_black] text-[15px] font-semibold text-[#323232] p-2.5 focus:outline-none focus:border-[#2d8cf0] placeholder-[#666] placeholder-opacity-80"
name="password"
placeholder="Password"
type={hidden ? "password" : "text"}
type={hidden ? 'password' : 'text'}
onChange={(e) => handleChange(e)}
/>
<button className="absolute top-1/2 -translate-y-1/2 right-4" onClick={(e)=>{
e.preventDefault();
setHidden(!hidden)
}}>
{hidden ? <FaEyeSlash/> : <FaEye/>}
<button
className="absolute top-1/2 -translate-y-1/2 right-4"
onClick={(e) => {
e.preventDefault();
setHidden(!hidden);
}}
>
{hidden ? <FaEyeSlash /> : <FaEye />}
</button>
</div>

<div className="transform hover:text-red-500 transition">
<Link to={'/email-verify'}>Forgot Password?</Link>
</div>
Expand All @@ -104,10 +106,21 @@ const Login = () => {
<Link to={'/signup'}>Register Here</Link>
</span>
</h3>
<a
href="http://localhost:3000/api/user/auth/google"
className="text-[#666] font-semibold text-xl transform hover:scale-110 hover:-translate-y-1 hover:text-green-500 transition w-full"
>
<button
type="button"
className="button-confirm px-4 w-full h-10 rounded-md border-2 border-black bg-beige shadow-[4px_4px_0px_0px_black] text-[17px] font-semibold text-[#323232] cursor-pointer active:shadow-none active:translate-x-[3px] active:translate-y-[3px]"
>
Sign in with Google
</button>
</a>
{error && <p className="text-red-500 mt-2">{error}</p>}
<button
type="submit"
className="button-confirm mx-auto mt-12 px-4 w-30 h-10 rounded-md border-2 border-black bg-beige shadow-[4px_4px_0px_0px_black] text-[17px] font-semibold text-[#323232] cursor-pointer active:shadow-none active:translate-x-[3px] active:translate-y-[3px]"
className="button-confirm px-4 w-30 h-10 rounded-md border-2 border-black bg-beige shadow-[4px_4px_0px_0px_black] text-[17px] font-semibold text-[#323232] cursor-pointer active:shadow-none active:translate-x-[3px] active:translate-y-[3px]"
>
{isLoading ? 'Loading...' : 'Let’s Log you in →'}
</button>
Expand Down
65 changes: 42 additions & 23 deletions frontend/src/components/Pages/Signup.jsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@

import { useState , useEffect } from "react";
import photo from "../../assets/login.png";
import { useNavigate } from "react-router-dom";
import { Link } from "react-router-dom";
import { FaEye } from "react-icons/fa";
import { FaEyeSlash } from "react-icons/fa6";
import zxcvbn from "zxcvbn"; // Import zxcvbn for password strength check
import { useState, useEffect } from 'react';
import photo from '../../assets/login.png';
import { useNavigate } from 'react-router-dom';
import { Link } from 'react-router-dom';
import { FaEye } from 'react-icons/fa';
import { FaEyeSlash } from 'react-icons/fa6';
import zxcvbn from 'zxcvbn'; // Import zxcvbn for password strength check

const Signup = () => {
const API_URL = import.meta.env.VITE_BACKEND_URL || 'http://localhost:3000';
Expand All @@ -18,12 +17,12 @@ const Signup = () => {
email: '',
password: '',
});
const [hidden, setHidden] = useState(true)
const [hidden, setHidden] = useState(true);

const handleChange = (e) => {
setData({ ...data, [e.target.name]: e.target.value });

if (e.target.name === "password") {
if (e.target.name === 'password') {
const result = zxcvbn(e.target.value);
setPasswordStrength(result.score); // Update password strength score
}
Expand Down Expand Up @@ -81,17 +80,17 @@ const Signup = () => {
}
};

useEffect(() => {
window.scrollTo(0, 0);
}, []);
useEffect(() => {
window.scrollTo(0, 0);
}, []);

const getPasswordStrengthColor = (score) => {
const colors = ["#ff4d4d", "#ff944d", "#ffd24d", "#d2ff4d", "#4dff88"];
const colors = ['#ff4d4d', '#ff944d', '#ffd24d', '#d2ff4d', '#4dff88'];
return colors[score];
};

const getPasswordStrengthText = (score) => {
const strengthLevels = ["Very Weak", "Weak", "Okay", "Good", "Strong"];
const strengthLevels = ['Very Weak', 'Weak', 'Okay', 'Good', 'Strong'];
return strengthLevels[score];
};

Expand Down Expand Up @@ -131,20 +130,29 @@ const Signup = () => {
className="input w-full h-10 rounded-md border-2 border-black bg-beige shadow-[4px_4px_0px_0px_black] text-[15px] font-semibold text-[#323232] p-2.5 focus:outline-none focus:border-[#2d8cf0] placeholder-[#666] placeholder-opacity-80"
name="password"
placeholder="Password"
type={hidden ? "password" : "text"}
type={hidden ? 'password' : 'text'}
onChange={(e) => handleChange(e)}
/>
<button className="absolute top-1/2 -translate-y-1/2 right-4" onClick={(e)=>{
e.preventDefault()
setHidden(!hidden)
}}>
{hidden ? <FaEyeSlash/> : <FaEye/>}
<button
className="absolute top-1/2 -translate-y-1/2 right-4"
onClick={(e) => {
e.preventDefault();
setHidden(!hidden);
}}
>
{hidden ? <FaEyeSlash /> : <FaEye />}
</button>
</div>

{/* Password Strength Meter */}
<div className="w-full mt-2">
<div className="h-2 rounded-full" style={{ backgroundColor: getPasswordStrengthColor(passwordStrength), width: `${(passwordStrength + 1) * 20}%` }}></div>
<div
className="h-2 rounded-full"
style={{
backgroundColor: getPasswordStrengthColor(passwordStrength),
width: `${(passwordStrength + 1) * 20}%`,
}}
></div>
<p className="text-sm text-[#666] mt-1">
Strength: {getPasswordStrengthText(passwordStrength)}
</p>
Expand All @@ -161,8 +169,19 @@ const Signup = () => {
<Link to={'/login'}>Login</Link>
</span>
</h3>
<a
href="http://localhost:3000/api/user/auth/google"
className="text-[#666] font-semibold text-xl transform hover:scale-110 hover:-translate-y-1 hover:text-green-500 transition w-full "
>
<button
type="button"
className="button-confirm px-4 w-full h-10 rounded-md border-2 border-black bg-beige shadow-[4px_4px_0px_0px_black] text-[17px] font-semibold text-[#323232] cursor-pointer active:shadow-none active:translate-x-[3px] active:translate-y-[3px]"
>
Sign up with Google
</button>
</a>
<button
samar12-rad marked this conversation as resolved.
Show resolved Hide resolved
className="button-confirm mx-auto mt-12 px-4 w-30 h-10 rounded-md border-2 border-black bg-beige shadow-[4px_4px_0px_0px_black] text-[17px] font-semibold text-[#323232] cursor-pointer active:shadow-none active:translate-x-[3px] active:translate-y-[3px]"
className="button-confirm mx-auto px-4 w-30 h-10 rounded-md border-2 border-black bg-beige shadow-[4px_4px_0px_0px_black] text-[17px] font-semibold text-[#323232] cursor-pointer active:shadow-none active:translate-x-[3px] active:translate-y-[3px]"
onClick={(e) => handleSubmit(e)}
>
{isLoading ? 'Loading...' : "Let's go →"}
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/components/Shared/Navbar.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ const Navbar = () => {
<div className="px-4 pt-4 pb-4 space-y-2">
{menuItems.map((item) => (
<Link
onClick={()=> setIsMenuOpen((prev)=>!prev)}
onClick={() => setIsMenuOpen((prev) => !prev)}
key={item.name}
to={item.path}
className={`block px-4 py-3 rounded-md text-base font-semibold transition duration-300
Expand Down
Loading
Loading