So I'm looking to implement passport, however, I'm getting a 500 error
localhost is currently unable to handle this request. HTTP ERROR 500
mongoose and the mongodb server is running, I have taken a look at the terminal and nothing of note error wise is showing.
Here is some code:
register.pug
extends ./shared/layout block content section(class='flex items-center flex-wrap' id='hero') section(class='w-full py-6 px-6 text-center') h1(class='text-4xl uppercase md:text-4xl text-grey-darkest mb-4') Register form(class='w-full max-w-md m-auto p-8' action='/register' method='POST') section(class='flex flex-wrap -mx-3 mb-3') section(class='w-full md:w-1/2 px-3') label(class='block uppercase tracking-wide text-grey-darker text-xs font-bold mb-2' for='first_name') First Name input(class='appearance-none resize-none block w-full bg-grey-lighter text-grey-darker border border-grey-lighter rounded py-3 px-4 mb-3' type='text' name='first_name' placeholder='Jane') section(class='w-full md:w-1/2 px-3') label(class='block uppercase tracking-wide text-grey-darker text-xs font-bold mb-2' for='last_name') Last Name input(class='appearance-none resize-none block w-full bg-grey-lighter text-grey-darker border border-grey-lighter rounded py-3 px-4 mb-3' type='text' name='last_name' placeholder='Doe') section(class='flex flex-wrap -mx-3 mb-3') section(class='w-full px-3') label(class='block uppercase tracking-wide text-grey-darker text-xs font-bold mb-2' for='email') Email Address input(class='appearance-none resize-none block w-full bg-grey-lighter text-grey-darker border border-grey-lighter rounded py-3 px-4 mb-3' type='text' name='email' placeholder='jane.doe@example.com') section(class='flex flex-wrap -mx-3 mb-3') section(class='w-full px-3') label(class='block uppercase tracking-wide text-grey-darker text-xs font-bold mb-2' for='message') Password input(class='appearance-none resize-none block w-full bg-grey-lighter text-grey-darker border border-grey-lighter rounded py-3 px-4 mb-3' type='password' name='password' placeholder='password') button(href='#' class='inline-block px-4 py-3 border bg-teal-light rounded text-white border-none w-full hover:border-teal hover:bg-teal hover:text-white no-underline mr-2 lg:mt-0' type='submit') Register
user.js
const express = require('express'); const mongoose = require('mongoose'); const bcrypt = require('bcryptjs'); var app = express(); var UserSchema = mongoose.Schema({ first_name: String, last_name: String, email: { type: String, required: true, unique: true }, password: String, admin: { type: Boolean, default: false }, // reset password resetPasswordToken: String, resetPasswordExpires: Date }); var User = module.exports = mongoose.model('User', UserSchema); module.exports.createUser = function(newUser, callback){ bcrypt.genSalt(10, function(err, salt) { bcrypt.hash(newUser.password, salt, function(err, hash) { newUser.password = hash; newUser.save(callback); }); }); } module.exports.getUserByEmail = function(email, callback){ var query = {email: email}; User.findOne(query, callback); } module.exports.getUserById = function(id, callback){ User.findById(id, callback); } module.exports.comparePassword = function(candidatePassword, hash, callback) { bcrypt.compare(candidatePassword, hash, function(err, isMatch) { if(err) throw err; callback(null, isMatch); }); }
routes.js
var express = require('express'); var router = express.Router(); var samplePages_controller = require('../controllers/samplePages_controller'); var contacts_controller = require('../controllers/contacts_controller'); var dashboards_controller = require('../controllers/dashboards_controller'); var users_controller = require('../controllers/users_controller'); var User = require('../models/user'); /* samplePages ROUTES */ router.get('/', samplePages_controller.index); router.get('/about', samplePages_controller.about); /* users ROUTES */ router.get('/login', users_controller.login); router.get('/register', users_controller.register); router.post('/register', users_controller.post_register); /* dashboards ROUTES */ router.get('/dashboard', dashboards_controller.index); /* contact ROUTES. */ router.get('/contact', contacts_controller.show); router.post('/contact/send', contacts_controller.send_contact); module.exports = router;
users_controller.js
var nodemailer = require('nodemailer'); var passport = require('passport'); var LocalStrategy = require('passport-local').Strategy; var User = require('../models/user'); exports.register = function(req, res, next) { res.render('register', { title: 'Rafflefly | Register' }); } exports.post_register = function(req, res, next) { var first_name = req.body.first_name; var last_name = req.body.last_name; var email = req.body.email; var password = req.body.password; // validations req.checkBody('first name', 'The first name is required').notEmpty(); req.checkBody('last name', 'The last name is required').notEmpty(); req.checkBody('email', 'An account email is required').notEmpty(); req.checkBody('email', 'This account email is not valid').isEmail(); req.checkBody('password', 'An account password is required').notEmpty(); if (error) { req.flash('error', 'The form could not send successfully'); } else { var newUser = new User({ first_name: first_name, last_name: last_name, email: email, password: password, }); nodemailer.createTestAccount((err, account) => { // create reusable transporter object using the default SMTP transport if (process.env.NODE_ENV === 'production') { transporter = nodemailer.createTransport({ host: "smtp.sendgrid.net", port: 587, auth: { user: process.env.SENDGRID_USERNAME, pass: process.env.SENDGRID_PASSWORD, } }); } else { transporter = nodemailer.createTransport({ host: "smtp.ethereal.email", port: 587, auth: { user: '********************', pass: '********************', } }); } // setup email data with unicode symbols let mailOptions = { from: process.env.GLOBAL_EMAIL || 'ben@benbagley.co.uk', // sender address to: `${email}`, // list of receivers subject: 'Welcome to Rafflefly', // Subject line html: `Welcome to Rafflefly` // html body }; // send mail with defined transport object transporter.sendMail(mailOptions, (error, info) => { if (error) { return console.log(error); } req.flash('success', 'You are now registered, you can now login!'); res.redirect('/'); }); }); User.createUser(newUser, function(err, user) { if(err) throw err; console.log(user); }); } }; passport.use(new LocalStrategy({ usernameField: 'email' }, function(email, password, done) { User.getUserByEmail(email, function(err, user){ if(err) throw err; if(!user){ return done(null, false, {message: 'Unknown Email Address'}); } User.comparePassword(password, user.password, function(err, isMatch){ if(err) throw err; if(isMatch){ return done(null, user); } else { return done(null, false, {message: 'Invalid password'}); } }); }); })); passport.serializeUser(function(user, done) { done(null, user.id); }); passport.deserializeUser(function(id, done) { User.getUserById(id, function(err, user) { done(err, user); }); }); exports.login = function(req, res, next) { res.render('login', { title: 'Rafflefly | Login' }); } exports.post_login = function(req, res, next) { res.post('/login', passport.authenticate('local', { successRedirect: '/dashboard', failureRedirect: '/login', failureFlash: true }) ); }
I'm at a loss here, I have gone over the documentation and can't see anything I've missed (although I properly have).
Any help here is appricated.
1 Answers
Answers 1
First, try to edit User model as following:
const express = require('express'); const mongoose = require('mongoose'); const bcrypt = require('bcryptjs'); var UserSchema = mongoose.Schema({ first_name: String, last_name: String, email: { type: String, required: true, unique: true }, password: String, admin: { type: Boolean, default: false }, resetPasswordToken: String, resetPasswordExpires: Date }); UserSchema.methods.getUserByEmail = function(email, callback) { var userObj = this; userObj.findOne({email: email}, callback); } UserSchema.methods.getUserById = function(id, callback) { var userObj = this; userObj.findById(id, callback); } UserSchema.methods.comparePassword = function (candidatePassword, cb) { bcrypt.compare(candidatePassword, this.password, function (err, isMatch) { if (err) return cb(err); cb(null, isMatch); }); }; module.exports = mongoose.model('User', UserSchema);
Second part is passport setup
var _ = require('lodash'); var async = require('async'); var crypto = require('crypto'); var nodemailer = require('nodemailer'); var passport = require('passport'); var User = require('../models/User'); var secrets = require('../config/secrets'); /** * GET /login * Login page. */ exports.getLogin = function (req, res) { if (req.user) return res.redirect('/authenticated/view/...'); res.render('login', { title: 'Login' }); }; /** * POST /login * Sign in using email and password. */ exports.postLogin = function (req, res, next) { req.assert('email', 'Email is not valid').isEmail(); req.assert('password', 'Password cannot be blank').notEmpty(); var errors = req.validationErrors(); if (errors) { req.flash('errors', errors); //!TODO return res.redirect('/login'); } passport.authenticate('local', function (err, user, info) { if (err) return next(err); if (!user) { req.flash('errors', { msg: info.message }); return res.redirect('/login'); } req.logIn(user, function (err) { if (err) return next(err); res.redirect('/authenticated/view/...'); }); })(req, res, next); }; exports.index = function (req, res, next) { return res.redirect('/'); } /** * GET /logout * Log out. */ exports.logout = function (req, res) { req.logout(); res.redirect('/'); }; /** * GET /signup * Signup page. */ exports.getSignup = function (req, res) { if (req.user) return res.redirect('/authenticated/view/...'); res.render('signup', { title: 'Create account' }); }; /** * POST /signup * Create a new local account. */ exports.postSignup = function (req, res, next) { var user = new User({ email: req.body.email, password: req.body.password }); User.findOne({ email: req.body.email }, function (err, existingUser) { if (existingUser) { req.flash('errors', { msg: 'Account with that email address already exists.' }); return res.redirect('/login'); } req.assert('confirmPassword', 'Passwords are diffrent!').equals(req.body.password); user.save(function (err) { if (err) return next(err); req.logIn(user, function (err) { if (err) return next(err); res.redirect('/authenticated/view/...'); }); }); }); }; /** * GET /account * Profile page. */ exports.getAccount = function (req, res) { res.render('account/profile', { title: 'Manage your profile' }); }; /** * POST /account/profile * Update profile information. */ exports.postUpdateProfile = function (req, res, next) { User.findById(req.user.id, function (err, user) { if (err) return next(err); user.email = req.body.email || ''; user.profile.name = req.body.name || ''; user.profile.gender = req.body.gender || ''; user.profile.location = req.body.location || ''; user.profile.website = req.body.website || ''; user.save(function (err) { if (err) return next(err); req.flash('success', { msg: 'Changes saved' }); res.redirect('/account'); }); }); }; /** * POST /account/password * Update current password. */ exports.postUpdatePassword = function (req, res, next) { req.assert('password', 'Password has to be at least 4 length').len(4); req.assert('confirmPassword', 'Passwords are diffrent!').equals(req.body.password); var errors = req.validationErrors(); if (errors) { req.flash('errors', errors); return res.redirect('/account'); } User.findById(req.user.id, function (err, user) { if (err) return next(err); user.password = req.body.password; user.save(function (err) { if (err) return next(err); req.flash('success', { msg: 'Password changed propertly' }); res.redirect('/account'); }); }); }; /** * POST /account/delete * Delete user account. */ exports.postDeleteAccount = function (req, res, next) { User.remove({ _id: req.user.id }, function (err) { if (err) return next(err); req.logout(); req.flash('info', { msg: 'Account deleted' }); res.redirect('/'); }); };
0 comments:
Post a Comment