Update: I have downloaded express-4.x-local-example and can't seem to get it working either. Is there something that I'm missing?
I'm trying to set a local strategy for passport but it's not being fired. After entering the credentials, the page redirects to failureRedirect.
app.js
const express = require('express')
, app = express()
, mainRouter = require('./controllers/mainRouter');
mainRouter(app);
mainRouter.js
const bodyParser = require('body-parser')
, passport = require('passport')
, passportConfig = require('../config/passport');
passportConfig(passport);
module.exports = (app) => {
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(passport.initialize());
app.use(passport.session());
app.post('/login', passport.authenticate(('local'), {
successRedirect: '/',
failureRedirect: 'login/',
})
);
}
passport.js
const LocalStrategy = require('passport-local').Strategy;
module.exports = (passport) => {
passport.use(new LocalStrategy({usernameField: 'email'},
(email, password, done) => {
console.log('This message is not being logged.');
})
);
}
Your not actually calling the strategy in your mainRouter.js file.
Before the app.post, add passport.use(passportConfig);
Related
I am using passport to implement a login function on my application. However, every time I try to authenticate the user, I cannot get passed the authentication and am redirected to the failure URL. I have confirmed that there is a user in the MongoDB database and the user supplied password is correct. However, I cannot get past the passport authentication. Can anyone please help me out ?
This is my index.js
const express = require('express');
const app = express();
const mongoose = require('mongoose');
const path = require('path');
const ejsMate = require('ejs-mate');
const loginRoutes = require("./routes/login");
const User = require('./models/users');
const session = require('express-session');
const userRoutes = require('./routes/user');
const passport = require('passport');
const localStrategy = require('passport-local');
sessionConfig = {
name: "session",
secret: 'BetterSecret',
resave: false,
saveUninitialized: true,
cookie: {
httpOnly: true,
expires: Date.now() + 604800000, //Date.NOW + No. of Miliseconds in the week
maxAge: 604800000
}
};
//Connection strings only beyond this line
mongoose.connect('mongodb://localhost:27017/myLoc').then(console.log("DB connected")).catch(error => handleError(error));
app.listen(5500, (req, res, next) => {
console.log("Connected");
});
//app.uses
app.use(express.urlencoded({ extended: true }));
app.use("/", loginRoutes);
app.use("/business", userRoutes);
app.engine('ejs', ejsMate);
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views')); //setting up the views directory
app.use(express.static(path.join(__dirname, 'public'))); //public directory to serve static content
app.use(session(sessionConfig));
app.use(passport.initialize());
app.use(passport.session());
passport.use(new localStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
This is the router for the login:
const express = require('express');
const router = express.Router();
const users = require('../controllers/users');
const passport = require('passport');
router.route('/login')
.get(users.renderLoginForm)
.post(passport.authenticate('local', { successRedirect: '/', failureRedirect: '/login' }), users.login);
router.route('/register')
.get(users.renderRegisterForm)
.post(users.createNewUser);
module.exports = router;
and for the controller I just have a console.log for now
module.exports.login = (req, res, next) => {
console.log("I am here");
};
I'm developing a website with Node.js and express. I want to have an option to sign in with Discord.
I've followed the guide on the npm page as well as a video guide
I can access the Discord OAuth page but when I click "Authorize" it will log my discord ID on the console but it will not redirect(supposed to redirect to /auth/success). If I click "cancel" it will immediately redirect to /auth/forbidden, as intended. There are no errors.
app.js
const express = require('express');
const http = require('http');
const session = require('express-session');
const passport = require('passport');
const discordStrategy = require('./strategies/discordstrategy');
const app = express();
app.use(session({
secret: "secret",
cookie: {
maxAge: 60000 * 60 * 24
},
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
app.use('/auth', require('./routes/auth'))
const httpServer = http.createServer(app);
httpServer.listen(80, () => {
console.log("HTTP Server running on port 80");
});
auth.js
const express = require('express');
const passport = require('passport');
const router = express.Router();
router.get('/success', (req, res) => {
res.send("sucessful")
});
router.get('/forbidden', (req, res) => {
res.send("forbidden")
});
router.get('/', passport.authenticate('discord'));
router.get('/redirect', passport.authenticate('discord', {
failureRedirect: '/auth/forbidden'
}), function(req, res) {
res.redirect('/auth/success')
});
module.exports = router;
discordstrategy.js
const DiscordStrategy = require('passport-discord').Strategy;
const passport = require('passport');
var scopes = ['identify', 'guilds'];
passport.use(new DiscordStrategy({
clientID: '[redacted]',
clientSecret: '[redacted]',
callbackURL: '/auth/redirect',
scope: scopes
},
function(accessToken, refreshToken, profile, cb) {
console.log(profile.id)
}));
After Authing, discord and express use a cache system to store your user, so that you dont have to log in everytime. try going on incognito or a different account and logging in.
I have 2 modules
users
blogs
i have implemented users for login register with passport authentication . When i try to use current user data(req.user) in blog model it results 'undefined'.
i have share my code below
app.js
const express = require('express');
const app =express();
const path = require('path');
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended : false }));
app.use(bodyParser.json());
const Users = require("./routes/Users");
const Blogs = require("./routes/Blog");
app.use("/users",Users);
app.use("/blogs",Blogs);
app.set('views',path.join(__dirname, 'views'));
app.set('view engine','ejs');
app.listen(3000, function() {
console.log('Server started...');
});
users.js
const passport = require('passport');
const express=require('express');
const users = express.Router();
const models = require('../models');
const User = models.users;
var cookieParser = require('cookie-parser');
const session = require('express-session');
users.use(cookieParser());
users.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: true
}));
users.use(passport.initialize());
users.use(passport.session());
require('../config/passport.js')(passport, User);
users.post('/register',passport.authenticate('local-register', {
successRedirect: '/users/profile',
failureRedirect: '/users/register'
}
));
users.post('/login',passport.authenticate('local-login', {
session: true,
successRedirect: '/users/profile',
failureRedirect: '/users/profile'
}
));
module.exports =users;
blogs.js
const express = require('express');
const blogs = express.Router();
const blogModel = require('../models/blogs');
blogs.get('/',(req,res) =>{
console.log(req.user) // RESULTS UNDEFINED
res.send('Blog List');
});
passport.js
const bCrypt = require('bcryptjs');
const LocalStrategy = require('passport-local').Strategy;
module.exports = function(passport, user) {
const User = user;
passport.use('local-register', new LocalStrategy( { usernameField: 'email', passwordField: 'password', passReqToCallback: true },
function(req, email, password, done) {
... ....
}
));
passport.use('local-login', new LocalStrategy({ usernameField: 'email', passwordField: 'password', passReqToCallback: true },
function(req, email, password, done) {
..... .....
}
));
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser((id, done) => {
const User =user;
User.findById(id).then((user) =>{
if (user) {
done(null, user);
} else {
done(user.errors, null);
}
});
});
}
You are initiating passport (which handles req.user) only for Users router, this way only routes starting with /users will actually have access to req.user.
In order to use req.user inside the Blogs module, you need to initiate passport for the entire express app (instead of just the users router).
You would probably want to move the initialization to the app.js file
app.use(bodyParser.urlencoded({extended : false }));
app.use(bodyParser.json());
app.use(cookieParser());
app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());
I believe your problem is you are using multiple objects/instance of express packages and trying to pass from one to another. It won't work as expected. To make it working you should have multiple routes using the same express instance.
this is my app.js
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const cors = require('cors');
const passport = require('passport');
const app = express();
app.use(cors());
//Mongodb connection
mongoose.connect("mongodb://localhost/expressWithAngular")
.then(() => {
console.log("mongodb connected");
})
//bodyparser middleware
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
//load routes
const users = require("./routes/users");
//include passport
require("./config/passport")(passport);
// use routes
app.use('/user' , users);
app.get('' ,(req,res) => {
res.send('home');
})
const port = 5000;
app.listen(port , () => {
console.log(`server is running in port ${port}`);
})
this is my user routes routes/user.js
const express = require('express');
const mongoose = require('mongoose');
const router = express.Router();
const bcrypt = require('bcryptjs');
const passport = require('passport');
//user model init
require('./../models/User');
const User = mongoose.model('users');
router.post('/login' , (req,res,next)=>{
console.log("bodyparser" ,req.body);
passport.authenticate('local',{
session: false
},function(req,res,next){
console.log(res);
})
})
module.exports = router;
this is my config/passport.js
const LocalStrategy = require('passport-local').Strategy;
const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
const User = mongoose.model('users');
module.exports = function(passport){
passport.use(new LocalStrategy(
{
usernameField : 'email'
},
function(email,password,done){
console.log(email);
}
))
}
- i was trying to connect my mean stack app with passport
authentication, i am able to send details to backend but i couldn't
pass the value to local strategy
- I don't know where i am missing, when i consoled the local strategy is
not called, please correct me where i am missing
I believe that you have problem in your router configuration. passport.authenticate is generating middleware for you, but in your case you have wrapped it in function so you could log input parameters and you haven't returned generated middleware to router:
router.post('/login' , (req,res,next)=>{
console.log("bodyparser" ,req.body);
passport.authenticate('local',{
session: false
},function(req,res,next){
console.log(res);
})
})
I would advise you to modify your code to work like in example in official documentation:
router.post('/login' , passport.authenticate('local',{
session: false
});
)
If you really need to log req.body just add a middleware before authentication like this:
router.post('/login' , (req, res, next) {
console.log("bodyparser" ,req.body);
next();
},
passport.authenticate('local', {session: false});
)
I'm trying to build a login system using express and passport.
As far as I know, I can use the req.user to access user id and correctly store their actions and req.isAuthenticated() would be true if Passport is working properly, however it isn't working.
For some reason, req.user is always undefined and req.isAuthenticated() is always false.
This is my app.js ->
const express = require('express');
const http = require('http');
const session = require('express-session');
const bodyParser = require('body-parser');
const passport = require('passport');
const route = require('./controllers/core'); **// CORE.JS**
const app = express();
app.set('view engine', 'ejs');
app.use('/css', express.static('css'));
app.use('/js', express.static('js'));
app.use('/themify', express.static('themify'));
app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: false
//cookie: { secure: true }
}));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(passport.initialize());
app.use(passport.session());
app.use(route);
//core(app);
app.listen(3000);
And this is my core.js
const router = require('express').Router();
const passport = require('passport');
const bodyParser = require('body-parser');
const mysql = require('mysql');
const connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'pharmate',
dateStrings: 'date'
});
const urlencodedParser = bodyParser.urlencoded({ extended: false });
router.get('/index', function(req,res){
console.log(req.user);
});
router.post('/index', urlencodedParser, function(req,res){
var email = req.body.email;
var pass = req.body.password;
connection.query("SELECT `Pharmacy_ID`, `Email`, `Password` FROM `pharmacy` WHERE Email = ? AND Password = ?", [email, pass], function (error, results, fields) {
if (error) res.send(error);//throw error;
else{
if(results.length>0){
req.login(results[0], function(err){
res.redirect('index');
});
}
else{
res.redirect('login');
}
}
});
});
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
done(null, user);
});
module.exports = router;
Any help would be appreciated. Thanks in advance.
You should handle the authentication like:
app.post('/login',
passport.authenticate('local', {
successRedirect: '/secret',
failureRedirect: '/login',
})
);
Did you setup the passport local strategy ?