How to add security on my node.js web pages? - node.js

Beginner NodeJs here.
I have created a registration and login page using nodejs and mysql.
It is just a basic setup wherein:
I have a form which submit to nodejs to register (will add a row in mysql database with email and password) and login/authenticate (which will just do a lookup in mysql and search for equivalent email and password).
I can register and login no problem.
The steps I followed are from here:
http://www.expertphp.in/article/user-login-and-registration-using-nodejs-and-mysql-with-example
I have also edited the code a little that if It login successfully, it will redirect to a page via this code..
if (password==results[0].password){
// res.json({
// status:true,
// message: 'successfully authenticated'
// });
var sample = req.body.email;
var newsample = sample.split('#')[0];
return res.redirect('/users/1/?username=' + newsample);
and I also have this route in my users.js
router.get('/1/*', function(req, res, next) {
var q = url.parse(req.url, true).query;
var txt = "Welcome" + q.username;
res.send(txt);
});
it works fine.
What I want to accomplish is that, I can only access the link
http://localhost:3000/users/1/?username=*
if I came from the login page and have authenticated.
Hope you can guide me on how to do about it or a hint on how it is done.
I have search but only found links which uses a different library or authentication which i find hard to understand. Pardon my being noob.
A working example would be very helpful for me.
Thank you.

I think you handle user authentication in a hard way, you can use passport.js it will help you a lot
but you can use the session to save what is necessary to check if the user is logged in like user id and check this session in a custom middleware

Related

Get token from activation url sended from server

I'm newbie to coding login systems and now I'm coding an account activation logic after registration.
I'm sending an email to the registered user with an url like this:
127.0.0.1:3000/activate/(token here)
And I'm handling it on server side when user access to that url on this way:
app.get('/activate', ( req, res) => {
res.sendFile( __dirname + '/public/activation.html')
})
But of course there's not a handler for every unique token so I need a way to access to enter on that app.get... /activate but kinda ignoring the second part where the token is so the file is served but keeping this token in a variable to operate with it later on it's inside logic.
How can achieve it? Am I totally wrong on my approach?
Thanks in advance.
You can use dynamic link
app.get("/activation/:token",(req,res,next)=>{
const token = req.params.token;
//don't use token directly in sql database
});

ExpressJS redirect user with data without EJS

I want to create a login system, using Node JS and ExpressJS. The user types their credentials, then the server checks these to see if they are valid. If they are valid, the server will redirect the user the home page and send along data, including the user's credentials (for further use). This is RESTful.
const app = require("express")();
const bodyParser = require('body-parser');
app.get("/login", function(req, res)
{
res.sendFile(__dirname + "/front-end/login.html");
});
app.post("/login",function(req, res)
{
var username = req.body.username;
var password = req.body.password;
//returns whether the credentials work
var credentialsPassed = checkCredentials(username,password);
if(credentialsPassed)
{
//redirect to home-page and pass along the user's credentials for further use
}
});
I already read How do I redirect in expressjs while passing some context?. The answer sends data in the url. However, I need to send the user's credentials, so it would be insecure to pass it in the URL. The other alternative is to use EJS (or something similar), but I would have to download a pretty big module just for this 1 task.
Is there any better way?
If you don't want the data to be passed in the URL you can add it to req.users or res.locals/req.locals.Definition:
[req.locals vs. res.locals vs. res.data vs. req.data vs. app.locals in Express middleware
Also in the link you passed they said you could save that data in req.session maybe that is the best way to solve your problem

how to give user specific file access in express js

I'm using express js and passport js as authentication system also using view engine. I'm looking for a solution that would give access to user and let users see their file, not the other one's file. for example, in the image folder, the user would access to their files and after that, I want to pass these files to view engine. If I use the public folder, anyone is able to see every file in there. what solution do you recommend?
You should create a directory for each users.
then, for example, your URL is /show/files
the inside your logic, filter the directory by user info.
app.get('/show/files', (req,res)=>{
// filter resources by user info
})
don't forget to create a secure URL for your resources.
Bad Idea: /images/amin/profile.png
Good Idea:
create a route to serve your resources.
app.get('/resources', (req,res)=>{
// add query parameter for resource for example profile.png
// then check user directory and send it
})
your url converts into
/resousrce?file=profile.png
I assume you already have a login system in place, so all you have to do, is create a middleware that checks if the user is logged in, and checks if the image is his image.
app.use("/user/:user/**",function(req,res){
if (req.params.user == thisuser){
//serve the file
} else {
res.status(403); //access denied
res.end();
}
//check based on cookies whether the user has the permission to view this image
});
I would suggest you to use Passport.Js local authentication. You can look into the official docs - http://www.passportjs.org/docs/authenticate/ I personally have used this in the same scenario you're in.
Here is a litte code snippet of the custom middleware function I wrote using passport -
module.exports = {
ensureAuthenticated : function(req, res, next){
if(req.isAuthenticated()){
return next();
}
req.flash('error_msg', 'Please login to view this resource.')
res.redirect('/users/login');
}
}
Feel free to check the entire solution on my github repo -
https://github.com/StechAnurag/loginsys

How should I structure user login and others in this website I am working on? Please see description

I apologize if the question is not too clear.
As a background, I am working with ExpressJS and MongoDB (with mongoose etc). Also, I am a bit familiar with the topic, but I would like to do this the right way. I also use Handlebars as a view engine.
What I am trying to get at is, how do make it so that the server knows that a user is logged in and sends the right page, navigation bar, and other things?
I worked on a hackathon where I did something like this. Basically, it worked like this. When a user created an account, their informations were saved in a database. Inside the index js, I would check if the password and all matched (they were encrypted with Passport), then it they do, send the page with a parameter logged = true. If they weren't logged in, I would send the page with logged = false. Here's an example for logged out:
router.get('/', function(req, res, next) {
res.render('index', {title:'randomtitle', logged=false});
});
An example for logged in:
router.get('/', function(req, res, next) {
// code checks for cookies. Results shows that user exists. So we send this. we also find the username saved in the variable "someuser"
res.render('index', {title:'randomtitle', logged=true, username: someuser});
});
Then, the handlebars page will check if the user is logged in. For example:
<body>
{{if logged}}
<li> Hello {{username}}! </li>
{{else}}
<li> LOGIN </li>
{{/if}}
</body>
Hopefully, that makes sense. But I think that's a very sketchy approach of doing this! How do professional websites do it? Is there somewhere I can find examples for this?
Also, when I create initialize a server with express for example, it creates 2 routes automatically: index.js and user.js. What is the user.js for?
If anyone knows how it works in general (not specific to Node or Express), also please let me know.
A lot of people use passportjs.org for authentication in express. You have a lot of work to do. basically you can save user info from frontend form (html) to the database with get and post requests then add user info to session. This way at your routes you know who is authenticated. You could send the session to the front end template.
you could check to see if the user object is in the session and if it is that means they are logged in.
passportjs helps out with this a lot.
you could do req.session.logged = true

Express JS routing based authentication

I have created node js app using express framework.
I have created middleware for restricting access to some routes.
Middleware actually works fine. but i have difficulties in displaying data.
Suppose In My app i have created route for display list of countries('/country/master')i.e html page which is using internally different/default route ('/country/') to get data from mongoDB.
In this case user will not able to see data cause i have not given permission to "/" routes. but i want to display data but not allow him to make use of "/" route to check data.
How can i deal with this case ????
The answer depends on your authentication strategy i.e. are you using session identifiers, access tokens, etc.
In either case I suggest that you break out the credential exchange (aka login) from the authentication. They should be separate middleware functions. Below is an example of what this looks like.
While this answers your question, specific to ExpressJS, it does leave out a lot of other details that matter when you are building an authentication system (like how to securely store passwords). I work at Stormpath, we provide user management as an API so that you don't have to worry about all the security details! It's very easy to integrate our API into your application, using the express-stormpath module. You'll have a fully featured user database in minutes, without having to setup mongo or a user table.
All that said, here's the example:
/* pseudo example of building your own authentication middleware */
function usernamePasswordExchange(req,res,next){
var username = req.body.username;
var password = req.body.password;
callToAuthService(username,password,function(err,user){
if(err){
next(err); // bad password, user doesn’t exist, etc
}else{
/*
this part depends on your application. do you use
sessions or access tokens? you need to send the user
something that they can use for authentication on
subsequent requests
*/
res.end(/* send something */);
}
});
}
function authenticate(req,res,next){
/*
read the cookie, access token, etc.
verify that it is legit and then find
the user that it’s associated with
*/
validateRequestAndGetUser(req,function(err,user){
if(err){
next(err); // session expired, tampered, revoked
}else{
req.user = user;
next();
}
});
}
app.post('/login',usernamePasswordExchange);
app.get('/protected-resource',authenticate,function(req,res,next){
/*
If we are here we know the user is authenticated and we
can know who the user is by referencing req.user
*/
});
You can positioning of middleware in you app.for example:-
app.get('/country/master',function(req,res){
})
app.use(function(req,res){
your middle ware for providing authentication
})
// other routes where authentication should be enabled
app.get('other urls')

Resources