I'm trying to implement the facebook login in my angular application. the login works alright but the issue is after the login i want to alert the data that is coming from facebook but I'm having problems with it.
.controller('facebook_login',['$scope', '$ionicModal', '$timeout', 'ngFB', function($scope, $ionicModal, $timeout, ngFB) {
$scope.fbLogin = function () {
ngFB.login({scope: 'email,public_profile,publish_actions'}).then(
function (response) {
if (response.status === 'connected') {
//alert('Facebook login succeeded, got access token: ' + response.authResponse.accessToken);
//$scope.closeLogin();
ngFB.api({
path: '/me',
params: {fields: 'id,name'}
}).then(
function (user) {
$scope.user = user;
alert(params)
});
} else {
alert('Facebook login failed');
}
});
};
}])
Please try changing the params: fields to the following
fields: 'first_name,last_name,gender,email,picture'
Instead of invoking alert on the params, alert on the response object i.e. user in this case.
alert(user)
Related
I am currently building an Ionic hybrid application.
Unfortunately, I am having difficulties accessing the response data of the request during the Facebook sign-up process.
We want to retrieve data from an inappbrowser and are using Cordova's inappbrowser for a callback. Unfortunately we can't. What is the best way of accomplishing this?
function InAppBrowser($scope, $cordovaInAppBrowser, $rootScope, $http, $window) {
var durr;
$scope.facebook = facebook;
$scope.foobar = foobar;
function facebook() {
var options = {
location: 'no',
clearcache: 'yes',
toolbar: 'no'
};
durr = $cordovaInAppBrowser.open('https://www.facebook.com/dialog/oauth?scope=email,public_profile,user_friends,user_likes,user_photos,user_posts&client_id={client_id}&redirect_uri={callback_url}', '_blank', options)
.then(function(e) {
console.log(e);
})
.catch(function(e) {
console.log(e);
});
$rootScope.$on('$cordovaInAppBrowser:loadstop', function(e, event) {
$cordovaInAppBrowser.executeScript(
{ code: "localStorage.setItem('hurr', document.body.innerHTML)" },
function(data) {
console.log(data);
});
});
}
function foobar() {
console.log(durr);
// console.log(durr.localStorage.getItem('hurr'));
}
}
I don't use this for Facebook but the plugin Oauth. This plugin uses InAppBrowser : " https://github.com/nraboy/ng-cordova-oauth/blob/master/README.md ". It's very simple to use.
$cordovaOauth.facebook("Your client id", "scope", "options").then(function (result) {
Console.log(JSON.stringify(result);
// Get the information about the user's account
// See more at https://developers.facebook.com/docs/graph-api/reference/v2.2/user
$http.get("https://graph.facebook.com/v2.2/me", {
params: {
access_token: "your token",
fields: "id,last_name,first_name,gender,picture,birthday,location,email",
format: "json"
}
}).then(function (result) {
/** your code **/
}
I am using Angular (1.3.5) and Firebase to write a toy blog program, and am currently struggling with the user login part.
I first created an Angular module:
var blogApp = angular.module('blogApp', ['ngRoute', 'firebase', 'RegistrationController']);
Then on top of blogApp, I created a controller called ** RegistrationController **:
blogApp.controller('RegistrationController', function ($scope, $firebaseAuth, $location) {
var ref = new Firebase('https://myAppName.firebaseio.com');
// var authLogin = $firebaseAuth(ref);
$scope.login = function(){
ref.authWithPassword({
email: $scope.user.email,
password: $scope.user.password
}, function(err, authData) {
if (err) {
$scope.message = 'login error';
} else {
$scope.message = 'login sucessful!';
}
});
}; // login
}); //RegistrationController
I attached the login() method to ng-submit in my user-login form in the scope of RegistratinController.
When I click to submit the login form, the form does not make any response, without any errors showing.
The login form works only when I click the 'Submit' button twice - why is this? confusing
You are using the Firebase JavaScript library and not AngularFire for the login methods.
You need to pass the Firebase reference into the $firebaseAuth binding.
var auth = $firebaseAuth(ref);
From there you can call auth.$authWithPassword.
$scope.login = function(){
auth.$authWithPassword({
email: $scope.user.email,
password: $scope.user.password
}, function(err, authData) {
if (err) {
$scope.message = 'login error';
} else {
$scope.message = 'login successful!';
}
});
}; // login
AngularFire is an Angular binding for the Firebase Library that handles auto syncing over objects and arrays. AngularFire also handles when to call $scope.apply to properly update the view.
In your case, the login code is working the first click, but it doesn't get applied to the page. You can wrap this code in a $timeout, but it would be better to use the $firebaseAuth service.
Thanks to user jacobawenger, for the solution he posted here:
Can't get new password authentication methods to work in AngularFire 0.9.0?
This works as expected:
myApp.controller('RegistrationController',
function($scope, $firebaseAuth, $location) {
var ref = new Firebase('https://myApp.firebaseio.com');
var simpleLogin = $firebaseAuth(ref);
$scope.login = function() {
simpleLogin.$authWithPassword({
email: $scope.user.email,
password: $scope.user.password
}).then(function() {
$location.path('/mypage');
}, function(err) {
$scope.message = err.toString();
});
} // login
}); // RegistrationController
So, what I'm trying to do here is something simple:
check the role of the loggedUser on each route (with a resolve that sets the user if a token or login credentials are valid on the backend)
redirect to the intended route
if not allowed for a route, redirect to a different route
In my route provider I have something like
$routeProvider
...
.when('/admin', {
templateUrl: 'views/admin/dashboard.html',
controller: 'AdminDashboardCtrl',
resolve: {
checkLoggedUser: check
}
})
...
where ckeck is this function
var check = function($rootScope, $q, AuthService) {
var deferred = $q.defer();
if($rootScope.loggedUser) {
return;
}
console.log('inside resolve check')
AuthService.check().success(function(data) {
$rootScope.loggedUser = data.user;
deferred.resolve(data.user);
});
console.log('finished check')
return deferred.promise;
};
And my AuthService.check() is this function
check: function()
{
var authtoken = StorageService.get('authtoken');
if(!authtoken) {
$location.path('login');
}
console.log('before returning');
return $http.post($rootScope.base + 'auth/authenticate', { 'authtoken': authtoken });
},
In my .run(function I have
$rootScope.$on('$routeChangeSuccess', function() {
setIntendedUrl();
console.log($rootScope.loggedUser);
console.log($location.path());
});
and setIntendedUrl() check for the loggedUser and redirects to the correct page (or, in what I'm trying to accomplish, redirect to a different page if not allowed, for example the loggedUser has role = 1, can visit only the routes /admin, if a user has role = 2, and the requested path is /admin, he has to be redirected to /user)
So after all this code, when the app run this is my log in the console (see in the code where are they called)
inside resolve check app.js:29
before returning authservice.js:24
finished check app.js:36
intended: /admin/agents/create app.js:149 <--- here is where I redirect the user
Object {id: "21", name: "Kyle", surname: "Butler", roleId: "2"...} app.js:167
/admin/agents/create <--- requested path
This is not what I was expecting, so the first three logs are good, the third doesn't wait the promise to be returned (so I don't have a loggedUser) then the AuthService:check() returns the user and it's everything done at this point, the user with role = 2 is in a route that is not allowed to see.
Just to complete the code, this is the setIntendedUrl function
var setIntendedUrl = function() {
intended = $location.path();
console.log('intended: ' + intended)
if(intended !== '/login') {
if($rootScope.loggedUser && $rootScope.loggedUser.roleId === '1' && !/^\/admin*/.test(intended)) {
intended = '/admin';
} else if($rootScope.loggedUser && $rootScope.loggedUser.roleId === '2' && !/^\/manager*/.test(intended)) {
intended = '/manager';
}
StorageService.set('intended', intended);
//$location.path(intended);
}
};
What I am doing wrong? Why the user in the check function is not resolved before the other code is executed?
Can you make use of session/locals storage or $rootScope where you can store the users authorization object with given routes, permission info once user logged in.
Now is route resolve or run() block you can retrieve the user auth object perform authorization action.
e.g.
.run(['sessionService', '$rootScope', '$location', function(sessionService, $rootScope, $location) {
$rootScope.$on( "$routeChangeStart", function(event, next, current) {
var currentUser = sessionService.get('user_details');
if(next.taskAccess && next.taskAccess != ""){
var hasPerm = $rootScope.getPermission(next.taskAccess);
if(!hasPerm){
$location.path('/unauthorized');
}
}
});
}]);
In my Angular app I created a service:
.factory('Auth', function($http) {
return {
is_authenticated: function() {
return $http.get('/api/users/is_authenticated');
}
}
});
My method in my API backed by Laravel:
public function is_authenticated()
{
if(Auth::check())
{
return Response::json(array('authenticated' => true));
}
return Response::json(array('authenticated' => false));
}
And then in my controller:
Auth.is_authenticated()
.success(function(data) {
$scope.is_authenticated = data.authenticated;
if(data.authenticated)
console.log('yes');
});
When I go to /api/users/is_authenticated I see nothing on the page, however, when I echo Auth::check() there is a 1 on the page.
In my view I have a list with ng-show="is_authenticated" but it's not working.
What am I doing wrong here? I'm failing to see the problem. Why is 'yes' not being logged to the console?
And yes, I have injected the Auth service into my controller.
Tutorial: http://www.thinkster.io/angularjs/wBhtRLWHIR/6-authenticating-users-with-a-service
I'm following this tutorial and it seems like I'm losing my user as soon as they register.
Here is my auth.js factory:
'use strict';
app.factory('Auth', function($firebaseSimpleLogin, FIREBASE_URL, $rootScope){
var ref = new Firebase(FIREBASE_URL);
var auth = $firebaseSimpleLogin(ref);
var Auth = {
register : function(user) {
return auth.$createUser(user.email, user.password);
},
signedIn : function() {
// PROBLEM: authUser is always null
console.log(auth.user);
return auth.user !== null;
},
logout : function () {
auth.$logout();
}
};
$rootScope.signedIn = function () {
return Auth.signedIn();
};
return Auth;
});
Here is my auth.js controller:
'use strict';
app.controller('AuthCtrl', function($scope, $location, Auth){
if (Auth.signedIn()) {
$location.path('/');
}
$scope.register = function () {
Auth.register($scope.user).then(function (authUser) {
console.log(authUser);
$location.path('/');
});
};
});
The console.log under signedIn in the factory is always null. Any idea where the disconnect is? The registration itself is working fine, and authUser is populated in the console.log in the controller when registering.
The latest documentation for Angularfire says that the $createUser method of $firebaseSimpleLogin returns a promise but it doesn't mention any parameters being passed to the then callback.
You can use the $getCurrentUser method to get the current user after the user registers.
The tutorial needs to be updated and you should always be checking the documentation for whatever libraries you're using yourself.
Your code for signedIn should look like this:
Auth.signedIn = function() {
auth.$getCurrentUser().then(function(currentUser) {
console.log(currentUser);
}, function() {
console.log('error');
});
};
I found a very similar question that is further along in the tutorial :can't show logout button after $createUser
In the answer I learned that angularfire used to automatically log the user in after it was created. Apparently now it no longer does that which is why the auth.user in signedIn was null.
I am now doing the same tutorial. This code (in auth controller) worked for me:
$scope.register = function () {
Auth.register($scope.user).then(function (authUser) {
console.log(authUser);
Auth.login($scope.user);
$location.path('/');
});
};
I'm a total n00b, but what (I think) this is doing is authenticating the user, then running a function that logs the user in right after. Logout button is now functioning as expected.