I finished my CRUD blog using nodejs + express.js but the only thing I need is everytime I go to 'post/:id/edit' or 'post/new' the browser ask for an admin user to continue with that request. This is to prevent that any user can create post in my blog.
How can I achieve that? I couldn't find anything about this. And I don't really need a CRUD for users because I will be the only one creating/editing post.
Thanks
As mentioned in the comment above, use passport.js to create the authentication part.
Once you do that, you will have to create a middleware to make sure the user have authorization do handle particular case. Since you are using Node.js and Express.js this part will be super easy.
Suppose user wants to create a post
router.get('/post/create',authenticate.ensureUser, function (req,
res) {}
authenticate.ensureUser: is middleware. Which will look like this :
> ensureUser: function(req,res,next){
> if(req.isAuthenticated()){
> return next() ;
> }else{
> req.flash('danger','Please login.');
> res.redirect('/login');
> }
> },
Related
Is there a way to protect the api route when a user enter that in the url? Please see my screen shot. I know there's a way to authenticate a user in the backend using a middleware but it seems like if the data can be viewed publicly, the JSON payloads can also be viewed publicly. I'm still new to this, so forgive me if this question has already been asked. I use Node.js, React, Express and Sequelize.
I'm assuming that you do not want your /api/users route to be accessible to the public, I think this solution should work, although there might be better solutions.
You can try protecting specific routes based on the role of the user. I suggest you add a user_role field to your user schema, and create a middleware function that only allows logged in users with a specific role to access the route, as shown in the pseudo code below:
function (req, res, next) {
// Check if user is logged in and is assigned the role you want to allow.
if(user is logged in) return next();
else throw error;
}
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
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
I am currently using node.js, express, and mongodb for an instagram app. I have found that many times I would like to know whether or not a user is already logged into instagram (be it through my app via the instagram-node authentication or through instagram's actual website).
Is there an easy way to do this?
I ended up using passport to solve this problem. Passport conveniently takes care of handling instagram authorization and they even include an example app to see how it all works. https://github.com/jaredhanson/passport-instagram/blob/master/examples/login/app.js
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) { return next(); }
res.redirect('/login')
}
Is especially useful since it can be placed at the top of your routing file and all the routes underneath it will first check to see if the user is authenticated.
Using express.js and everyauth with mongoose-auth, how can I create an external authentication route for an API I'm creating? I want to do this to authenticate a native iOS app against the user records in my MongoDB.
So for example, here's some semi-faux code:
app.post('/api/auth', function(req, res){
if(everyauth.authenticate(req.username, req.password)){
res.json({success:true});
}
});
So my question is, How do I utilize everyauth/mongoose-auth's authentication from outside of everyauth's typical methods and views?
Answering my own question after doing some more digging.
The following seems to work for my needs. It returns the user record if the authentication is successful. I'm just responding with a basic success true/false message for testing purposes. This assumes that User is the model that you used for mongoose-auth.
User.authenticate(req.body.email, req.body.password, function(err, userdoc){
if (userdoc){
res.json({success:true});
}
else {
res.json({success:false});
}
});