I am using session storage to grab my access token generated on the end of my URL by Instagram when a user has authenticated. This isn't working for me on my localhost, please look at the pen I have created as an example of the output. http://codepen.io/anon/pen/eHGBf#access_token=12345.67890
Here is the code I am using:
var token = window.location.hash.substr(1).split("=");
var storeToken = token[1];
if (typeof(Storage) != 'undefined') {
sessionStorage.setItem('accessToken', storeToken);
document.getElementById('access_token').innerHTML = sessionStorage.getItem('accessToken');
} else {
document.getElementById('access_token').innerHTML = 'Sorry, your browser does not support Web Storage';
}
and to display the access token:
<div id="access_token"></div>
When I refresh the page on my localhost (without the access token in the URL) or navigate to other pages and back to the homepage where the token has been displayed in the ID, it returns 'undefined' and I have to log in again. I thought it should have saved the token?
Any help is greatly appreciated.
var token = window.location.hash.substr(1).split("=");
var storeToken = token[1];
if (storeToken) {
sessionStorage.setItem('accessToken', storeToken);
}
if (sessionStorage.getItem('accessToken')) {
document.getElementById('access_token').innerHTML = sessionStorage.getItem('accessToken');
}
Related
I'm not sure I'm even attempting the right thing. Heres my issue.
I'm loading data to a screen if the user is authenticated. Its a summary screen. I can click a item and it will send me to a new "details" page (window.location) . I'm passing the ID in the URL and then doing a GET request to get the details to display. When I implement my rules on the firebase DB, (".read": "auth != null"), I get a "401 Unauthorized" error in the console.
So somehow I need to either pass the user to the details.js or set Persistence somehow. Anyone have any suggestions?
THIS IS THE CODE FROM THE MAIN.JS
auth.onAuthStateChanged(user => {
console.log(user);
if (user) {
database.on('value', function(data) {
myData = data.val()
keys = Object.keys(myData)
buildProperties();
})
// tempBuild()
} else {
$('.eachProperty').empty()
$('.eachProperty').append($(`<h1>You must be signed in to view properties</h1>`))
}
})
$('body').on('click', '.singleProp', function() {
id = $(this).attr('id')
window.location = "/details.html?id=" + id
})
THIS IS THE CODE FROM THE DETAILS.JS
var myLocation = location.search.slice(4)
$.get(`https://XXXXXX.firebaseio.com/property/${myLocation}/.json`).then(myProperty)
function myProperty(prop) {
$('.propAddress').text(prop.address)
$('.zip').text(prop.zip)
if(prop.pictures){
for (var i = 0; i < prop.pictures.length; i++) {
var myImg = prop.pictures[i]
$('.imgContainer').append($(`<div class="eachPicDiv"><img src="${myImg}" alt="0" class="detailPic">
<ion-icon class="rBtn" name="arrow-redo-outline"></ion-icon>
</div`))
}
} else {
$('.imgContainer').append($(`<h1>THERE WERE NO PICTURES</h1>`))
}
}
You are using jQuery to fetch your data from Firebase Database,
$.get is a jQuery method, and for that to succeed you need to have some sort of auth token.
Firebase already provides best in class access, read more about access here.
Learn by example here.
I have a set of devices with device Id. On right clicking each device, it will pass device Id and open same page in multiple tabs(on each right click same page in new tab) with corresponding details of clicked device.
And here I have to keep a different token(random string variable) for each tab. And also token should not be changed on page refresh.
How can I do this ? I tried something but it's not working.
Created a random string, appended device Id to it and stored in local Storage as,
var prToken = window.localStorage.getItem('token');
if(prToken){
var subString = prToken.substring(10, prToken.length);
if(subString == GlobalVar.Inventory.device.id){
console.log(window.localStorage.getItem('token')+"====token");
}else{
var rString = GlobalVar.Inventory.randomString(10, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',GlobalVar.Inventory.device.id);
window.localStorage.setItem('token', rString);
}
}else{
var rString = GlobalVar.Inventory.randomString(10, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',GlobalVar.Inventory.device.id);
window.localStorage.setItem('token', rString);
}
here I am getting different token for each tab, but the problem is that, token is changing on page refresh.
Need help.
Solved myself, and it's working fine for me.
I
replaced 'token' variable with the device Id
. Then everything worked fine.
Then the code will be,
var prToken = window.localStorage.getItem(GlobalVar.Inventory.device.id);
if(prToken){
var subString = prToken.substring(10, prToken.length);
if(subString == GlobalVar.Inventory.device.id){
console.log(window.localStorage.getItem(GlobalVar.Inventory.device.id)+"====token");
}else{
var rString = GlobalVar.Inventory.randomString(10, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',GlobalVar.Inventory.device.id);
window.localStorage.setItem(GlobalVar.Inventory.device.id, rString);
}
}else{
var rString = GlobalVar.Inventory.randomString(10, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',GlobalVar.Inventory.device.id);
window.localStorage.setItem(GlobalVar.Inventory.device.id, rString);
}
I'm using javascript with drive + spreadsheet api. Now I am able to get the access token. But I tries a lot with stack answers and google guide for get refresh token request. But I did not found any way that how to access the refresh token by access token. Please help me with some code.
My script is:
var _url = https://accounts.google.com/o/oauth2/auth?scope=https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email&client_id={my_client_id}&client_secret={My_secret_key}","redirect_uri=httpmypath to currentrunningfile/oauth&response_type=token
function getAccessDetails() {
var win = window.open(_url, "windowname1", 'width=800, height=600');
var pollTimer = window.setInterval(function() {
try {
console.log(win.document.URL);
if (win.document.URL.indexOf(REDIRECT) != -1) {
window.clearInterval(pollTimer);
var url = win.document.URL;
console.log('url is :'+url);
acToken = gup(url, 'access_token');
tokenType = gup(url, 'token_type');
expiresIn = gup(url, 'expires_in');
console.log('acToken :' + acToken + 'tokenType :' + tokenType + 'expiresIn :' + expiresIn);
win.close();
validateToken(acToken);
}
} catch(e) {
}
}, 500);
}
What is the next step and how to code it for access the refresh token? Actully I want user to login first time to app with their google login details for their drive files access by my app. The next time when user use my app to access his drive files. He can access files without login.
I have made a register form, from where data is getting stored into the local storage. Only after user logs in successfully, it redirects to success.html or else takes user back to the login page. I have added the following script at the head of success.html-
<script>
if (localStorage.getItem('status') != null)
{
//redirect to page
window.location.href = "success.html";
}
else
{
//show validation message
window.location.href = "login.html"
}
</script>
and following is my login validation function-
//Storing data from local storage into an array of objects
var usersdata = JSON.parse( localStorage.getItem('key_users' ) );
function loginvalidate()
{
usersdata = JSON.parse( localStorage.getItem('key_users' ) );
var usernameinput = document.getElementById("username");
var passwordinput = document.getElementById("password");
for(var p in usersdata)
{
console.log(p+':'+usersdata[p].username+'|'+usersdata[p].email);
if(usernameinput==usersdata[p].username && passwordinput==usersdata[p].password)
{
alert("Logged in successfully");
}
}
jQuery(window).load(function() {
localStorage.setItem('status','loggedIn')
});
}
Here, I am unable to set the status to 'loggedIn' and if I set it manually through console the success.html keeps on loading just like running any infinite loop.
The loop is occurring because of the following condition on the success page. It redirects even when you are at the success page and thus the loop.
if (localStorage.getItem('status') != null)
{
//redirect to page
window.location.href = "success.html";
}
Change it to
if (localStorage.getItem('status') == null)
{
//show validation message
window.location.href = "login.html"
}
P.S. I do highly recommend not to use localstorage to send the username and password to the clientside. It breaks the whole point of authentication and authorization services even existing.
Is it possible to programmatically add contacts to the adress book/ people app in Windows 10 like it is possible in Android?
I have a server on which contact information is stored, and I would like to make an app to synchronise my contacts with Windows 10.
I tried several things, but it didn't really work out. This is how far I've come:
Successfully download the contact data.
put the contact data in a Contact object.
This is what I've tried:
contacts.ContactManager.requestStoreAsync().done(function (contactStore) {
contactStore.createContactListAsync("name").done(function (contactList) {
for (i = 0; i < data.length; i++) {
var contact = new contacts.Contact;
//populate Contact item
contactList.saveContactAsync(contact);
}
contactList.saveAsync;
});
});
But I'm getting an acces denied error.
Any help would be appreciated. Thanks in advance!
Firstly, ensure you have added the contacts capability in app manifest.
<Capabilities>
<Capability Name="internetClient" />
<uap:Capability Name="contacts"/>
</Capabilities>
You will also get the access denied error if you had not request the read/write permission to the contact store.
ContactStoreAccessType enumeration
In this case, you can request the “appContactsReadWrite” permission.
But as I tested, there will be some API issues when calling the createContactListAsync method.
The current workaround is adding windows Runtime Component wrapper:
public sealed class ContactManagerWrapper
{
public IAsyncAction AddContactAsync(string userName, string email)
{
return AsyncInfo.Run(async (token) =>
{
var store = await ContactManager.RequestStoreAsync(ContactStoreAccessType.AppContactsReadWrite);
var contactLists = await store.FindContactListsAsync();
var contactList = contactLists.FirstOrDefault();
var contact = new Contact();
contact.Name = userName;
contact.Emails.Add(new ContactEmail() { Address = email, Kind = ContactEmailKind.Personal });
await contactList.SaveContactAsync(contact);
});
}
}
WinJS Project:
document.getElementById('click_me').addEventListener("click", function () {
var mgr = new UWPRuntimeComponent.ContactManagerWrapper();
mgr.addContactAsync('Jeffrey', 'jeffrey.chen#example.com').done(function () {
console.log("add contact successfully");
});
});
Try this
contacts.ContactManager.requestStoreAsync(ContactStoreAccessType.AppContactsReadWrite);
instead of this
contacts.ContactManager.requestStoreAsync()
you open the default store and I think its not accessible by developer.