Advertisement
Guest User

Untitled

a guest
Jul 13th, 2017
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 11.23 KB | None | 0 0
  1. var express = require('express');
  2. var path = require('path');
  3. var favicon = require('serve-favicon');
  4. var logger = require('morgan');
  5. var cookieParser = require('cookie-parser');
  6. var bodyParser = require('body-parser');
  7. var session = require('express-session');
  8.  
  9. var mongoose = require('mongoose');
  10. var passport = require('passport');
  11. var flash = require('connect-flash');
  12.  
  13. var configDB = require('./config/database.js');
  14.  
  15. var index = require('./routes/index');
  16. var rotaslogin = require('./routes/rotaslogin-cadastro');
  17. var users = require('./routes/users');
  18.  
  19.  
  20. var app = express();
  21.  
  22. // configuration ===============================================================
  23. mongoose.connect(configDB.url); // connect to our database
  24.  
  25. // view engine setup
  26. app.set('views', path.join(__dirname, 'views'));
  27. app.set('view engine', 'ejs');
  28.  
  29. // uncomment after placing your favicon in /public
  30. //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
  31. app.use(logger('dev'));
  32. app.use(bodyParser.json());
  33. app.use(bodyParser.urlencoded({ extended: false }));
  34. app.use(cookieParser());
  35. app.use(express.static(path.join(__dirname, 'public')));
  36.  
  37. app.use(session({
  38. secret: 'secreto',
  39. resave: true,
  40. saveUnitialized: true
  41. })); // session secret
  42.  
  43. app.use(passport.initialize());
  44. app.use(passport.session()); // persistent login sessions
  45. app.use(flash()); // use connect-flash for flash messages stored in session
  46.  
  47.  
  48. app.use('/', index);
  49. app.use('/users', users);
  50. app.use('/', rotaslogin);
  51.  
  52. require('./routes/rotaslogin-cadastro')(app, passport);
  53. require('./config/passport')(passport); // pass passport for configuration
  54.  
  55. // catch 404 and forward to error handler
  56. app.use(function(req, res, next) {
  57. var err = new Error('Not Found');
  58. err.status = 404;
  59. next(err);
  60. });
  61.  
  62. // error handler
  63. app.use(function(err, req, res, next) {
  64. // set locals, only providing error in development
  65. res.locals.message = err.message;
  66. res.locals.error = req.app.get('env') === 'development' ? err : {};
  67.  
  68. // render the error page
  69. res.status(err.status || 500);
  70. res.render('error');
  71. });
  72.  
  73. module.exports = app;
  74.  
  75. // config/passport.js
  76.  
  77. // load all the things we need
  78. var LocalStrategy = require('passport-local').Strategy;
  79.  
  80. // load up the user model
  81. var User = require('../models/user');
  82.  
  83. // expose this function to our app using module.exports
  84. module.exports = function(passport) {
  85.  
  86. // =========================================================================
  87. // passport session setup ==================================================
  88. // =========================================================================
  89. // required for persistent login sessions
  90. // passport needs ability to serialize and unserialize users out of session
  91.  
  92. // used to serialize the user for the session
  93. passport.serializeUser(function(user, done) {
  94. done(null, user.id);
  95. });
  96.  
  97. // used to deserialize the user
  98. passport.deserializeUser(function(id, done) {
  99. User.findById(id, function(err, user) {
  100. done(err, user);
  101. });
  102. });
  103.  
  104. // =========================================================================
  105. // LOCAL SIGNUP ============================================================
  106. // =========================================================================
  107. // we are using named strategies since we have one for login and one for signup
  108. // by default, if there was no name, it would just be called 'local'
  109.  
  110. passport.use('local-signup', new LocalStrategy({
  111. // by default, local strategy uses username and password, we will override with email
  112. usernameField: 'email',
  113. passwordField: 'senha',
  114. telefoneField: 'telefone',
  115. nomeField: 'nome',
  116. passReqToCallback: true // allows us to pass back the entire request to the callback
  117. },
  118. function(req, email, senha, telefone, nome, done) {
  119.  
  120. // asynchronous
  121. // User.findOne wont fire unless data is sent back
  122. process.nextTick(function() {
  123.  
  124. // find a user whose email is the same as the forms email
  125. // we are checking to see if the user trying to login already exists
  126. User.findOne({ 'local.email': email }, function(err, user) {
  127. // if there are any errors, return the error
  128. if (err)
  129. return done(err);
  130.  
  131. // check to see if theres already a user with that email
  132. if (user) {
  133. return done(null, false, req.flash('signupMessage', 'Esse email já existe.'));
  134. } else {
  135.  
  136. // if there is no user with that email
  137. // create the user
  138. var newUser = new User();
  139.  
  140. // set the user's local credentials
  141. newUser.local.email = email;
  142. newUser.local.senha = newUser.generateHash(senha);
  143. newUser.local.telefone = telefone;
  144. newUser.local.nome = nome;
  145.  
  146. // save the user
  147. newUser.save(function(err) {
  148. if (err)
  149. throw err;
  150. return done(null, newUser);
  151. });
  152. }
  153.  
  154. });
  155.  
  156. });
  157.  
  158. }));
  159.  
  160. // =========================================================================
  161. // LOCAL LOGIN =============================================================
  162. // =========================================================================
  163. // we are using named strategies since we have one for login and one for signup
  164. // by default, if there was no name, it would just be called 'local'
  165.  
  166. passport.use('local-login', new LocalStrategy({
  167. // by default, local strategy uses username and password, we will override with email
  168. usernameField: 'email',
  169. passwordField: 'senha',
  170. passReqToCallback: true // allows us to pass back the entire request to the callback
  171. },
  172. function(req, email, senha, telefone, nome, done) { // callback with email and password from our form
  173.  
  174. // find a user whose email is the same as the forms email
  175. // we are checking to see if the user trying to login already exists
  176. User.findOne({ 'local.email': email }, function(err, user) {
  177. // if there are any errors, return the error before anything else
  178. if (err)
  179. return done(err);
  180.  
  181. // if no user is found, return the message
  182. if (!user)
  183. return done(null, false, req.flash('loginMessage', 'Não existe um usuario com esse email.')); // req.flash is the way to set flashdata using connect-flash
  184.  
  185. // if the user is found but the password is wrong
  186. if (!user.validPassword(password))
  187. return done(null, false, req.flash('loginMessage', 'Oops! senha errada.')); // create the loginMessage and save it to session as flashdata
  188.  
  189. // all is well, return successful user
  190. return done(null, user);
  191. });
  192.  
  193. }));
  194.  
  195. };
  196.  
  197. module.exports = function(app, passport) {
  198.  
  199. // LOGIN ===============================
  200. // show the login form
  201. app.get('/login', function(req, res, next) {
  202. passport.authenticate('local-login', function(err, user, info) {
  203. if (err) { return next(err); }
  204. //if there is no user in the response send the info back to modal
  205. if (!user) {
  206. return res.send(info);
  207. }
  208. //user was able to login, send true and redirect
  209. req.logIn(user, function(err) {
  210. if (err) { return next(err); }
  211. return res.send({ valid: true });
  212. });
  213. })(req, res, next);
  214. });
  215.  
  216. // process the login form
  217. app.post('/login', passport.authenticate('local-login', {
  218. successRedirect: '/', // redirect to the secure profile section
  219. failureRedirect: '/login', // redirect back to the signup page if there is an error
  220. failureFlash: true // allow flash messages
  221. }));
  222.  
  223. // SIGNUP ==============================
  224. // show the signup form
  225. app.get('/signup', function(req, res, next) {
  226. passport.authenticate('local-login', function(err, user, info) {
  227. if (err) { return next(err); }
  228. //if there is no user in the response send the info back to modal
  229. if (!user) {
  230. return res.send(info);
  231. }
  232. //user was able to login, send true and redirect
  233. req.logIn(user, function(err) {
  234. if (err) { return next(err); }
  235. return res.send({ valid: true });
  236. });
  237. })(req, res, next);
  238. });
  239.  
  240. // process the signup form
  241. app.post('/signup', passport.authenticate('local-signup', {
  242. successRedirect: '/', // redirect to the secure profile section
  243. failureRedirect: '/signup', // redirect back to the signup page if there is an error
  244. failureFlash: true // allow flash messages
  245. }));
  246.  
  247. // PROFILE SECTION =====================
  248. // we will want this protected so you have to be logged in to visit
  249. // we will use route middleware to verify this (the isLoggedIn function)
  250.  
  251. /*app.get('/profile', isLoggedIn, function(req, res) {
  252. res.render('profile.ejs', {
  253. user: req.user // get the user out of session and pass to template
  254. });
  255. });*/
  256.  
  257. // LOGOUT ==============================
  258. app.get('/logout', function(req, res) {
  259. req.logout();
  260. res.redirect('/');
  261. });
  262. };
  263.  
  264. // route middleware to make sure a user is logged in
  265. function isLoggedIn(req, res, next) {
  266.  
  267. // if user is authenticated in the session, carry on
  268. if (req.isAuthenticated())
  269. return next();
  270.  
  271. // if they aren't redirect them to the home page
  272. res.redirect('/');
  273. }
  274.  
  275. // app/models/user.js
  276. // load the things we need
  277. var mongoose = require('mongoose');
  278. var bcrypt = require('bcrypt-nodejs');
  279.  
  280. // define the schema for our user model
  281. var userSchema = mongoose.Schema({
  282.  
  283. local: {
  284. nome: String,
  285. telefone: String,
  286. email: String,
  287. senha: String,
  288. },
  289. facebook: {
  290. id: String,
  291. token: String,
  292. email: String,
  293. name: String
  294. },
  295. twitter: {
  296. id: String,
  297. token: String,
  298. displayName: String,
  299. username: String
  300. },
  301. google: {
  302. id: String,
  303. token: String,
  304. email: String,
  305. name: String
  306. }
  307.  
  308. });
  309.  
  310. // methods ======================
  311. // generating a hash
  312. userSchema.methods.generateHash = function(password) {
  313. return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
  314. };
  315.  
  316. // checking if password is valid
  317. userSchema.methods.validPassword = function(password) {
  318. return bcrypt.compareSync(password, this.local.password);
  319. };
  320.  
  321. // create the model for users and expose it to our app
  322. module.exports = mongoose.model('User', userSchema);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement