This is solved. Actually, the problem is with postman not on Passport code
I have a login system which is implemented through Nodejs Passport. For Login I use Handlebars for creating the UI and send the form data from frontend to backend.
These is my login Handlebars File
<form id="userloginform" method="post" action="/user/login">
<div class="form-group">
<label>Username</label>
<input type="text" name="username" class="form-control" placeholder="Username or Email">
</div>
<div class="form-group">
<label>Password</label>
<input type="password" name="password" class="form-control" placeholder="Password">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
and on User.js file I have a code of authentication i.e like this
//Login Handler
passport.use('local-user', new LocalStrategy(
function(username, password, done) {
User.getUserByUsername(username, function(err, user){
if(err) {
console.log('error')
logger.log('error', 'Error Generates on User.getUserByUsername Query on users.js file');
throw err;
}
if(!user){
return done(null, false, {message: 'Unknown User'});
}
User.comparePassword(password, user.password, function(err, isMatch){
if(err) {
logger.log('error', 'Error Generates on User.comparePassword Query on users.js file');
throw err;
}
if(isMatch){
return done(null, user);
}else{
return done(null, false, {message: 'Invalid Credential, please check carefully...!'})
}
});
});
}
));
//Login Authentication
router.post('/login',
passport.authenticate('local-user', {
failureRedirect: '/user/login',
badRequestMessage: 'Field cannot be blank.!!', //missing credentials
failureFlash: true
}),
function(req, res) {
console.log('hello');
req.flash('success_msg', 'Welcome ' + req.user.name);
req.flash('custom_msg', token);
//res.redirect('/success?username='+req.user.username);
res.redirect('/user/dashboard');
});
All these things are working pefectly.
Now when I call it through postman and pass two parameters i.e username and password then it does nothing. Simply failure redirect.
I have done this through proper nodejs with form submitted pattern. Now I want to be done through API from different Server.
Anyone have any idea then let me know. Any help is really appreciated.
Related
m trying to make auth system with react and Passport js
My passport look like this:
let passport = require('passport');
let User = require('../models/user');
let localStorage = require('passport-local').Strategy;
passport.serializeUser(function(user, done){
done(null, user.id)
});
passport.deserializeUser(function(id, done){
User.findById(id, (err, user) => {
done(err, user)
})
});
passport.use('local.signup', new localStorage({
usernameField: 'email', passwordField: 'password', passReqToCallback: true
}, function(req, email, password, done){
//Check valid
req.checkBody(req.body.email, 'Invalid email').notEmpty().isEmail();
req.checkBody(req.body.password, 'Invalid password').notEmpty().isLength({min: 4});
req.checkBody(req.body.name, 'Name is require!').notEmpty();
let errors = req.validationErrors(); //Get all errors for checkBody
if(errors){
let messages = [];
errors.forEach(function(error){
messages.push(error.msg)
});
return done(null, false, req.flash('error', messages));
}
User.findOne({'email': req.body.email}, function(err, user){
if(err) return done(err);
if(user) return done(null, false, {message: 'Email is already in use'});
var newUser = new User();
newUser.email= req.body.email;
newUser.password = newUser.encryptPassword(req.body.password);
newUser.name = req.body.name;
newUser.save((err, user) => {
if(err) return done(err);
return done(null, user);
})
})
}));
My route file:
const express = require('express');
const passport = require('passport');
let router = express.Router();
let User = require('../models/user');
router.post('/signup', passport.authenticate('local.signup', {
failureRedirect: '/', failureFlash: true
}), function(req, res,next){
console.log('Yes signUp');
});
module.exports = router;
React file:
handleChange = ev => {
this.setState({[ev.target.name]: ev.target.value});
}
onSubmit = ev => {
ev.preventDefault();
let user = {
name: this.state.name,
email: this.state.email,
password: this.state.password
}
axios.post('http://localhost:3001/signup', user)
.then(res=> { console.log(res) })
.catch(err=> { console.error(err) })
}
render() {
return (
<div className="container login-container">
<div className="title-login text-center">Login</div>
<hr/>
<div className="login-form">
<div className="form-group">
<input type="email" className="form-control" name="email" value={this.state.email} placeholder="Enter your Email.." onChange={this.handleChange} />
</div>
<div className="form-group">
<input type="text" className="form-control" name="name" value={this.state.name} placeholder="Enter your Name.." onChange={this.handleChange} />
</div>
<div className="form-group">
<input type="password" className="form-control" name="password" value={this.state.password} placeholder="Enter your password.." onChange={this.handleChange} />
</div>
<button className="btn btn-outline-primary btn-block" onClick={this.onSubmit}>Send</button>
</div>
</div>
)
}
The error is:
OPTIONS http://localhost:3001/ 404 (Not Found) signup:1 Failed to load
http://localhost:3001/: Response for preflight has invalid HTTP status
code 404. index.js:2178 Error: Network Error
at createError (createError.js:16)
at XMLHttpRequest.handleError (xhr.js:87)
Help!
I am new to the whole user authentication things with node and I am trying to learn how to use Passport's LocalStrategy to add users to a Mongo database.
I'm trying to follow a particular tutorial and for some reason things aren't going to plan. Whenever I submit the registration form the strategy always fails (is redirected to the failure page). I have a feeling it is something to do with the body of he request not being passed (since the log I placed in where the strategy is declared is not run). However it seems like the current infrastructure makes it hard to refactor. Can this code be refactored such that the request can be parsed manually (e.g. request.body.* name *) before handing it over to passport?
Unless the issue is something completely different, in which case I have no idea...
index.js:
// Use middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(expressSession({ secret: 'whatkindofgamedoyouthinkthisishey',
cookie: {maxAge:null},
resave: false,
saveUninitialized: false}));
require("./config/passport")(passport);
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
// Obtain application modules
var userModels = require("./schemas/user")(mongoose);
var loginPage = require("./routes/login")(passport, userModels);
// Initialize Routes
app.use("/", loginPage);
passport.js (should come up with a better name):
var LocalStrategy = require("passport-local").Strategy,
User = require("../schemas/user");
module.exports = function (passport) {
passport.serializeUser(function (user, done) {
done(null, user.id);
});
passport.deserializeUser(function (id, done) {
User.findById(id, function (err, user) {
done(err, user);
});
});
passport.use("local-signup", new LocalStrategy({
email: "email",
password: "password",
passReqToCallback: true
},
function (request, email, password, done) {
console.log("message sent to sign up"); // log not running
process.nextTick(function () {
User.findOne({email: email}, function (err, user) {
if (err) {
return done(err);
}
if (user) {
return done(null, false, request.flash("signupMessage", "That email is already taken"));
} else {
var newUser = new User();
newUser.email = email;
newUser.password = password;
newUser.save(function (err) {
if (err) {
throw err;
} else {
return done(null, newUser);
}
});
}
});
});
}
));
};
login.js (router being exported)
router.post("/register", passport.authenticate("local-signup", {
successRedirect: "/loggedIn",
failureRedirect: "/connectFailed",
failureFlash: false
}));
Html form:
<form class="form-signin" action="/register" method="POST">
<div class="logoContainer">
<img src="images/LogoWithoutText.png" class="image image-responsive" id="loginImage">
</div>
<h2 class="form-signin-heading">Please sign in</h2>
<label for="inputEmail" class="sr-only">Email address</label>
<input type="email" id="inputEmail" class="form-control" name="email" placeholder="Email address" required autofocus>
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" id="inputPassword" class="form-control" name="password" placeholder="Password" required>
<div class="checkbox">
<label>
<input type="checkbox" value="remember-me"> Remember me
</label>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</form>
From what I can read in the passportjs.org/docs, it looks like passport.use has the following signature:
var passport = require('passport'),
LocalStrategy = require('passport-local').Strategy;
passport.use(new LocalStrategy({
email: "email",
password: "password",
passReqToCallback: true
},
function(req, email, password, done) {
User.findOne({ username: username }, function(err, user) {
if (err) { return done(err); }
if (!user) {
return done(null, false, { message: 'Incorrect username.' });
}
if (!user.validPassword(password)) {
return done(null, false, { message: 'Incorrect password.' });
}
return done(null, user);
});
}
));
So, try changing the way passport.use is written and try you luck.
I have been trying to get local authentication work with passport on nodejs and as far as i can tell all of my code it is correct but i keep getting the same annoying error about "unknown authentication strategy so maybe someone else can help me with this problem my code is shown below.
Here is my code for passport configuration in nodejs.
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var User = require('../models/user');
module.exports = function(passport) {
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
passport.use('local-signup', new LocalStrategy({
usernameField : 'username',
passwordField : 'password',
passReqToCallback : true
},
function(req, username, password, done) {
process.nextTick(function() {
User.findOne({ 'local.username' : username}, function(err, user) {
if (err)
return done(err);
if(user) {
return done(null, false, req.flash('signupMessage', 'That Username is already taken.'));
}
else {
var newUser = new User();
newUser.local.username = username;
newUser.local.password = newUser.generateHash(password);
newUser.save(function(err) {
if(err)
throw err;
return done(null, newUser);
});
}
});
});
}));
passport.use('local-login', new LocalStrategy({
usernameField : 'username',
passwordField : 'password',
passReqToCallback : true
},
function(req, username, password,done) {
User.findOne({ 'local.username' : username}, function(err, user) {
if(err)
return done(err);
if(!user)
return done(null, false, req.flash('loginMessage', 'No user found.'));
if(!user.validPassword(password))
return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.'));
return done(null, user);
});
}));
};
And here is the post on the server side.
app.post('/signin', passport.authenticate('local-login', {
successRedirect : '/profile',
failureRedirect : '/login',
failureFlash : true
}));
And here is the form in the html doc
<div id="signin">
<form class="form-horizontal" method="POST" action="/signin">
<div class="form-group">
<label class="control-label col-sm-2">Username:</label>
<div class="col-xs-3">
<input type="text" class="form-control"></input><br>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Password:</label>
<div class="col-xs-3">
<input type="password" class="form-control"></input><br><br>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default btn-lg">Sign In</button><br><br>
</div>
</div>
</form>
<div id="accountlinks">
Create Account<br>
Forgot Password
</div>
</div>
Can anyone please help me by telling me what i have done wrong. thanks
require('./config/passport')(passport);
Change the path of the file. Without this working, passport's configurations will not be passed to the routes.
Here is a snippet of where the line should be located:
// server.js
// configuration
===============================================================
mongoose.connect(configDB.url); // connect to our database
require('./config/passport')(passport); // pass passport for configuration
I also had the same problem but when I put this line of code after the app.use(flash()) it worked:
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
require('./config/passport')(passport);
I want a login page where the user enters their username and password, if it match then login is successful otherwise I want to show the flash message.
I've tried many different ways of doing this but couldn't find the correct way.
router.get('/login', function (req, res) {
res.render('login', {
layout: 'layouts/main/subpages',
topimagetype: 'home',
title: 'Log In',
message: req.flash('loginMessage')
});
});
You use the connect flash which is really simple to use.
Install the connect-flash via npm.
Here i give you example might be its works for you.
index.js // Router
router.get('/login', function (req, res) {
res.render('login', {
layout: 'layouts/main/subpages',
topimagetype: 'home',
title: 'Log In',
message: req.flash('loginMessage')
});
});
Passport.js // Configuration file
passport.use('local-login', new LocalStrategy({
usernameField: 'email',
passwordField: 'password',
passReqToCallback: true
},
function (req, email, password, done) {
pool.getConnection(function (err, connection) {
connection.query("SELECT * FROM user WHERE user_name = '" + email + "'", function (err, rows) {
if (err)
return done(err);
if (!rows.length) {
return done(null, false, req.flash('loginMessage', 'No user found.'));
}
if (!(passwordHash.verify(password, rows[0].password)))
return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.'));
var userType={};
userType.super=false;
userType.admin=false;
userType.normal=false;
if (rows[0].Roll_id == 1) {
userType.super=true;
} else if (rows[0].Roll_id == 2) {
userType.admin=true;
}
else {
userType.normal=true;
}
rows[0].type=userType;
rows[0].created_date = rows[0].created_date.toDateString();
return done(null, rows[0]);
});
});
}));
Html View
<div class="login">
<div class="login-screen">
<div class="container">
{{#message}}
<div style="margin-left: 35%; width: 30%;">
<div class="alert alert-danger">{{ message }}</div>
</div>
{{/message}}
<section class="main">
<form action="/login" method="post" role="form" class="form-1">
<p class="field">
<input type="text" name="email" placeholder="email" id="login-name">
<i class="icon-user icon-large"></i>
</p>
<p class="field">
<input type="password" name="password" placeholder="password" id="login-pass">
<i class="icon-lock icon-large"></i>
</p>
<p class="submit">
<button type="submit" name="submit"><i class="icon-arrow-right icon-large"></i></button>
</p>
</form>
</section>
</div>
i need a help in passport.js authentication.
passort.js authentiction working fine.
but i dont know how can i create authentication login in popup window.
all the authentication process functions in backend.
please help me.
'linkedin': function(req, res) {
passport.authenticate('linkedin', {failureRedirect: '/login', scope: ['r_basicprofile', 'r_emailaddress']},
function(err, user) {
req.logIn(user, function(err) {
if (err) {
// console.log(err);
res.view('500');
return;
}
req.session.user = user;
return res.redirect('/user');
});
})(req, res);
},
'facebook': function(req, res) {
passport.authenticate('facebook', {failureRedirect: '/login', scope: ['email','publish_stream'],display:'popup' },
function(err, user) {
req.logIn(user, function(err) {
if (err) {
throw err;
res.view('500');
return;
}
req.session.user = user;
if (p) {
//write the post project function
}
return res.redirect('/user');
});
})(req, res);
},
this is my login page
<form action ="/auth/linkedin" method = "POST" class="columns small-12 iconized" >
<input type="hidden" value="test messge" name="title">
<button type="submit" class="icon-linkedin">Linkedin</button>
</form>
please help how can i resize the window .
One solution is jquery.lightbox_me.js found here http://www.freshdesignweb.com/demo/index.php?p=1379320109
Just follow the steps:
1) download the source code, and copy the .js file to assets/js, and copy the .css file to assets/style
2) change your html code to
<button id="loginBtn" class="btn btn-success btn-med">Login</button>
<form id="loginForm" action ="/auth/linkedin" method = "POST" class="columns small-12 iconized" display: none; >
<input type="text" value="test messge" name="title">
<button type="submit" class="icon-linkedin">Linkedin</button>
</form>
<script>
$('#loginBtn').click(function(e) {
$('#loginForm').lightbox_me({
centered: true,
onLoad: function() {
$('#loginForm').find('input:first').focus()
}
});
e.preventDefault();
});
</script>
3) This should do the trick. However eventually it will best if you keep your js scripts out of the html/ejs files, so things are more tidy.
Since Sails comes with ejs-locals, I would put the content within the tags in a separate file and make a call to <% block ... %> instead. Check this page for more info:
Sails.js - How to inject a js file to a specific route?