I am using Wunderlist SDK for a sample app that im developing for academic purposes.
From the Wunderlist's docs i have the following code working:
$(document).ready(function(){
var WunderlistSDK = window.wunderlist.sdk;
WunderlistAPI = new WunderlistSDK({
'accessToken': access_token,
'clientID': client_id
});
WunderlistAPI.initialized.done(function () {
WunderlistAPI.http.lists.all().done(handleListData).fail(handleError);
});
function handleListData(data){
$("#tasks").append("<button onclick='lookup_tasks(" + data.id + ")'>Search tasks for this list</button>");
}
function handleError(error,event){
alert("Error: "+ JSON.stringify(error));
}
});
I am confused on using the the rest of the API because i cant figure out how can i perform other requests using the REST API
For instance if i want to search all tasks by a list_id i am trying the following but it wont work:
function lookup_tasks(list_id){
$.get("http://a.wunderlist.com/api/v1/tasks",{list_id: list_id},function(data){
alert(JSON.stringify(data));
}); //Neither works passing the client_id and access_token as params
}
Anyone knows what am i misunderstanding?
Related
I am very new to using API and getting JSON data using OAuth. Could anybody help me? I am trying to access clients google photos and read them. These code snippets are from google photos documentation. I modified it but still having error: "Failed to load resource: the server responded with a status of 401 ()" and "Uncaught {error: "idpiframe_initialization_failed", details: "Not a valid origin for the client: http://127.0.0.…itelist this origin for your project's client ID."}"
Thank you!!!
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script async defer src="https://apis.google.com/js/api.js"
onload="this.onload=function(){};handleClientLoad()"
onreadystatechange="if (this.readyState === 'complete') this.onload()">
</script>
<script>
var GoogleAuth;
var SCOPE = 'https://www.googleapis.com/auth/drive.photos.readonly';
function handleClientLoad() {
// Load the API's client and auth2 modules.
// Call the initClient function after the modules load.
gapi.load('client:auth2', initClient);
}
function initClient() {
// Retrieve the discovery document for version 3 of Google Drive API.
// In practice, your app can retrieve one or more discovery documents.
var discoveryUrl = 'https://www.googleapis.com/discovery/v1/apis/photos/v1/rest';
// Initialize the gapi.client object, which app uses to make API requests.
// Get API key and client ID from API Console.
// 'scope' field specifies space-delimited list of access scopes.
gapi.client.init({
'apiKey': 'XXXXXXXXXXXX',
'discoveryDocs': [discoveryUrl],
'clientId': 'XXXXXXXXXXXXXXXXXX',
'scope': SCOPE
}).then(function () {
GoogleAuth = gapi.auth2.getAuthInstance();
// Listen for sign-in state changes.
GoogleAuth.isSignedIn.listen(updateSigninStatus);
// Handle initial sign-in state. (Determine if user is already signed in.)
var user = GoogleAuth.currentUser.get();
setSigninStatus();
// Call handleAuthClick function when user clicks on
// "Sign In/Authorize" button.
$('#sign-in-or-out-button').click(function () {
handleAuthClick();
});
$('#revoke-access-button').click(function () {
revokeAccess();
});
});
}
function handleAuthClick() {
if (GoogleAuth.isSignedIn.get()) {
// User is authorized and has clicked 'Sign out' button.
GoogleAuth.signOut();
} else {
// User is not signed in. Start Google auth flow.
GoogleAuth.signIn();
}
}
function revokeAccess() {
GoogleAuth.disconnect();
}
function setSigninStatus(isSignedIn) {
var user = GoogleAuth.currentUser.get();
var isAuthorized = user.hasGrantedScopes(SCOPE);
if (isAuthorized) {
$('#sign-in-or-out-button').html('Sign out');
$('#revoke-access-button').css('display', 'inline-block');
$('#auth-status').html('You are currently signed in and have granted ' +
'access to this app.');
} else {
$('#sign-in-or-out-button').html('Sign In/Authorize');
$('#revoke-access-button').css('display', 'none');
$('#auth-status').html('You have not authorized this app or you are ' +
'signed out.');
}
}
function updateSigninStatus(isSignedIn) {
setSigninStatus();
}
</script>
<button id="sign-in-or-out-button"
style="margin-left: 25px">Sign In/Authorize
</button>
<button id="revoke-access-button"
style="display: none; margin-left: 25px">Revoke access
</button>
<div id="auth-status" style="display: inline; padding-left: 25px"></div>
use this link to get more details
On right side there is button Execute, on click that button you will get all photos ,
you can also find code just clicking a icon right side square icon of text Try this API, a popup will open, click on JAVASCRIPT Tab , you will find code
https://developers.google.com/photos/library/reference/rest/v1/mediaItems/search
Accessing Google Photo API with your standard Google Apps Script token
I believe you can use the token that you already have with Google Apps Script.
I did go into the Console and setup the credentials for this project but I'm not using them.
function listImages() {
var token='';
var html='';
var n=0;
do{
var params = {muteHttpExceptions:true,headers: {"Authorization": "Bearer " + ScriptApp.getOAuthToken()}};
var url=Utilities.formatString('https://photoslibrary.googleapis.com/v1/mediaItems?pageSize=100%s',(token!=null)?"&pageToken=" + token:"");
var resp=UrlFetchApp.fetch(url,params);
Logger.log(resp);
var js=JSON.parse(resp.getContentText());
for(var i=0;i<js.mediaItems.length;i++) {
html+=Utilities.formatString('<br />%s - File Name: %s<br /><img src="%s" width="265"/>',++n,js.mediaItems[i].filename,js.mediaItems[i].baseUrl);
}
token=js.nextPageToken;
}while(token!=null);
var userInterface=HtmlService.createHtmlOutput(html).setWidth(1200).setHeight(500);
//SpreadsheetApp.getUi().showModelessDialog(userInterface, 'Images')//dialog
SpreadsheetApp.getUi().showSidebar(userInterface);//sidebard
}
Try This Code
call onAuthPhotoApiLoad function on button click
**also include js of google **
var scopeApi = ['https://www.googleapis.com/auth/photoslibrary', 'https://www.googleapis.com/auth/photoslibrary.readonly', 'https://www.googleapis.com/auth/photoslibrary.readonly.appcreateddata'];
function onAuthPhotoApiLoad() {
window.gapi.auth.authorize(
{
'client_id': "Put Client ID Here",
'scope': scopeApi,
'immediate': false
},
handlePhotoApiAuthResult);
}
function handlePhotoApiAuthResult(authResult) {
if (authResult && !authResult.error) {
oauthToken = authResult.access_token;
GetAllPhotoGoogleApi();
}
}
function GetAllPhotoGoogleApi() {
gapi.client.request({
'path': 'https://photoslibrary.googleapis.com/v1/mediaItems:search',
'method': 'POST',
'body': {
"filters": {
"mediaTypeFilter": {
"mediaTypes": ["PHOTO"]
}
}
}
}).then(function (response) {
console.log(response);
}, function (reason) {
console.log(reason);
});
}
So I have some graphs in Power BI which I want to share with my clients.
I'm making a custom page here on my server and trying to embed those graphs using Power BI Embedded setup.
I'm following this link https://learn.microsoft.com/en-us/power-bi/developer/get-azuread-access-token
However, how do I get an access token via javascript API?
Generate EmbedToken is basically a REST API call. you can use NodeJs or AJAX to issue this request and get your EmbedToken.
For AAD auth, I can maybe refer you to ADAL.js: https://github.com/AzureAD/azure-activedirectory-library-for-js
which can help with auth against AAD
I don't think that's possible in Javascript at the moment. I tried to create access tokens in Javascript not a long time ago but failed to find a way to do that.
I ended up doing a bit of server side code (something like this https://learn.microsoft.com/en-us/power-bi/developer/walkthrough-push-data-get-token) and printed the access code to a hidden div. Then I grabbed the token with Javascript and continued with Javascript from there (created the embed token and embedded the report itself).
It might be possible to do a sort of Javascript solution with a proxy, but that's out of my expertise (the proxy has the server side code).
The only pure Javascript solution I'm aware of is the Publish to web -solution (https://learn.microsoft.com/en-us/power-bi/service-publish-to-web), but it's got some limitations and security issues.
I have already embed the Power BI reports into my web application. And also, i have faced problems while embedding report into my application but finally i embed the reports. Below is the code that will help you to get the Access token.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
<script src="https://secure.aadcdn.microsoftonline-p.com/lib/1.0.12/js/adal.min.js"></script>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
window.config = {
instance: 'https://login.microsoftonline.com/',
tenant: 'common', //COMMON OR YOUR TENANT ID
clientId: '49df1bc7-db68-4fb4-91c0-6d93f770d1a4', //This is your client ID
redirectUri: 'https://login.live.com/oauth20_desktop.srf', //This is your redirect URI
callback: userSignedIn,
popUp: true
};
var ADAL = new AuthenticationContext(config);
function signIn() {
ADAL.login();
}
function userSignedIn(err, token) {
console.log('userSignedIn called');
if (!err) {
showWelcomeMessage();
ADAL.acquireToken("https://analysis.windows.net/powerbi/api", function(error, token) {
// Handle ADAL Error
if (error || !token) {
printErrorMessage('ADAL Error Occurred: ' + error);
return;
}
// Get TodoList Data
$.ajax({
type: "GET",
url: "https://api.powerbi.com/v1.0/myorg/datasets",
headers: {
'Authorization': 'Bearer ' + token,
},
}).done(function(data) {
console.log(data);
// Update the UI
$loading.hide();
}).fail(function() {
printErrorMessage('Error getting todo list data')
}).always(function() {
// Register Handlers for Buttons in Data Table
registerDataClickHandlers();
});
});
} else {
console.error("error: " + err);
}
}
function getDataSets() {
var trythis = "Bearer " + token;
var request = new XMLHttpRequest();
request.open('GET', 'https://api.powerbi.com/v1.0/myorg/datasets'); request.setRequestHeader('Authorization', trythis);
request.onreadystatechange = function() {
if (this.readyState === 4) {
console.log('Status:', this.status);
console.log('Body:', this.responseText);
}
};
request.send();
}
function showWelcomeMessage() {
var user = ADAL.getCachedUser();
var divWelcome = document.getElementById('WelcomeMessage');
divWelcome.innerHTML = "Welcome " + user.profile.name;
}
</script>
</head>
<body>
<button id="SignIn" onclick="signIn()">Sign In</button>
<h4 id="WelcomeMessage"></h4>
</body>
</html>
For more information you can go through the link that i will provide here.
Link : https://community.powerbi.com/t5/Developer/get-Access-token-using-js/m-p/352093#M10472
I'm doing an app for a homework in my school and I'm using Onesignal REST API, but I want to save the player id in my database to use it in another application like a server sender. My application is in intel xdk and I'm using Cordova to build on Android. The problem is that I can't find any example getting the player id. Can anybody help me with this problem ?
I'm using JavaScript
Thanks.
this is what I have in my .js :
document.addEventListener('deviceready', function () {
var notificationOpenedCallback = function(jsonData) {
console.log('notificationOpenedCallback: ' + JSON.stringify(jsonData));
};
window.plugins.OneSignal
.startInit("XXXXXX-XXXX-XXX-XXXX-XXXXXXXXX") // <- api id
.handleNotificationOpened(notificationOpenedCallback)
.endInit();
OneSignal.push(function() {
OneSignal.getUserId(function(userId) {
console.log("OneSignal User ID:", userId);
});
OneSignal.getUserId().then(function(userId) {
console.log("OneSignal User ID:", userId);
});
});
}, false);
Here's a working code snippet:
window.plugins.OneSignal
.startInit("YOUR-APP-ID")
.handleNotificationOpened(notificationOpenedCallback)
.endInit();
window.plugins.OneSignal.getPermissionSubscriptionState(function(status) {
idapp = status.subscriptionStatus.userId;
});
Add this block of code after the endInit() method:
window.plugins.OneSignal.getIds(function(ids) {
// Player ID will be available at the object ids.userId
});
Here's a complete example on how you can display the player ID in an alert!
document.addEventListener('deviceready', function () {
// Enable to debug issues.
// window.plugins.OneSignal.setLogLevel({logLevel: 4, visualLevel: 4});
var notificationOpenedCallback = function(jsonData) {
console.log('notificationOpenedCallback: ' + JSON.stringify(jsonData));
};
window.plugins.OneSignal
.startInit("YOUR_APP_ID_HERE")
.handleNotificationOpened(notificationOpenedCallback)
.endInit();
window.plugins.OneSignal.getIds(function(ids) {
alert("player id: " + ids.userId);
});
}, false);
Don't forget to replace YOUR_APP_ID_HERE by your real app id.
OneSignal prototype provides a function getIds which gives the player id and push token for the current device.
window.plugins.OneSignal
.startInit("XXXXXX-XXXX-XXX-XXXX-XXXXXXXXX") <- api id
.getIds(function(userDetails) {
console.log(userDetails.userId); // Player ID
console.log(userDetails.pushToken);
})
.endInit();
https://documentation.onesignal.com/docs/cordova-sdk#section--postnotification-
after installing oneSignal plugin, you can get a player id using this function in the console.
await OneSignal.getUserId();
https://documentation.onesignal.com/docs/users-and-devices#finding-users
In order to debug I use this snippet:
console.log("Site notification permission: ", await OneSignal.getNotificationPermission());
console.log("Push enabled: ", await OneSignal.isPushNotificationsEnabled());
console.log("Player id: ", await OneSignal.getUserId());
I am implementing Google log in for the first time as described here and here.
I am using HTML with Javascript.
The problem that needs solving is as follows: How can I, after the initial login, on a different page (say a landing page, or portal that the user sees after logging in), check if the user is logged in? Is there a service I can call to check the user's login in status with my app key or something similar?
I assume I would have to include the google API on each page.
Login Page Code:
Script In Head (Code from Google's tutorial listed above):
<head>
....
<script src="https://apis.google.com/js/platform.js" async defer></script>
<script>
function onSignIn(googleUser)
{
var profile = googleUser.getBasicProfile();
console.log('ID: ' + profile.getId());
console.log('Name: ' + profile.getName());
console.log('Image URL: ' + profile.getImageUrl());
console.log('Email: ' + profile.getEmail());
alert(profile.getName());
}
function logout()
{
alert('logging out');
var auth2 = gapi.auth2.getAuthInstance();
auth2.signOut().then(function () {
console.log('User signed out.');
});
}
...
</head>
Code In Body (1st line from Google's tutorial listed above, 2nd line to trigger logout test)
<body>
...
<div class="g-signin2" data-onsuccess="onSignIn"></div>
<div onmousedown="logout()">Logout</div>
...
</body>
Is there some way I can include the google API on another page, and then call some check login status function? Or another way to concretely tell if the user is logged in or out?
You do not need to store anything on local storage. The library allows you to check if the user is logged in or not using the isSignedIn.get() on the auth2 of the gapi object.
Load the JavaScript library, make sure you are not deferring the load :
<script src="https://apis.google.com/js/platform.js"></script>
Then initialize the library and check if the user is logged in or not
var auth2;
var googleUser; // The current user
gapi.load('auth2', function(){
auth2 = gapi.auth2.init({
client_id: 'your-app-id.apps.googleusercontent.com'
});
auth2.attachClickHandler('signin-button', {}, onSuccess, onFailure);
auth2.isSignedIn.listen(signinChanged);
auth2.currentUser.listen(userChanged); // This is what you use to listen for user changes
});
var signinChanged = function (val) {
console.log('Signin state changed to ', val);
};
var onSuccess = function(user) {
console.log('Signed in as ' + user.getBasicProfile().getName());
// Redirect somewhere
};
var onFailure = function(error) {
console.log(error);
};
function signOut() {
auth2.signOut().then(function () {
console.log('User signed out.');
});
}
var userChanged = function (user) {
if(user.getId()){
// Do something here
}
};
Don't forget to change the app id
You can stringify a custom userEntity object and store it in sessionStorage where you can check it anytime you load a new page. I have not tested the following but it should work (doing something similar with WebAPI tokens in the same way)
function onSignIn(googleUser)
{
var profile = googleUser.getBasicProfile();
console.log('ID: ' + profile.getId());
console.log('Name: ' + profile.getName());
console.log('Image URL: ' + profile.getImageUrl());
console.log('Email: ' + profile.getEmail());
var myUserEntity = {};
myUserEntity.Id = profile.getId();
myUserEntity.Name = profile.getName();
//Store the entity object in sessionStorage where it will be accessible from all pages of your site.
sessionStorage.setItem('myUserEntity',JSON.stringify(myUserEntity));
alert(profile.getName());
}
function checkIfLoggedIn()
{
if(sessionStorage.getItem('myUserEntity') == null){
//Redirect to login page, no user entity available in sessionStorage
window.location.href='Login.html';
} else {
//User already logged in
var userEntity = {};
userEntity = JSON.parse(sessionStorage.getItem('myUserEntity'));
...
DoWhatever();
}
}
function logout()
{
//Don't forget to clear sessionStorage when user logs out
sessionStorage.clear();
}
Of course, you can have some internal checks if the sessionStorage object is tampered with. This approach should work with modern browsers like Chrome and Firefox.
To check is user Signed-in use:
gapi.auth2.getAuthInstance().isSignedIn.get()
Adding on to Joseph's answer above, you can then get information about the user by calling auth2.currentUser.get().getBasicProfile().
if (auth2.isSignedIn.get()) {
googleUserProfile = auth2.currentUser.get().getBasicProfile()
console.log('ID: ' + googleUserProfile.getId());
console.log('Full Name: ' + googleUserProfile.getName());
console.log('Given Name: ' + googleUserProfile.getGivenName());
console.log('Family Name: ' + googleUserProfile.getFamilyName());
console.log('Image URL: ' + googleUserProfile.getImageUrl());
console.log('Email: ' + googleUserProfile.getEmail());
}
From the docs: https://developers.google.com/identity/sign-in/web/people
according to the link from Phyrik post (https://developers.google.com/identity/sign-in/web/people) -
google stopped supporting the Sign-In Javascript web auth API:
We are discontinuing the Google Sign-In JavaScript Platform Library for web. The library will be unavailable for download after the March 31, 2023 deprecation date. Instead, use the new Google Identity Services for Web.
By default, newly created Client IDs are now blocked from using the older Platform Library, existing Client IDs are unaffected. New Client IDs created before July 29th, 2022 can set plugin_name to enable use of the Google Platform Library.
I know how to embed a feed which has a certain ID. I already did it. Now I'd like to implement the following functionality: If a user receives a private message, it will appear on an embedded feed. The best option in my opinion would be to embed the whole "chat window", but I didn't find a single code sample on the web. How can I do that?
You cannot really embed private messages like you can with feeds, because Yammer's REST APIs (incl. private messages) require authentication via OAuth 2.0. That means you have to create a Yammer API application which will ask your users to log in and allow you to access their messages. The overall concept of that described in their documentation here and here.
Yammer provides several SDKs you can use, one of them is the Javascript SDK. I pieced togehter a simple example of how you can ask users to log in and then it will display their private messages. Mind you, this is a very simple solution, I just tested it on a single one-to-one conversation.
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" data-app-id="YOUR-APP-CLIENT-ID" src="https://c64.assets-yammer.com/assets/platform_js_sdk.js"></script>
</head>
<body>
<span id="yammer-login"></span>
<div id="messages"></div>
<script>
yam.connect.loginButton('#yammer-login', function (resp) {
if (resp.authResponse) {
document.getElementById('yammer-login').innerHTML = 'Welcome to Yammer!';
}
});
var msgdiv = document.querySelector("#messages");
yam.getLoginStatus(
function(response) {
if (response.authResponse) {
console.log("logged in");
var myId = response.authResponse.user_id;
yam.platform.request({
url: "messages/private.json",
method: "GET",
success: function (response) {
console.log("The request was successful.");
var usernames = {};
response.references.forEach(function(ref){
if(ref.type === "user") {
usernames[ref.id] = ref.full_name;
}
});
response.messages.forEach(function(message){
var msg = document.createElement("span");
msg.innerHTML = usernames[message.sender_id] + ": " + message.body.parsed + "<br/>";
msgdiv.appendChild(msg);
})
},
error: function (response) {
console.log("There was an error with the request.");
console.dir(private);
}
});
}
else {
console.log("not logged in")
}
}
);
</script>
</body>
</html>
The response from the messages/private.json API endpoint is a JSON file that you can go through. It includes information about the message and the users involved in the conversation.