emails from gmail but response is gmail.readonly - gmail-api

I am trying to get the emails from gmail using https://www.googleapis.com/auth/gmail.readonly/?access_token='fdrt654vfdgfe6545But in response I am getting gmail.readonlyBut the System.HttpResponse[Status=OK, StatusCode=200] is fine. Can any guide me is there anything I am missing out.
This I how I requested got auth but in the response I received access token
<script type="text/javascript">
(function() {
var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
po.src = 'https://apis.google.com/js/client:plusone.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
})();
</script>
<script type="text/javascript">
(function() {
var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
po.src = 'https://apis.google.com/js/client:plusone.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
})();
var AuthStates = {google: null};
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');
//alert(authResult['code']);
console.log('code state: ' + authResult['code']);
//console.log('authResult : ' + authResult[]);
AuthStates.google = authResult;
console.log('authResult 1 : ' + authResult['status']['method']);
console.log('auth Result : ' + authResult['id_token']);
//{!access_token} = authResult['access_token'];
//{!code} = authResult['code'];
connection(authResult['access_token'], authResult['code']);
} 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']);
}
}
</script>
<apex:outputPanel >
<span id="signinButton">
<span
class="g-signin"
data-callback="signinCallback"
data-clientid="clientid"
data-cookiepolicy="single_host_origin"
data-scope="https://www.googleapis.com/auth/gmail.readonly"
data-response_type="code"
data-redirect_uri="http://test-on.ap1.visual.force.com/apex/Gmail_inbox">
</span>
</span>
<apex:form >
So as i got my access token from my request I can go directly for getting all information related to the logedin user. As I am getting all the information regarding the user I am trying to get all the emails related to him. Is I am doing right or I am wrong any place. I am very new with api and web service trying to learn. please do help me put out.

You're actually making an HTTP GET call to that URL ( https://www.googleapis.com/auth/gmail.readonly/?access_token= ...)? Isn't that just the auth scope identifier?
Once you have a valid Oauth2 token you can set in the Auth header then you can make HTTP requests to the API. For example, to list messages see:
https://developers.google.com/gmail/api/v1/reference/users/messages/list
That has the URL to access (GET https://www.googleapis.com/gmail/v1/users/me/messages ) then once you have the message IDs you can get the messages individually following: https://developers.google.com/gmail/api/v1/reference/users/messages/get (e.g. GET https://www.googleapis.com/gmail/v1/users/me/messages/ ).
Usually there are good client libraries for the Google APIs. Not sure if that works for you, but see, for example:
https://developers.google.com/gmail/api/downloads

Related

Satellizer OAuth Unlinking gives 404 error

I'm testing satellizer example with Laravel back end for Facebook, once user links the Facebook account to the app its impossible to unlink it with satellizer, whenever user clicks Facebook Unilink button it gives 404 error,
http://localhost:8000/auth/unlink
404 Not found.
But on Laravel router.
Route::get('auth/unlink/{provider}', ['middleware' => 'auth', 'uses' => 'AuthController#unlink']);
Please help me to fix this bug.
Did you find the solution for this?
After check the below link I end up founding a solution for my issue.
https://github.com/sahat/satellizer/issues/269
Basically in the Satellizer documentation explain that provider and httpOptions was the parameters you can send via the unlink call, however, the options never gets passed as it only retrieves the information from the first parameter which is the provider.
You can see a bit more about the accepted parameters in the piece of code below that is inside of the satellizer.js file.
OAuth.prototype.unlink = function (provider, httpOptions) {
if (httpOptions === void 0) { httpOptions = {}; }
httpOptions.url = httpOptions.url ? httpOptions.url : joinUrl(this.SatellizerConfig.baseUrl, this.SatellizerConfig.unlinkUrl);
httpOptions.data = { provider: provider } || httpOptions.data;
httpOptions.method = httpOptions.method || 'POST';
httpOptions.withCredentials = httpOptions.withCredentials || this.SatellizerConfig.withCredentials;
return this.$http(httpOptions);
};
My not so elegant solution is as below:
html
<button class="btn btn-sm btn-danger float-left" ng-if="user.facebook"
ng-click="unlink({provider:'facebook', options: {'param1':'value','param2':'value2'}})"><i class="ion-social-facebook"></i> Unlink Facebook Account
</button>
I have basically wrapped the information I want to send by the variable provider (renamed to just data) in the JS code below.
//unlink a social login profile from user's profile
$scope.unlink = function (data) {
console.log(data);
$auth.unlink(data)
.then(function () {
toastr.info('You have unlinked a ' + data.provider + ' account');
$scope.getProfile();
})
.catch(function (response) {
toastr.error(response.data ? response.data.message : 'Could not unlink ' + data.provider + ' account', response.status);
});
The JSON sent via view does not look pretty but works:
provider Object
provider "facebook"
options Object
flag "unlink"
view "profile"
userId 236
Nothing of the above resolved the 404 issue but resolve the passing of parameters from the original satellizer unlink function.
The issue with the route happens because Laravel is blocking that route in the file Authenticate.php inside of the function "public function handle($request, Closure $next)"
You can ether route without the middware like this
Route::post('auth/unlink', 'AuthController#unlink');
Route::get('auth/unlink', 'AuthController#unlink');
Route::any('auth/unlink', 'AuthController#unlink');
The above will make sure the call will hit the controller one whay or another. how you are getting the parameters in the controller will depend if you choose post/get/any. Meaning you will retrieve the parameters via Laravel variable $request from
public function unlink(Request $request)
or using the Input facade like this
$input = Input::all();
in here you can do whatever you want with the variable values passed. Now is up to you on the handling.
Note: The satellizer code sets by default the method to POST if no method is passed in the httpOptions as you can see below:
OAuth.prototype.unlink = function (provider, httpOptions) {
if (httpOptions === void 0) { httpOptions = {}; }
httpOptions.url = httpOptions.url ? httpOptions.url : joinUrl(this.SatellizerConfig.baseUrl, this.SatellizerConfig.unlinkUrl);
httpOptions.data = { provider: provider } || httpOptions.data;
httpOptions.method = httpOptions.method || 'POST';
httpOptions.withCredentials = httpOptions.withCredentials || this.SatellizerConfig.withCredentials;
return this.$http(httpOptions);
};
That does not really helps when the code with the Laravel example comes with the route calling the get method not the post and in the js example no options of http is set to get. Meaning you are trying to call get where post is the default therefore the route will never work.
Sorry if I am not more clear as this is my first time trying to put my thinking here and English is not really my first language.
Good luck.

Link Sails's authenticated user to websocket's user

I am currently trying to create an sails+angular web-app.
I already have a user-authentication system working (based on this tutorial : https://github.com/balderdashy/activity-overlord-2-preview). I am trying to integrate a very simple chat inside using websocket.
My issue is to link websocket's "user" to the authenticated user.
Because when an authenticated user writes a message, I want to send the message as data but not the id of the current user, i would like to get this id from the sail's controller.
This is my actual sails chatController :
module.exports = {
addmsg:function (req,res) {
var data_from_client = req.params.all();
if(req.isSocket && req.method === 'GET'){
// will be used later
}
else if(req.isSocket && req.method === 'POST'){
var socketId = sails.sockets.getId(req);
/* Chat.create(data_from_client)
.exec(function(error,data_from_client){
console.log(data_from_client);
Chat.publishCreate({message : data_from_client.message , user:currentuser});
}); */
}
else if(req.isSocket){
console.log( 'User subscribed to ' + req.socket.id );
}
}
}
and this is my angular's controller
io.socket.get('http://localhost:1337/chat/addmsg');
$scope.sendMsg = function(){
io.socket.post('http://localhost:1337/chat/addmsg',{message: $scope.chatMessage});
};
req.session.me
...was the solution.

Firebase: How can i use onDisconnect during logout?

How can i detect when a user logs out of firebase (either facebook, google or password) and trigger the onDisconnect method in the firebase presence system. .unauth() is not working. I would like to show a users online and offline status when they login and out, minimize the app (idle) - not just when the power off their device and remove the app from active applications on the device.
I'm using firebase simple login for angularjs/ angularfire
Im using code based off of this tutorial on the firebase site.
https://www.firebase.com/blog/2013-06-17-howto-build-a-presence-system.html
Please i need help with this!
Presence code:
var connectedRef = new Firebase(fb_connections);
var presenceRef = new Firebase(fb_url + 'presence/');
var presenceUserRef = new Firebase(fb_url + 'presence/'+ userID + '/status');
var currentUserPresenceRef = new Firebase(fb_url + 'users/'+ userID + '/status');
connectedRef.on("value", function(isOnline) {
if (isOnline.val()) {
// If we lose our internet connection, we want ourselves removed from the list.
presenceUserRef.onDisconnect().remove();
currentUserPresenceRef.onDisconnect().set("<span class='balanced'>☆</span>");
// Set our initial online status.
presenceUserRef.set("<span class='balanced'>★</span>");
currentUserPresenceRef.set("<span class='balanced'>★</span>");
}
});
Logout function:
var ref = new Firebase(fb_url);
var usersRef = ref.child('users');
service.logout = function(loginData) {
ref.unauth();
//Firebase.goOffline(); //not working
loggedIn = false;
seedUser = {};
clearLoginFromStorage();
saveLoginToStorage();
auth.logout();
};
The onDisconnect() code that you provide, will run automatically on the Firebase servers when the connection to the client is lost. To force the client to disconnect, you can call Firebase.goOffline().
Note that calling unauth() will simply sign the user out from the Firebase connection. It does not disconnect, since there might be data that the user still has access to.
Update
This works for me:
var fb_url = 'https://yours.firebaseio.com/';
var ref = new Firebase(fb_url);
function connect() {
Firebase.goOnline();
ref.authAnonymously(function(error, authData) {
if (!error) {
ref.child(authData.uid).set(true);
ref.child(authData.uid).onDisconnect().remove();
}
});
setTimeout(disconnect, 5000);
}
function disconnect() {
ref.unauth();
Firebase.goOffline();
setTimeout(connect, 5000);
}
connect();

how do I get the signed request from a facebook canvas app authorization?

Once a user has authorized my app I need to parse the signed request so I can access their user id etc. Where in my code do I put the url to the page that processes it? I need a code example. I've looked through the documentation and it doesn't explain clearly how to do this for a canvas app. The variable redirectUrl has the url of the canvas app itself. Is that supposed to contain the url of the code that parses the signed request instead? I'm not sure.
<body>
<div id="fb-root"></div>
<script type="text/javascript">
$(document).ready(function(){
var appId = 278*****2040;
// If logging in as a Facebook canvas application use this URL.
var redirectUrl = "http://apps.facebook.com/MYAPP";
// If the user did not grant the app authorization go ahead and
// tell them that. Stop code execution.
if (0 <= window.location.href.indexOf ("error_reason"))
{
$('#authCancel').empty();
$(document.body).append ("<p>Authorization denied!</p>");
return;
}
// When the Facebook SDK script has finished loading init the
// SDK and then get the login status of the user. The status is
// reported in the handler.
window.fbAsyncInit = function(){
//debugger;
FB.init({
appId : 278****40,
status : true,
cookie : true,
oauth : true
});
// Sandbox Mode must be disabled in the application's settings
// otherwise the callback will never be invoked. Monitoring network
// traffic will show an error message in the response. Change the
// Sandbox Mode setting in: App Settings - Advanced - Authentication.
FB.getLoginStatus (onCheckLoginStatus);
};
// Loads the Facebook SDK script.
(function(d)
{
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));
// Handles the response from getting the user's login status.
// If the user is logged in and the app is authorized go ahead
// and start running the application. If they are not logged in
// then redirect to the auth dialog.
function onCheckLoginStatus (response)
{
if (response.status != "connected")
{
top.location.href = "https://www.facebook.com/dialog/oauth?client_id=" + appId + "&redirect_uri=" + encodeURIComponent (redirectUrl) + "&scope=user_photos,friends_photos";
}
else
{
// Start the application (this is just demo code)!
$(document.body).append ("<p>Authorized!</p>");
FB.api('/me', function (response) {
$(document.body).append ("<pre>" + JSON.stringify (response, null, "\t") + "</pre>");
});
}
}
});
</script>
You can definitely use canvas page URL itself.
IN the same page you can put the following code. I have done that and working perfectly fine.
if(isset($_REQUEST["code"]))
{
$code = $_REQUEST["code"];
$my_url = "https://apps.facebook.com/CANVAS_APP_URL/";
$token_url = "https://graph.facebook.com/oauth/access_token?". "client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url)
. "&client_secret=" . $app_secret . "&code=" . $code;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $token_url );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output1 = curl_exec($ch);
curl_close($ch);
$tokenarray = explode("&", $output1);
$tokenarray1 = explode("=", $tokenarray[0]);
$access_token = $tokenarray1[1];
$urltoopen = 'https://graph.facebook.com/me?access_token=' . $access_token;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $urltoopen);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
echo $output;
}
Hope this helps !!
~ ABW

google plus login api cookie

I am using google app engine python. I followed the example code to let user login. After this step am I supposed to create my own cookie or session to remember the user? Because when i refresh the page, the login button appears again.
This is the javascript.
<script src="https://apis.google.com/js/plusone.js" type="text/javascript"></script>
<script type="text/javascript">
/*
* Triggered when the accepts the the sign in, cancels, or closes the
* authorization dialog.
*/
function loginFinishedCallback(authResult) {
if (authResult) {
if (authResult['error'] == undefined){
gapi.auth.setToken(authResult); // Store the returned token.
toggleElement('signin-button'); // Hide the sign in upon successful sign in.
getEmail(); // Trigger request to get the email address.
} else {
console.log('An error occurred');
}
} else {
console.log('Empty authResult'); // Something went wrong
}
}
/*
* Initiates the request to the userinfo endpoint to get the user's email
* address. This function relies on the gapi.auth.setToken containing a valid
* OAuth access token.
*
* When the request completes, the getEmailCallback is triggered and passed
* the result of the request.
*/
function getEmail(){
// Load the oauth2 libraries to enable the userinfo methods.
gapi.client.load('oauth2', 'v2', function() {
var request = gapi.client.oauth2.userinfo.get();
request.execute(getEmailCallback);
});
}
function getEmailCallback(obj){
var el = document.getElementById('email');
var email = '';
if (obj['email']) {
email = 'Email: ' + obj['email'];
}
//console.log(obj); // Uncomment to inspect the full object.
el.innerHTML = email;
toggleElement('email');
}
function toggleElement(id) {
var el = document.getElementById(id);
if (el.getAttribute('class') == 'hide') {
el.setAttribute('class', 'show');
} else {
el.setAttribute('class', 'hide');
}
}
</script>
This is the login button.
<span id="signin-button" class="show">
<div class="g-signin" data-callback="loginFinishedCallback"
data-approvalprompt="force"
data-clientid="279937419542.apps.googleusercontent.com"
data-scope="https://www.googleapis.com/auth/plus.login
https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/plus.me https://www.googleapis.com/auth/userinfo.profile"
data-height="short"
data-cookiepolicy="single_host_origin"
>
</div>
</span>

Resources