Meteor facebook login - user is not show in SignIn space - facebook

I try to add Facebook login function on my app, it work but I have some problems
I start with:
meteor add accounts-password
meteor add accounts-ui
meteor add service-configuration
meteor add accounts-facebook
Then I write a test app on facebook, adding login and get my appId and secret
I copy documentation's code to configure settings (server side) and I put my appId and secret
ServiceConfiguration.configurations.upsert(
{ service: "facebook" },
{
service : "facebook",
appId: '123456789012345678',
secret: '123456789012345678123456789012345678123456789012345678',
loginStyle : "popup",
requestPermissions: ['email','user_friends']
}
);
I try to login with facebook and I have (showing in console.log) all the data I need (the picture is the picture profile in facebook), but the SignIn name is nto show in the top of the app
When I signin with a normal email password login I have no problem

The problem was in this function:
Accounts.onCreateUser(function(options, user) {
var imgAvatar = "/img/user.png";
var username = "NewPlayer_" + Math.floor(Math.random() * (9000 - 1000) + 1000);
if (user.hasOwnProperty('services') && user.services.hasOwnProperty('facebook') ) {
imgAvatar = "http://graph.facebook.com/" + user.services.facebook.id + "/picture/?type=small";
username = user.services.facebook.name;
}
return user;
});
I discover the correct way to use this function in this post
Accounts.onCreateUser((function(_this) {
return function(options, user) {
options = {
username: 'pippo'
}
return Object.assign({}, user, options);
};
})(this));

Related

Laravel Passport and Ionic2 Facebook-Login

I am developing a mobile app which should do API calls to an own laravel backend.
Frontend: Ionic 2 + Angular2
Backend: Laravel 5.3 + Laraval Passport + MySQL
At the user can log in with password grant (username + password).
Now I want to offer a login via Facebook.
I've implemented a Login with Facebook-button in the app. This works fine. I get the profile information from the Facebook API: id, email, name
Now this user (has no email + password combination from our server) should be able to make API calls to our Laravel server and should be linked to user in the users-table of the MySQL-database behind the laravel backend. Users which login with Facebook shouldn't need any username or password to login. Just Facebook.
I want to generate a new user in the database for each facebook user (simply with a column facebook_id). But how to give such users an access_token?
Accepting just the Facebook ID, match this (or create new) user in the database and create an access_token would be very unsecure because Facebook ID is public...
I must say I have same problem couple of weeks ago. Only difference I got was that I have both, ionic2 app and website. Both must support username/password login as social login (google, facebook).
So how did I did that (I will write for facebook, google is slightly different - better):
Prepare your facebook app to accept logins from mobile AND webpage. You will need facebook client_id and client_secret.
Install socialite package for laravel. And set it up to work with facebook ( in app/services.php set facebook ).
Now when you got this you can start coding. You said you already have it working on Ionic2 part. So that means you get token and other data from facebook for user.
What I did is I make request to my api and send this token and user_id. Then on my API side I check if token is valid, login user and issue passport token.
Ionic2 code:
Facebook.login(["public_profile"])
.then(response => {
// login success send response to api and get token (I have auth service class to do that)
this.auth.facebookLogin(response.authResponse).then(
...
);
}, error => {
this.showAlert( this.loginFailedTitle, this.loginFailedText );
});
Now Laravel part. I made SocialController.php and url (POST request) /api/social-login/facebook:
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Model\SocialLogin;
use App\User;
use Illuminate\Http\Request;
use Socialite;
class SocialController extends Controller
{
public function facebook(Request $request) {
$user = Socialite::driver('facebook')->userFromToken( $request->input('accessToken'));
abort_if($user == null || $user->id != $request->input('userID'),400,'Invalid credentials');
// get existing user or create new (find by facebook_id or create new record)
$user = ....
return $this->issueToken($user);
}
private function issueToken(User $user) {
$userToken = $user->token() ?? $user->createToken('socialLogin');
return [
"token_type" => "Bearer",
"access_token" => $userToken->accessToken
];
}
}
Now this will return you passport token and you can make api request to protected routes.
About passport, email, username, ..... you will have to change database and make it nullable. And add facebook_id field.
And be sure to make requests over https, because your are sending token.
Hope it helps.
in addition to #Bostjan's answer adding my generalised implementation :
SocialAccount here is a laravel model where you'll provider and provider_user_id and local database user id. Below is the example of social_accounts table
And in SocialController :
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Http\Request;
use App\User;
use App\SocialAccount;
use Socialite;
class SocialController extends Controller
{
public function social(Request $request) {
$provider = $request->input('provider');
switch($provider){
case SocialAccount::SERVICE_FACEBOOK:
$social_user = Socialite::driver(SocialAccount::SERVICE_FACEBOOK)->fields([
'name',
'first_name',
'last_name',
'email'
]);
break;
case SocialAccount::SERVICE_GOOGLE:
$social_user = Socialite::driver(SocialAccount::SERVICE_GOOGLE)
->scopes(['profile','email']);
break;
default :
$social_user = null;
}
abort_if($social_user == null , 422,'Provider missing');
$social_user_details = $social_user->userFromToken($request->input('access_token'));
abort_if($social_user_details == null , 400,'Invalid credentials'); //|| $fb_user->id != $request->input('userID')
$account = SocialAccount::where("provider_user_id",$social_user_details->id)
->where("provider",$provider)
->with('user')->first();
if($account){
return $this->issueToken($account->user);
}
else {
// create new user and social login if user with social id not found.
$user = User::where("email",$social_user_details->getEmail())->first();
if(!$user){
// create new social login if user already exist.
$user = new User;
switch($provider){
case SocialAccount::SERVICE_FACEBOOK:
$user->first_name = $social_user_details->user['first_name'];
$user->last_name = $social_user_details->user['last_name'];
break;
case SocialAccount::SERVICE_GOOGLE:
$user->first_name = $social_user_details->user['name']['givenName'];
$user->last_name = $social_user_details->user['name']['familyName'];
break;
default :
}
$user->email = $social_user_details->getEmail();
$user->username = $social_user_details->getEmail();
$user->password = Hash::make('social');
$user->save();
}
$social_account = new SocialAccount;
$social_account->provider = $provider;
$social_account->provider_user_id = $social_user_details->id;
$user->social_accounts()->save($social_account);
return $this->issueToken($user);
}
}
private function issueToken(User $user) {
$userToken = $user->token() ?? $user->createToken('socialLogin');
return [
"token_type" => "Bearer",
"access_token" => $userToken->accessToken
];
}
}

Meteor + facebook login (loginWithFacebook) issue. client_id is always undefined in login popup's URL

I put this issue in gist as well:
https://gist.github.com/yhagio/7561f34d12bc5edb9b5fe0fc1b4bb2b6
Github Repo : https://github.com/yhagio/meteor-tatter
Issue
When I click facebook login button, it opens the login popup, but
the URL in the popup always shows that client_id=undefined, and gives "Sorry, something went wrong".
I installed service-configuration and accounts-facebook meteor packages and configured as follows.
Also, cretead the app & added Facebook Login product in https://developers.facebook.com
Am I missing something?
Screenshot
The URL is like this:
https://www.facebook.com/v2.2/dialog/oauth?client_id=undefined&redirect_uri=http://localhost:3000/_oauth/facebook&display=popup&scope=public_profile&state=eyJsb2dpblN0eW...
In server https://github.com/yhagio/meteor-tatter/blob/master/imports/startup/server/index.js
import { Meteor } from 'meteor/meteor';
import { clientId, secret } from './secret.js';
Meteor.startup(() => {
ServiceConfiguration.configurations.upsert(
{ service: "facebook" },
{
$set: {
clientId: clientId,
loginStyle: "popup",
secret: secret
}
}
);
});
In client https://github.com/yhagio/meteor-tatter/blob/master/imports/ui/helpers/auth.js
import { Meteor } from 'meteor/meteor';
export default function auth() {
return new Promise((resolve, reject) => {
Meteor.loginWithFacebook({
requestPermissions: ['public_profile']
}, (err, user) => {
if (err !== null) return reject(err);
resolve(user);
});
});
}
Problem was that it should be appId instead of clientId. Even though the guide shows clientId. Ref: http://docs.meteor.com/api/accounts.html#service-configuration

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

Meteor Facebook login (Meteor.loginWithFacebook) issue extracting public profile, email and user_friends

Trying to get Meteor Facebook login to work. It functions fully in that it uses Facebook API and requests the correct permissions from the users account and then logs in successfully.
The problem is it doesn't save the permission requested information even though its been approved and only the basic name and ID are available in Meteor.user().services.facebook. Is this code not working because it's not saving the users details on login? I can't find a resource that details how to save or extract the other data.
Simply trying to console log the data to see that it's been extracted out of the Facebook user account on log in.
Within Meteor.isClient code:
Template.login.events({
'click #facebook-login': function(event) {
Meteor.loginWithFacebook({ requestPermissions: ['email', 'public_profile', 'user_friends', 'user_likes']}, function(err){
if (err) {
throw new Meteor.Error("Facebook login failed");
}
console.log(Meteor.user().services.facebook.name);
console.log(Meteor.user().services.facebook.id);
console.log(Meteor.user().services.facebook.email);
console.log(Meteor.user().services.facebook.gender);
});
},
'click #logout': function(event) {
Meteor.logout(function(err){
if (err) {
throw new Meteor.Error("Logout failed");
}
});
}
The config code:
ServiceConfiguration.configurations.remove({
service: 'facebook'
});
ServiceConfiguration.configurations.insert({
service: 'facebook',
appId: 'correctAppID',
secret: 'CorrectSecret'
});
For Facebook v2.4 API after you have requested for certain permissions you can then access them by making a graph API call and requesting them with a valid auth token. The code is as follows:
if (user.hasOwnProperty('services') && user.services.hasOwnProperty('facebook') ) {
var result = Meteor.http.get('https://graph.facebook.com/v2.4/' + user.services.facebook.id + '?access_token=' + user.services.facebook.accessToken + '&fields=first_name, last_name, birthday, email, gender, location, link, friends');
console.log(result.data.first_name);
console.log(result.data.last_name);
console.log(result.data.birthday);
console.log(result.data.email);
console.log(result.data.gender);
console.log(result.data.location);
console.log(result.data.link);
console.log(result.data.friends);
}

Facebook login on cordova app shows blank white screen

This problem has been bugging me for a long time and I can't seem to find the solution, all the settings in my Facebook Developer panel are configured correctly, Site URL, App Domain and OAuth URLs.
When I run my app on my iPhone (I have it installed through iTunes) and click the authentication button I am successfully prompted with this screen:
However, after logging in, I am faced with a blank white screen instead of being redirected to my main.html page.
I am using the OpenFB plugin along with Parse and the Facebook Graph API to authenticate and store my users data, here is my login code:
login.html:
$('.facebookLogin').click(function(){
Parse.User.logOut(); // log current user out before logging in
login();
});
function login() {
openFB.login(function(response) {
if(response.status === 'connected') {
console.log('Facebook login succeeded');
Parse.FacebookUtils.logIn("email", { // permission request to use email
success: function(user) {
if (!user.existed()) {
FB.api('/me', function(response) {
var firstName = response.first_name;
var lastName = response.last_name;
var email = response.email;
var user_id = response.id;
user.set("firstName",firstName);
user.set("lastName",lastName);
user.set("email",email);
user.save();
});
window.location.href= "main.html";
}
else {
window.location.href= "main.html";
}
},
error: function(user, error) {
alert("User cancelled the Facebook login or did not fully authorize.");
}
});
}
else {
alert('Facebook login failed: ' + response.error);
}
}, {scope: 'email'});
}
oauthcallback.html:
<html>
<body>
<script>
// redirects to main page
window.location.href= "main.html";
</script>
</body>
</html>
Note: I have added main.html, login.html and oauthcallback.html to the Valid OAuth redirect URIs list on my panel.
Check that your site is using SSL with a valid certificate.
There might be an error trying to redirect from a non-secure site to an encrypted site.