Implement a window to log in LinkedIn in MVC 5 - javascript

I'm working in an mvc5 application where users have their own profiles, there should be a button which would open a pop-up window so that an individual user logs into LinkedIn as to sync his/her LinkedIn profile picture with our site's.
I don't think it can be implemented with modals because there's page navigation involved, so I thought about what I stated previously: a pop-up, is there a way to do this via javascript? Like, opening a pop-up and expecting a response to determine if the user logged in. If there is a better way, any info would be greately appreciated, my aim is to be able to sync the profile picture without having the user to get redirected to linked in from their profile view, I want them to change it from there and not leave the view. Is it possible to do so?
EDIT: To clarify, getting the image URL is not a problem, what I need to do is get the url from the profile window, which comes from the popup window.

You should have a look at their API it is well documented. You'll need additional permissions to retrieve the full profile. LinkedIn Profile API

I ended up using the Javascript SDK:
$('#btnSyncLinkedInPicture').on('click',
function () {
var myID = 3;
IN.User.authorize(function () {
IN.API.Raw("/people/~:(picture-url)").result(function (data) {
$.ajax({
type: 'GET',
url: '/MyController/MyAction?pictureUrl= ' + data.pictureUrl + '&id=' + myID,
success: function (result) {
$('#imgProfilePicture').attr('src', result);
}
});
}).error(function () {
});
});
});
First, we authorize the user which will open a pop-up window so that we authenticate, the SDK will abstract us from the OAuth process. After authenticating, we may want to write a callback function, in which we can already perform REST calls via the SDK methods (you can do it elsewhere as long as you have successfully authenticated).

Related

How to detect login window close event on LinkedIn Javascript SDK?

I am using LinkedIn Javascript SDK to log my users in, and I need to detect if a user closes the login/auth window before they complete the login or authorization. Current SDK doesn't fire the login callback when the window is closed (I naturally expect it to be called with IN.User.isAuthorized() set to false just like in Facebook Javascript SDK).
How can I detect when the user closes the Login with LinkedIn window?
The LinkedIn API is a bit of a nightmare to deal with.
I had a similar issue where it was firing multiple requests if they opened the auth window more than once. I solved this by adding a count each time they opened the window and then ignoring everything if count > 1. My solution involves Angular and Promises so I'm not going to post the full solution.
For you, I would just add authTriggered and authComplete variables. The triggered gets set when they click they link/button to authorise with LinkedIn and the complete variable gets set in the auth callback.
Something like this perhaps?
var LinkedIn = LinkedIn || {};
LinkedIn = {
authTriggered: false,
authComplete: false,
authorise: function() {
IN.User.authorize(function() {
this.authComplete = true;
});
}
};
var authLink = document.getElementById('auth-link');
authLink.addEventListener('click', function(e) {
e.preventDefault();
LinkedIn.authTriggered = true;
LinkedIn.authorise();
});
Instead of IN.User.authorize() please use IN.UI.Authorize() as
var linkedin = IN.UI.Authorize().place();
linkedin.onWindowRemove.subscribe(function() {
// perform some action
});
thanks sanju for this answer
https://sanjutalks.wordpress.com/2017/10/04/linkedin-javascript-sdk-detecting-login-windows-close-event/

How to get Facebook user's friends' profile picture using Javascript SDK V2.0

I am creating a website using Facebook API V2.0 JavaScript SDK and I would like to display the profile pictures of the user's friends.
I have managed to display my profile picture using the graph API but I can't manage to get the ID of all my friends if I am logged in my app (I am an admin). If I have the ID, I'll be able to show their profile picture.
In the graph explorer, I have checked all permissions (User Data Permissions + Extended Permissions). I have noticed if I switch to API V1.0, I get friends permission which is exactly what I'd like.
Also, I have added a couple of permission to my app in Facebook developers > App details > App Center Listed Platforms > Configure app center permissions. (user_friends + friends_birthday + friends_religion_politics + friends_relationships + friends_relationship_details + friends_location + friends_photos + friends_about_me)
So far, my html looks like this :
<fb:login-button scope="public_profile,email,user_friends,read_friendlists" onlogin="checkLoginState();">
After loading the Facebook SDK, I have :
function getUserFriends() {
FB.api('me/friends?fields=first_name,gender,location,last_name', function (response) {
console.log('Got friends: ', response);
$("#friendslist").html('<img src="https://graph.facebook.com/'+ response.id+'/picture?type=large"/>');
});
}
However, the array which is suppose to contain all my friends info is empty (see image : http://www.screencast.com/t/W02GaOm3h)
If all you need is their image, this can be found in the "taggable_friends" scope. However, do note that this field is very limited (by design) and that you require additional review by Facebook in order to present it to the average user.
It contains:
A taggable id. This is an id with the express purpose of tagging; it cannot be used to identify the user or otherwise gather information from their profile.
A name. The user's first and last name.
A picture, with common related fields. Url, is_silhouette, height and width.
function getUserFriends() {
FB.api('me/taggable_friends', function (response) {
console.log('Got friends: ', response.data);
$("#friendslist").html('<img src="'+response.data[0].picture.data.url+'"/>');
// maybe an $.each as well
// var friendMarkup = '';
// $.each(response.data, function(e, v) {
// friendMarkup += '<img src="' + v.picture.data.url +'" alt="'+ v.name +' picture"/>';
// }
// $("#friendlist").html(friendMarkup);
});
}
Related reading:
https://developers.facebook.com/docs/graph-api/reference/v2.0/user/taggable_friends
https://developers.facebook.com/docs/opengraph/using-actions/v2.0 - Tagging friends and Mentioning friends sections
A disclaimer: I've been battling with this issue for several days without really being able to mention-tag. My submission to use taggable_friends as a comprehensive, navigatable list for the user was rejected and I speculate (speculation ho!) it was because I did no actual tagging. I'll get back to this in a few days when I've clarified and re-submitted my request for a review on Facebook.
-- Edit --
It would seem the reason my initial submission was rejected was because I was using a special development url and did not point out clearly enough why it was not enough to use the url set under settings. This time I clearly pointed out and explained this reasoning in both the general description of my submission and in the step-by-step notes. In summary, be exceptionally clear in your submission about everything; your reasoning as to why you need this permission, how they can access it, etc. Just to make sure it isn't missed if skim-read.
It seems like in V2.0, Friends permission have dissapeared :
Facebook graph api explorer doesn't show 'Friends Data Permission' tab
https://developers.facebook.com/docs/facebook-login/permissions/v2.0

Facebook auth.sessionChange event and page changes

I am creating a Facebook Canvas application, and I am following more or less the demo app.
As in the demo, I can get the user data from the signed_request which is POSTed to my site on the first page load. Moreover, as suggested in the demo, I use the following snippet to reload the page on user changes:
var Config;
function facebookInit(config) {
Config = config;
FB.init({...});
FB.Event.subscribe('auth.sessionChange', handleSessionChange);
...
}
function handleSessionChange(response) {
if ((Config.userIdOnServer && !response.session) ||
Config.userIdOnServer != response.session.uid) {
goHome();
}
}
function goHome() {
top.location = 'http://apps.facebook.com/' + Config.canvasName + '/';
}
Here Config is an object which is populated with info from the server.
The problem appears when the user navigates the application using a link. If I use AJAX, the page is not actually reloaded and everything works fine. But if I use a standard link, the user comes to another page of my application with a standard GET request. In this case, I do not know how to get the info about the user, so Config.userIdOnServer is undefined and a page reload is triggered.
Of course I can avoid this by removing the call to handleSessionChange, or by making a one-page app with only AJAX links, but I feel I am missing something basic about the Facebook flow.
My fault, I had problems in retrieving the cookie with the user identity for subsequent requests.

Simple example of popup authentication with Facebook Graph API

Trying to get Facebook to authenticate my users via a javascript popup. Right now, I have:
<input type="button" value="Connect with Facebook" onclick="window.open('https://graph.facebook.com/oauth/authorize?client_id=XXXXXXXXXXX&redirect_uri=http://example.com/step2&display=popup')" />
But when the user logs in via Facebook, the popup just displays the Facebook.com homepage. I'd like for the popup to authenticate the user and go away so that I can start retrieving user data from the graph api.
Is there a better / easier way to do this? Simple examples are appreciated.
Thank you.
oauth2 in facebook involves two steps, call authorize to get code, then call access_token to get token.
One way to deal with the pop login:
open login url in new window just like you did,when the facebook redirects back to your url in the popup, you set the cookie either through server side code or using javascript to capture url query parameter, when page is loaded in the popup, close the window immediately window.close.
On your main page, after your window.open code, add JavaScript code to detect if popup is closed and capture the cookie:
var signinWin;
$('#FacebookBtn').click(function () {
var pos = screenCenterPos(800, 500);
signinWin = window.open("[URL]", "SignIn", "width=780,height=410,toolbar=0,scrollbars=0,status=0,resizable=0,location=0,menuBar=0,left=" + pos.x + ",top=" + pos.y);
setTimeout(CheckLoginStatus, 2000);
signinWin.focus();
return false;
});
function CheckLoginStatus() {
if (signinWin.closed) {
$('#UserInfo').text($.cookie("some_cookie"));
}
else setTimeout(CheckLoginStatus, 1000);
}
Why not simply...
function authorizeAppInPopup() {
FB.login(function(response) {
if (response.authResponse) {
// User authorized app
} else {
// User cancelled login or did not fully authorize
}
}, {scope: 'publish_stream'});
}
??? : ]
https://developers.facebook.com/docs/reference/javascript/FB.login/
Checkout this article: Create Facebook PopUp Authentication Window using PHP and javascript for customize popup authentication.
It might be a good idea to do both a callback function from the Child window as Avner says as well as a timer that watches for the window to be closed. That way if the Child window is closed without a specific action you can take appropriate action on the Parent window.
**On Child**
// Set oAuthToken from server side when it comes back from authenticating
// and you have the token on the server side.
var oAuthToken = "";
oAuthToken = "--STRING INSERTED BY SERVER SIDE CODE--";
window.opener.pbFromPopup(oAuthToken);
**On Parent :**
function CheckLoginStatus() {
if (authWindow.closed) {
// Handle error if authentication window is closed
// without any action on Allow or Deny
alert("window closed");
//location.href = "errorPage.aspx?error=authwinclosed;
}
else setTimeout(CheckLoginStatus, 1000);
}
function pbFromPopup(token) {
// Function called from child window,
// token is passed back from child
authWindow.close();
// Put token in a hidden form field and submit the form to pass
// it back to the server
$("#authToken").val(token);
$("#form1").submit();
}

Prompt-Permission on facebook?

I am having trouble of understanding how the fb:prompt-permission work. I can have a link appear when the user click the fb:login-button either the user already logged in from facebook to our application or through our website. On the other hand, without clicking the login-button, the link or the permission dialog doesn't render if the user already logged in from facebook to our page.
Doesn't that mean prompt-permission only available when the user clicks the login button ... Is there a way to avoid that?
Use this:
<fb:login-button perms="publish_stream, email">Login and Install</fb:login-button>
Source: http://developers.facebook.com/docs/guides/web
Use the standard FB Connect loginbutton, add on onlogin() function call
<fb:login-button onlogin="OnRequestPermission();"></fb:login-button>
and use this function to manually invoke the permission request dialog :
function OnRequestPermission(){
var myPermissions = "publish_stream"; // permissions your app needs
FB.Connect.showPermissionDialog(myPermissions , function(perms) {
if (!perms)
{
// handles if the user rejects the request for permissions.
// This is a good place to log off from Facebook connect
}
else
{
// finish up here if the user has accepted permission request
}
});
}
Source: http://forum.developers.facebook.com/viewtopic.php?pid=190797

Categories