Consuming a message sent by OneSignal - javascript

I have vue js application and i am consuming messages sent from a php script like this
document.addEventListener("deviceready", OneSignalInit, false);
function OneSignalInit() {
// Uncomment to set OneSignal device logging to VERBOSE
// window.plugins.OneSignal.setLogLevel(6, 0);
// NOTE: Update the setAppId value below with your OneSignal AppId.
window["plugins"].OneSignal.setAppId("");
window["plugins"].OneSignal.setNotificationOpenedHandler(function(jsonData) {
console.log('notificationOpenedCallback: ' + JSON.stringify(jsonData));
});
// iOS - Prompts the user for notification permissions.
// * Since this shows a generic native prompt, we recommend instead using an In-App Message to prompt for notification permission (See step 6) to better communicate to your users what notifications they will get.
window["plugins"].OneSignal.setNotificationReceivedHandler(function(jsonData) {
this.$router.push({path: '/my_ads'});
});
window["plugins"].OneSignal.promptForPushNotificationsWithUserResponse(function(accepted) {
console.log("User accepted notifications: " + accepted);
});
}
In my code above, this gives me a notification that shows on android. I would like to send a message that do not require a notification prompt but i would like to consume the message sent inside my application i.e use the message sent and do something with it i.e go to another route
this.$router.push({path: '/another_route'});
How can i do that?

Related

How can I ensure re-dispatch of original Google Chat message after OAuth2 authentication succeeds?

I'm writing a Google Hangouts Chat bot with Google Apps Script. The bot authenticates with a third party service with the apps script OAuth2 library. As documented in this How-To, when a message is received by the bot but authentication with the third party service is required, the bot sends a special REQUEST_CONFIG reply to Chat containing the configCompleteRedirectUrl.
var scriptProperties = PropertiesService.getScriptProperties();
function onMessage(event) {
var service = getThirdPartyService();
if (!service.hasAccess()) {
return requestThirdPartyAuth(service, event);
}
Logger.log('execution passed authentication');
return { text: 'Original message ' + event.message.argumentText };
}
function getThirdPartyService() {
var clientId = scriptProperties.getProperty('CLIENT_ID');
var clientSecret = scriptProperties.getProperty('CLIENT_SECRET');
return OAuth2.createService('ThirdPartyApp')
// Set the endpoint URLs.
.setAuthorizationBaseUrl('https://...')
.setTokenUrl('https://.../oauth/token')
// Set the client ID and secret.
.setClientId(clientId)
.setClientSecret(clientSecret)
// Set the name of the callback function that should be invoked to
// complete the OAuth flow.
.setCallbackFunction('authThirdPartyCallback')
// Set the property store where authorized tokens should be persisted.
.setPropertyStore(PropertiesService.getUserProperties())
.setCache(CacheService.getUserCache())
.setLock(LockService.getUserLock())
// Set the scope and other parameters.
.setScope('...')
.setParam('audience', '...')
.setParam('prompt', 'consent');
}
function requestThirdPartyAuth(service, event) {
Logger.log('Authorization requested');
return { "actionResponse": {
"type": "REQUEST_CONFIG",
"url": service.getAuthorizationUrl({
configCompleteRedirectUrl: event.configCompleteRedirectUrl
})
}};
/**
* Handles the OAuth callback.
*/
function authThirdPartyCallback(request) {
var service = getThirdPartyService();
var authorized = service.handleCallback(request);
if (authorized) {
Logger.log("user authorized");
//https://stackoverflow.com/a/48030297/9660
return HtmlService.createHtmlOutput("<script>window.top.location.href='" + request.parameter.configCompleteRedirectUrl + "';</script>");
} else {
Logger.log("user denied access");
return HtmlService.createHtmlOutput('Denied');
}
}
The service defines a callback authentication function, which in turn sends the browser to the configCompleteRedirectUrl. After this URL has been reached, the original message is supposed to be sent or re-dispatched a second time (see How-To step 7.3).
The authentication callback is successful because the last page displayed in the browser OAuth flow is the one specified in event.configCompleteRedirectUrl. Within the Chat window, the configuration prompt is erased, and the original message is changed to public. However, the original message is not dispatched again. The last log displayed in the apps script console is from the authentication callback event.
Is there something I have done incorrectly that prevents the original message from being dispatched again?
After much back and forth with a Google support team member, it turns out that there is a bug in the Hangouts Chat implementation when run against the V8 Apps Script runtime.
My appsscript.json file had "runtimeVersion": "V8" set. The re-dispatch does not work in this scenario. After I reverted to "runtimeVersion": "STABLE" in appsscript.json and re-deployed my scripts, the re-dispatch started working.

Getting the Auth Token for the secondary Id from Google chrome extension using OAuth 2.0 & Client ID

I am fairly new to developing chrome extensions, more specifically to the user authentication part in chrome extensions. I am following User Identity example from Google Developer docs.
The example works perfectly fine. I was able to generate the client id for the chrome app, add the scope for API's in my case Gmail API. And finally get the Auth Token by adding the identitypermission in manifest.json as follows
"oauth2": {
"client_id": "MY CLIENT ID",
"scopes": [
"https://www.googleapis.com/auth/gmail.readonly",
"https://www.googleapis.com/auth/gmail.modify"
]
}
And my app.js is a content_script which has the following code.
chrome.identity.getAuthToken({ 'interactive': true }, function(token) {
/* With which I can use xhr requests to get data from Gmail API */
console.log('Access Token : '+token);
});
Now this token that I get gives me the result for the user with which I have logged into chrome. Meaning Let's say I have a UserA with email address user_a#gmail.com and I have used this log into the chrome browser.
Question
How do I get the associated accounts or the secondary accounts? For instance, let's say a User Blogs into Gmail from the chrome browser. Is it possible to access the Gmail API for that particular user who is currently logged in?
I have tried a couple of things here.
gapi.auth.authorize({
'client_id': CLIENT_ID,
'scope': SCOPES.join(' '),
'immediate': true
},
function(authResult){//do something});
In the above scenario, the client id and scopes are fetched from the manifest.json using chrome.runtime.getManifest();.
This method uses the client.js from google api's and makes use of gapi variable.
In this case, I get the access token for the user whom I generated the client id, not even the chrome application user.
Furthermore, When I open an incognito mode and access this plugin, still I get the same user's access token.
Additional Note
I tried the same gapi.auth.authorize() using a Web OAuth 2 Client Id. It works perfectly fine. I mean whenever this authorize is executed it fetches the current logged in user's data or it asks for a login where the user can log in and authenticate. How do I achieve the same thing in chrome extension? Kindly let me know if I am missing something here.
As of now, this is not possible using supported APIs in Google Chrome stable (Version 63). However, in the Dev channel and most likely with a future release, the following will be possible:
chrome.identity.getAccounts(function(accounts) {
// accounts is a list of accounts.
chrome.identity.getAuthToken({ 'interactive': true, 'account': accounts[0] }, function(token) {
/* With which i can use xhr requests to get data from gmail api */
console.log('Access Token : '+token);
});
});
See the documentation for getAccounts().
EDIT: Something that might work in the meantime is registering for the onSigninChanged event.
How I ended up handling is was this (summary):
In the page layer, on load, I send a message down the stack to the background layer.
I used launchWebAuthFlow() to https://accounts.google.com/o/oauth2/auth to get the access_token for the account.
I made an AJAX call to https://www.googleapis.com/oauth2/v4/token using the access_token to get a refresh token.
When a user changes which account they are using via the avatar button on the top-right, this process is triggered again, as it is initiated by onLoad for the page layer of the extension.
The things left out the description above are caching and error handling, which are super-important.
http://developer.streak.com/2014/10/how-to-use-gmail-api-in-chrome-extension.html
is the complete solution which I have recently implemented on background page to work with Gmail API.
The content script is calling popup window to authorize using generated URL and simple server endpoint to store the refresh token.
$.oauthpopup = function (options) {
options.windowName = options.windowName || 'ConnectWithOAuth'; // should not include space for IE
var left = (screen.width / 2) - (800 / 2);
var top = (screen.height / 2) - (500 / 1.4);
options.windowOptions = options.windowOptions || 'location=0,status=0,width=800,height=500,left=' + left + ',top=' + top;
options.callback = options.callback || function () {
window.location.reload();
};
var that = this;
debug('oauthpopup open separate _oauthWindow');
that._oauthWindow = window.open(options.path, options.windowName, options.windowOptions);
};
$.oauthpopup({
path: 'https://accounts.google.com/o/oauth2/auth?' +
'access_type=offline' +
'&approval_prompt=force' +
'&client_id=' + clientID +
'&redirect_uri=' + callBackUrl +
'&response_type=code' +
'&scope=https://mail.google.com/ email profile' +
'&state=' + login.timyoUUID +
'&user_id=' + login.user_email,
callback: function () {
// do callback stuff
},
});
callBackUrl is used to store refresh token on the server.
Here is the example how I set access token for every request to gapi
export function setTokenForGAPI(accessToken) {
return getGAPIClient()
.then(() => {
const isSameToken = (currentAccessToken === accessToken);
const noToken = ((accessToken === undefined) || (accessToken === ''));
if (isSameToken || noToken) return;
gapi.auth.setToken({
access_token: accessToken,
});
currentAccessToken = accessToken;
})
.catch(function (e) {
console.log('error in setTokenForGAPI', e);
});
}
export function getEmailsByThreadIds(accessToken, ids) {
return setTokenForGAPI(accessToken)
.then(groupedThreadDetailsRequests(ids))
.then(processEmailDetailsResponse);
}

Android Push notification- Only show the notification message to user

I am trying to include Push Notification in my Hybrid Application.
While doing this, I am able to send the push notification message from rest client and also able to receive the notification in my Android device.
Now I want to the device user to get only the alert message which I send from the server.
For example:
In the body of my Post method,I am sending:
{
"alert": "Hello android"
}
Then, only "Hello Android" should be visible to him, even if I open the application.
Currently,when I test the above example,
when the user's app is open, he gets an alert message with details related to gcm sender, collapse_key information, apart from the alert message.
I am attaching screenshot here
function processNotification(notification) {
console.log("Hi! You have received a notification: " + JSON.stringify(notification));
alert("Hi! You have received a notification: " + JSON.parse(notification));
if(sap.Push.isPlatformIOS()){
sap.Push.resetBadge(resetBadgeSuccess);
}
}
Any Help would be appreciated

Having an hard issues with google and his API or login buttons

I followed the documentation from them and i don't see what is my error from my part !
I'm trying to get the information from the profile of the user (which could be the name gender etc etc...)
And i followed all the steps from google website (in my case, the javascript code)
Everything works, less that request which i want to do to the user profile!
This example is the callback function after logging to the google account which is automatically executed:
function signinCallback(authResult) {
if (authResult['status']['signed_in']) {
// Update the app to reflect a signed in user
// Hide the sign-in button now that the user is authorized, for example:
//document.getElementById('signinButton').setAttribute('style', 'display: none');
console.log(authResult);
gapi.client.setApiKey('API_KEY'); //(That function gaves me an error which is invalid credentials, i did put my API_KEY (from the google console ))
gapi.client.load('plus','v1', function(){
var request = gapi.client.plus.people.get({
'userId': 'me'
});
request.execute(function(resp) {
console.log(resp);
//console.log('Retrieved profile for:' + resp.displayName);
});
});
gapi.auth.signOut(); // logging out !
} else {
// Update the app to reflect a signed out user
// Possible error values:
// "user_signed_out" - User is signed-out
// "access_denied" - User denied access to your app
// "immediate_failed" - Could not automatically log in the user
console.log('Sign-in state: ' + authResult['error']);
}
}
Everything works less than setAPIkeys and everything below !
If i don't put the set function and the code below, i receive an 400 error ("message": "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.").
So i'm losing hope in doing that sincerely ... i think that google's documentation is awful !
What's wrong with that?
Merry christmas to everyone !
P.S. : yeah i know that the API key musn't be hard coded, but i'm so lost with the documentation from google sincerely ...
Possible solutions:
Try removing
gapi.client.setApiKey('API_KEY');
and
gapi.auth.signOut(); // logging out !
signOut works very fast, while gapi.client.load is asynchronous function which loads js code. User is probably signed out before gapi.client.load callback is executed.
I'm not sure if that's required:
Go to the Google Developers Console.
Select your project.
In the sidebar on the left, select APIs & auth.
In the displayed list of APIs, find the Google+ API and set its status to ON.
Make sure you're requesting scope https://www.googleapis.com/auth/plus.login or https://www.googleapis.com/auth/plus.me while signing in.

Prompt-Permission on facebook?

I am having trouble of understanding how the fb:prompt-permission work. I can have a link appear when the user click the fb:login-button either the user already logged in from facebook to our application or through our website. On the other hand, without clicking the login-button, the link or the permission dialog doesn't render if the user already logged in from facebook to our page.
Doesn't that mean prompt-permission only available when the user clicks the login button ... Is there a way to avoid that?
Use this:
<fb:login-button perms="publish_stream, email">Login and Install</fb:login-button>
Source: http://developers.facebook.com/docs/guides/web
Use the standard FB Connect loginbutton, add on onlogin() function call
<fb:login-button onlogin="OnRequestPermission();"></fb:login-button>
and use this function to manually invoke the permission request dialog :
function OnRequestPermission(){
var myPermissions = "publish_stream"; // permissions your app needs
FB.Connect.showPermissionDialog(myPermissions , function(perms) {
if (!perms)
{
// handles if the user rejects the request for permissions.
// This is a good place to log off from Facebook connect
}
else
{
// finish up here if the user has accepted permission request
}
});
}
Source: http://forum.developers.facebook.com/viewtopic.php?pid=190797

Categories