Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const passport = require("passport");
- const GoogleStrategy = require("passport-google-oauth").OAuth2Strategy;
- const TwitterStrategy = require("passport-twitter").Strategy;
- const mongoose = require("mongoose");
- const keys = require("../config/keys");
- const User = mongoose.model("users");
- passport.serializeUser((user, done) => {
- done(null, user.id);
- });
- passport.deserializeUser(async (id, done) => {
- const user = await User.findById(id);
- done(null, user);
- });
- passport.use(
- new GoogleStrategy(
- {
- clientID: keys.googleClientID,
- clientSecret: keys.googleClientSecret,
- callbackURL: "/auth/google/callback",
- proxy: true,
- passReqToCallback: true
- },
- async (req, accessToken, refreshToken, profile, done) => {
- console.log("req", req.session);
- console.log("req", req.user);
- console.log("req", profile.id, profile.displayName);
- console.log("*-------------------------------*");
- // Not logged-in currently with any other social account.
- if (!req.user) {
- let existingGoogleUser = await User.findOne({ googleId: profile.id });
- //check if there is an existing user already with that social account Id.
- //like (twitterId, googleId etc)
- if (existingGoogleUser) {
- return done(null, existingGoogleUser);
- }
- //if there is no existing user with that social account Id
- //create a new user with that social account Id
- let user = await new User({ googleId: profile.id }).save();
- return done(null, user);
- }
- // Logged in currently with some other social account
- //Only update the user document if the current authenticated user
- //has not linked his google account already.
- if (!req.user.googleId) {
- //if there is a google account with the same id, return the authenticated user.
- if(await User.findOne({ googleId: profile.id })) {
- return done(null, req.user);
- }
- let existingUser = await User.findByIdAndUpdate(
- req.user.id,
- { googleId: profile.id },
- { new: true }
- );
- return done(null, existingUser);
- } else {
- // If the user has already linked his google account and tries
- // to login from the same computer with a different account
- // then create a new user document
- if (req.user.googleId !== profile.id) {
- let user = await new User({ googleId: profile.id }).save();
- return done(null, user);
- }
- // If the user logs in with the same google account again
- // Continue with the passport authentication flow and log him in.
- done(null, req.user);
- }
- }
- )
- );
- passport.use(
- new TwitterStrategy(
- {
- consumerKey: keys.twitterConsumerKey,
- consumerSecret: keys.twitterConsumerSecret,
- callbackURL: "/auth/twitter/callback",
- proxy: true,
- passReqToCallback: true
- },
- async (req, token, tokenSecret, profile, done) => {
- console.log("req", req.session);
- console.log("req", req.user);
- console.log("req", profile.id, profile.displayName);
- console.log("*-------------------------------*");
- // Not logged-in currently with any other social account.
- if (!req.user) {
- let existingTwitterUser = await User.findOne({ twitterId: profile.id });
- if (existingTwitterUser) {
- return done(null, existingTwitterUser);
- }
- //if there is no existing user with that social account Id
- //create a new user with that social account Id
- let user = await new User({ twitterId: profile.id }).save();
- return done(null, user);
- }
- // Logged in currently with some other social account
- //Only update the user document if the current authenticated user
- //has not linked his twitter account already.
- if (!req.user.twitterId) {
- //if there is a twitter account with the same id, return the authenticated user.
- if(await User.findOne({ twitterId: profile.id })) {
- return done(null, req.user);
- }
- let existingUser = await User.findByIdAndUpdate(
- req.user.id,
- { twitterId: profile.id },
- { new: true }
- );
- return done(null, existingUser);
- } else {
- // If the user has already linked his twitter account and tries
- // to login from the same computer with a different account
- // then create a new user document
- if (req.user.twitterId !== profile.id) {
- let user = await new User({ twitterId: profile.id }).save();
- return done(null, user);
- }
- // If the user logs in with the same twitter account again
- // Continue with the passport authentication flow and log him in.
- return done(null, req.user);
- }
- }
- )
- );
- const passport = require("passport");
- module.exports = app => {
- //google auth
- app.get(
- "/auth/google",
- passport.authenticate("google", {
- scope: ["profile", "email"],
- prompt: "select_account"
- })
- );
- app.get("/auth/google/callback", passport.authenticate("google"));
- //twitter auth
- app.get("/auth/twitter", passport.authenticate("twitter"));
- app.get("/auth/twitter/callback", passport.authenticate('twitter'));
- app.get("/api/logout", (req, res) => {
- req.logout();
- res.send(req.user);
- });
- app.get("/api/current_user", (req, res) => {
- res.send(req.user);
- });
- };
- const mongoose = require("mongoose");
- const { Schema } = mongoose;
- const userSchema = new Schema({
- googleId: {
- type: String,
- },
- twitterId: {
- type: String,
- }
- });
- mongoose.model("users", userSchema);
- const express = require("express");
- const mongoose = require("mongoose");
- const cookieSession = require("cookie-session");
- const passport = require("passport");
- require("./models/User");
- require("./services/passport");
- const keys = require("./config/keys");
- mongoose.connect(keys.mongoURI);
- const app = express();
- app.use(
- cookieSession({
- maxAge: 30 * 24 * 60 * 60 * 1000,
- keys: [keys.cookieKey]
- })
- );
- app.use(passport.initialize());
- app.use(passport.session());
- require("./routes/authRoutes")(app);
- const PORT = process.env.PORT || 5000;
- app.listen(PORT, () => {
- console.log(`Started Server on ${PORT}`);
- });
Add Comment
Please, Sign In to add comment