Giter Site home page Giter Site logo

node_passport_login's Introduction

Node.js & Passport Login

This is a user login and registration app using Node.js, Express, Passport, Mongoose, EJS and some other packages.

Version: 2.0.0

Usage

$ npm install
$ npm start
# Or run with Nodemon
$ npm run dev

# Visit http://localhost:5000

MongoDB

Open "config/keys.js" and add your MongoDB URI, local or Atlas

node_passport_login's People

Contributors

0mega28 avatar amide-init avatar bradtraversy avatar dependabot[bot] avatar dicentes avatar hudsonpereira avatar ldgmaia avatar mehdifracso avatar narayansiddhu avatar nases avatar ofirlana avatar sanjeev0007 avatar skidi3 avatar stephangriesel avatar tareqtms avatar theodorklauritzen avatar vijoytechy avatar virtualabi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

node_passport_login's Issues

Views not rendering

res.render() not Working with .ejs middleware.....
change it with pug

npm install pug --save

// Middlewares
app.set('view engine' , 'pug');
app.set('views', path.join(__dirname, 'views'));

// tescode
app.get(''/testcode', (req, res) => res.render(''welcome'))

Note: change all views file to .pug extention

ERR_EMPTY_RESPONSE

I've followed the YouTube tutorial on this closely and I believe my code matches verbatim, but I can't get the registration form to submit. I get ERR_EMPTY_RESPONSE after a long wait. Can you help me troubleshoot? I'm a newbie if that's not obvious.

My code can be found here:
https://github.com/jehartman/passportPractice

Thanks!

issue in validation

hey, please correct me if i am wrong,
if you don't enter password2 then it is showing password doesnt match instead of passsword2 field empty.
and,
if you don't enter email then it is showing email is not valid along with email is empty.

First time authentication gets hung, thereafter it works fine.

Hello,

Everytime , I am closing my browser, starting it, and then trying to log in, the page just gets stuck on the log in page showing processing request. But without doing anything if I click on the login or go to the URL localhost:5000/dashboard it shows authenticated and goes to the dashboard. Now after logging out , as many times I login with a new user , it happens in one shot.

Why is the logging in problem only happening for the first time after reopening the browser. I see that cookies are also not there once I reopen the browser.

Not being able to solve this issue. Can you please help?

Logout Does not Work

I followed the video tutorial and noticed that if you logout and then press the back button, the user is still recognized, when it should be redirected to the Login page. I thought I'd typed in something wrong, so downloaded the project from here, but still get the same problem. Is this an issues with the Passport Local authentication. Seems pretty pointless if something so simple doesn't work. This seems to be an issue others have, but I can't seem to find a definitive solution that works. Any ideas?

Colin

Why is Mongo throwing this error?

(node:10576) UnhandledPromiseRejectionWarning: MongoNetworkError: failed to conn ect to server [localhost:27017] on first connect [MongoNetworkError: connect ECO NNREFUSED 127.0.0.1:27017] at Pool.<anonymous> (C:\Users\xxxxxx\Documents\GitHub\website_test \loginapp\node_modules\mongoose\node_modules\mongodb-core\lib\topologies\server. js:505:11) at emitOne (events.js:116:13) at Pool.emit (events.js:211:7) at Connection.<anonymous> (C:\Users\xxxxxxx\Documents\GitHub\website_test\loginapp\node_modules\mongoose\node_modules\mongodb-core\lib\connection\pool.js:329:1 2) at Object.onceWrapper (events.js:317:30) at emitTwo (events.js:126:13) at Connection.emit (events.js:214:7) at Socket.<anonymous> (C:\Users\xxxxxxxx\Documents\GitHub\website_test\loginapp\node_modules\mongoose\node_modules\mongodb-core\lib\connection\connection.js:245 :50) at Object.onceWrapper (events.js:315:30) at emitOne (events.js:116:13) at Socket.emit (events.js:211:7) at emitErrorNT (internal/streams/destroy.js:64:8) at _combinedTickCallback (internal/process/next_tick.js:138:11) at process._tickCallback (internal/process/next_tick.js:180:9) (node:10576) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or b y rejecting a promise which was not handled with .catch(). (rejection id: 1) (node:10576) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js pr ocess with a non-zero exit code.
What is the solution to this. I tried a couple of things but I can't figure it out.
Thanks

TypeError: require(...) is not a function

Hello Brad,

I'm almost at the very end of your perfect course (I really like it), but I cannot get over one error that my terminal throws at me:

require('./config/passport')(passport);
^
TypeError: require(...) is not a function

I crawled through your entire repo but I cannot get it working.
Note: That arrow is between .../passport') and (passport)

Can you help me, please?

req.flash doesn't work

I follow your instructions but I failed on req.flash, is that flash method return array?

Case sensitive error - mongoURI key

It's just a typo, but is throwing an error.
On the file "config/keys.js", the key/value pair is "mongoURI: dbPassword" (lower case "m" on mongoURI).
On the file app.js, line 14, is the key is "MongoURI" (uppercase "M").

ERR_EMPTY_RESPONSE

Hi,

I am trying to run the basic program but i'm not sure what I am doing wrong. I am completey new to Node.js.

I have got this as my app.js:

var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var exphbs = require('express-handlebars');
var expressValidator = require('express-validator');
var flash = require('connect-flash');
var session = require('express-session');
var passport = require('passport');
var localStrategy = require('passport-local').Strategy;

var routes = require('./routes/index');
var users = require('./routes/users');


//Initialise App
var app = express();

//View Engine
app.set('views', path.join(__dirname, 'views'));
app.engine('handlebars', exphbs({defaultLayout:'layout'}));
app.set('view engine','handlebars');

// Body Parser Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());

// set static folder
app.use(express.static(path.join(__dirname, 'public')));

// Express session
app.use(session({
  secret: 'trout',
  saveUninitialized: true,
  resave: true
}));

//passport Initialise
app.use(passport.initialize());
app.use(passport.session());

// Express Validator
app.use(expressValidator({
  errorFormatter: function(param,msg,value){
    var namespace = param.split('.')
    , root = namespace.shift()
    , formParam = root;

    while(namespace.length) {
      formParam += '[' + namespace.shift() + ']';
    }
    return {
      param : formParam,
      msg: msg,
      value: value
    };
  }
}));

// Connect flash
app.use(flash());

//Global Vars
app.use(function (req, res, next){
  res.locals.success_msg = req.flash('success_msg');
  res.locals.error_msg = req.flash('error_msg');
  res.locals.error = req.flash('error');
});

app.use('/', routes);
app.use('/users', users);

//set port
app.set('port', (process.env.PORT || 8080));

app.listen(app.get('port'), function(){
  console.log('Server started on port '+app.get('port'));
});

When I run the server (npm start) it says that the server is started on port 8080, but when I try and load the page I get nothing... Have I missed something really obvious?

As a test I changed the line:
res.locals.success_msg = req.flash('success_msg');
to
res.local.success_msg = req.flash('success_msg');
The server started, but when I tried to load a page it kicked up an errror. So it is trying to do something. I suspect I have messed up a route or something, but I can't see it

I handtyped everything so I could use it as a learning example. The file structure has been created exactly as in the first youtube video (really good by the way).

Any help would be greatly appreciated!

Steve

Adding webpage

This is an excellent Tutorial - thanks a lot. I have one issue, i am unable to add additional webpages to the menu. Can you please provide me the approach. Thank you.

Validation errors not showing up on the top of signup and login form

if I don't satisfy the validation requirement in the signup form, It doesn't redirect to the next page and 3-4 line gap comes right below my signup and login form heading tags. This means my errors are coming on the top of signup and login form but it is not visible may be some color issues or something.

Please help me fix the issue. i want the validation errors should be dispalyed on top on both the forms

This is my main server.js file

const express = require('express');
const app = express();


const mongoose = require('mongoose');
mongoose
  .connect(
    "mongodb+srv://mongoDB313:[email protected]/userdetails?retryWrites=true&w=majority",
    { useNewUrlParser: true, useUnifiedTopology: true }
  )
  .then(() => console.log('MongoDB is Connected successsfully'))
  .catch(err => console.log(err));


const expressLayouts = require('express-ejs-layouts');
app.use(expressLayouts);
app.set('view engine', 'ejs');

const passport = require('passport');
require('./config/passport')(passport);

const flash = require('connect-flash');
const session = require('express-session');

app.use(express.urlencoded({ extended: true }));


app.use(
  session({
    secret: 'secret',
    resave: true,
    saveUninitialized: true
  })
);


app.use(passport.initialize());
app.use(passport.session());


app.use(flash());


app.use(function (req, res, next) {
  res.locals.success_msg = req.flash('success_msg');
  res.locals.error_msg = req.flash('error_msg');
  res.locals.error = req.flash('error');
  next();
});


app.use('/', require('./routes/main.js'));
app.use('/indiviual', require('./routes/indiviual.js'));

const PORT = process.env.PORT || 5000;

app.listen(PORT, console.log(`Server started on port `${PORT}`));`

This is my partial ejs file

<% if(typeof errors != 'undefined'){ %> <% errors.forEach(function(error) { %>
<div class="alert alert-warning alert-dismissible fade show" role="alert">
  <%= error.msg %>
  <button type="button" class="close" data-dismiss="alert" aria-label="Close">
    <span aria-hidden="true">&times;</span>
  </button>
</div>
<% }); %> <% } %> <% if(success_msg != ''){ %>
<div class="alert alert-success alert-dismissible fade show" role="alert">
  <%= success_msg %>
  <button type="button" class="close" data-dismiss="alert" aria-label="Close">
    <span aria-hidden="true">&times;</span>
  </button>
</div>
<% } %> <% if(error_msg != ''){ %>
<div class="alert alert-danger alert-dismissible fade show" role="alert">
  <%= error_msg %>
  <button type="button" class="close" data-dismiss="alert" aria-label="Close">
    <span aria-hidden="true">&times;</span>
  </button>
</div>
<% } %> <% if(error != ''){ %>
<div class="alert alert-danger alert-dismissible fade show" role="alert">
  <%= error %>
  <button type="button" class="close" data-dismiss="alert" aria-label="Close">
    <span aria-hidden="true">&times;</span>
  </button>
</div>
<% } %>

This is my routes files

const express = require('express');
const router = express.Router();
const bcrypt = require('bcryptjs');
const passport = require('passport');
// Load User model
const User = require('../models/User');
const { forwardAuthenticated } = require('../config/auth');

// reqlogin Page
router.get('/reqlogin', forwardAuthenticated, (req, res) => res.render('reqlogin'));

// Register Page
router.get('/register', forwardAuthenticated, (req, res) => res.render('register'));

// Register
router.post('/register', (req, res) => {
  const { country, firstname, lastname, email, password, password2, address, city, state, zip_postal, mobile_number } = req.body;
  let errors = [];

  if (!country || !firstname || !lastname || !email || !password || !password2 || !address || !city || !state || !zip_postal || !mobile_number) {
    errors.push({ msg: 'Please enter all fields' });
  }

  if (password != password2) {
    errors.push({ msg: 'Passwords do not match' });
  }

  if (password.length < 8) {
    errors.push({ msg: 'Password must be at least 8 characters' });
  }

  if (errors.length > 0) {
    res.render('register', {
      errors,
      country,
      firstname,
      lastname,
      email,
      password,
      password2,
      address,
      city,
      state,
      zip_postal,
      mobile_number
    });
  } else {
    User.findOne({ email: email }).then(user => {
      if (user) {
        errors.push({ msg: 'Email already exists' });
        res.render('register', {
          errors,
          country,
          firstname,
          lastname,
          email,
          password,
          password2,
          address,
          city,
          state,
          zip_postal,
          mobile_number
        });
      } else {
        const newUser = new User({
          country,
          firstname,
          lastname,
          email,
          password,
          password2,
          address,
          city,
          state,
          zip_postal,
          mobile_number
        });

        bcrypt.genSalt(10, (err, salt) => {
          bcrypt.hash(newUser.password, salt, (err, hash) => {
            if (err) throw err;
            newUser.password = hash;
            newUser
              .save()
              .then(user => {
                req.flash(
                  'success_msg',
                  'You are now registered and can log in'
                );
                res.redirect('/indiviual/reqlogin');
              })
              .catch(err => console.log(err));
          });
        });
      }
    });
  }
});

// reqlogin
router.post('/reqlogin', (req, res, next) => {
  passport.authenticate('local', {
    successRedirect: '/reqtask',
    failureRedirect: '/indiviual/reqlogin',
    failureFlash: true
  })(req, res, next);
});

// Logout
router.get('/logout', (req, res) => {
  req.logout();
  req.flash('success_msg', 'You are logged out');
  res.redirect('/indiviual/reqlogin');
});

module.exports = router;

In Register View value on Password and Password 2 looks at typeof email != 'undefined'

In register.ejs the value on 'password' and 'password2' checks to see if typeof email != 'undefined' but I think you meant to say typeof password and typeof password2 respectively. Was this just a mistake when you copied and pasted the inputs?

<div class="form-group">
  <label for="password">Password</label>
  <input
    type="password"
    id="password"
    name="password"
    class="form-control"
    placeholder="Create Password"
    value="<%= typeof email != 'undefined' ? password : '' %>"
  />
</div>
<div class="form-group">
  <label for="password2">Confirm Password</label>
  <input
    type="password"
    id="password2"
    name="password2"
    class="form-control"
    placeholder="Confirm Password"
    value="<%= typeof email != 'undefined' ? password2 : '' %>"
  />
</div>

Login

Unknown authentication strategy 'local' please help

EJS-Lint problem

Hi Brad,

Thanks for your tutor.
But when I follow your code, it found a problem with ejs files. I've then added the ejs-lint package and "lint:ejs": "ejslint views/some-template.ejs" in the "scripts" of package.json (views is the folder of ejs files). It works, but not sure. Can this problem be solved?
By the way, if I use express-handlebars instead of 'express-ejs-layouts', is it the same code?

MongoError: no mongos proxy available at Timeout.<anonymous>

Server started on port 5000
{ MongoError: no mongos proxy available
at Timeout. (D:\Mayka\Lab\node_passport_login-master\node_modules\mongoose\node_modules\mongodb-core\lib\topologies\mongos.js:757:28)
at ontimeout (timers.js:498:11)
at tryOnTimeout (timers.js:323:5)
at Timer.listOnTimeout (timers.js:290:5) name: 'MongoError', [Symbol(mongoErrorContextSymbol)]: {} }

"Need your advise for above problem..."

view engine

I am trying to change the view engine to EJS.
But I have some trouble with this part.
<div class="row"> <div class="col-lg-12"> {{#if success_msg}} <div class="alert alert-success">{{success_msg}}</div> {{/if}} {{#if error_msg}} <div class="alert alert-danger">{{error_msg}}</div> {{/if}} {{#if error}} <div class="alert alert-danger">{{error}}</div> {{/if}} {{{body}}} </div> </div>

any help?

How to display new model to the protected view

Hi, Brad how to make the new model available to protected view?

// Dashboard
router.get('/dashboard', ensureAuthenticated, (req, res) => {
  res.render('dashboard', {
    user: req.user, <-- This can be viewed
    phone: req.phone
  })
});
// Phone view
router.get('/phones', ensureAuthenticated, (req, res) => {
  res.render('phones', {
    phone: req.phone <-- This one not
  })
});

Really new to backend languages.

I would like to add more entries to Mongo DB than email, pass and username...I tried everything...changed register.ejs and users.js...It simply won't take new key: value pairs...Thanks for the help i advance :)

License?

Very helpful information.
Any chance of putting a License - MIT or Unlicense so we can use the code?

can't login

Hey Brad, great videos. I'm attempting to learn node.js and passport. When I go to login I get a 404 error. I even attempted to download your copy and try it from there and get the same result. I followed your YouTube presentation on it but I can't seem to locate the bug. Any ideas?

validate user

I think this need a user validation either through email or sms.
one could use mailgun to send the email or setup twilio for sms. these are just examples of providers. has anyone looked add what it would take to add these?

Under what license are you releasing this code?

First of all, your YouTube videos are amazing!
I wanted to extend your work to use in my own application, but I couldn't find a license file with the "loginapp". Can you clarify what license you are releasing this code under?

Thanks!

  • Fahad
    (big fan!)

ensureAuthenticated returns false after successful log in

I can't get the ensureAuthenticated to work properly :(

Problem:

  • After logging in with a user I try another route (which is "protected" by ensureAuthenticated) and returns 401 :(

Don't want to spam with code here (sorry if it's not allowed to post links to other repositories, but mine is entirely based on Brad's tutorial just with Angular on the Front-end side.

Link to the repository: https://github.com/andreivirabean/BookSharing

Any help is highly appreciated.

node app?

Hi Brad,

Your README file states to use npm start. I am getting the following error

npm ERR! Windows_NT 6.1.7601
npm ERR! argv "c:\\Program Files\\nodejs\\node.exe" "c:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "start"
npm ERR! node v4.2.2
npm ERR! npm  v2.14.7

npm ERR! missing script: start
npm ERR!
npm ERR! If you need help, you may report this error at:
npm ERR!     <https://github.com/npm/npm/issues>

Did you mean to write node app?

Thanks!
perogi.

Pushing to Heroku(still learning)

I am still learning, so this is most likely just a realm of me not knowing what I am doing. But I am trying to push this application to heroku. So I can play with it in a production realm.

Any chance you can help me out and maybe point me in the right direction.

screen shot 2016-07-16 at 12 56 17 pm

Register

After I register a user the page is just loading and then says that there is a user using that email already, and it doesn't redirect you to the login page.

duplicate record

Hello, I am very new for this and really appreciate if you guys help me to fix.
Registration page, currently i can submit duplicate record. how to fix if user is already exist in db based on user's email. Thanks

Could not launch project

Upon running I get the following error. Had to change filename /models/user.js to /models/User.js

aniket@aniket:~/node_passport_login$ npm start

 [email protected] start /home/aniket/node_passport_login
 node app.js

module.js:550
    throw err;
    ^

Error: Cannot find module '../models/User'
    at Function.Module._resolveFilename (module.js:548:15)
    at Function.Module._load (module.js:475:25)
    at Module.require (module.js:597:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/home/aniket/node_passport_login/config/passport.js:6:14)
    at Module._compile (module.js:653:30)
    at Object.Module._extensions..js (module.js:664:10)
    at Module.load (module.js:566:32)
    at tryModuleLoad (module.js:506:12)
    at Function.Module._load (module.js:498:3)
    at Module.require (module.js:597:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/home/aniket/node_passport_login/app.js:11:1)
    at Module._compile (module.js:653:30)
    at Object.Module._extensions..js (module.js:664:10)
    at Module.load (module.js:566:32)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] start: `node app.js`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the [email protected] start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

{ MongoNetworkError: failed to connect to server [test-cluster1-shard-00-02-ioe1x.mongodb.net:27017]

{ MongoNetworkError: failed to connect to server [test-cluster1-shard-00-02-ioe1x.mongodb.net:27017] on first connect [MongoError: bad auth Authentication failed.]
at Pool. (C:\xampp\htdocs\nodejs_authentication\node_modules\mongodb-core\lib\topologies\server.js:431:11)
at Pool.emit (events.js:198:13)
at connect (C:\xampp\htdocs\nodejs_authentication\node_modules\mongodb-core\lib\connection\pool.js:557:14)
at callback (C:\xampp\htdocs\nodejs_authentication\node_modules\mongodb-core\lib\connection\connect.js:109:5)
at provider.auth.err (C:\xampp\htdocs\nodejs_authentication\node_modules\mongodb-core\lib\connection\connect.js:352:21)
at _authenticateSingleConnection (C:\xampp\htdocs\nodejs_authentication\node_modules\mongodb-core\lib\auth\auth_provider.js:66:11)
at sendAuthCommand (C:\xampp\htdocs\nodejs_authentication\node_modules\mongodb-core\lib\auth\scram.js:215:18)
at Connection.messageHandler (C:\xampp\htdocs\nodejs_authentication\node_modules\mongodb-core\lib\connection\connect.js:334:5)
at Connection.emit (events.js:198:13)
at processMessage (C:\xampp\htdocs\nodejs_authentication\node_modules\mongodb-core\lib\connection\connection.js:364:10)
at TLSSocket. (C:\xampp\htdocs\nodejs_authentication\node_modules\mongodb-core\lib\connection\connection.js:533:15)
at TLSSocket.emit (events.js:198:13)
at addChunk (_stream_readable.js:288:12)
at readableAddChunk (_stream_readable.js:269:11)
at TLSSocket.Readable.push (_stream_readable.js:224:10)
at TLSWrap.onStreamRead [as onread] (internal/stream_base_commons.js:94:17)
name: 'MongoNetworkError',
errorLabels: [ 'TransientTransactionError' ],
[Symbol(mongoErrorContextSymbol)]: {} }

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.