Handling Facebook/Google login with ngCordovaOauth in Ionic + Firebase - ionic-framework

I'm trying to implement Firebase authentication with angularfire signInWithCredential method for my Ionic app. As I'm using Firebase 3.x SDK, the methods signInWithRedirect and signInWithPopup are not yet supported on mobile devices. Thus I'm using the plugin ngCordovaOauth.
var ref = firebase.database().ref().child("users");
$scope.users = $firebaseArray(ref);
$cordovaOauth.facebook("//removed_client_id", [ "public_profile", "email"]).then(function(result) {
var credentials = firebase.auth.FacebookAuthProvider.credential(result.access_token);
$scope.authObj.$signInWithCredential(credentials).then(function(authData) {
var existUser = $scope.users.$getRecord(authData.uid);
if(existUser == null){
$scope.user = {
uid: authData.uid,
displayName: authData.displayName,
avatar: authData.photoURL,
email: authData.email,
contact: "0000000000",
provider: "facebook"
}
firebase.database().ref("users/" + authData.uid).set($scope.user);
}
$rootScope.result = authData;
$state.go("menu.home");
}, function(error) {
console.error("ERROR: " + error);
});
}, function(error) {
console.log("ERROR: " + error);
});
The problem that I'm facing is I have no idea what the structure of 'authdata' is as I couldn't find any documentation for the same. With sigInWithPopup, firebase returns 'result' object; contents of which can be accessed like 'result.user.uid', 'result.user.displayName' or 'result.user.email'. How can I achieve the same here as I'm trying to store the user profile when he logs in for the first time? Any help? I'm testing on android device. Thank you!

signInWithCredential returns a promise that resolves with a firebase.User same as signInWithEmailAndPassword and all other sign in apis.
Check the docs for more info on firebase.User:
https://firebase.google.com/docs/reference/js/firebase.User

Related

Save Facebook credentials on React Native and Firebase

I'm really new to React Native. My intention is that by storing the credentials provided by FBSDK's loginWithReadPermissions, the user won't have to log in each time the app launches, but just one time after it is first installed. Maybe store it somewhere I can check the credentials in componentWillMount().
My first question is: does the FBSDK do this automatically? If not, how can I do this?
I have this code for Facebook Auth:
facebookAuthentication(callback){
LoginManager.logInWithReadPermissions(['public_profile', 'user_likes', 'email']).then(
function(result) {
if (result.isCancelled) {
alert('Inicio de sesiĆ³n cancelado');
} else {
AccessToken.getCurrentAccessToken().then((accessTokenData) =>{
const credential = Firebase.auth.FacebookAuthProvider.credential(accessTokenData.accessToken);
Firebase.auth().signInWithCredential(credential).then((result) =>{
return callback;
}, (error) =>{
console.log('Error en firebase' + error);
});
}, (error) =>{
console.log('ACCESS TOKEN ERROR: ' + error);
});
}
},
function(error) {
console.log('Login failed with error: ' + error);
}
);
}
The code works perfectly, thanks in advance.
With React Native you can use Asyncstorage, which is basically what localstorage is for the web realm: a key-value pair mini-database.
Actually, you can retrieve the currently logged in user using Firebase's firebase.auth().currentUser. Maybe you can check on app startup if it returns a valid user object.

google-api-nodejs-client: how to call google+ domain api locally? (by the plusDomains.media.insert)

I am going to use the Nodejs google api client(google-api-nodejs-client) to post a photo to my google+. (I have listed all my code at end of this post.)
Let me introduce a little bit background:
I have created a project on: console.developers.google.com
I have enabled google+ domain API for this project.
I have created credentials for this project as well. (it is a OAuth 2.0 client ID)
I have a little bit experience of using the client (google-api-nodejs-client) and I can post images and files to my google drive by it.
However, posting to google+ photo is different, the auth is the key different. I have tried several different ways, but none of them works.
The api always return me this:
{ [Error: Forbidden]
code: 403,
errors: [ { domain: 'global', reason: 'forbidden', message: 'Forbidden' } ] }
I also found this:
Warning: The Google+ Sign-In button and the plus.login scope used by
Google+ Sign-In, are not currently supported for use with the Google+
Domains API. Requests that are made to the Google+ Domains API using
an authentication token granted for the
www.googleapis.com/auth/plus.login scope, or generated by the
Google+ Sign-In button, will fail.
If it doesn't support the sign-button, what does it support?
This page tell me to add a domain delegation (https://developers.google.com/+/domains/authentication/delegation), but i haven't push my program into any server, i just try to run it locally.
I was wondering if it is possible to use this client to post photo to google+ by run a nodejs program locally?
var CLIENT_ID = "xxxxxxx.apps.googleusercontent.com";
var CLIENT_SECRET = "xxxxxxxx";
var REDIRECT_URL = "https://xxxxxxx";
var readline = require('readline');
var async = require('async');
var google = require('googleapis');
var request = require('request');
var OAuth2 = google.auth.OAuth2;
var oauth2Client = new OAuth2(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL);
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
function getAccessToken (oauth2Client, callback) {
// generate consent page url
var scopes = [
'https://www.googleapis.com/auth/plus.me',
'https://www.googleapis.com/auth/plus.stream.read',
'https://www.googleapis.com/auth/plus.stream.write',
'https://www.googleapis.com/auth/plus.circles.read',
'https://www.googleapis.com/auth/plus.circles.write',
'https://www.googleapis.com/auth/plus.media.upload'
];
var url = oauth2Client.generateAuthUrl({
access_type: 'offline', // 'online' (default) or 'offline' (gets refresh_token)
scope: scopes, // If you only need one scope you can pass it as string,
key: 'p7UALH460Deqodhvb2zESYya'
});
console.log('Visit the url: ', url);
rl.question('Enter the code here:', function (code) {
// request access token
oauth2Client.getToken(code, function (err, tokens) {
if (err) {
return callback(err);
}
// set tokens to the client
// TODO: tokens should be set by OAuth2 client.
oauth2Client.setCredentials(tokens);
console.dir(tokens);
callback();
});
});
}
getAccessToken(oauth2Client, function () {
var plusDomains = google.plusDomains({ version: 'v1', auth: oauth2Client });
var requestObj = request({url:'http://asset1.cxnmarksandspencer.com/is/image/mands/2643f540b32fe8c6cccdec95b3a2c5239166232f?$editorial_430x430$'});
const Readable = require('stream').Readable;
var iamgeStream = new Readable().wrap(requestObj);
plusDomains.media.insert({
userId: 'me',
collection: 'cloud',
resource: {
name: 'testimage.png',
mimeType: 'image/png'
},
media: {
mimeType: 'image/png',
body: iamgeStream
},
access:{domainRestricted :"true"}
}, callbackFn);
function callbackFn(argument) {
console.dir(argument);
}
});
Thanks you very much!
Peter

How to get email from facebook in cordova application?

i want to get email after login with my cordova application
but when i added a permission with Graph API Explorer , i found this
message
yes i added permission :
in my controller :
.controller("LoginController", function($scope, $cordovaOauth, $localStorage, $location) {
$scope.login = function() {
$cordovaOauth.facebook("app-id", ["email", "user_birthday","user_website", "user_location", "user_relationships"]).then(function(result) {
$localStorage.accessToken = result.access_token;});
.controller("ProfileController", function($scope, $http, $localStorage, $location) {
$scope.init = function() {
if($localStorage.hasOwnProperty("accessToken") === true) {
$http.get("https://graph.facebook.com/v2.2/me", { params: { access_token: $localStorage.accessToken, fields: "id,email,name,gender,email,location,website,picture,relationship_status", format: "json" }}).then(function(result) {
$scope.profileData = result.data;
//alert(JSON.stringify(result.data));
}, function(error) {
//alert("There was a problem getting your profile. Check the logs for details.");
console.log(error);
});
i found this result :
[![enter image description here][4]][4]
Users don't need an email to use Facebook afaik, and it may not be confirmed yet. The debug message is very clear about that. There is no guarantee to always get the Email, even with the email permission.
Just to make sure, test this API call: https://developers.facebook.com/tools/explorer/?method=GET&path=me%3Ffields%3Demail&version=v2.5

Getting user app token using react-native facebook SDK

I've gotten facebook login working using the new https://github.com/facebook/react-native-fbsdk, however I can't seem to get the user token which is usually returned in the response. Anyone found a way to get this information? The other SDK's https://github.com/magus/react-native-facebook-login returns it on the login request but the new FB sdk doesn't, and the documentation on the github page doesn't mention it anywhere.
Found the answer after some more digging. You need to use the fbsdkcore to access the user token. Heres how you use it.
var FBSDKCore = require('react-native-fbsdkcore');
var {
FBSDKAccessToken,
} = FBSDKCore;
var Login = React.createClass({
render: function() {
return (
<View>
<FBSDKLoginButton
onLoginFinished={(error, result) => {
if (error) {
alert('Error logging in.');
} else {
if (result.isCanceled) {
alert('Login cancelled.');
} else {
FBSDKAccessToken.getCurrentAccessToken((token) => {
console.log(token.tokenString);
})
}
}
}}
onLogoutFinished={() => console.log('Logged out.')}
readPermissions={[]}
publishPermissions={['publish_actions']}/>
</View>
);
}
});
You don't need a third party module (react-native-fbsdkcore)
The package (react-native-fbsdk) has instructions on it's Github page: https://github.com/facebook/react-native-fbsdk#usage
After you've logged the user in, you can fetch the access credentials as follows:
import { AccessToken } from 'react-native-fbsdk';
AccessToken.getCurrentAccessToken().then(data => {
console.log(data.accessToken.toString())
})

Trying to retrieve facebook user email using facebook connect for cordova 3.2

I'm developing an android app wherein it requires to be logged into the app via facebook. I'm using facebook connect for cordova 3.2 and its working fine.But the problem is I'm not able to get the user's email address. I tried scope : email , permissions : 'email', but it simply does not work.I have installed facebook sdk for android the cordova 3.2 version and configured that with my project. I call the facebook login uri with a button click event.
var facebookConnect;
$("#facebookfbtn").unbind("click").click(function () {
facebookConnect.login(loginCallback, true);
});
document.addEventListener("deviceready", deviceready, false);
function deviceready(){
facebookConnect = window.plugins.facebookConnect;
}
loginCallback = function(result){
alert(result);
if(result == "OPENED")
{
facebookConnect.me(meCallback);
}
}
logoutCallback = function(result){
alert(result);
}
meCallback = function(result){
alert(JSON.stringify(result));
//var test = JSON.stringify(result);
alert('Good to see you, ' + result.name + '!' + '\n'+ 'Your Details :'+ '\n'+'Location:'+result.location+'\n'+'Email: '+result.email);
}
statusCallback = function(result){
alert(result);
}