I want to get the access token in order to diaply the images of an account. So I display a pop up where the user can connect. The pop up works but it redirects to instagram site, with the user connected instead of send me the code. The link to the connection is something like :
https://www.instagram.com/accounts/login/?force_classic_login=&next=/oauth/authorize/%3Fclient_id=aaaaaaaa&redirect_uri=url&response_type=token
I log in and then, it redirects me to :
https://www.instagram.com/oauth/authorize/?client_id=aaaaaaa&redirect_uri=url&response_type=token
I don't understand how I can get the code. And I also used the exact same code as : https://github.com/radykal/instagram-popup-login
Can someone help me please ?
EDIT
var loc = window.location.host+window.location.pathname;
var accessToken = null; //the access token is required to make any endpoint calls, http://instagram.com/developer/endpoints/
var authenticateInstagram = function(instagramClientId, instagramRedirectUri, callback) {
//the pop-up window size, change if you want
var popupWidth = 700,
popupHeight = 500,
popupLeft = (window.screen.width - popupWidth) / 2,
popupTop = (window.screen.height - popupHeight) / 2;
//the url needs to point to instagram_auth.php
var popup = window.open('instagram_auth.php', '', 'width='+popupWidth+',height='+popupHeight+',left='+popupLeft+',top='+popupTop+'');
popup.onload = function() {
//open authorize url in pop-up
if(window.location.hash.length == 0) {
popup.open('https://instagram.com/oauth/authorize/?client_id='+instagramClientId+'&redirect_uri='+instagramRedirectUri+'&response_type=token', '_self');
}
//an interval runs to get the access token from the pop-up
var interval = setInterval(function() {
try {
console.log(window.location);
//check if hash exists
if(popup.location.hash.length) {
//hash found, that includes the access token
clearInterval(interval);
accessToken = popup.location.hash.slice(14); //slice #access_token= from string
popup.close();
if(callback != undefined && typeof callback == 'function') callback();
}
}
catch(evt) {
//permission denied
console.log("error");
}
}, 100);
}
};
function login_callback() {
alert("You are successfully logged in! Access Token: "+accessToken);
}
function login() {
authenticateInstagram(
'16edb5c3bc05437594d69178f2aa646a', //instagram client ID
'localhost/facebook', //instagram redirect URI
login_callback //optional - a callback function
);
return false;
}
The code is ok, I think it is a problem with your app settings: Login to Instagram Developer, go to "Manage Client" and the "security" tab an disable "Implicit OAuth".
Related
I'm using oAuth to login or sign up using gmail account and decided to use popup window to do it. I found a snippet here which describes the process. But I can't understand how I'll be able to get the values or code if the user logged in with his email.
I can open the modal by this:
//Authorization popup window code
$.oauthpopup = function(options)
{
options.windowName = options.windowName || 'ConnectWithOAuth'; // should not include space for IE
options.windowOptions = options.windowOptions || 'location=0,status=0,width=800,height=400';
options.callback = options.callback || function(){ window.location.reload(); };
var that = this;
log(options.path);
that._oauthWindow = window.open(options.path, options.windowName, options.windowOptions);
that._oauthInterval = window.setInterval(function(){
if (that._oauthWindow.closed) {
window.clearInterval(that._oauthInterval);
options.callback();
}
}, 1000);
};
And use that as follows:
$.oauthpopup({
path: urltoopen,
callback: function()
{
log('callback');
//do callback stuff
}
});
But now, I'm wondering how to auto close the popup and pass parameters from popup window to the main window.
all!
I've followed as many tips and tutorials as I can, but I can't figure out how to obtain an element in Node JS Selenium after moving from the starting page.
In my use case, I go to a login screen, enter the pertinent information, and then run a click() on the login button. I am taken to the home screen.
After this, I cannot select any elements! I just keep getting 'not found' warnings.
I'm sleeping for 6000ms, and I have set the implicit timeouts to 30s.
What am I missing here?
My problematic part would be in the function GoToSettings, which is called after the Login button is clicked.
Thanks
var webdriver = require('selenium-webdriver'),
By = webdriver.By,
until = webdriver.until;
const TIMEOUT = 30
var driver = new webdriver.Builder().forBrowser('chrome').build();
const capabilities = driver.getCapabilities().then(()=>{
capabilities['map_'].set('timeouts', { implicit: TIMEOUT, pageLoad: TIMEOUT, script: TIMEOUT });
});
var info = require('./info.json')
driver.get('http://www.okcupid.com/settings?')
driver.sleep(2000);
//We may already be logged in at this point
driver.getTitle().then((title) => {
driver.getCurrentUrl().then((url) => {
LoginOrHome(title, url);
});
});
function LoginOrHome(title, url){
if(title == "Free Online Dating | OkCupid" || url == "https://www.okcupid.com/login?p=/settings") {
//needslogin.exe
console.log("Logging in!");
login();
} else if (title == "Welcome! | OkCupid" || url == "https://www.okcupid.com/settings?") {
//We are already logged in
console.log("Already logged in. Changing location.");
goToSettings();
} else {
console.log(title);
console.log(url);
}
}
function goToSettings() {
driver.sleep(6000);
driver.switchTo().window(driver.getWindowHandle()).then( () => {
driver.getCurrentUrl().then((title) => {
//This prints the URL of the previous page
console.log(title);
});
})
}
function login(){
driver.findElement(By.name("username")).sendKeys(info.email).then(() => {
driver.findElement(By.name("password")).sendKeys(info.password).then(() => {
driver.findElement(By.css("div > input[type=submit]")).click().then(()=> { goToSettings() });
});
});
}
Using - HTML, JavaScript, JQueryMobile, Phonegap. (One page architecture, all pages are on one html page)
I have an if/else statement for user login, so the if statement directs the user to the homepage (if user/pass found in the database) which works perfectly fine, however I currently have a notification for the else statement but the issue is that after the notification it redirects the user back to the index page instead of remaining on the same page and allowing the user to try again.
What can I use to prevent the page being reloaded to another page for the else statement? I have already tried event.preventDefault(); and event.stopPropagation(); but I just get an error.
See below my current code -
function loginUser()
{
db = window.openDatabase("SoccerEarth", "2.0", "SoccerEarthDB", 2*1024*1024);
db.transaction(loginDB, errorCB);
}
function loginDB(tx)
{
var Username = document.getElementById("username").value;
var Password = document.getElementById("password").value;
tx.executeSql("SELECT * FROM SoccerEarth WHERE UserName='" + Username + "' AND Password= '" + Password + "'", [], renderList);
}
function renderList(tx,results)
{
if (results.rows.length > 0) {
navigator.notification.alert("Login Success!");
window.location = "#page4";
}
else
{
event.preventDefault();
event.stopPropagation();
/* navigator.notification.alert("Incorrect! Please try again. "); */
}
}
function renderList(event, tx, results) {
if (results.rows.length > 0) {
window.location = "#page4";
} else {
event.preventDefault();
event.stopPropagation();
/* navigator.notification.alert("Incorrect! Please try again. "); */
}
You need to pass the event in as a arguement. Then prevent the default behaviour on it by using event.preventDefault();
But I'd like to point out that you aren't using an event here, this is just checking to see if something is on the page.
I need to logout an user if he/she tries to submit any valid URL from the address bar?
I tried jQuery on items below but it is not working.
window.location.href
window.unload
unload code
(window).unload(
function(event) {
//code to handle
});
location href code
(function() //create a scope so 'location' is not global
{ var location = window.location.href;
setInterval(function()
{
if(location != window.location.href)
{
location = window.location.href;
window.location.changed(location);
}
}, 1000);
}
)();
window.location.changed = function(e)
{ console.log(e);//outputs http://newhref.com
//this is fired when the window changes location
}
I am a newbie as far as web development is concerned and even more so with Google App Scripts and OAuth2.0. Having said that, I have researched enough and also tried several tricks, but still can't get past this issue.
I borrowed sample from here:
Google Developers - Client API Library
Then created an Apps Script project with an index.html file with code from that page. I also created a project on the developer console, created a client ID, API key and turned on the required API support. I also made the required changes to the sample to reflect the new client ID and API key.
The index.html page is served from HTML Service with SandBox Mode set to IFRAME. If I load the URL in a browser window (say using incognito mode) and click "Authorize" button, it opens the Google sign-in window. But after signing in, it opens two new tabs with messages
Please close this window
and the original browser window shows no change.
The JavaScript console shows error messages like these:
Unsafe JavaScript attempt to initiate navigation for frame with URL ''
from frame with URL
https://accounts.google.com/o/oauth2/postmessageRelay?parent=https%3A%2F%2F…6lxdpyio6iqy-script.googleusercontent.com#rpctoken=288384029&forcesecure=1.
The frame attempting navigation is sandboxed, and is therefore
disallowed from navigating its ancestors.
From the messages, it seems its an effect of using IFRAME and some sort of security feature is preventing the callback being delivered to the original window. If I reload the original window, things work OK. But that's not what I would ideally like.
How do I work around this issue? Its a very simple project and I can provide source code if that helps.
Thanks,
Pavan
Edit: Here is the sample code I'm trying. You would need to have your client ID and API Key and also set JS origins in the Google Console for things to work:
Code.gs
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('index').setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
index.html
<!--
Copyright (c) 2011 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License"); you may not
use this file except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations under
the License.
To run this sample, replace YOUR API KEY with your application's API key.
It can be found at https://code.google.com/apis/console/?api=plus under API Access.
Activate the Google+ service at https://code.google.com/apis/console/ under Services
-->
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
</head>
<body>
<!--Add a button for the user to click to initiate auth sequence -->
<button id="authorize-button" style="visibility: hidden">Authorize</button>
<script type="text/javascript">
// Enter a client ID for a web application from the Google Developer Console.
// The provided clientId will only work if the sample is run directly from
// https://google-api-javascript-client.googlecode.com/hg/samples/authSample.html
// In your Developer Console project, add a JavaScript origin that corresponds to the domain
// where you will be running the script.
var clientId = 'YOUR_CLIENT_ID';
// Enter the API key from the Google Develoepr Console - to handle any unauthenticated
// requests in the code.
// The provided key works for this sample only when run from
// https://google-api-javascript-client.googlecode.com/hg/samples/authSample.html
// To use in your own application, replace this API key with your own.
var apiKey = 'YOUR API KEY';
// To enter one or more authentication scopes, refer to the documentation for the API.
var scopes = 'https://www.googleapis.com/auth/plus.me';
// Use a button to handle authentication the first time.
function handleClientLoad() {
gapi.client.setApiKey(apiKey);
window.setTimeout(checkAuth,1);
}
function checkAuth() {
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: true, response_type: 'token'}, handleAuthResult);
}
function handleAuthResult(authResult) {
var authorizeButton = document.getElementById('authorize-button');
if (authResult && !authResult.error) {
authorizeButton.style.visibility = 'hidden';
makeApiCall();
} else {
authorizeButton.style.visibility = '';
authorizeButton.onclick = handleAuthClick;
}
}
function handleAuthClick(event) {
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: false, response_type: 'token'}, handleAuthResult);
return false;
}
// Load the API and make an API call. Display the results on the screen.
function makeApiCall() {
gapi.client.load('plus', 'v1', function() {
var request = gapi.client.plus.people.get({
'userId': 'me'
});
request.execute(function(resp) {
var heading = document.createElement('h4');
var image = document.createElement('img');
image.src = resp.image.url;
heading.appendChild(image);
heading.appendChild(document.createTextNode(resp.displayName));
heading.appendChild(document.createTextNode(resp.emails[0].value));
document.getElementById('content').appendChild(heading);
});
});
}
</script>
<script src="https://apis.google.com/js/client.js?onload=handleClientLoad"></script>
<div id="content"></div>
<p>Retrieves your profile name using the Google Plus API.</p>
</body>
</html>
found a solution... not nice but works oO:
the trick is to remove the oauth2relay iframes before the auth window is closed. after the window is closed you have to add the frames again and do a immediate request, if that works the user authorized the app.
be careful:
this script does not check if the user meanwhile is logged out or the token is expired, as long as the webapp window is open the same token is used.
Code.js:
function doGet(e) {
return HtmlService.createTemplateFromFile('Index').evaluate().setTitle(formSettings.title).setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function include(file) {
return HtmlService.createHtmlOutputFromFile(file).getContent();
}
function doPost(meta) {
if (!meta || !meta.auth) {
throw new Error('not authorized');
return;
}
var auth = JSON.parse(UrlFetchApp.fetch('https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=' + meta.auth.access_token, { muteHttpExceptions: true }).getContentText());
if (auth.error || !auth.email) {
throw new Error('not authorized');
return;
}
if (typeof this[meta.method + '_'] == 'function') {
return this[meta.method + '_'](auth.email, meta.data);
}
throw new Error('unknown method');
}
function test_(email, data) {
return email;
}
Index.html:
<html>
<head>
<?!= include('JavaScript'); ?>
</head>
<body>
<div class="content-wrapper">
</div>
</body>
</html>
Javascript.html:
<script type='text/javascript' src="//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script type='text/javascript' src="//apis.google.com/js/client.js?onload=apiLoaded" async></script>
<script type='text/javascript'>
var clientId = '*************-********************************.apps.googleusercontent.com';
var scopes = ['https://www.googleapis.com/auth/plus.me', 'https://www.googleapis.com/auth/userinfo.email'];
var loaded = false;
var auth = null;
function apiLoaded() {
loaded = true;
login();
}
window._open = window.open;
window._windows = [];
window.open = function(url) {
var w = window._open.apply(window,arguments);
window._windows.push(w);
return w;
}
function login(step) {
step || (step = 0);
if (!loaded) {
return;
}
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: (step <= 0 || step >= 2) }, function(authResult) {
if (authResult) {
if (authResult.error) {
if (authResult.error == 'immediate_failed' && authResult.error_subtype == 'access_denied' && step <= 0) {
var interval = setInterval(function() {
var $ifr = $('iframe');//[id^=oauth2relay]');
if (!window._windows.length) {
clearInterval(interval);
return;
}
if ($ifr.length) {
clearInterval(interval);
$ifr.detach();
var w = window._windows.pop();
if (w) {
var interval2 = setInterval(function() {
if (w.closed) {
clearInterval(interval2);
$('body').append($ifr);
login(2);
}
});
} else {
$('body').append($ifr);
}
}
},500);
login(1);
} else if (authResult.error == 'immediate_failed' && authResult.error_subtype == 'access_denied' && step >= 2) {
//user canceled auth
} else {
//error
}
} else {
auth = authResult;
doPost('test', { some: 'data' }, 'test');
}
} else {
//error
}
});
}
function test() {
console.log(arguments);
}
//with this method you can do a post request to webapp server
function doPost(method, data, callbackName) {
data || (data = {});
google.script.run.withSuccessHandler(onSuccess).withFailureHandler(onError).withUserObject({ callback: callbackName }).doPost({ method: method, data: data, auth: auth });
}
function onSuccess(data, meta) {
if (typeof window[meta.callback] == 'function') {
window[meta.callback](null, data);
}
}
function onError(err, meta) {
if (typeof window[meta.callback] == 'function') {
window[meta.callback](err);
}
}
</script>