Skip to content

Instantly share code, notes, and snippets.

@killercup
Created June 30, 2013 14:34
Show Gist options
  • Save killercup/5895378 to your computer and use it in GitHub Desktop.
Save killercup/5895378 to your computer and use it in GitHub Desktop.
angular.module('Facebook', [])
.factory('Facebook', function($rootScope, $q){
var facebook = {};
/**
* @name facebook.getPermission
* @requires $q
*
* @description
* Try to receive permissions from Facebook.
*
* @param {string} permission The identifier of the permissions to request,
* see <https://developers.facebook.com/docs/reference/login/#permissions>
* @returns {Promise} Promise will be resolved with Object containing
* `permission_granted` (bool) and possible also `uid` and `accessToken`,
* or rejected with Object containing `permission_granted: false`.
*/
facebook.getPermission = function(permission) {
var deferred = $q.defer();
var promise = deferred.promise;
FB.getLoginStatus(function(response) {
if(response.authResponse) {
FB.api('/me/permissions', function(perms_response) {
if(perms_response['data'][0][permission]) {
$rootScope.$apply(function() {
deferred.resolve({
permission_granted: true
});
});
} else {
FB.login(function(response) {
if(response.authResponse) {
$rootScope.$apply(function() {
deferred.resolve({
permission_granted: true,
uid: response.authResponse.userID,
accessToken: response.authResponse.accessToken
});
});
} else {
$rootScope.$apply(function() {
deferred.reject({
permission_granted: false
});
});
}
}, {scope: permission});
}
});
} else {
FB.login(function(response) {
if(response.authResponse) {
$rootScope.$apply(function() {
deferred.resolve({
permission_granted: true,
uid: response.authResponse.userID,
accessToken: response.authResponse.accessToken
});
});
} else {
$rootScope.$apply(function() {
deferred.reject({
permission_granted: false
});
});
}
}, {scope: permission});
}
});
return promise;
};
facebook.init = function() {
var deferred = $q.defer();
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
/*
The user is logged in and connected to your app, and
`response.authResponse` supplies:
* user's ID
* a valid access token
* a signed request
and the time the access token and signed request each expire.
*/
$rootScope.$apply(function() {
deferred.resolve({
status: response.status,
uid: response.authResponse.userID,
accessToken: response.authResponse.accessToken
});
});
} else if (response.status === 'not_authorized') {
/*
The user is logged in to Facebook, but not connected to the app.
*/
$rootScope.$apply(function() {
deferred.resolve({
status: response.status
});
});
} else {
/*
The user isn't even logged in to Facebook.
*/
$rootScope.$apply(function() {
deferred.reject({
status: 'not_facebook_user'
});
});
}
});
return deferred.promise;
};
return facebook;
})
;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment