Skip to content

Commit

Permalink
Facebook & Google
Browse files Browse the repository at this point in the history
  • Loading branch information
sivm99 committed Oct 8, 2024
1 parent ec4785d commit f875ea7
Show file tree
Hide file tree
Showing 6 changed files with 241 additions and 2 deletions.
124 changes: 124 additions & 0 deletions Controller/auth2.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
import passport from "passport";
import { Strategy as GoogleStrategy } from "passport-google-oauth20";
import { Strategy as FacebookStrategy } from 'passport-facebook';
import User from "../Models/userModel.js";
import asyncErrorHandler from "../utils/asyncErrorHandler.js";
import CustomError from "../utils/CustomError.js";
import createSendResponse from "../utils/createSendResponse.js";
import { sendUser } from "../utils/safeResponseObject.js";

// Configure Google OAuth Strategy
passport.use(
new GoogleStrategy(
{
clientID: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
callbackURL: "/api/v1/auth/google/callback",
},
async (accessToken, refreshToken, profile, done) => {
try {
const { id, displayName, emails } = profile;
const email = emails && emails[0]?.value;

// Check if user already exists in the database
let user = await User.findOne({ email });

if (!user) {
// Create a new user if not found
user = new User({
username: displayName,
name: displayName,
email,
password: " ", // Set password as null since this is OAuth
passwordConfirm: " ",
active: true,
providor: "google",
});
await user.save({ validateBeforeSave: false });
}
done(null, user);
} catch (error) {
done(error, null);
}
}
)
);

// Middleware to handle Google login
export const googleLogin = asyncErrorHandler(async (req, res, next) => {
passport.authenticate("google", { scope: ["profile", "email"] })(
req,
res,
next
);
});

// Middleware to handle Google OAuth callback
export const googleCallback = asyncErrorHandler(async (req, res, next) => {
passport.authenticate("google", async (err, user, info) => {
if (err || !user) {
console.log(err);
console.log(user);
return next(
new CustomError(
`Authentication Failed due to ${err.message} ${err}`,
401
)
);
}

const id = user.id || user._id;
const safeUser = sendUser(user);
createSendResponse(safeUser, 200, res, "user", id);
})(req, res, next);
});


passport.use(
new FacebookStrategy(
{
clientID: process.env.FACEBOOK_CLIENT_ID,
clientSecret: process.env.FACEBOOK_CLIENT_SECRET,
callbackURL: "/api/v1/auth/facebook/callback",
profileFields: ['id', 'displayName', 'emails'],
},
async (accessToken, refreshToken, profile, done) => {
try {
const { id, displayName, emails } = profile;
const email = emails && emails[0]?.value;

// Check if user already exists in the database
let user = await User.findOne({ email });

if (!user) {
// Create a new user if not found
user = await User.create({
username: displayName,
name: displayName,
email,
password: ' ', // Set password as null since this is OAuth
passwordConfirm: ' ',
active: true,
});
}

done(null, user);
} catch (error) {
done(error, null);
}
}
)
);

// Middleware to handle Facebook login callback
export const facebookCallback = asyncErrorHandler(async (req, res, next) => {
passport.authenticate('facebook', async (err, user, info) => {
if (err || !user) {
return next(new CustomError("Facebook authentication failed", 401));
}

const id = user.id || user._id;
const safeUser = sendUser(user);
createSendResponse(safeUser, 200, res, "user", id);
})(req, res, next);
});
2 changes: 1 addition & 1 deletion Controller/authController.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export const login = asyncErrorHandler(async (req, res, next) => {
const user = await User.findOne({ $or: [{ username }, { email }] }).select(
"+password +active"
);
if (!user || !user.active) {
if (!user || !user.active || user.provider) {
return next(new CustomError("Incorrect username or password", 401));
}
if (!(await user.correctPassword(password, user.password))) {
Expand Down
3 changes: 3 additions & 0 deletions Models/userModel.js
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,9 @@ const userSchema = new mongoose.Schema({
message: "Passwords are not the same",
},
},
povidor: {
type: String,
},
passwordChangedAt: Date,
passwordResetToken: String,
passwordResetExpires: Date,
Expand Down
100 changes: 99 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@
"mongoose": "^8.5.4",
"morgan": "^1.10.0",
"nodemailer": "^6.9.14",
"passport": "^0.7.0",
"passport-facebook": "^3.0.0",
"passport-google-oauth20": "^2.0.0",
"validator": "^13.12.0"
},
"devDependencies": {
Expand Down
11 changes: 11 additions & 0 deletions routes/authRoutes.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Router } from "express";
import { signup, login , forgetPassword, resetPassword, protect, logout } from "../Controller/authController.js";
import { facebookCallback, googleCallback, googleLogin } from "../Controller/auth2.js";
const router = Router();

router
Expand All @@ -20,4 +21,14 @@ router
router
.route('/logout')
.post(protect, logout);

router
.route("/google")
.get(googleLogin);
router
.route("/google/callback")
.get(googleCallback);
router
.route("/facebook/callback")
.get(facebookCallback);
export default router;

0 comments on commit f875ea7

Please sign in to comment.