I need to update/Refresh my JSON Web Token - javascript

I need to update/refresh my JSON web token. I have a value of hasPaid that is created and stored inside of my JWT. It works successfully when I login. Because that is when the JWT is created. However, when I pay inside of the application; the JWT isn't updated to reflect that I have paid. And the JWT is reading this data from the database. So i need the JWT to update or refresh and reflect this change.
Here is where my JWT is created:
userSchema.methods.generateJwt = function() {
console.log("I'm creating a JSON WebToken");
console.log(this.hasPaid);
var expiry = new Date();
expiry.setDate(expiry.getDate() + 7);
return jwt.sign({
_id: this._id,
email: this.email,
name: this.name,
hasPaid : this.hasPaid,
exp: parseInt(expiry.getTime() / 1000),
}, "MY_SECRET"); // DO NOT KEEP YOUR SECRET IN THE CODE!
};
Here is my AJAX request where I make the payment. I need it update here:
$.ajax({
url: 'http://localhost:8082/charge',
type: 'POST',
data: {
stripeToken: response.id,
currentUser: user
},
complete: function(response, state, e) {
window.location.assign("video");
return e.localStorage["token"]; // on success of ajax post update JWT
}
});

Related

localStorage won't store data

I have a demo of a simple Login and Logout application with access token. If the user haven't login yet and they try to access other page, which mean access token is null, they will be direct back to Login page. I use sessionStorage to store user token and it work fine. When I try using localStorage, my application won't work anymore. It still login in but for an instance moment, it direct me back to the Login page like my token isn't saved at all. It still generate new token after successfully login so I guess it having something to do with localStorage.
Edit: I just checked back and they both storage my token but I can't parse it to other pages with localStorage.
My Login Page Code:
$('#btnLogin').click(function () {
$.ajax({
url: '/token',
method: 'POST',
contentType: 'application/json',
data: {
userName: $('#txtFullname').val(),
password: $('#txtPassword').val(),
grant_type: 'password'
},
// Khi đăng nhập thành công, lưu token vào sessionStorage
success: function (response) {
//sessionStorage.setItem("accessToken", response.access_token);
localStorage.setItem("accessToken", response.access_token);
window.location.href = "User.html";
//$('#divErrorText').text(JSON.stringify(response));
//$('#divError').show('fade');
},
// Display errors if any in the Bootstrap alert <div>
error: function (jqXHR) {
$('#divErrorText').text(jqXHR.responseText);
$('#divError').show('fade');
}
});
});
Other page base code:
if (localStorage.getItem('accessToken') == null) {
window.location.href = "Login.html";
}
Are you sure that response.access_token does not come null?
You can check it from the development tools in Chrome (Windows: Ctrl + Shift + i or macOs: command + option + i)> Application > Storage > Local Storage:
As you can see the value can be set null.
I hope it helps.
localStorage supports only string values. Chances are response.access_token might not be a string value. So try this instead:
localStorage.setItem("accessToken", JSON.stringify(response.access_token));
And While retrieving,
JSON.parse(localStorage.getItem("accessToken"))
Try to save object in localstorage use following method (as shown in https://stackoverflow.com/a/2010948)
var testObject = { 'one': 1, 'two': 2, 'three': 3 };
// Put the object into storage
localStorage.setItem('testObject', JSON.stringify(testObject));
// Retrieve the object from storage
var retrievedObject = localStorage.getItem('testObject');
console.log('retrievedObject: ', JSON.parse(retrievedObject));
And in your code we can do it like this
$('#btnLogin').click(function () {
$.ajax({
url: '/token',
method: 'POST',
contentType: 'application/json',
data: {
userName: $('#txtFullname').val(),
password: $('#txtPassword').val(),
grant_type: 'password'
},
// Khi đăng nhập thành công, lưu token vào sessionStorage
success: function (response) {
var obj= { 'accessToken': response.access_token};
localStorage.setItem(JSON.stringify(obj));
window.location.href = "User.html";
},
// Display errors if any in the Bootstrap alert <div>
error: function (jqXHR) {
$('#divErrorText').text(jqXHR.responseText);
$('#divError').show('fade');
}
});
});

Get hold of json content that is being sent to Jquery

That's how I reach when I send some values that are specified in my input and therefore they need to send to a API.
When I try to send them to the monkey, my monkey tells me that nothing has been sent.
At my console.log(token), it tells me what data is available and I also agree that it all fits together. But the problem is just that it has to come over to my API.
function PayStripe() {
// Open Checkout with further options:
handler.open({
name: 'XXX ',
description: 'XX abonnement',
currency: "dkk",
amount: $('#HiddenPrice').val() * 100,
email: $('#Email').val()
});
};
// Close Checkout on page navigation:
$(window).on('popstate', function () {
handler.close();
});
var handler = StripeCheckout.configure({
key: 'pk_test_xxxx',
locale: 'auto',
token: function (token) {
token.subscriptionId = $('#SubscriptionId').val();
token.City = $('#City').val();
token.Postnr = $('#Postnr').val();
token.Mobil = $('#Mobil').val();
token.Adresse = $('#Adresse').val();
token.CVRVirksomhed = $('#CVRVirksomhed').val();
console.log(token.subscriptionId);
console.log(token);
$.ajax({
type: "POST",
url: "/api/Stripe",
contentType: "application/json",
data: token,
success: function (data) {
//window.location.href = '/Subscriptions/Succes';
alert(data + "Succes")
},
error: function (data) {
console.log(data + "Error");
},
dataType: 'json'
});
// You can access the token ID with `token.id`.
// Get the token ID to your server-side code for use.
}
});
Where the problem lies is that the API is by no means able to get informed information from jquery. so it's like it can not / will receive it.
[HttpPost]
[Route("api/Stripe")]
[Produces("application/json")]
public async Task<IActionResult> Post([FromForm] JObject token)
When I grab the token that I need for example. then I do this here:
var SubscriptionId = (int)token.GetValue("subscriptionId");
When you set contentType: "application/json", you need to stringify the data to json yourself
data: JSON.stringify(token),

session data getting stored every time

Below is the API that basically stores data in session if not already present then returns an empty JSON, otherwise sends the session data stored corresponding to that mail:
app.use('/session', function(req, res) {
if (req.body.email in req.session) {
console.log("user data already available");
res.send(req.session[req.body.email]);
} else {
req.session[req.body.email] = {};
req.session[req.body.email]["email"] = req.body.email;
req.session[req.body.email]["gender"] = req.body.gender;
req.session[req.body.email]["dbname"] = req.body.dbname;
console.log("user session stored");
res.send({});
}
});
Below is the ajax call that I am making from my application. It is a cross domain call and I have set the response header accordingly.
$.ajax({
url: 'url/session',
type: "POST",
crossOrigin: true,
data: {
"email": "email",
"gender": "all",
"dbname": "dbname"
},
success: function(data) {
console.log("inside session api call success");
console.log(data)
}
});
});
Now the problem is that if I hit the API using postman, it works fine but when I use that in my application, it overwrites the session every time and returns empty json. What am I doing wrong?
edit : Figured out that each time ajax call is happening, past session data gets deleted for all emails ids.session value gets reset but still unable to figure out why this is happening.

How to set up session in vuejs django after successful login?

If login is successful i need to redirect to a login success page and I need to include a session in that.. How can it be possible. I am using html with vue js for front end and back end is django.
This is my vue js script for login.
<script>
logBox = new Vue({
el: "#logBox",
data: {
email : '',
password: '',
response: {
authentication : '',
}
},
methods: {
handelSubmit: function(e) {
var vm = this;
data = {};
data['email'] = this.email;
data['password'] = this.password;
$.ajax({
url: '/login/',
data: data,
type: "POST",
dataType: 'json',
success: function(e) {
if(e.status){
alert("Login Success");
// Redirect the user
window.location.href = "/loginsuccess/";
}
else {
vm.response = e;
alert("failed to login!");
}
}
});
return false;
}
},
});
</script>
So, how can I include session in login successpage.. This is the first time I am doing a work.. Please help me ..
If you are not doing a SPA, you can use the usual way of store sessions, put the session token in a cookie (the server is the responsible of doing when a successful login request happens). The next time the user do a request the cookie will send automatically to the server.
If you are doing a SPA, you can store the session token in the localStorage. In this case, you should configure the ajax calls to set a header with the token or any other way you prefer to send the token to the server.

Backbone Login Verification

I'm asking this question in part for a whole class. We are having a hard time getting a token for login. Also, if you guys don't mind, tells us how we can improve our question asking skills.
"I am trying to use my API to assign the account we are logging in as with a token. I've tried various things, but nothing really seems to work. What needs to be sent to the URL for the token to be generated looks like this:
{
"grant_type": "password",
"username": "user#example.com",
"password": "password"
}
Then we need to be able to receive the token so that we can do some things with that account. Could anybody push me in the right direction to accomplish this? Also want to add - do we need a model and collection for our token?
Our Goal is to be able to retrieve a token, so that after we create a user we can login into our app on the login page.
// User Model and Collection. Used to input user data.
var User = Backbone.Model.extend({
url: "https://twitterapii.herokuapp.com/users"
});
//Collection for when we GET data from API
var Users = Backbone.Collection.extend({
model: User,
url: "https://twitterapii.herokuapp.com/users",
parse: function(response) {
return response.data;
}
})
//Collection for when we GET data from API
var UsersTokens = Backbone.Collection.extend({
model: User,
url: "https://twitterapii.herokuapp.com/oauth/token",
parse: function(response) {
return response.data;
}
})
var signinView = Backbone.View.extend({
tagName: 'section',
template: _.template($('#signInTemplate').html()),
events: {
"click .signinButton": 'handleLoginClick'
},
send: function(){
var signin = this.$('.signinButton').val();
console.log("clicking!!");
var email = this.$(".email").val();
var password = this.$(".password").val();
logUser: UsersTokens.fetch( {
headers: {
grant_type: password,
username: email,
password: password
} });
},
render: function(){
this.$el.html(this.template());
},
handleLoginClick: function(){
event.preventDefault();
this.send();
console.log("login clicksss!!");
}
});

Categories

Resources