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

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/

Related

Microsoft authorization with new tab

I need to implement login functionality with Microsoft via a new tab.
Currently our login process works with Microsoft in a way which is not really suited for our needs. The user clicks a login button, gets redirected to the Microsoft sign in page, enters his information and gets redirected back to our login page. This all happens on the same tab. In the code bellow is an example of this:
authenticateOffice(finallyCallback?: () => void): void {
finallyCallback = finallyCallback || (() => {
});
let currentUrl = location.href;
this.redirectLocationUrl = currentUrl.substr(0, currentUrl.indexOf('#'));
let url = "https://login.microsoftonline.com/".concat(this.office365Domain, "/oauth2/v2.0/authorize?client_id=", this.clientId,
"&response_type=id_token&redirect_uri=", this.redirectLocationUrl, "&response_mode=fragment&scope=openid profile&state=12345&nonce=678910");
window.location.href = url;
}
Pretty straightforward and nothing too complex.
What we need to do in layman's terms is:
1. Open a new tab when clicking the login button
2. User enters his information on the Microsoft login page
3. When authorized, tab is automatically closed
4. Our login page then receives the "id_token" from Microsoft from oauth2 and with this I do the rest of my login logic
else if (!StringHelper.isNullOrEmpty(window.location.hash) && window.location.hash.startsWith('#id_token')) {
let response = window.location.hash;
this._office365Service.getOfficeId(response)
.subscribe((result: string) => {
let key = result;
if (key) {
this._loginService.processOfficeIdResult(key);
} else {
abp.message.warn(this._localizationService.localize('Office365User', this.localizationSourceName));
}
});
}
My question is this:
How can we regain or rather take control of this "new" tab and do something with it?
How can we know when authorization is complete?If it fails or is successful?
In my previous research all i could come by was the callback approach but how can you send a function to a new tab which knows when to close the tab?And how can you receive authorization information when the user is successfully authenticated?
var win = window.open("window.html");
And then what? You write a function which calls itself every second and checks for input?
(just throwing ideas here)

Implement a window to log in LinkedIn in MVC 5

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).

How to emit an AngularJS event from a popup?

Scenario: I have an AngularJS app that uses Google's auth.
Depends on the resource, when Angular calls (my) backend, it can return a response asking for Oauth token.
In this case, Angular will show a popup (not a Bootstrap's modal dialog) with that redirect URL.
Google will authenticated, ask for permission, and send the user back to me.
There is a callback URL that will process the 'code' and get the real token. This callbak URL will be called inside that popup.
When I get the token, the popup should close itself, and notify Angular to try that last request again (now I have the token in user's session)
Problem: how can a popup emit an Angular event?
Actually, it doesn't need to be that $rootScope.$emit, but just a way to notify Angular.
I saw this option, but it doesn't seem good for Angular :(
you can use localStorage events, take a look at this demo: http://html5demos.com/storage-events
// this should be in the main page
$window.addEventListener('storage', function(event) {
if(event.key === 'login-notification') {
// got it!
// you can get the value from
// the notification with "event.newValue"
}
}, false);
// send the event with just a setItem from the popup
$window.localStorage.setItem('login-notification', 'ayy');
Create a service first.
app.service("servicee", function(){
return {
set : function(k,v){
this[k] = v;
},
get : function (k){
return this[k]
}
}
});
Now in the popup you can set the token in the service, now you have the value available throught out the app. Also you can $watch the specific key in the service and take some action when the value is set.

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