Changing sent HTML files using express? - node.js

I am trying to set up a basic login page using express, socket.io, and nodejs. I initially serve the client an index page using:
app.get('/', function (req, res) {
res.send(__dirname + '/index.html');
});
I have the logic for authentication set up. I need to know how to then route my user to the successful login page. I am having trouble understanding the way this middleware works, and any help would be appreciated.

Usually you need to check the req.user object, it will hold the current logged in user object, that is a good practice to fill this req.user if you are building your own auth layer, I'm not sure if you are doing that or not, but I would recommend using the very good passport npm package
So you can have something like:
app.get('/', function (req, res) {
if(req.user) { // user is logged in
res.send(__dirname + '/index.html');
}
else { // anonymous user
res.send(__dirname + '/login.html');
}
});

Related

Page displays 'null' after authentication

I'm creating a simple PWA to draw in multiple data sources into one application. I'm currently trying to set up authentication using a combination of passport and the twitter-strategy.
After the user has successfully authenticated they're account, twitter redirects to the callback endpoint, with the valid user data.... essentially the auth has been successful. However, when sending the user back to the client side application a html document with the word null is presented, rather than the application.
With the following code, I expect:
Twitter to return to callback URL
Server to perform actions in authSuccess function
Redirect to the provided url on the client
routes.js to server the application shell via the catch all route
Client application to boot and handle the URL served
Currently, only the first two steps are successful, and the app simply displays null (with the correct url in the address bar), rather than the expected output. Changing the location of the writeHead() call to / works, and the user is authenticated as expected ().
routes.js
let users = require('../controllers/userController');
app.get('/user/auth/twitter/callback',
passport.authenticate('twitter', {
failWithError: true
}),
function(req, res) {
console.log('[Twitter] Auth success route hit');
users.authSuccess(req, res);
},
function(err, req, res, next) {
console.log('[Twitter] Auth failure route hit');
users.authFailure(err, req, res, next);
}
);
app.get('*', function(req, res){
console.log('[Route] Catch All: ' + req.path);
res.sendFile(path.resolve(__dirname, '../../public/index.html'));
});
userController.js
authSuccess(req, res) {
console.log('[User Controller] User',req.user);
// Set some cookies here
res.writeHead(302, {'Location': '/user/profile'});
// res.redirect('/user/profile');
res.end();
}
Any help much appreciated. If you need more code, just ask :)
Thanks

NodeJS + Passport.js - no session stored?

I have a problem with sessions in my app. I'm trying to learn Passport.js based on this tutorial: http://www.sitepoint.com/local-authentication-using-passport-node-js/ . What I want to do is to allow the acccess for only authenticated users. The process of login works great, but when I check if the user is authenticated, it always says not. What could go wrong?
Here is the checking function:
if (req.isAuthenticated()) {
return next();
else {
res.redirect('/');
}
Here is the path from the router:
router.get('/secret', isAuthenticated, function(req, res) {
res.send('Welcome to the secret page');
});
I didn't find any domunentation about how to check if the session was established, where it is and so on.
Try this, taken from passport.js documentation.
app.get('/secret', passport.authenticate('local'), function(req, res) {
// If this function gets called, authentication was successful.
// `req.user` contains the authenticated user.
});
http://passportjs.org/guide/authenticate/

Session is UNDEFINED after redirecting to another page in ExpressJS

What I am trying to do is
-> use a logic form which posts to '/check_user'
-> check_user has logic to generate session and it creates the session perfectly
-> then it redirects to '/chat' which is restricted by verify() function
-> verify checks the session if persists (AT THIS POINT SESSION IS ALWAYS UNDEFINED FOR SOME REASON)
--> check_user does create session and it persists there but when redirected to '/chat' and hits verify, the session is lost.
Here is the code snippet I am using, I am not using any templating engines but plain HTML files. Any help is highly appreciated. Thanks!
app.use(express.static(__dirname + '/public'));
app.get('/login', function (req, res) {
res.sendfile(__dirname + '/public/index.html');
});
app.get('/chat', verify, function(req, res){
res.sendfile(__dirname + '/public/chat.html');
});
// when login form is posted to check_user, handle the username and passwords validation.
app.post('/check_user', function(req, res){
req.session.regenerate(function(){
req.session.user = "test";
//debugging codes debug code 1
console.log("3");
console.log(req.session.user);
//End debugging codes
res.redirect('/chat');
});
});
function verify(req, res, next) {
console.log(req.session.user);
if (req.session.user) {
console.log("1");//debug code 2
next();
} else {
console.log("2");//debug code 3
req.session.error = 'Access denied!';
res.redirect('/login');
}
};
Fixed! it. The problem was I was using res.render after ajax submit. I used window.location on ajax submit and it worked.
And another thing I found out is,
removing this closure made my session persistant throughout my application
req.session.regenerate(function(){
});

Parse.com redirect user depending on whether he's logged in or not (Express server)

I'm building a web app using Parse.com Express server and I'd like to redirect a user depending on whether he's logged in or not on the server side.
Is there an easy way to do this?
This is how I do it with Passport.js handling the session and loading the user for me.
If you are using another method, you may need to test something different than if(req.user).
function redirectIfAnon(req, res, next){
if(req.user){
return next(); // go to next handling function in middleware chain
} else {
var dest = encodeURIComponent(req.originalUrl);
res.redirect('/login?bounce='+dest)
// careful about redirect loops here... if you apply this middleware to /login,
// and an anonymous user visits /login, it will keep redirecting to /login
};
};
app.get('/test',
redirectIfAnon,
function(req, res){
// req.user is guranteed to be populated if we get here
parse.fetch(req.user.parseID, function(err...){
...
// or something. ive never used parse.com
res.render('parseResults');
})
});

accessing session variables in redirected file in node.js

I am building a crappy login system as a newbie. I have done this so far:
app.post("/verifyLogin",function(request,response){
var usr=request.body.username;
var pass=request.body.password;
userModel.find({$and:[{username:usr},{password:pass}]},function(err,user){
if(user.length==0)
{
response.redirect("/?msg=failed");
}
else
{
request.session.user=user;
response.redirect("/dashboard");
}
});
});
This works fine but after successful login i want to get the user details in the dashboard. I am clueless. Please shed some light.
EDIT
I have the following setup for dashboard in routes:
app.get("/dashboard",function(request,response){
response.sendfile('/lms/site/dashboard.html');
});
If you mean you want to pass the users' details to a template:
app.get('/dashboard', function(req, res) {
res.render('dashboard', {
user : req.session.user
});
});
This assumes a few things though:
you have a working templating setup;
you have a template called dashboard (with an extension matching your templating setup);
you're going to provide some sort of setup to make sure a user is logged in before they can open /dashboard.
EDIT: since you don't want to use templating, you could use AJAX to get the user details from the server into the client:
// server side
app.get('/userdata', function(req, res) {
// check if a user is logged in
...
// return the user details as JSON
res.send(req.session.user);
});
// client side (in 'dashboard.html', this assumes is will load jQuery)
$.getJSON('/userdata', function(user) {
// process user data, insert it into the DOM somewhere...
});
EDIT 2: to check if a user is logged in, you could create a middleware which would check for the existence of req.session.user and redirect to the login page if it's undefined:
var isLoggedIn = function(req, res, next) {
if (req.session && req.session.user)
next(); // user logged in, so pass
else
res.redirect('/'); // not logged in, redirect to login page
};
You would use the isLoggedIn middleware for all routes that require a user to be logged in:
app.get('/userdata', isLoggedIn, function(req, res) {
res.send(req.session.user);
});

Resources