Skip to content

Commit

Permalink
Connect MongoDB and Save Third-Party Auth user data
Browse files Browse the repository at this point in the history
  • Loading branch information
The-Anton committed Jul 27, 2021
1 parent d9fe3e4 commit 7df2126
Show file tree
Hide file tree
Showing 9 changed files with 144 additions and 143 deletions.
69 changes: 32 additions & 37 deletions packages/backend/api/auth/controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,53 +11,48 @@ passport.use(auth.googleStrategy);
passport.deserializeUser(auth.deserializeUser);
passport.serializeUser(auth.serializeUser);

router.get("/auth/github", passport.authenticate("github"));
router.get(
"/auth/github/callback",
passport.authenticate("github"),
(req, res) => {
res.redirect(301, "http://localhost:3000/");
}
);
router.get("/profile", (req, res) => {
res.send(user);
});
//Github
const authGithub = passport.authenticate("github");

//Google
router.get(
"/auth/google",
passport.authenticate("google", {
const authGoogle = passport.authenticate("google", {
scope: ["profile", "email"],
})
);
router.get(
"/auth/google/callback",
passport.authenticate("google"),
(req, res) => {
res.redirect(301, "http://localhost:3000/");
}
);
//linkedin
});

router.get("/auth/linkedin", passport.authenticate("linkedin"));
const authGoogleCallback = passport.authenticate("google");

router.get(
"/auth/linkedin/callback",
passport.authenticate("linkedin"),
(req, res) => {
res.redirect(301, "http://localhost:3000/");
}
);
//linkedin
const authLinkedin = passport.authenticate("linkedin");

//userinfo
router.get("/user", (req, res) => {
const redirect = (req, res) => {
res.redirect(301, "http://localhost:3000/");
};

const profile = (req, res) => {
//res.send(user);
res.send("User Data");
};

const userInfo = (req, res) => {
console.log("getting user data!");
});
};

router.get("/auth/logout", (req, res) => {
const authLogout = (req, res) => {
logout();
console.log("logging out!");
user = {};
res.redirect(301, "http://localhost:3000/");
});
module.exports = router;
};


module.exports = {
authGithub,
authGoogle,
authGoogleCallback,
authLinkedin,
authLogout,
userInfo,
redirect,
profile
};
34 changes: 34 additions & 0 deletions packages/backend/api/auth/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
const express = require("express");
const router = express.Router();
const authController = require('./controller.js');
const logout = require("express-passport-logout");
const passport = require("passport");
const auth = require("../../config/passport");

passport.use(auth.githubStrategy);
passport.use(auth.linkedinStrategy);
passport.use(auth.googleStrategy);

passport.deserializeUser(auth.deserializeUser);
passport.serializeUser(auth.serializeUser);

//Github
router.get("/auth/github", authController.authGithub);
router.get("/auth/github/callback", authController.authGithub, authController.redirect);
router.get("/profile", authController.profile);

//Google
router.get("/auth/google", authController.authGoogle);
router.get("/auth/google/callback", authController.authGoogleCallback, authController.redirect);

//linkedin
router.get("/auth/linkedin", authController.authLinkedin);
router.get("/auth/linkedin/callback", authController.authLinkedin, authController.redirect);

//userinfo
router.get("/user", authController.userInfo);

//logout
router.get("/auth/logout", authController.authLogout);

module.exports = router;
24 changes: 14 additions & 10 deletions packages/backend/api/auth/model.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
const express = require('express');
const {login, register, logout, updatePassword} = require('./controller');
// eslint-disable-next-line new-cap
const router = express.Router();
router.route('/register').post(register);
// /api/v1/auth/register
router.route('/login').post(login);
router.route('/logout').get(logout);
// router.route('/reset').get(updatePassword);
module.exports = router;
const mongoose = require('mongoose');

var Schema = mongoose.Schema;

const userSchema = new mongoose.Schema({
googleId:{ type: String, require: true },
displayName: { type: String, require: true },
email: { type: String, require: true },
photo: { type: String, require: true },
provider: { type: String, require: true }
});


module.exports = mongoose.model('User', userSchema);
11 changes: 0 additions & 11 deletions packages/backend/api/user/controller.js

This file was deleted.

7 changes: 0 additions & 7 deletions packages/backend/api/user/index.js

This file was deleted.

59 changes: 0 additions & 59 deletions packages/backend/api/user/model.js

This file was deleted.

14 changes: 7 additions & 7 deletions packages/backend/config/db.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
const mongoose = require("mongoose");

const connectDB = async () => {
// const conn = await mongoose.connect(process.env.MONGO_URI, {
// useNewUrlParser: true,
// useCreateIndex: true,
// useFindAndModify: false,
// useUnifiedTopology: true,
// });
// console.log(`MongoDB Connected: ${conn.connection.host}`.cyan.underline.bold);
const conn = await mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
useUnifiedTopology: true,
});
console.log(`MongoDB Connected: ${conn.connection.host}`.cyan.underline.bold);
};

module.exports = connectDB;
63 changes: 55 additions & 8 deletions packages/backend/config/passport.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ const passport = require("passport");
const GithubStrategy = require("passport-github").Strategy;
const GoogleStrategy = require("passport-google-oauth20").Strategy;
const LinkedInStrategy = require("passport-linkedin-oauth2").Strategy;
const User = require('../../backend/api/auth/model')
const chalk = require("chalk");
let user = {};

Expand All @@ -20,10 +21,26 @@ exports.githubStrategy = new GithubStrategy(
clientSecret: process.env.GITHUB_clientSecret,
callbackURL: "/auth/github/callback",
},
(accessToken, refreshToken, profile, cb) => {
async (accessToken, refreshToken, profile, cb) => {
console.log(chalk.yellow(JSON.stringify(profile)));
user = { ...profile };
return cb(null, profile);
console.log(chalk.red(JSON.stringify(profile)));

const newUser = {
googleId: profile.id,
displayName: profile.displayName,
email: profile.emails[0].value,
photo: profile.photos[0].value,
provider: "github"
}

let storedUser = await User.findOne({googleId: profile.id});
if(!storedUser){
tmp = await User.create(newUser);
console.log(tmp);
user = tmp;
}

return cb(null, profile);
}
);

Expand All @@ -34,14 +51,29 @@ exports.googleStrategy = new GoogleStrategy(
clientSecret: process.env.GOOGLE_clientSecret,
callbackURL: "/auth/google/callback",
},
(accessToken, refreshToken, profile, cb) => {
async (accessToken, refreshToken, profile, cb) => {
console.log(chalk.red(JSON.stringify(profile)));
user = { ...profile };

const newUser = {
googleId: profile.id,
displayName: profile.displayName,
email: profile.emails[0].value,
photo: profile.photos[0].value,
provider: "google"
}

let storedUser = await User.findOne({googleId: profile.id});
if(!storedUser){
tmp = await User.create(newUser);
console.log(tmp);
user = tmp;
}

return cb(null, profile);
}
);
//Linkedin Stratergy

//Linkedin Stratergy
exports.linkedinStrategy = new LinkedInStrategy(
{
clientID: process.env.LINKEDIN_clientID,
Expand All @@ -50,9 +82,24 @@ exports.linkedinStrategy = new LinkedInStrategy(
scope: ["r_emailaddress", "r_liteprofile"],
passReqToCallback: true,
},
(accessToken, refreshToken, profile, cb) => {
async (accessToken, refreshToken, profile, cb) => {
console.log(chalk.blue(JSON.stringify(profile)));
user = { ...profile };

const newUser = {
googleId: profile.id,
displayName: profile.displayName,
email: profile.emails,
photo: profile.photo,
provider: "linkedin"
}

let storedUser = await User.findOne({googleId: profile.id});
if(!storedUser){
tmp = await User.create(newUser);
console.log(tmp);
user = tmp;
}

return cb(null, profile);
}
);
6 changes: 2 additions & 4 deletions packages/backend/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,11 @@ dotenv.config({ path: "./config/config.env" });
require("dotenv").config();
// Import DB
const connectDB = require("./config/db");
// connectDB();
connectDB();
require("colors");

// route files
const auth = require("./api/auth/controller");
const user = require("./api/user");
const auth = require("./api/auth/index");
const app = express();
// Body Parser

Expand Down Expand Up @@ -70,7 +69,6 @@ app.use(express.static(path.join(__dirname, "./public"), options));

// Use Routes
app.use("/", auth);
app.use("/api/v1/user", user);
app.get("*.*", express.static("./public/frontend")); // production

app.all("*", (req, res) => {
Expand Down

0 comments on commit 7df2126

Please sign in to comment.