Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var express = require('express');
- var path = require('path');
- var favicon = require('serve-favicon');
- var logger = require('morgan');
- var cookieParser = require('cookie-parser');
- var bodyParser = require('body-parser');
- var session = require('express-session');
- var mongoose = require('mongoose');
- var passport = require('passport');
- var flash = require('connect-flash');
- var configDB = require('./config/database.js');
- var index = require('./routes/index');
- var rotaslogin = require('./routes/rotaslogin-cadastro');
- var users = require('./routes/users');
- var app = express();
- // configuration ===============================================================
- mongoose.connect(configDB.url); // connect to our database
- // view engine setup
- app.set('views', path.join(__dirname, 'views'));
- app.set('view engine', 'ejs');
- // uncomment after placing your favicon in /public
- //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
- app.use(logger('dev'));
- app.use(bodyParser.json());
- app.use(bodyParser.urlencoded({ extended: false }));
- app.use(cookieParser());
- app.use(express.static(path.join(__dirname, 'public')));
- app.use(session({
- secret: 'secreto',
- resave: true,
- saveUnitialized: true
- })); // session secret
- app.use(passport.initialize());
- app.use(passport.session()); // persistent login sessions
- app.use(flash()); // use connect-flash for flash messages stored in session
- app.use('/', index);
- app.use('/users', users);
- app.use('/', rotaslogin);
- require('./routes/rotaslogin-cadastro')(app, passport);
- require('./config/passport')(passport); // pass passport for configuration
- // catch 404 and forward to error handler
- app.use(function(req, res, next) {
- var err = new Error('Not Found');
- err.status = 404;
- next(err);
- });
- // error handler
- app.use(function(err, req, res, next) {
- // set locals, only providing error in development
- res.locals.message = err.message;
- res.locals.error = req.app.get('env') === 'development' ? err : {};
- // render the error page
- res.status(err.status || 500);
- res.render('error');
- });
- module.exports = app;
- // config/passport.js
- // load all the things we need
- var LocalStrategy = require('passport-local').Strategy;
- // load up the user model
- var User = require('../models/user');
- // expose this function to our app using module.exports
- module.exports = function(passport) {
- // =========================================================================
- // passport session setup ==================================================
- // =========================================================================
- // required for persistent login sessions
- // passport needs ability to serialize and unserialize users out of session
- // used to serialize the user for the session
- passport.serializeUser(function(user, done) {
- done(null, user.id);
- });
- // used to deserialize the user
- passport.deserializeUser(function(id, done) {
- User.findById(id, function(err, user) {
- done(err, user);
- });
- });
- // =========================================================================
- // LOCAL SIGNUP ============================================================
- // =========================================================================
- // we are using named strategies since we have one for login and one for signup
- // by default, if there was no name, it would just be called 'local'
- passport.use('local-signup', new LocalStrategy({
- // by default, local strategy uses username and password, we will override with email
- usernameField: 'email',
- passwordField: 'senha',
- telefoneField: 'telefone',
- nomeField: 'nome',
- passReqToCallback: true // allows us to pass back the entire request to the callback
- },
- function(req, email, senha, telefone, nome, done) {
- // asynchronous
- // User.findOne wont fire unless data is sent back
- process.nextTick(function() {
- // find a user whose email is the same as the forms email
- // we are checking to see if the user trying to login already exists
- User.findOne({ 'local.email': email }, function(err, user) {
- // if there are any errors, return the error
- if (err)
- return done(err);
- // check to see if theres already a user with that email
- if (user) {
- return done(null, false, req.flash('signupMessage', 'Esse email já existe.'));
- } else {
- // if there is no user with that email
- // create the user
- var newUser = new User();
- // set the user's local credentials
- newUser.local.email = email;
- newUser.local.senha = newUser.generateHash(senha);
- newUser.local.telefone = telefone;
- newUser.local.nome = nome;
- // save the user
- newUser.save(function(err) {
- if (err)
- throw err;
- return done(null, newUser);
- });
- }
- });
- });
- }));
- // =========================================================================
- // LOCAL LOGIN =============================================================
- // =========================================================================
- // we are using named strategies since we have one for login and one for signup
- // by default, if there was no name, it would just be called 'local'
- passport.use('local-login', new LocalStrategy({
- // by default, local strategy uses username and password, we will override with email
- usernameField: 'email',
- passwordField: 'senha',
- passReqToCallback: true // allows us to pass back the entire request to the callback
- },
- function(req, email, senha, telefone, nome, done) { // callback with email and password from our form
- // find a user whose email is the same as the forms email
- // we are checking to see if the user trying to login already exists
- User.findOne({ 'local.email': email }, function(err, user) {
- // if there are any errors, return the error before anything else
- if (err)
- return done(err);
- // if no user is found, return the message
- if (!user)
- 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
- // if the user is found but the password is wrong
- if (!user.validPassword(password))
- return done(null, false, req.flash('loginMessage', 'Oops! senha errada.')); // create the loginMessage and save it to session as flashdata
- // all is well, return successful user
- return done(null, user);
- });
- }));
- };
- module.exports = function(app, passport) {
- // LOGIN ===============================
- // show the login form
- app.get('/login', function(req, res, next) {
- passport.authenticate('local-login', function(err, user, info) {
- if (err) { return next(err); }
- //if there is no user in the response send the info back to modal
- if (!user) {
- return res.send(info);
- }
- //user was able to login, send true and redirect
- req.logIn(user, function(err) {
- if (err) { return next(err); }
- return res.send({ valid: true });
- });
- })(req, res, next);
- });
- // process the login form
- app.post('/login', passport.authenticate('local-login', {
- successRedirect: '/', // redirect to the secure profile section
- failureRedirect: '/login', // redirect back to the signup page if there is an error
- failureFlash: true // allow flash messages
- }));
- // SIGNUP ==============================
- // show the signup form
- app.get('/signup', function(req, res, next) {
- passport.authenticate('local-login', function(err, user, info) {
- if (err) { return next(err); }
- //if there is no user in the response send the info back to modal
- if (!user) {
- return res.send(info);
- }
- //user was able to login, send true and redirect
- req.logIn(user, function(err) {
- if (err) { return next(err); }
- return res.send({ valid: true });
- });
- })(req, res, next);
- });
- // process the signup form
- app.post('/signup', passport.authenticate('local-signup', {
- successRedirect: '/', // redirect to the secure profile section
- failureRedirect: '/signup', // redirect back to the signup page if there is an error
- failureFlash: true // allow flash messages
- }));
- // PROFILE SECTION =====================
- // we will want this protected so you have to be logged in to visit
- // we will use route middleware to verify this (the isLoggedIn function)
- /*app.get('/profile', isLoggedIn, function(req, res) {
- res.render('profile.ejs', {
- user: req.user // get the user out of session and pass to template
- });
- });*/
- // LOGOUT ==============================
- app.get('/logout', function(req, res) {
- req.logout();
- res.redirect('/');
- });
- };
- // route middleware to make sure a user is logged in
- function isLoggedIn(req, res, next) {
- // if user is authenticated in the session, carry on
- if (req.isAuthenticated())
- return next();
- // if they aren't redirect them to the home page
- res.redirect('/');
- }
- // app/models/user.js
- // load the things we need
- var mongoose = require('mongoose');
- var bcrypt = require('bcrypt-nodejs');
- // define the schema for our user model
- var userSchema = mongoose.Schema({
- local: {
- nome: String,
- telefone: String,
- email: String,
- senha: String,
- },
- facebook: {
- id: String,
- token: String,
- email: String,
- name: String
- },
- twitter: {
- id: String,
- token: String,
- displayName: String,
- username: String
- },
- google: {
- id: String,
- token: String,
- email: String,
- name: String
- }
- });
- // methods ======================
- // generating a hash
- userSchema.methods.generateHash = function(password) {
- return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
- };
- // checking if password is valid
- userSchema.methods.validPassword = function(password) {
- return bcrypt.compareSync(password, this.local.password);
- };
- // create the model for users and expose it to our app
- module.exports = mongoose.model('User', userSchema);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement