I am making a admin which will request just for a certain passport.
But when I type it I cannot log in ? How can I solve it ?
const mongoose = require('mongoose');
const UserSchema = mongoose.Schema({
password:{
type: String,
required: true
}
});
const User = module.exports = mongoose.model('User', UserSchema);
In my command line, I created a users collectin and inserted a password:'sifre'
This is my password.js :
const LocalStrategy = require('passport-local').Strategy;
const User = require('../models/user');
const config = require('../config/database');
const bcrypt = require('bcryptjs');
module.exports = function(passport){
// Local Strategy
passport.use(new LocalStrategy(function(password){
let query = {password:password};
User.findOne(query, function(err, user){
if(err) throw err;
if(!user){
return done(null, false, {message: 'No user found'});
}
/*Also I have tried:
// Match Username
let query = {username:username};
User.findOne(query, function(err, user){
if(err) throw err;
if(!user){
return done(null, false, {message: 'No user found'});
} */
/* to understand if it is about user name. Even I added username to models, db.collections
and other code pages but I couldnt solve. Because again
I couldnt reflect the models to db, I think.*/
// Match Password
bcrypt.compare(password, user.password, function(err, isMatch){
if(err) throw err;
if(isMatch){
return done(null, user);
} else {
return done(null, false, {message: 'Wrong password'});
}
});
});
}));
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
}
Also this is my user.js:
const express = require("express");
const router = express.Router();
const bcrypt = require('bcryptjs');
const passport = require('passport');
let User = require('../models/user');
// Register Form
router.get('/login', function(req, res){
const password = req.body.password;
req.checkBody('password', 'Password is required').notEmpty();
let errors = req.validationErrors();
res.render('login');
});
router.post('/login', function(req, res, next){
passport.authenticate('local', {
successRedirect:'/',
failureRedirect:'/users/login',
failureFlash: true
})(req, res, next);
});
// logout
router.get('/logout', function(req, res){
req.logout();
req.flash('success', 'You are logged out');
res.redirect('/login');
});
module.exports = router;
And also this is my command line
db.createCollection('users');
...
db.users.insert{(password:'123'});
...
So how can I implement the inserted password to these code blocks. I cannot understand why it is not working. For now I dont get any errors but when I type that inserted password, I cannot move to user page.
Edit:
bcrypt.compare(password, user.password, function(err, isMatch){
console.log("asd");
if(err) throw err;
if(isMatch){
return done(null, user);
} else {
return done(null, false, {message: 'Wrong password'});
}
});
});
}));
This part is not working.(which is in passport.js)
Also I cannot entegrate the module(user.js) o my mongodb.
Related
This is my MiddleWare for Passport.js the issue i am getting here i cant logged in getting no errors, register route is working successfully i am entering the Right Credentials and everything from my view is great but i am not redirecting to anywhere i tried i am getting http:500 error and getting NO Select query where username='username' and password='password'
//Passport config
require('./config/passport')(passport)
//Passport MiddleWare
app.use(passport.initialize());
app.use(passport.session());
This is my passport.js file code
var LocalStrategy = require('passport-local').Strategy;
var User = require('../models/user');
var bcrypt = require('bcryptjs');
module.exports = function (passport) {
passport.use(new LocalStrategy(function (username, password, done) {
models.User.findOne({
where:{username: username}
}.then(function (err,user) {
if(err) console.log(err);
if (!user) {
return done(null, false, {message: 'No user found!'});
}
bcrypt.compare(password, user.password, function (err, isMatch) {
if (err)
console.log(err);
if (isMatch) {
return done(null, user);
} else {
return done(null, false, {message: 'Wrong password.'});
}
});
})
)
}));
passport.serializeUser(function (user, done) {
done(null, user.id);
});
passport.deserializeUser(function (id, done) {
User.findById(id, function (err, user) {
done(err, user);
});
});
}
this is my login method in route
/*
*Post Login
*/
router.post('/login',function(req,res,next){
passport.authenticate('local',{
successRedirect:'/',
failureRedirect:'/admin/pages',
failureFlash:true
})(req,res,next);
})
This is my user.js
var express=require('express');
var router=express.Router();
var User = require('../models/user');
var models=require('../models');
var passport=require('passport');
var bcrypt=require('bcryptjs');
//Get Register
router.get('/register',function(req,res){
res.render('register',{
title:'Register'
})
});
/*
* Register Post
*/
router.post('/register',function(req,res){
var name=req.body.name;
var email=req.body.email;
var username=req.body.username;
var password=req.body.password;
var password2=req.body.password2;
models.User.findOne({
where:{username:username}
}).then(function(copyuser){
if(copyuser){
console.log('User already exist');
redirect('/users/login');
}
else{
var user={
name: name,
email: email,
username: username,
password: password,
admin: 0
};
// res.json(user);
bcrypt.genSalt(10,function(err,salt){
bcrypt.hash(user.password,salt,function(err,hash){
user.password=hash;
models.User.create(user).then(function(user){
res.json(user);
})
console.log('You are now registered');
res.redirect('/admin/pages')
})
})
}
})
})
/*
* Get Login
*/
router.get('/login',function(req,res){
if(res.locals.user) res.redirect('/');
res.render('login',{
title:'log in'
})
})
/*
*Post Login
*/
router.post('/login',function(req,res,next){
passport.authenticate('local',{
successRedirect:'/',
failureRedirect:'/admin/pages',
failureFlash:true
})(req,res,next);
})
//Exports
module.exports=router;
First, i have this in my route, i need to use Passport to Authenticate the User Sign Up Process :
router.post('/user/signup', passport.authenticate('local.signup',{
successRedirect: '/user/profile',
failureRedirect: '/user/signup',
failureFlash: true
}));
I'm learning Node JS from Youtube Video, in the tutorial, there is a step to create Folder called "config", and inside the "config" folder, there is a file called "passport.js".
The problem is, there is "req" parameter inside one of the function in this "passport.js". When i try to run my program, there is an error that said, "req is not defined". this is the source code of "passport.js" :
var express = require('express');
var passport = require('passport');
var User = require('../models/user');
var LocalStrategy = require('passport-local').Strategy;
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: 'email',
passwordField: 'password',
passReqToCallBack: true
}, function(req, email, password, done){ //here is the problem
console.log('REQ :');
console.log(req);
console.log('password :');
console.log(email);
console.log('email :');
console.log(password);
console.log('done :');
console.log(done);
req.checkBody('email','Invalid Email').notEmpty().isEmail();
req.checkBody('password','Invalid password').notEmpty().isLength({min:4});
var errors = req.validationErrors();
if(errors){
var message = [];
errors.forEach(function(error){
message.push(error.msg);
});
return done(null, false, req.flash('error', messages));
}
User.findOne({'email': 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 = email;
newUser.password = newUser.encryptPassword(password);
newUser.save(function(err, result){
if(err){
return done(err);
}
return done(null, newUser);
});
});
}));
How to bring the req to fill the parameter in the passport.js ?
The parameter is called passReqToCallback, not passReqToCallBack (notice that the b needs to be lower-case).
Ok, I edit the question, Can someone help me with fix this code, to work??
I am fallow the guide with youtube about creating login system with using passport, I dont understand here about function
passport.use(new LocalStrategy(
When is she called, And from where it gets an argument login, password.
USER MODEL
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var UserSchema = new Schema({
login: { type: String, maxlength: 20, required: false },
password: { type: String, maxlength: 202, required: false },
updated: { type: Date, default: Date.now },
created: { type: Date, default: Date.now }
});
module.exports = mongoose.model('User', UserSchema);
module.exports.comparePassword = function(candidatePassword, hash, callback){
bcrypt.compare(candidatePassword, hash, function(err, isMatch) {
if(err) throw err;
callback(null, isMatch);
});
}
module.exports.getUserById = function(id, callback){
User.findById(id, callback);
}
User Model
var express = require('express');
var MongoClient = require('mongodb').MongoClient;
var router = express.Router();
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var Product = require('../../model/product.model');
var Category = require('../../model/category.model');
var mongoose = require('mongoose');
var User = require('../../model/user.model');
var _ = require('lodash');
var bcrypt = require('bcrypt');
const saltRounds = 10;
router.post('/create', function (req, res, next) {
var newUser = {
login: req.body.login,
password: req.body.password
}
console.log(req.body)
req.checkBody('login', 'Login is required').notEmpty();
req.checkBody('password', 'Password is required').notEmpty();
var errors = req.validationErrors();
if (errors) {
console.log(errors)
res.send(errors);
} else {
bcrypt.hash(newUser.password, saltRounds, function (err, hash) {
if (err) {
console.log(err)
} else {
newUser.password = hash;
var user = new User(newUser);
user.save()
.then(function (User) {
res.send(User);
})
}
});
req.flash('success_msg', 'You are registered and can now login');
//res.redirect('/');
}
});
passport.use(new LocalStrategy(
function(login, password, done) {
User.findOne({ login: login }, function(err, user){
if(err) {
console.log(err);
}
if(!user) {
return done(null, false, {
message: 'Unkown User'
})
}
});
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);
});
});
router.post('/login', function (req, res, next) {
console.log(req.body)
passport.authenticate('local', { successRedirect: '/', failureRedirect: '/', failureFlash: true }),
function (req, res) {
res.redirect('/product/list')
}
})
module.exports = router;
When is she called?
passport.use(new LocalStrategy( will be used when you call passport.authenticate('local'..
In your project it is while getting post request with '/login'.
LocalStrategy provides strategy to authenticate requests. You can choose different strategy. Strategies, and their configuration, are supplied via the use() function. More information: Passport Documentation
From where it gets an argument login, password?
By default, LocalStrategy expects to find credentials in parameters named username and password. If your site prefers to name these fields differently, options are available to change the defaults.
From LocalStrategy Documentataion
I'm trying to get a handle on user authentication with PassportJS, and I cannot get it to work my database setup.
I'm using MongoDB without Mongoose, and I can't get the LocalStrategy module to work.
Hopefully my database queries aren't too cumbersome to read.
Local Strategy:
passport.use(new LocalStrategy(
function(username, password, done) {
//Fire up database
mongo.connect("mongodb://localhost:27017/formulas", function(e, db) {
if (e) {return next(e);}
var col = db.collection("users");
//Do a database query to find a record by username
col.findOne({"username": username}, function(err, user){
if (err) { return done(err);}
if(!user) {
return done(null, false, { message: "Please check your log in credentials." });
}
//if it exists call done() object with user information
bcrypt.compare(password, user.password, function(err, res){
if (err) throw err;
if (res == true) {
return done(null, {username: username, password: password});
} else {
return done(null, false, { message: "Invalid password."});
}
});
});
});
}));
I call passport.authenticate() like this:
router.post('/login',
passport.authenticate('local', {successRedirect:'/', failureRedirect:'/about',failureFlash: false}),
function(req, res){
console.log(req.body);
console.log(req.user);
console.log("The user was logged");
});
SerializeUser and deserializeUser look like this:
passport.serializeUser(function(user, done) {
done(null, user.username);
});
passport.deserializeUser(function(id, done) {
mongo.connect("mongodb://localhost:27017/formulas", function(e, db){
if (e) {return next(e);}
var col = db.collection("users");
col.findOne({"username": id}, function(err, user){
done(err, {"username": id});
});
});
});
When I call app.post(/login) I'm taken directly to /about and nothing is logged to the console so I'm not quite sure what's going wrong.
Advice on what to fix or how to troubleshoot is greatly appreciated.
Firstly when u serialize user object , then in deserialize also whole user object must be passed.
Consider the example below.
For routes :
router.post('/login', function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err) { return next(err); }
if (!user) { return res.redirect('/login'); }
req.logIn(user, function(err) {
if (err) { return next(err); }
req.session.user = req.user;
return res.redirect('/home');
});
})(req, res, next);
});
For passport.js , place the localstrategy and passport in same folder
var passport = require('passport'),
session = require('express-session');
var local = require('./localstrategy.js');
module.exports = function (app) {
app.use(session({
secret: 'Site visit',
resave: true,
saveUninitialized: true,
cookie: { secure: false }
}));
app.use(passport.initialize());
app.use(passport.session());
passport.serializeUser(function(user, done){
done(null, user);
});
passport.deserializeUser(function(user, done){
done(null, user);
});
local();
};
For local strategy :
'use strict';
var passport = require('passport'),
local = require('passport-local').Strategy;
var user;
// path where the db.js is placed
var db = require('./../db.js');
var ObjectId = db.getObjectID();
var bcrypt = require('bcrypt');
module.exports = function(){
passport.use(new local({
usernameField : 'username',
passwordField : 'password'
}, function(username, password, done){
var collection = db.getDb().collection('users');
collection.findOne({
username: username,
}, function (err, result) {
if(result == null){
cb(null, false);
}else {
bcrypt.compare(password, result.password, function (err, passRes) {
if (passRes == true) {
user = user;
done(err, user);
}else{
done(null, false, { message : 'Invalid Password'});
}
});
}
});
}));
};
I am new to MEAN. I've been trying to create a 'facebook' login for my new MEAN Application. I am making use of strategy from: "passport-facebook".
The code from my User.js file, where i've created a new Schema for facebook users is as follows:
var mongoose = require('mongoose');
var fbuserSchema = mongoose.Schema({
id: String,
token: String,
email: String,
name: String
});
var fbUser = mongoose.model('fbUser', fbuserSchema);
My passport.js file has something like this:
var fbUser = mongoose.model('fbUser'),
FacebookStrategy = require('passport-facebook').Strategy;
module.exports = function(){
passport.serializeUser(function (user, done) {
if (user) {
done(null, user.id);
}
});
passport.deserializeUser(function (id, done) {
User.findOne({_id: id }).exec(function (err, user) {
if (user) {
return done(null, user);
} else {
return done(null, false);
}
});
});
passport.use(new FacebookStrategy({
'clientID' : 'xxxxxxxxxxxxxxx',
'clientSecret' : 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
'callbackUrl' : 'http://localhost:3030/auth/facebook/callback'
},
function(accessToken, refreshToken, profile, done) {
process.nextTick(function(){
fbUser.findOne({'id':profile.id}, function(err, user){
if(err){
return done(err);
}
if(user){
return done(null, user);
}
else{
var newUser = new fbUser();
newUser.id = profile.id;
newUser.token = accessToken;
newUser.name = profile.name.givenName + ' ' + profile.name.familyName;
newUser.email = profiel.emails[0].value;
newUser.save(function(err){
if(err){
throw err;
}
return done(null, newUser);
});
}
});
});
})
)
}
and my routes.js has:
var auth = require('./auth'),
users = require('../controllers/users'),
mongoose = require('mongoose'),
User = mongoose.model('User'),
fbUSer = mongoose.model('fbUser'),
passport = require('passport');
module.exports= function(app) {
app.get('/api/users', auth.requiresRole('admin'), users.getUsers);
app.post('/api/users', users.createUser);
app.put('/api/users', users.updateUser);
app.get('/partials/*', function (req, res) {
res.render('../../public/app/' + req.params[0]);
});
app.post('/login', auth.authenticate);
app.get('/auth/facebook', passport.authenticate('facebook'));
app.get('/auth/facebook/callback',
passport.authenticate('facebook', { successRedirect: '/',
failureRedirect: '/login' }));
app.post('/logout', function(req,res){
req.logout();
res.end();
});
app.get('*', function (req, res) {
res.render('index', {
bootstrappedUser: req.user
});
});
}
I have provided the:
a(href="/auth/facebook") Facebook
in my login.jade file.
When i click on this link though all i am getting is a error saying:
The parameter redirect_uri is required
Can someone please help me on this issue.
My facebook URL is as follows:
https://www.facebook.com/v2.2/dialog/oauth?response_type=code&redirect_uri=&client_id=xxxxxxxxxxxxxxxx
I am missing the "redirect_uri=" value in this. How do i get that?
MEAN already had an facebook support;
Go for facebook.js under config/strategies/
Change the facebook id and app secret according to the one you filled in the facebook website.
Thats it