Comments (2)
from get-programming-with-nodejs.
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)
- findByIdAndUpdate
- Pre Save Hook doesnt fire on updating password which is really unexpected!
- Express-Validator Middlewares: A clean and similar approach HOT 1
- Passport Local strategy from ground up (Lesson I learned and it is just for sharing) HOT 1
- Join To Course Issue:After Joining class Event should removed! (Lesson 27) HOT 1
- Add course.IsJoined Property in Other method (Lesson 27)
- Authentication in Socket.io and getting currentUser (Lesson 32)
- Using JWT to Authneticate Socket.IO An Have current user in Our codes
- MongoLab doesnt provide service for Heroku HOT 1
- Can't log in if the email contains a dot
- Tiresome Console Error from Express?
- solve Error: Failed to lookup view "index" in views directory
- solve: can't read static files in project unit 2 lesson 12
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from get-programming-with-nodejs.