localStorage won't store data - javascript

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');
}
});
});

Related

How to save JavaScript sessionStorage to django

I have an Sdk to call which returns an applicationID that I need to store in my django application so that if the user is approved, then he can move to the next page. I am trying to save in JS sessionStorage than pass the data to another html page where I'm using ajax to pass it to my django views. The problem is that I need to have this data unique for the user that is logged in.
How can I link this data to the current user logged in and so on?
const widget = window.getidWebSdk.init({
apiUrl: '',
sdkKey: '',
containerId: "targetContainer",
flowName: '',
onComplete: (data) => {
console.log(JSON.stringify(data))
let appId = data;
console.log(data)
sessionStorage.setItem("appId", JSON.stringify(appId))
window.location.href = "/kycsubmit";
return;
},
onFail: ({ code, message}) => { console.log("something went wrong: " + message )},
});
second html page:
let application = JSON.parse(sessionStorage.getItem("appId"));
let kycStatus = application.applicationId
$.ajax({
type: "GET",
dataType: "json",
url: `api/application/${kycStatus}`,
headers: {
'Content-Type': 'application/json',
'X-API-Key': '',
},
success: function(data) {
document.getElementById("test").innerHTML = data.overallResult.status
document.getElementById("test-1").innerHTML = application.applicationId
console.log(data.overallResult.status)
}
})

Calling Outlook API to Add event to outlook calendar using ajax call

I need to Add an event from my database to outlook calendar for which I have been trying to make an ajax call to the outlook auth API first which looks like this
$scope.authorizeOutlook = function () {
let redirect = 'http://localhost:51419';
let clientId = 'xxx';
var authData = 'client_id=' + clientId + '&response_type=code&redirect_uri=' + redirect + '&response_mode=query&scope=https%3A%2F%2Fgraph.microsoft.com%2Fcalendars.readwrite%20&state=12345';
debugger
$.ajax({
url: 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize',
type: 'POST',
host: 'https://login.microsoftonline.com',
contentType: "application/x-www-form-urlencoded",
contentLength: "600",
data: authData,
success: function (response) {
debugger;
alert(response.status);
//alert("success");
},
error: function (response) {
alert(response.status);
//alert("fail");
}
});
}
But I am getting response status as 0. What does that mean? Where am I doing it wrong?
If you use Oauth2.0, you need to add " token-type: Bearer ".
Reference from:
Get access tokens to call Microsoft Graph

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),

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.

CORS error when trying to post message

I have an AngularJS Application I am trying to post a message through. I am successfully able to log the user in, get the access token, and I have ensured I have my domain in the JavaScript Origins within Yammer.
Whenever I try to post a message, however, I get the following error:
The strange thing is when it does the preflight it seems OK but as the error states I can't figure out why it isn't coming back in the CORS header as I have it registered within the Yammer Client area.
Here is the code for posting:
$scope.YammerPost = function (Yammer) {
var _token = Yammer.access_token.token;
var config = {
headers: {
'Authorization': 'Bearer ' + _token
}
};
$http.post('https://api.yammer.com/api/v1/messages.json', { body: 'blah blah', group_id: XXXXXXX }, config);
}
I call that scope variable in the view via a button click.
Here is the logic I use to sign the user in:
function checkYammerLogin() {
$scope.Yammer = {};
yam.getLoginStatus(
function (response) {
if (response.authResponse) {
$scope.Yammer = response;
console.dir(response); //print user information to the console
}
else {
yam.platform.login(function (response) {
if (response.authResponse) {
$scope.Yammer = response;
console.dir(response);
}
});
}
}
);
}
I ended up finding the issue.
For some odd reason, every time I would try to use an $http post it would include an Auth token from AD (app using Azure AD for authentication).
I ended up using jQuery inside of my Angular scope function on the button click and it works as I can control the headers for the request.
$.ajax({
url: 'https://api.yammer.com/api/v1/messages.json',
type: 'post',
data: {
body: 'this is a test from jQuery using AngularJS',
group_id: <group_id>
},
headers: {
'Authorization': _token
},
dataType: 'json',
success: function (data) {
console.info(data);
}
});
Fixed the issue and I can now post.
If anyone sees any issues with this practice please let me know, still a little new to angular

Categories

Resources