maaveran

nodejs

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