Guest User

Untitled

a guest
Mar 24th, 2018
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.22 KB | None | 0 0
  1. const passport = require("passport");
  2. const GoogleStrategy = require("passport-google-oauth").OAuth2Strategy;
  3. const TwitterStrategy = require("passport-twitter").Strategy;
  4. const mongoose = require("mongoose");
  5.  
  6. const keys = require("../config/keys");
  7.  
  8. const User = mongoose.model("users");
  9.  
  10. passport.serializeUser((user, done) => {
  11. done(null, user.id);
  12. });
  13.  
  14. passport.deserializeUser(async (id, done) => {
  15. const user = await User.findById(id);
  16. done(null, user);
  17. });
  18.  
  19. passport.use(
  20. new GoogleStrategy(
  21. {
  22. clientID: keys.googleClientID,
  23. clientSecret: keys.googleClientSecret,
  24. callbackURL: "/auth/google/callback",
  25. proxy: true,
  26. passReqToCallback: true
  27. },
  28. async (req, accessToken, refreshToken, profile, done) => {
  29. console.log("req", req.session);
  30. console.log("req", req.user);
  31. console.log("req", profile.id, profile.displayName);
  32. console.log("*-------------------------------*");
  33.  
  34. // Not logged-in currently with any other social account.
  35. if (!req.user) {
  36. let existingGoogleUser = await User.findOne({ googleId: profile.id });
  37.  
  38. //check if there is an existing user already with that social account Id.
  39. //like (twitterId, googleId etc)
  40. if (existingGoogleUser) {
  41. return done(null, existingGoogleUser);
  42. }
  43.  
  44. //if there is no existing user with that social account Id
  45. //create a new user with that social account Id
  46. let user = await new User({ googleId: profile.id }).save();
  47. return done(null, user);
  48. }
  49.  
  50. // Logged in currently with some other social account
  51.  
  52. //Only update the user document if the current authenticated user
  53. //has not linked his google account already.
  54. if (!req.user.googleId) {
  55. //if there is a google account with the same id, return the authenticated user.
  56. if(await User.findOne({ googleId: profile.id })) {
  57. return done(null, req.user);
  58. }
  59. let existingUser = await User.findByIdAndUpdate(
  60. req.user.id,
  61. { googleId: profile.id },
  62. { new: true }
  63. );
  64. return done(null, existingUser);
  65. } else {
  66. // If the user has already linked his google account and tries
  67. // to login from the same computer with a different account
  68. // then create a new user document
  69. if (req.user.googleId !== profile.id) {
  70. let user = await new User({ googleId: profile.id }).save();
  71. return done(null, user);
  72. }
  73.  
  74. // If the user logs in with the same google account again
  75. // Continue with the passport authentication flow and log him in.
  76. done(null, req.user);
  77. }
  78. }
  79. )
  80. );
  81.  
  82. passport.use(
  83. new TwitterStrategy(
  84. {
  85. consumerKey: keys.twitterConsumerKey,
  86. consumerSecret: keys.twitterConsumerSecret,
  87. callbackURL: "/auth/twitter/callback",
  88. proxy: true,
  89. passReqToCallback: true
  90. },
  91. async (req, token, tokenSecret, profile, done) => {
  92. console.log("req", req.session);
  93. console.log("req", req.user);
  94. console.log("req", profile.id, profile.displayName);
  95. console.log("*-------------------------------*");
  96.  
  97. // Not logged-in currently with any other social account.
  98. if (!req.user) {
  99. let existingTwitterUser = await User.findOne({ twitterId: profile.id });
  100.  
  101.  
  102. if (existingTwitterUser) {
  103. return done(null, existingTwitterUser);
  104. }
  105.  
  106. //if there is no existing user with that social account Id
  107. //create a new user with that social account Id
  108. let user = await new User({ twitterId: profile.id }).save();
  109. return done(null, user);
  110. }
  111.  
  112. // Logged in currently with some other social account
  113.  
  114. //Only update the user document if the current authenticated user
  115. //has not linked his twitter account already.
  116. if (!req.user.twitterId) {
  117. //if there is a twitter account with the same id, return the authenticated user.
  118. if(await User.findOne({ twitterId: profile.id })) {
  119. return done(null, req.user);
  120. }
  121.  
  122. let existingUser = await User.findByIdAndUpdate(
  123. req.user.id,
  124. { twitterId: profile.id },
  125. { new: true }
  126. );
  127. return done(null, existingUser);
  128. } else {
  129. // If the user has already linked his twitter account and tries
  130. // to login from the same computer with a different account
  131. // then create a new user document
  132. if (req.user.twitterId !== profile.id) {
  133. let user = await new User({ twitterId: profile.id }).save();
  134. return done(null, user);
  135. }
  136.  
  137. // If the user logs in with the same twitter account again
  138. // Continue with the passport authentication flow and log him in.
  139. return done(null, req.user);
  140. }
  141. }
  142. )
  143. );
  144.  
  145. const passport = require("passport");
  146.  
  147. module.exports = app => {
  148. //google auth
  149. app.get(
  150. "/auth/google",
  151. passport.authenticate("google", {
  152. scope: ["profile", "email"],
  153. prompt: "select_account"
  154. })
  155. );
  156.  
  157. app.get("/auth/google/callback", passport.authenticate("google"));
  158.  
  159. //twitter auth
  160. app.get("/auth/twitter", passport.authenticate("twitter"));
  161. app.get("/auth/twitter/callback", passport.authenticate('twitter'));
  162.  
  163. app.get("/api/logout", (req, res) => {
  164. req.logout();
  165.  
  166. res.send(req.user);
  167. });
  168.  
  169. app.get("/api/current_user", (req, res) => {
  170. res.send(req.user);
  171. });
  172. };
  173.  
  174. const mongoose = require("mongoose");
  175. const { Schema } = mongoose;
  176.  
  177. const userSchema = new Schema({
  178. googleId: {
  179. type: String,
  180. },
  181. twitterId: {
  182. type: String,
  183. }
  184. });
  185.  
  186. mongoose.model("users", userSchema);
  187.  
  188. const express = require("express");
  189. const mongoose = require("mongoose");
  190. const cookieSession = require("cookie-session");
  191. const passport = require("passport");
  192.  
  193. require("./models/User");
  194. require("./services/passport");
  195. const keys = require("./config/keys");
  196.  
  197. mongoose.connect(keys.mongoURI);
  198.  
  199. const app = express();
  200.  
  201. app.use(
  202. cookieSession({
  203. maxAge: 30 * 24 * 60 * 60 * 1000,
  204. keys: [keys.cookieKey]
  205. })
  206. );
  207.  
  208. app.use(passport.initialize());
  209. app.use(passport.session());
  210.  
  211. require("./routes/authRoutes")(app);
  212.  
  213. const PORT = process.env.PORT || 5000;
  214.  
  215. app.listen(PORT, () => {
  216. console.log(`Started Server on ${PORT}`);
  217. });
Add Comment
Please, Sign In to add comment