Giter Site home page Giter Site logo

Comments (2)

abdollahkahne avatar abdollahkahne commented on July 23, 2024

Screenshot from 2021-02-26 03-23-50

from get-programming-with-nodejs.

abdollahkahne avatar abdollahkahne commented on July 23, 2024

Of course this not the best solution for getting API in browser. It is better to use both of the Auth method where it is needed:

  • in browser or other client with session support use the passport session
  • in curl and other client that doesnt support use of passport session and doesn't recognize req.isAuthenticated() function use the JWT for authentication. for this purpose only needs to change the verifyJWTToken with a littele line as follows:
verifyJWT:(req,res,next)=>{
       //this is the only change
        if (req.isAuthenticated()) {return next();}
        //end of change
        let jwt=req.headers.token;
        if (jwt) {
            JWT.verify(jwt,jwtSecret,(err,payload)=>{
                if (payload) {
                    User.findById(payload.data)
                    .then(user=>{
                        if (user) {
                            next();
                        } else {
                            res.status(statusCodes.CONFLICT)
                            .json({
                                status:statusCodes.CONFLICT,
                                success:false,
                                message:"Please Login and Try again!"
                            });
                        }
                    })
                    .catch(err=>{
                        res.status(statusCodes.INTERNAL_SERVER_ERROR)
                        .json({
                            status:statusCodes.INTERNAL_SERVER_ERROR,
                            success:false,
                            message:err.message
                        });
                    })
                } else {
                    res.status(statusCodes.UNAUTHORIZED)
                    .json({
                        status:statusCodes.UNAUTHORIZED,
                        success:false,
                        message:"Attached Token is Invalid"
                    });
                }
            });
        } else {
            res.status(statusCodes.UNAUTHORIZED)
            .json({
                status:statusCodes.UNAUTHORIZED,
                success:false,
                message:"You should provide a valid token"
            });
        }
    }

And do not forget to return apiAuthenticate action to its original state as follows:

apiAuthenticate:(req,res,next)=>{
        passport.authenticate("local",(err,user)=>{
            if (user) {
                let signedToken=JWT.sign({
                    data:user._id,
                    exp:(new Date()).setDate((new Date()).getDate()+1)
                },jwtSecret);
                res.status(statusCodes.OK);
                return res.json({
                    status:statusCodes.OK,
                    success:true,
                    token:signedToken
                })
            } else {
                res.status(statusCodes.UNAUTHORIZED);
                return res.json({
                    status:statusCodes.UNAUTHORIZED,
                    success:false,
                    message:"Couldn't Authenticate User!"
                });
                
            }
        })(req,res,next);
    },

with this change in place there is no need to apply token in Client Side Javascripts (AJAX Calls) and they should be as it be at the last lesson as follows:


$(function() {
    $("#modal-button").on('click',function() {
        // $("#myModal .modal-body").load("/courses?format=json");
        $("#myModal .modal-body").html('');
        $.get("/_api/courses",(result)=>{
            result.data.forEach(course => {
                $("#myModal .modal-body").append(
                    `<div class="course">
                        <span class="course-title">
                            ${course.title}
                        </span>

                        <button class="${'button'+" "+(course.isJoined?'joined-button':'join-button')}" data-id="${course._id}" >${course.isJoined?"Leave":"Join"}</button>
                        <div class="course-description">
                            ${course.description}
                        </div>
                       
                    </div>
                    `
                );
            });
        })
        .then(()=>{
            addJoinButtonListenerDynamic();
        });
    });
    
})

//this dynamicly set event when needed and can do without the content of modal
let addJoinButtonListenerDynamic=()=>{
    $("#myModal").on("click","button.join-button",function(event) {
        // let $button=$(event.target);
        let $button=$(this);
        let courseId=$button.data("id");
        debugger;
        $.get(`/_api/courses/${courseId}/join`,data=>{
            if (data.success) {
                $button.text("Joined")
                .addClass("joined-button")
                .removeClass("join-button");
            } else {
                $button.text("Try Again");
            }
        });
    });
    $("#myModal").on("click","button.joined-button",function(event) {
        // let $button=$(event.target);
        let $button=$(this);
        let courseId=$button.data("id");
        debugger;
        $.get(`/_api/courses/${courseId}/leave`,data=>{
            if (data.success) {
                $button.text("Join")
                .addClass("join-button")
                .removeClass("joined-button");
            } else {
                $button.text("Try Again");
            }
        });
    });
}
//This should do after setting the content in modal to find buttons
let addJoinButtonListener=()=>{
    $(".join-button").click(event => {
        let $button = $(event.target),
          courseId = $button.data("id");
          debugger;
        $.get(`/_api/courses/${courseId}/join`, (data) => {
          if (data.success) {
            $button
              .text("Joined")
              .addClass("joined-button")
              .removeClass("join-button");
          } else {
            $button.text("Try again");
          }
        });
      });
}

now code works like a charm!

from get-programming-with-nodejs.

Related Issues (14)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.