Get current logged in username using Passport JS? - javascript

I have created a simple user login application following an online tutorial using Node, Express and Passport. Login works correctly but I would like to get the username of the current logged in user and I can't seem to get this working.
I have the following in my app.js:
/// Configuring Passport
var passport = require('passport');
var expressSession = require('express-session');
app.use(expressSession({
secret: 'cookie_secret',
name: 'cookie_name',
proxy: true,
resave: true,
saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session({
secret: 'cookie_secret',
name: 'cookie_name',
proxy: true,
resave: true,
saveUninitialized: true
}));
From what I read in similar posts, I need to expose the username so that I may use it in other files. I tried to do this in my app.js:
app.get('/home', function(req, res) {
res.render('home.jade', { username: req.user.username });
});
Home is a route where I would like to use the the username, and I am trying to access the username with an alert like the following:
alert(req.user.username);
This does not work, the req object is undefined...I'm not sure what I am missing?
Managed to get this working. In my app.js I have:
app.get('/home', function(req, res) {
res.render('home.jade', { username: req.user.username });
});
And then in my /home route I can access the username by doing:
req.user.username

You are mixing two things, one is the client side, and the other is the server side, both use javascript but for render server side code in the cliente side you could not use directly in the client side. you must pass to the view as you do with
app.get('/home', function(req, res) {
res.render('home.jade', { username: req.user.username });
});
here you expose the username variable to the view
In the jade file you should do this
alert(#{username})
instead of
alert(req.user.username)

try:
app.use(cookieParser());
app.use(session({
secret: 'cookie_secret',
name: 'cookie_name',
proxy: true,
resave: true,
saveUninitialized: true
})
);
app.use(passport.initialize());
app.use(passport.session());
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
on controller use req.user

{ username: user.local.username }
Please go with the below link
https://github.com/hnagarkoti/passportauthenticationWorking

Related

How can I use req.user outside of app.get?

I have been working on a web-app similar to this https://rustbet.com. Here's some code :
passport.serializeUser(function(user, done) {
done(null, JSON.stringify(user));
});
passport.deserializeUser(function(obj, done) {
done(null, JSON.parse(obj));
});
I'm serializing the users locally.
passport.use(new SteamStrategy({
returnURL: 'http://localhost:80/auth/steam/return',
realm: 'http://localhost:80/',
apiKey: '------------------'
},
function(identifier, profile, done) {
process.nextTick(function () {
profile.identifier = identifier;
return done(null, profile);
});
}
));
Using steam passport strategy
app.use(session({
secret: '---------',
name: 'user_session',
resave: true,
saveUninitialized: true}));
Sessions
app.get('/account', ensureAuthenticated, function(req, res){
res.render('account', { user: req.user });
});
And here's how i'm currently using the data
How can I use the req.user object outside of a http request/ EJS template? For instance in a socket.io app that i need. I have surfed stackoverflow and found a multitude of answers but none of them were recent. Also, I'm open to any best practices that i most likely missed.

Sessions are not persistent using Nodejs Server

I'm creating REST APIs using NodeJS and MongoDB as a database.
I'm using passport for handling the authentication.
I'm wondering why the sessions are not persistent! Also why the deserialization is never invoked!
passport.serializeUser(function (user, done) {
done(null, user._id);
});
passport.deserializeUser(function (id, done) {
User.findById(id, function (err, user) {
console.log(user, "deserialization"); // --> Never invoked!
done(err, user);
});
});
passport.use(User.createStrategy());
app.use(
session({
secret: process.env.SECRET,
resave: false,
saveUninitialized: false,
store: new MongoStore({ mongooseConnection: mongoose.connection }) // --> Sessions has been saved to database after each login or register
})
);
app.use(passport.initialize());
app.use(passport.session());
exports.getRestaurants = async (req, res) => {
console.log(req.session); // --> Not contains any user info
console.log(req.user); // -->undefined and this is my problem
const restaurants = await liveRestaurants.find().sort({ rate: -1 });
if (!restaurants) return next();
res.status(200).json({ restaurants });
};
After my research, I concluded that it might be for the following reasons:
app.use should be in the correct order
localhost port have an effect on it "as I read"
cluster
and other

express session doesn't work on firebase function

Currently, this is my code:
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function(user, done) {
done(null, user);
});
app.use(express.static(__dirname+'/public'));
app.set('views', __dirname+'/views');
app.set('view engine','jsx');
app.engine('jsx', reactViews.createEngine());
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
app.use(
session({
secret:'key',
resave: true,
saveUninitialized: true,
cookie:{
maxAge: 30000000
}
})
);
app.use(passport.initialize());
app.use(passport.session())
It works fine when using app.listen(8080), but not on firebase functions. When I run the firebase function, the passport.serializeUser got called but no session was stored. It shows req.user is undefined. Is there a way to make express-session work on the firebase function?
You can safely disable session support
passport.authenticate('basic', { session: false })

Implement passportjs and angular4

Look, i've made a mean stack app with register/login using passportjs, and it was fine, when i change to angular2(the other was on angularjs) i've made the backend side and i think it works but i dont know how to test it on the fronted side, i know it has to be something with the url in the <a href=""> but when i put the route that passport gives me, example: /auth/facebook, my aplication does nothing... well it does something, send me to the homepage :c
here is my code so far on the backend side
const FacebookStrategy = require('passport-facebook').Strategy;
const session = require('express-session');
const secret = require('../config/database')
const user = require('../models/user')
module.exports = function(app, passport){
app.use(passport.initialize());
app.use(passport.session());
app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: true,
cookie: { secure: false }
}));
passport.serializeUser(function(user, done) {
token = jwt.sign({email: user.email}, secret, {expiresIn : '24h'});
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
passport.use(new FacebookStrategy({
clientID: '350645212059140',
clientSecret: '8a990aec6db37cc3535f4223c235c427',
callbackURL: "http://localhost:4200/auth/facebook/callback",
profileFields: ['id','displayName','email']
},
function(accessToken, refreshToken, profile, done) {
console.log(profile);
// User.findOrCreate(..., function(err, user) {
// if (err) { return done(err); }
// done(null, user);
// });
done(null, profile)
}
));
app.get('/auth/facebook',passport.authenticate('facebook', { scope: 'email' }));
app.get('/auth/facebook/callback' , passport.authenticate('facebook', {failureRedirect: '/login'}), function(res, res){
if (err) {
console.log(err)
}else{
res.send('wi')
}
})
return passport;
}
my question is, how can i implement this on the fronted side, remember angular 4 :)
Here is pseudo code for this.
Step 1: When you are submitting your form using ngSubmit call a function for instance passportLogin().
Step 2: Now in your component use this function and do an HTTP post request to your node js(express js) URL, for example, auth/login.
Step 3: In the server side write a routing
var express = require('express'),
router = express.Router();
module.exports = function(passport){
router.post('/login', passport.authenticate('local-login', {
successRedirect: '/auth/success',
failureRedirect: '/auth/failure'
}));
}

how to delete cookie on logout in express + passport js?

I want to "delete cookies on logout". I am not able to do that. I googled for answer and found following ways:
Assign new date of expiration to cookie
res.cookie('connect.sid', '', {expires: new Date(1), path: '/' });
Delete cookie using below lines
res.clearCookie('connect.sid', { path: '/' });
I tried both ways individually but they do not delete the cookie.
Here is my code:
routes.js
module.exports = function(app, passport, session){
app.get('/', function(req, res)
{
res.render('index.ejs');
});
app.get('/login', function(req,res){
res.render('login.ejs',{message:req.flash('loginMessage')});
});
app.get('/signup',checkRedirect , function(req, res) {
res.render('signup.ejs',{message: req.flash('signupMessage')});
});
app.get('/profile', isLoggedIn, function(req,res) {
res.render('profile.ejs', {
user :req.user
});
});
app.post('/signup', passport.authenticate('local-signup', {
successRedirect : '/profile',
failureRedirect : '/signup',
failureFlash : true
}));
app.post('/login', passport.authenticate('local-login', {
successRedirect : '/profile',
failureRedirect : '/login',
failureFlash :true
}));
app.get('/logout',function(req,res){
res.cookie('connect.sid', '', {expires: new Date(1), path: '/' });
req.logOut();
res.clearCookie('connect.sid', { path: '/' });
res.redirect('/');
});
function isLoggedIn(req, res, next){
if(req.isAuthenticated())
return next();
console.log("hiii");
res.redirect('/');
}
};
server.js
var express = require('express');
var app = express();
var port = process.env.PORT || 3000;
var mongoose = require('mongoose');
var passport = require('passport');
var flash=require('connect-flash');
var morgan=require('morgan');
var bodyParser = require('body-parser');
var cookieParser=require('cookie-parser');
//
var session=require('express-session');
var RedisStore = require('connect-redis')(session);
var redis = require("redis");
var redis_client = redis.createClient();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
var configDb=require('./config/database.js');
mongoose.connect(configDb.url);
require('./config/passport')(passport);
app.use(morgan('dev'));
app.use(cookieParser());
app.use(bodyParser());
app.set('view engine', 'ejs');
app.use(session({
store: new RedisStore({
host: '127.0.0.1',
port: 6379,
client: redis_client
}),
secret : 'foo',
resave: false,
saveUninitialized: false
}));
app.use(function (req, res, next) {
if (!req.session) {
return next(new Error('oh no')); // handle error
}
next();
});
});
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
require('./app/routes')(app, passport, session);
app.listen(port, function(){
console.log('server is at port' + port);
});
Please try this:
router.get('/logout', function (req, res) {
req.logOut();
res.status(200).clearCookie('connect.sid', {
path: '/'
});
req.session.destroy(function (err) {
res.redirect('/');
});
});
I was struggling with this issue myself. Previously I tried logout and session.destroy, and none worked for me. Then I found the above answers with the clearCookie addition, and that did the trick.
However, I was wondering if those functions are at all having any effect, given that without clearCookie they didn't. So I omitted them.
Also, as status(200) is overridden by redirect (which sets status to 302), I reckoned I'd omit that too.
As for the options to clearCookie in Will59's solution, they looked like they could be the defaults anyhow, so I tried omitting them as well.
I ended up with two lines of code bellow. They worked for me with Chrome, Firefox and Safari (the most recent versions at time of this writing).
router.get('/logout', function (req, res) {
res.clearCookie('connect.sid');
res.redirect('/');
});
You can use req.session.destroy in logout route to destroy the session below is the code for reference :)
app.get('/logout', function(req,res){
req.logOut();
req.session.destroy(function (err) {
res.redirect('/'); //Inside a callback… bulletproof!
});
});
res.clearCookies is kind of messed up. As an alternative, call res.cookie again with whatever options you used to create the cookie in the first place, along with expires: new Date(1), like this:
// Use the same httpOnly, secure, sameSite settings to "delete" the cookie
res.cookie("jwt", "", {
httpOnly: true,
secure: true,
sameSite: "none",
expires: new Date(1)
});
Essentially you are replacing the old cookie with a new one that expires immediately.
pjiaquan's did not work with chromium for me, the cookie was still around.
The issue comes from the res.clearCookie method, as explained in http://expressjs.com/en/api.html:
Web browsers and other compliant clients will only clear the cookie if the given options is identical to those given to res.cookie(), excluding expires and maxAge.
In my case, the solution ended up being:
router.get('/logout', function (req, res) {
req.logOut();
res.status(200).clearCookie('connect.sid', {
path: '/',
secure: false,
httpOnly: false,
domain: 'place.your.domain.name.here.com',
sameSite: true,
});
req.session.destroy(function (err) {
res.redirect('/');
});
});
So none of the suggestions here worked for me, until I realized I was doing a dumb:
Using Github, I set up an OAuth app (you can do this in your profile settings), and used that for authentication.
Worked a charm! But it was always sending me back the same profile, even when I logged out from my app. Clearing all browser storage didn't fix it.
Then it dawned on me that I was still logged into my github account (and that was the profile I was always getting)... once I logged out of that, then the OAuth app prompted me for my user/pw again.

Categories