Sending individual user data back to client from the server [NodeJS] - javascript

I am making a website where users login through Steam. I am able to get their information (such as profile picture and user name) but I've been struggling with sending it back to the client. The json of the user logging in is held within req.user inside of a get request. How would I go about sending the users info from the server to the client of the user that has just logged in?
This is my current code -
// Required to get data from user for sessions
passport.serializeUser((user, done) => {
done(null, user);
});
passport.deserializeUser((user, done) => {
done(null, user);
});
// Initiate Strategy
passport.use(new SteamStrategy({
returnURL: 'http://localhost:' + port + '/api/auth/steam/return',
realm: 'http://localhost:' + port + '/',
apiKey: 'xxxxxxxxxxxxxxxxxxxx'
}, function (identifier, profile, done) {
process.nextTick(function () {
profile.identifier = identifier;
return done(null, profile);
});
}
));
app.use(session({
secret: 'LoopTrades',
saveUninitialized: true,
resave: false,
cookie: {
maxAge: 3600000
}
}))
app.use(passport.initialize());
app.use(passport.session());
// Routes
app.get('/', (req, res) => {
res.send(req.user);
});
app.get('/api/auth/steam', passport.authenticate('steam', {failureRedirect: '/'}), function (req, res) {
res.redirect('/')
});
app.get('/api/auth/steam/return', passport.authenticate('steam', {failureRedirect: '/'}), function (req, res) {
res.redirect('/pages/deposit.html');
});

Related

steam passport implementation, convert from express to nestjs

I've started to convert express project to nestjs. How should it work in Nestjs. Here is working code from Express.
(Code below just redirects to steam sign-in page)
/* eslint-disable space-before-function-paren */
// Require all the installs
var express = require('express');
var passport = require('passport');
var session = require('express-session');
var passportSteam = require('passport-steam');
var SteamStrategy = passportSteam.Strategy;
var app = express();
// Let's set a port
var port = 4000;
// Spin up the server
app.listen(port, () => {
console.log('Listening, port ' + port);
});
// Set up the SteamStrategy
// Required to get data from user for sessions
passport.serializeUser((user, done) => {
done(null, user);
});
passport.deserializeUser((user, done) => {
done(null, user);
});
// Initiate Strategy
passport.use(
new SteamStrategy(
{
returnURL: 'http://localhost:' + port + '/api/auth/steam/return',
realm: 'http://localhost:' + port + '/',
apiKey: 'My API key',
},
function (identifier, profile, done) {
process.nextTick(function () {
profile.identifier = identifier;
return done(null, profile);
});
}
)
);
app.use(
session({
secret: 'Whatever_You_Want',
saveUninitialized: true,
resave: false,
cookie: {
maxAge: 3600000,
},
})
);
app.use(passport.initialize());
app.use(passport.session());
// Routes
app.get('/', (req, res) => {
res.send(req.user);
});
app.get(
'/api/auth/steam',
passport.authenticate('steam', { failureRedirect: '/' }),
function (req, res) {
res.redirect('/');
}
);
app.get(
'/api/auth/steam/return',
passport.authenticate('steam', { failureRedirect: '/' }),
function (req, res) {
res.redirect('/');
}
);
The question is how to implement same in the nestjs???
Or if I want to implement middlewares for passport lib (serializeUser, deserializeUser), how should it happen, in nest official docs I found this examples of custom middlewares
export function logger(req: Request, res: Response, next: NextFunction) {
console.log(`Request...`);
next();
};
But how I should use passport middlware

Passport.js Successful Login hangs without error using MySQL and Node.js

I'm trying to create an application that utilizes a registration and login functionality. I have completed the registration portion where all the information (Email and Password) is successfully passed and saved into a MySQL database.
Problem: My issue now is that when I put in any existing credential and email, the application will hang and refuse to redirect the user to a new page. On the bottom of my browser, it will say "Waiting for localhost...". If I leave the page up for too long, it'll eventually lead to an error page with the words "This page isn’t working. localhost didn’t send any data. ERR_EMPTY_RESPONSE".
I tried console logging for any errors but was unable to identify any causes/errors. I did ensure that the information I inputted is properly being compared to the values in the database table and that the redirection to the page is functioning. I also tried rewriting my code in multiple ways but ended up encountering the same issue.
Below is my passport.js file:
var LocalStrategy = require('passport-local').Strategy;
// Load User model
const User = require('../models/User');
// Reference: http://www.passportjs.org/docs/
module.exports = function (passport) {
passport.use(
new LocalStrategy({ usernameField: 'email' }, (email, password, done) => {
// Match user
User.findOne({ which: { email: email } })
.then(user => {
// Check if Email exists in database
if (!user) {
return done(null, false, {
message: "Email is not registered."
});
}
// Check if password matches the one found in the database (To Do: Encrypt this later!)
if (password != user.password) {
return done(null, false, { message: 'Password is incorrect.' });
} else {
return done(null, user);
}
})
.catch(err => console.log(err));
})
);
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser(function (id, done) {
// Find by Primary Key
User.findByPk(id, function (err, user) {
console.log(user);
done(err, user);
});
});
}
Below is my app.js (server) file:
var express = require('express')
var expressLayouts = require('express-ejs-layouts');
var flash = require('connect-flash');
var session = require('express-session');
var passport = require('passport');
var app = express();
// Embedded JavaScript (EJS)
app.use(expressLayouts);
app.set('view engine', 'ejs');
// Express Session
app.use(session({
secret: 'secret',
resave: false,
saveUninitialized: false
}));
// Bodyparser
app.use(express.urlencoded({ extended: false }));
// Passport
app.use(passport.initialize());
app.use(passport.session());
require('./config/passport')(passport);
// Connect flash for notification messages
app.use(flash());
// Global Variables to define specific notification messages
app.use((req, res, next) => {
// Notification for Registration Page
res.locals.success_msg = req.flash('success_msg')
res.locals.error_msg = req.flash('error_msg');
// Notification for Passport Login Verification
res.locals.error = req.flash('error');
next();
});
// Routes
app.use('/', require('./routes/index'));
// Login/Register Endpoints routes (ex. /users/login)
app.use('/users', require('./routes/users'));
// Image
//app.use(express.static('./public'));
var port = process.env.PORT || 8026;
app.listen(port);
console.log('Server Running');
console.log("Port: " + port);
Below is my function to handle the login and redirection:
router.post('/login', (req, res, next) => {
console.log(req.body);
passport.authenticate('local', {
successRedirect: '/dashboard',
failureRedirect: '/users/login',
failureFlash: true
})(req, res, next);
});
Please let me know if you need any other information. Thank you!
I think this could be a problem. On passport.use , if an error occurred, you are not returning anything.
passport.use(
new LocalStrategy({ usernameField: 'email' }, (email, password, done) => {
// Match user
User.findOne({ which: { email: email } })
.then(user => {
// Check if Email exists in database
if (!user) {
return done(null, false, {
message: "Email is not registered."
});
}
// Check if password matches the one found in the database (To Do: Encrypt this later!)
if (password != user.password) {
return done(null, false, { message: 'Password is incorrect.' });
} else {
return done(null, user);
}
})
.catch(err =>{
console.log(err));
return done(null, false, { message: 'Internal Server error.' });
}
})
Fixed the hanging issue. It was indeed something wrong with the way I wrote passport.js as the code works more for MongoDB rather than MySQL.
Here is the new working passport.js:
module.exports = function(passport) {
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
connection.query("select * from users where id = "+id,function(err,rows){
done(err, rows[0]);
});
});
passport.use(new LocalStrategy({
usernameField : 'email',
passwordField : 'password',
passReqToCallback : true // allows pass back of entire request to the callback
},
function(req, email, password, done) { // callback with email and password from form
// Match User
connection.query("SELECT * FROM `users` WHERE `email` = '" + email + "'",function(err,rows){
if (err)
return done(err);
// Check if Email exists in database
if (!rows.length) {
return done(null, false, { message: 'Email is not registered' });
}
// Check if password matches the one found in the database (To Do: Encrypt this later!)
if (!( rows[0].password == password))
return done(null, false, { message: 'Password is incorrect.' });
// All is well, return successful user
return done(null, rows[0]);
});
}));
};

Passport Authenticate doesn't redirect

I was writing a local-signup strategy and noticed that it doesn't work so I stepped back and tried to authenticate against my empty collection. Every time I submit the form it takes ~30-40s until it results in a timeout. I ensured passport.authenticate() is called but it seems ike it's not doing any redirects and hence it is timing out because I am not rendering something either.
Questions:
I expected that it would do a redirect to the failureUrl (which is '/signup'), but instead nothing is happening. What am I doing wrong here?
Why there is no single log message coming from passport? This is driving me crazy because I have absolutely no idea what is going wrong there.
I am new to node.js and as far as I got I don't need to pass the configured passport object to the router but instead I can just do const passport = require('passport') is that correct?
This is my function handler for the /signup route:
function processSignup (req, res) {
logger.info("POST request received")
logger.info(req.body)
passport.authenticate('local', {
successRedirect : '/profile', // redirect to the secure profile section
failureRedirect : '/signup', // redirect back to the signup page if there is an error
failureFlash : true // allow flash messages
})
}
Winston prints:
7:32:04 PM - info: POST request received 7:32:04 PM - info:
username=dassd#dass.de, password=dasdsa, submit=Register
My passport.js file looks like this:
const LocalStrategy = require('passport-local').Strategy
const User = require('./user-model')
const passport = require('passport')
// expose this function to our app using module.exports
function config() {
passport.serializeUser(function(user, done) {
done(null, user.id)
})
// used to deserialize the user
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user)
})
})
passport.use(new LocalStrategy(
function(username, 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);
});
}
));
}
module.exports = {
config: config
}
The relevant snipped of my app.js:
// required for passport
require('./authentication/passport').config();
app.use(cookieParser())
app.use(bodyParser())
app.use(session({
secret: 'secretToBeChanged',
saveUninitialized: false,
resave: false
}))
app.use(passport.initialize())
app.use(passport.session()) // persistent login sessions
app.use(flash()) // use connect-flash for flash messages stored in session
After a quick look at the documentation for passportjs, I think you need to do something like this:
function processSignup (req, res, next) {
logger.info("POST request received")
logger.info(req.body)
const handler = passport.authenticate('local', {
successRedirect : '/profile', // redirect to the secure profile section
failureRedirect : '/signup', // redirect back to the signup page if there is an error
failureFlash : true // allow flash messages
});
handler(req, res, next);
}
passport.authenticate() returns a function that is meant to be used as the route handler function.
Normally, you would type something like:
app.post('/login', passport.authenticate('local', {
successRedirect: '/',
failureRedirect: '/login',
failureFlash: true
}));
But since you have abstracted with your own route handler function, you need to invoke the one returned from passport.authenticate().
In the end Mikael Lennholm was right and he pointed me into the right direction. I couldn't find that in any passport.js tutorials. However the passport.js documentation contains this code snippet which represents the same but I prefer it's code style:
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); }
return res.redirect('/users/' + user.username);
});
})(req, res, next);

Express + Passport - req.session.passport undefined on subsequent requests

I have started developing little project where I have React with Redux on the client side, and the backend is being done with Node, Express and Passport.js
I will try to describe best What I am struggling with for some hours.
after authentication, when user is being send from server to client, field req.session.passport is set, along with req.user. but when i do next request, no matter is it logout or for example /something/add these fields are undefined.
when authenticating, serializeUser is being called, but deserializeUser not and i dont think it should here, maybe im wrong. as far as I went into debugging the problem, req.login is being called too.
on the next requests it seems that passport isnt doing anything, and i'm out of ideas and anwsers from SO and google. i didnt try the custom callback.
req.session just before sending anwser to client looks like:
Session {
cookie:
{ path: '/',
_expires: 2017-01-11T02:31:49.235Z,
originalMaxAge: 14400000,
httpOnly: false,
secure: false } }
the code on the server side is:
passport.serializeUser(function(user, done) {
done(null, user._id);
});
passport.deserializeUser(function(id, done) {
global.Models.User.findById(id, function(err, user) {
done(err, user);
});
});
passport.use(new LocalStrategy(
{
usernameField: 'login',
passwordField: 'password',
passReqToCallback: true
},
function(req, login, password, done) {
global.Models.User.logIn({login: login, password: password}, function(err, user){
if(err){
done(err);
}
else{
done(null, user);
}
});
}
));
var app = express();
var router = express.Router();
router.use(cookieParser());
router.use(bodyParser.urlencoded({extended: false}));
router.use(bodyParser.json());
router.use(session({
cookie : {
secure : false,
maxAge : (4 * 60 * 60 * 1000),
httpOnly: false
},
secret: this._config.session.secret,
resave: false,
saveUninitialized: true
}));
router.use(passport.initialize());
router.use(passport.session());
require('./Router')();
app.use(router);
session object here is the express-session. code under is the Router.js required above
var User = require('../Models/User');
var News = require('../Models/News');
var passport = global.Application.getInstanceOf("passport");
function setRoutes(){
router.use(function (req, res, next) {
var log = global.Application.getInstanceOf("logger");
var clientIP = req.headers['x-forwarded-for'] ||
req.connection.remoteAddress ||
req.socket.remoteAddress ||
req.connection.socket.remoteAddress;
log.log("info", req.method + " request from ip: " + clientIP);
res.header('Access-Control-Allow-Origin', 'http://localhost:8080');
res.header('Access-Control-Allow-Credentials', true);
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,PATCH,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
if('OPTIONS' == req.method){
res.sendStatus(200);
}
else{
next();
}
});
router.get('/ping', function(req, res){
res.send('ping');
});
router.get('/login/:login', (req, res) => {
Database.client.query(Database.queries.USER_LOGIN, {login: req.params.login}, {useArray: true},
(err, rows) => {
if(err){
res.send({error: "ERROR_DATABASE"});
}
else{
res.send(rows[0][0]);
}
});
});
router.post('/login', passport.authenticate('local', {session: true}),
function(req, res){
console.log(req.session);
req.session.save();
res.send(req.user);
}
);
router.post('/register', (req, res) => {
User.create(req.body, (err, result) => {
if(err){
res.send({error: "ERROR_DATABASE"});
}
res.send(result);
});
});
router.get('/logout', function(req, res){
console.log(req.session);
req.logout();
res.sendStatus(200);
});
router.post('/cms/article', isAuthenticated, (req, res) => {
res.send("BLA");
});
function isAuthenticated(req, res, next){
console.log(req.user);
console.log(req.session);
console.log(req.session.passport);
if(req.isAuthenticated()){
next();
}
else{
res.send("OK");
}
}
}
module.exports = setRoutes;
I have solved the problem.
Explanation:
Cookie was being sent by express to client, but it wasn't saved. For that, it needed change from using $.post to $.ajax with xhrFields option set to {withCredentials: true}.
Aside from that, the problem could also be that, that cookieParser probably need to know cookie secret too now.

Persistent Login with Passport.js no longer working. isAuthenticated returns false

I had this code working at some point and must have lost it in a careless save at some point. I am trying to achieve persistent login with passport but it does not seem to be doing that as I am getting false on the isAuthentiacted middleware.
Here is my primary server.js setup, as you can see the order is good. But I am not sure about the cookie settings as I'm new to this whole thing.
app.use(cookieParser('S3CRE7'));
app.use(bodyParser.json());
app.use(session({ key: 'express.sid', resave: false, saveUninitialized: false, maxAge: 3000}));
app.use(passport.initialize());
app.use(passport.session());
app.use('/users/', usersRouter);
app.use('/transcriptions', transRouter);
app.use(express.static('public'));
const basicStrategy = new BasicStrategy(function(username, password, callback) {
let user;
User
.findOne({username: username})
.exec()
.then(_user => {
user = _user;
if (!user) {
return callback(null, false, {message: 'Incorrect username'});
}
return user.validatePassword(password);
})
.then(isValid => {
if (!isValid) {
return callback(null, false, {message: 'Incorrect password'});
}
else {
return callback(null, user)
}
});
});
passport.use(basicStrategy);
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
Here is my initial Log In endpoint with custom callback function, which logs in just fine, as well as stores a cookie on the client side
router.post('/login', function(req, res, next) {
passport.authenticate('basic', function (err, account) {
req.logIn(account, function() {
res.status(err ? 500 : 200).send(err ? err : account);
});
})(req, res, next)
});
isAuthenticated function:
const isAuthenticated = function (req, res, next) {
if (req.isAuthenticated())
return next();
console.log('not authenticated');
}
First lines of where the authentication fails:
router.get('/', isAuthenticated,
(req, res) => {
console.log(req);
});

Categories

Resources