Catch User 'Allow/Deny' Response on Computer Location Query - javascript

I am using MaxMind GeoIP2 JavaScript API to determine a user's location when they enter my website. This prompts the user for their permission to provide the location via the browser. I am using this information to load as the default position of a map I have on my website.
I was wondering if there is some capture for this Allow/Deny prompt click. For example, the map loads the default position if the user were to deny the request, but if there user hasn't made a choice until after the map loads, I'd like to relocate the map if they do happen to click Allow once the browser has loaded the website.
For what it is worth, here is some example code that gets the users information once permission is given (taken from the URL above):
<script type="text/javascript" src="//j.maxmind.com/js/apis/geoip2/v2.0/geoip2.js"></script>
<script type="text/javascript">
var onSuccess = function(location){
alert(
"Lookup successful:\n\n" + JSON.stringify(location, undefined, 4)
);
};
var onError = function(error){
alert(
"Error:\n\n" + JSON.stringify(error, undefined, 4)
);
};
geoip2.city(onSuccess, onError);
</script>

Related

How to get username from authentication prompt popup

I have SharePoint Online classic page which has some custom JavaScript and jQuery scripts implemented and third party .NET app requiring some basic auth. When the user visits the page he is prompted to enter username and password. How can I get the username from this prompt? Prompt is standard and looks like this (picture is not mine)
You can use SharePoint's javascript API to retrieve the current user's information.
_spPageContextInfo.userId
see: https://social.technet.microsoft.com/wiki/contents/articles/29766.sharepoint-understanding-the-sppagecontextinfo-object.aspx
Another suggestion is to use the API:
<script type="text/javascript">
ExecuteOrDelayUntilScriptLoaded(getCurrentUser, "sp.js");
var currentUser;
function getCurrentUser(){
var ctx= new SP.ClientContext.get_current();
var web = ctx.get_web();
currentUser = web.get_currentUser();
ctx.load(currentUser);
ctx.executeQueryAsync(onSuccess, onFailure);
}
function onSuccess() {
alert(currentUser.get_title()); // Domain\Account
alert(currentUser.get_email());
document.getElementById('userLogin').innerHTML = currentUser.get_loginName();
}
function onFailure() {
alert('request failed' + args.get_message() + '\n' + args.get_stackTrace());
}
</script>
<div>Currently Logged User:
<span id="userLogin"></span>
</div>
MS reference: https://learn.microsoft.com/en-us/sharepoint/dev/sp-add-ins/complete-basic-operations-using-sharepoint-client-library-code
If someone is still interested in this I found a way to get the user principal name with microsoft graph API https://learn.microsoft.com/en-us/graph/api/user-get?view=graph-rest-1.0&tabs=http
https://graph.microsoft.com/v1.0/me?$select=mailnickname,onpremisesUserprincipalName was the actual request I needed

WebExtension: How can I access the background script in my browser action

I'm totally new to WebExtension (trying to use them under Firefox). I've written a browser action. In order to keep a persistent state I figured that I have to implement a background script.
How can I acccess variables defined in the background script from my browser-action script?
Or is the assumption wrong that the background script can contain the state for the browser action?
Ok, got it. I found a good start here and here.
I use message posting for communication between my browser-action and background script.
Think of a game where you can act in the browser action popup and the game state is in the background script. Here is an example for getting number of coins (player money) from the background script to the browser-action:
browser-action:
var _playerCoins = 0;
// I connect a 'port' with the name 'getCoins'.
var _port = chrome.runtime.connect({name: "getCoins"});
// This is the message that is called if the other side posts a message via the port.
// The background script puts the current amount of coins into the message
_port.onMessage.addListener(function(msg) {
// Save the number of coins in a local variable
_playerCoins = msg;
// Display number of coins on my browser action html page
document.getElementById("coins").innerHTML="Coins: " + _playerCoins;
});
background script:
// Add a listener for port connections
chrome.runtime.onConnect.addListener(function(port) {
// If there is a 'getCoins' connection coming in...
if(port.name == "getCoins") {
// ...add a listener that is called when the other side posts a message on the port.
port.onMessage.addListener(function(msg) {
port.postMessage(_playerCoins);
});
}
}

How to determine if google auth2.signIn() window was closed by the user?

Im implementing auth using this and am currently showing a loading icon in React when a user clicks the button to sign in and the auth2 account selection/login window shows.
However if a user closes the window, there doesnt seem to be any event fired i.e the signIn() function which returns a promise never resolves, I would have thought google would return an error for this promise if the window is closed. As a result there is no way for me to stop showing the loader icon and reshow the login menu.
I was wondering if anyone had a solution for this?
I try to modifiy my code that call Google OAuth 2.0 window.
You only have to add extra AJAX method that cover what is Google OAuth error result.
gapi.auth2.getAuthInstance().signIn()
Change it to this one,
gapi.auth2.getAuthInstance().signIn().then(function(response){
//If Google OAuth 2 works fine
console.log(response);
}, function(error){
//If Google OAuth 2 occured error
console.log(error);
if(error.error === 'popup_closed_by_user'){
alert('Oh Dude, Why you close authentication user window...!');
}
});
That's it...
For more detail about Google OAuth 2.0 information, you can visit this link.
https://developers.google.com/api-client-library/javascript/samples/samples#authorizing-and-making-authorized-requests
Sample code on JavaScript:
https://github.com/google/google-api-javascript-client/blob/master/samples/authSample.html
Although the API provides a mechanism for detecting when the user clicks the Deny button, there is not a built-in way for detecting that the user abruptly closed the popup window (or exited their web browser, shut down their computer, and so on). The Deny condition is provided in case you want to re-prompt the user with reduced scopes (e.g. you requested "email" but only need profile and will let the user proceed without giving you their email).
If the response from the sign-in callback contains the error, access_denied, it indicates the user clicked the deny button:
function onSignInCallback(authResult) {
if (authResult['error'] && authResult['error'] == 'access_denied') {
// User explicitly denied this application's requested scopes
}
}
You should be able to implement sign-in without detecting whether the window was closed; this is demonstrated in virtually all of the Google+ sample apps. In short, you should avoid using a spinner as you're doing and instead should hide authenticated UI until the user has successfully signed in.
It's not recommended you do this, but to implement detection of the pop-up closing, you could do something like override the global window.open call, then detect in window.unload or poll whether the window was closed without the user authenticating:
var lastOpenedWindow = undefined;
window.open = function (open) {
return function (url, name, features) {
// set name if missing here
name = name || "default_window_name";
lastOpenedWindow = open.call(window, url, name, features);
return lastOpenedWindow;
};
}(window.open);
var intervalHandle = undefined;
function detectClose() {
intervalHandle = setInterval(function(){
if (lastOpenedWindow && lastOpenedWindow.closed) {
// TODO: check user was !authenticated
console.log("Why did the window close without auth?");
window.clearInterval(intervalHandle);
}
}, 500);
}
Note that as I've implemented it, this mechanism is unreliable and subject to race conditions.

Chrome Extension: How to get user name?

I'm creating a Google chrome extension. For some functionality, I need user's system login name (no password). By using JavaScript, it is not possible to do so.
Some suggest NPAPI, but I have no idea about it, so I quit.
Next thing I'm trying to get user name in Chrome Browser. But still no success.
I try to use some thing like:
var currentUser;
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(data) {
if (xhr.readyState == 1) {
currentUser = null;
if (xhr.status == 200)
{
var re = new RegExp(/<b class="?gb4"?>[\s]*([^<]+#[^<]+) <\/b>/i);
var m = re.exec(xhr.responseText);
if (m && m.length == 2) {
currentUser = m[1];
}
}
console.log("Currently logged user (on google.com): " + currentUser);
}
};
xhr.open('GET', ' https://myaccount.google.com/?pli=1', false);
xhr.send(); `
still no success.
My whole agenda is to get user name (either desktop login name or Chrome login name), and I'm not able to get it.
I need to send this username as parameter to my service, as user name works as primary key.
First off, you say that you need this login information to identify a user, using it as a primary key.
That automatically disqualifies system login names: they are not unique.
Now, let's get back to logged-in Chrome user. Google Account is reasonably unique.
There are two approaches to take here.
Chrome's chrome.identity API can provide both the email and, maybe better for your purposes, a unique ID for the account.
You will need "identity" and "identity.email" permissions. Then:
chrome.identity.getProfileUserInfo(function(userInfo) {
/* Use userInfo.email, or better (for privacy) userInfo.id
They will be empty if user is not signed in in Chrome */
});
An alternative approach is to use Google's OAuth on your service. Again, see the chrome.identity documentation.
Chrome.identity has a method getProfileUserInfo but it gives out the details of only primary user.
There is an alternative:
When you open chrome, you launch onto the home screen and you should be able to see a circle on the top right corner which shows image of logged in user. You can access that using DOM. Once you do that you will be able to get information about all the logged in users.

Facebook Application permission

Hi I have developed a Facebook application in Flash using Action-script 3. The application is working fine. I have developed Facebook login and authentication in JavaScript. The problem is then the user is not sign in to Facebook the application works fine, provide the user login panel and application permission panel and post the desire thing on user wall but if the user is already sign in than the JavaScript wont ask for the Facebook app permission and hence the app wont post on user wall. My JavaScript code is
<script type="text/javascript">
var APP_ID = "xxxxxxxxxxxxxxx";
var REDIRECT_URI = "http://apps.facebook.com/engel-tanimiyorum/";
var PERMS = 'publish_stream , email, user_birthday'; //comma separated list of extended permissions
function init()
{
FB.init({appId:APP_ID, status: true, cookie: true, oauth: true});
FB.getLoginStatus(handleLoginStatus);
}
function handleLoginStatus(response)
{
if (response.authResponse && response.status=="connected")
{
//Show the SWF
$('#ConnectDemo').append('<h1>You need at least Flash Player 9.0 to view this page.</h1>');
swfobject.embedSWF("index.swf",
"ConnectDemo", "803", "516", "9.0", null, null, null, {name:"ConnectDemo"});
}
else
{
var params = window.location.toString().slice(window.location.toString().indexOf('?'));
top.location = 'http://graph.facebook.com/oauth/authorize?client_id='
+APP_ID
+'&scope='+PERMS
+'&redirect_uri=' + REDIRECT_URI
+ params;
}
}
$(init);
</script>
Yours quick response will be highly appreciable
Regards
I don't know if this helps or not. But instead of your
var PERMS = 'publish_stream , email, user_birthday';
I do believe it should be states as an Array and then you would list your permissions.
It works for me, so I think it should look like this:
public var PERMS:Array = ["publish_stream","email","user_birthday"];
Also, not having your variables public might be the problem too.
Also, from what I see, you don't have any buttons, or text input?
If not, you need to create those. Then have a click handler for when there is text in the text input it will activate a click handler that then will go to a submit post handler, which then goes to a get status handler that will show you the new status you have created. I may be saying this all wrong. After all, I am not using Java for my app. But it seems logical to me that that is what you would do.. Try my first suggestions out and get back to me. If you'd rather, email me at Shandan_Spencer#live.com, so I can help you some more.

Categories

Resources