Search code examples
node.jsmongoosepassport.js

I want to authenticate my comment section of my blog in node js


I have my comment section below a post. The only thing I want to know that how to authenticate the comment page. For example, in reddit unless you login you won't be able to comment right? so how to make that? what steps should I follow? And yeah I know how to authenticate, I am using passport js for authentication. I am able to block contents of my page and all that stuff but only having problem with the comment part.


Solution

  • Upon receiving request to fetch the post and the comments related to it, check to see if the user has sent the token in request headers. you can use simple if-else block to this. if you are using sessions, check to see if the user has an active session. So if these conditions are met, query comment documents and return them in response, else just return the post.

    in frontend if the response received from server does not have comments, are comments are null (it really depends on how you send the response) then just show a message saying that User must sign in

    Edit 1

    in express in request object there are headers and you can send token in these headers and access it like this:

    request.headers['your-token-name']
    

    after that you have the validate the token and grant or refuse access to contents.

    Now suppose the access is granted and decoded, token is saved in request object for example in variable named decoded. Now

    route.get('/:postId?', async(req, res, next)=>{
    
    //place the validate you postId format
    
    try {
     
        const post = await Posts.findOne({postId:req.params.postId})
        if(!post)
            return res.json({success:false, message:'Post not found'})
    
        if(req.decoded !== undefined || req.decoded !== null){
            const comments = await Comments.find({/*Your condition*/ })
            return res.json({success:true, comments: comments, post:post})
        }else{
            return res.json({success:true, message:'Login to view the comments', post:post})
        }
    
    
    
    } catch (error) {
        next(error)
    }})
    

    This is very simple code to just get simple idea of how it works in express backend. Now you also have to write a middleware to validate token.

    In this case if token is sent then validate it. if it is valid grant access else return access denied. Something like this

    App.use(async (Request,Response,Next)=>{
    try {
        let sentToken = Request.headers['access-token'];
        if(sentToken !== undefined && sentToken !== null){
            Request.decoded = await verify(sentToken,'your secret key');
            if(!isTokenValid(Request.decoded))
                return Response.status(403).send({success:false, message:'Please Sign Up or login to continue'});
        }
        await Next();
    } catch (error) {
        return Next(error);
    }});