Guest User

Untitled

a guest
May 2nd, 2018
172
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.67 KB | None | 0 0
  1. //routes.js
  2. module.exports = function(app, passport) {
  3.  
  4. // =====================================
  5. // HOME PAGE (with login links) ========
  6. // =====================================
  7. app.get('/', function(req, res) {
  8. res.render('index.ejs', {
  9. user : req.user
  10. });
  11. console.log(req.user);
  12. });
  13.  
  14. // =====================================
  15. // LOGIN ===============================
  16. // =====================================
  17. // show the login form
  18. app.get('/login', function(req, res) {
  19.  
  20. // render the page and pass in any flash data if it exists
  21. res.render('login.ejs', { message: req.flash('loginMessage'), user : req.user });
  22. });
  23.  
  24. // process the login form
  25. // app.post('/login', do all our passport stuff here);
  26.  
  27. // =====================================
  28. // SIGNUP ==============================
  29. // =====================================
  30. // show the signup form
  31. app.get('/signup', function(req, res) {
  32.  
  33. // render the page and pass in any flash data if it exists
  34. res.render('signup.ejs', { message: req.flash('signupMessage'), user : req.user });
  35. });
  36.  
  37. // process the signup form
  38. app.post('/signup', passport.authenticate('local-signup', {
  39. successRedirect : '/profile', // redirect to the secure profile section
  40. failureRedirect : '/signup', // redirect back to the signup page if there is an error
  41. failureFlash : true // allow flash messages
  42. })
  43. );
  44.  
  45. // process the login form
  46.  
  47.  
  48.  
  49. //v1. Authentication as a user with session and redirect
  50. app.post('/login',
  51. passport.authenticate('local-login', {
  52. successRedirect : '/profile', // redirect to the secure profile section
  53. failureRedirect : '/login', // redirect back to the signup page if there is an error
  54. failureFlash : true // allow flash messages
  55. })
  56. );
  57.  
  58. /*
  59. //v2. Authentication as an api user without session
  60. app.post('/login',
  61. passport.authenticate('local-login',{
  62. session: false
  63. }),
  64. function (req, res) {
  65. res.json(req.user);
  66. });
  67. */
  68.  
  69. // =====================================
  70. // PROFILE SECTION =====================
  71. // =====================================
  72. // we will want this protected so you have to be logged in to visit
  73. // we will use route middleware to verify this (the isLoggedIn function)
  74. app.get('/profile', isLoggedIn, function(req, res) {
  75. res.render('profile.ejs', {
  76. user : req.user, // get the user out of session and pass to template
  77. message: req.flash('newPassMessage')
  78. });
  79. });
  80.  
  81. app.post('/changePass', isLoggedIn, function (req, res) {
  82.  
  83. if(!req.user.validPassword(req.body.current_pass)){
  84. req.flash('newPassMessage', 'wrong password');
  85. res.redirect('/profile');
  86. return;
  87. }
  88. if(!req.body.new_pass1 || req.body.new_pass1!==req.body.new_pass2){
  89. req.flash('newPassMessage', 'passwords are different');
  90. res.redirect('/profile');
  91. return;
  92. }
  93. req.user.local.password = req.user.generateHash(req.body.new_pass1);
  94. req.user.save().then(() => {
  95. console.log('changed');
  96. req.flash('newPassMessage', 'password has been changed');
  97. res.redirect('/profile');
  98. });
  99.  
  100. });
  101.  
  102.  
  103. // =====================================
  104. // LOGOUT ==============================
  105. // =====================================
  106. app.get('/logout', function(req, res) {
  107. req.logout();
  108. res.redirect('/');
  109. });
  110. };
  111.  
  112. // route middleware to make sure a user is logged in
  113. function isLoggedIn(req, res, next) {
  114.  
  115. // if user is authenticated in the session, carry on
  116. if (req.isAuthenticated())
  117. return next();
  118.  
  119. // if they aren't redirect them to the home page
  120. res.redirect('/');
  121. }
  122.  
  123. //passport.js
  124.  
  125. // load all the things we need
  126. var LocalStrategy = require('passport-local').Strategy;
  127.  
  128. // load up the user model
  129. var User = require('../app/models/user');
  130.  
  131. // expose this function to our app using module.exports
  132. module.exports = function(passport) {
  133.  
  134. // =========================================================================
  135. // passport session setup ==================================================
  136. // =========================================================================
  137. // required for persistent login sessions
  138. // passport needs ability to serialize and unserialize users out of session
  139.  
  140. // used to serialize the user for the session
  141. passport.serializeUser(function(user, done) {
  142. done(null, user.id);
  143. });
  144.  
  145. // used to deserialize the user
  146. passport.deserializeUser(function(id, done) {
  147. User.findById(id, function(err, user) {
  148. done(err, user);
  149. });
  150. });
  151.  
  152. // =========================================================================
  153. // LOCAL SIGNUP ============================================================
  154. // =========================================================================
  155. // we are using named strategies since we have one for login and one for signup
  156. // by default, if there was no name, it would just be called 'local'
  157.  
  158. passport.use('local-signup', new LocalStrategy({
  159. // by default, local strategy uses username and password, we will override with email
  160. usernameField : 'email',
  161. passwordField : 'password',
  162. passReqToCallback : true // allows us to pass back the entire request to the callback
  163. },
  164. function(req, email, password, done) {
  165.  
  166. // asynchronous
  167. // User.findOne wont fire unless data is sent back
  168. process.nextTick(function() {
  169.  
  170. // find a user whose email is the same as the forms email
  171. // we are checking to see if the user trying to login already exists
  172. User.findOne({ 'local.email' : email }, function(err, user) {
  173. // if there are any errors, return the error
  174. if (err)
  175. return done(err);
  176.  
  177. // check to see if theres already a user with that email
  178. if (user) {
  179. return done(null, false, req.flash('signupMessage', 'That email is already taken.'));
  180. } else {
  181.  
  182. // if there is no user with that email
  183. // create the user
  184. var newUser = new User();
  185.  
  186. // set the user's local credentials
  187. newUser.local.email = email;
  188. newUser.local.password = newUser.generateHash(password);
  189.  
  190. // save the user
  191. newUser.save(function(err) {
  192. if (err)
  193. throw err;
  194. return done(null, newUser);
  195. });
  196. }
  197.  
  198. });
  199.  
  200. });
  201.  
  202. }));
  203.  
  204. passport.use('local-login', new LocalStrategy({
  205. // by default, local strategy uses username and password, we will override with email
  206. usernameField : 'email',
  207. passwordField : 'password',
  208. passReqToCallback : true // allows us to pass back the entire request to the callback
  209. },
  210. function(req, email, password, done) { // callback with email and password from our form
  211.  
  212. // find a user whose email is the same as the forms email
  213. // we are checking to see if the user trying to login already exists
  214. User.findOne({ 'local.email' : email }, function(err, user) {
  215. // if there are any errors, return the error before anything else
  216. if (err)
  217. return done(err);
  218.  
  219. // if no user is found, return the message
  220. if (!user)
  221. return done(null, false, req.flash('loginMessage', 'No user found.')); // req.flash is the way to set flashdata using connect-flash
  222.  
  223. // if the user is found but the password is wrong
  224. if (!user.validPassword(password))
  225. return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.')); // create the loginMessage and save it to session as flashdata
  226.  
  227. // all is well, return successful user
  228. return done(null, user);
  229. });
  230.  
  231. }));
  232.  
  233.  
  234. };
  235.  
  236. //user.js
  237.  
  238. // load the things we need
  239. var mongoose = require('mongoose');
  240. var bcrypt = require('bcrypt-nodejs');
  241.  
  242. // define the schema for our user model
  243. var userSchema = mongoose.Schema({
  244.  
  245. name: String,
  246. local : {
  247. email : String,
  248. password : String,
  249. },
  250. facebook : {
  251. id : String,
  252. token : String,
  253. name : String,
  254. email : String
  255. },
  256. twitter : {
  257. id : String,
  258. token : String,
  259. displayName : String,
  260. username : String
  261. },
  262. google : {
  263. id : String,
  264. token : String,
  265. email : String,
  266. name : String
  267. }
  268.  
  269. }, { collection: 'myUsers' });
  270.  
  271. // methods ======================
  272. // generating a hash
  273. userSchema.methods.generateHash = function(password) {
  274. return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
  275. };
  276.  
  277. // checking if password is valid
  278. userSchema.methods.validPassword = function(password) {
  279. return bcrypt.compareSync(password, this.local.password);
  280. };
  281.  
  282. // create the model for users and expose it to our app
  283. module.exports = mongoose.model('User', userSchema);
Add Comment
Please, Sign In to add comment