I'm using javascript with drive + spreadsheet api. Now I am able to get the access token. But I tries a lot with stack answers and google guide for get refresh token request. But I did not found any way that how to access the refresh token by access token. Please help me with some code.
My script is:
var _url = https://accounts.google.com/o/oauth2/auth?scope=https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email&client_id={my_client_id}&client_secret={My_secret_key}","redirect_uri=httpmypath to currentrunningfile/oauth&response_type=token
function getAccessDetails() {
var win = window.open(_url, "windowname1", 'width=800, height=600');
var pollTimer = window.setInterval(function() {
try {
console.log(win.document.URL);
if (win.document.URL.indexOf(REDIRECT) != -1) {
window.clearInterval(pollTimer);
var url = win.document.URL;
console.log('url is :'+url);
acToken = gup(url, 'access_token');
tokenType = gup(url, 'token_type');
expiresIn = gup(url, 'expires_in');
console.log('acToken :' + acToken + 'tokenType :' + tokenType + 'expiresIn :' + expiresIn);
win.close();
validateToken(acToken);
}
} catch(e) {
}
}, 500);
}
What is the next step and how to code it for access the refresh token? Actully I want user to login first time to app with their google login details for their drive files access by my app. The next time when user use my app to access his drive files. He can access files without login.
Related
I am currently working on a mobile app with Nativescript. So, I do have a WebView in the main page to log in with Spotify. After the login I have to retrieve headers/queryparams from the page in the WebView. Is this possible and if, how do I do that?
You can register the loadFinishedEvent and check for the URL to get the queryparameters that are returning back to you. I am doing the same for third party login.
webViewLoaded(args) {
const webview: WebView = <WebView>args.object;
webview.on(WebView.loadFinishedEvent, (webargs: LoadEventData) => {
let message;
if (!webargs.error) {
if (webargs.url.toLowerCase().indexOf('spotity') > -1) {
//Read the parameters and navigate
}
message = 'WebView finished loading of ' + webargs.url;
} else {
message = 'Error loading ' + webargs.url + ': ' + webargs.error;
}
});
}
I'm currently migrating my old website to a new one and I have just created some url redirect rules to redirect old links to their pages on the new website.
In order to test these redirect rules I'm using Postman but I can't find any way of getting the redirected url from Postman's scripts documentation. REDIRECTED_URL is the url after being processed by the redirect rule.
Here is my current test:
var root_url = postman.getEnvironmentVariable('root_url');
var oldurl = root_url + postman.getEnvironmentVariable('old_page');
var newurl = root_url + postman.getEnvironmentVariable('new_page');
if (REDIRECTED_URL == newurl)
{
tests[oldurl + " redirected"] = true;
}
else
{
tests[oldurl + " failed to redirect"] = false;
}
Is there a way to test this in postman or should I be using another application?
Switch off the setting Automatically follow redirects in Postman.
Do a request to example.com/test-page/test01
In the test tab, check if the https status code and the re-direct header are correct:
pm.test("Status Code is 301", function () {
pm.response.to.have.status(301);
});
pm.test("Location-header exists", function () {
pm.expect(postman.getResponseHeader("Location")).to.eq("example.com/tests/test01");
});
I'm trying to log in into gmail account using javascript, and I have a problem:
after I insert my email and press 'next', the page redirect me to new url asking for my password. my question is, How can I monitor the current url and know when it changes? Im trying to use page.onUrlChanged but it doesn't work
test.open(url, function(status) {
test.page.evaluate(function (email, password) {
document.getElementById('Email').value = email;
document.getElementById('next').click();
test.page.onUrlChanged = function(targetUrl) {
console.log(targetUrl);
}
}, email, password);});
you can use phatomjs for log URL change..below is simple code for that
var webPage = require('webpage');
var page = webPage.create();
page.onUrlChanged = function(targetUrl) {
console.log('New URL: ' + targetUrl);
};
find more about phantomjs
http://phantomjs.org/api/webpage/handler/on-url-changed.html
or
You can use
window.onblur = function() { console.log('blur'); }
I am implementing Google log in for the first time as described here and here.
I am using HTML with Javascript.
The problem that needs solving is as follows: How can I, after the initial login, on a different page (say a landing page, or portal that the user sees after logging in), check if the user is logged in? Is there a service I can call to check the user's login in status with my app key or something similar?
I assume I would have to include the google API on each page.
Login Page Code:
Script In Head (Code from Google's tutorial listed above):
<head>
....
<script src="https://apis.google.com/js/platform.js" async defer></script>
<script>
function onSignIn(googleUser)
{
var profile = googleUser.getBasicProfile();
console.log('ID: ' + profile.getId());
console.log('Name: ' + profile.getName());
console.log('Image URL: ' + profile.getImageUrl());
console.log('Email: ' + profile.getEmail());
alert(profile.getName());
}
function logout()
{
alert('logging out');
var auth2 = gapi.auth2.getAuthInstance();
auth2.signOut().then(function () {
console.log('User signed out.');
});
}
...
</head>
Code In Body (1st line from Google's tutorial listed above, 2nd line to trigger logout test)
<body>
...
<div class="g-signin2" data-onsuccess="onSignIn"></div>
<div onmousedown="logout()">Logout</div>
...
</body>
Is there some way I can include the google API on another page, and then call some check login status function? Or another way to concretely tell if the user is logged in or out?
You do not need to store anything on local storage. The library allows you to check if the user is logged in or not using the isSignedIn.get() on the auth2 of the gapi object.
Load the JavaScript library, make sure you are not deferring the load :
<script src="https://apis.google.com/js/platform.js"></script>
Then initialize the library and check if the user is logged in or not
var auth2;
var googleUser; // The current user
gapi.load('auth2', function(){
auth2 = gapi.auth2.init({
client_id: 'your-app-id.apps.googleusercontent.com'
});
auth2.attachClickHandler('signin-button', {}, onSuccess, onFailure);
auth2.isSignedIn.listen(signinChanged);
auth2.currentUser.listen(userChanged); // This is what you use to listen for user changes
});
var signinChanged = function (val) {
console.log('Signin state changed to ', val);
};
var onSuccess = function(user) {
console.log('Signed in as ' + user.getBasicProfile().getName());
// Redirect somewhere
};
var onFailure = function(error) {
console.log(error);
};
function signOut() {
auth2.signOut().then(function () {
console.log('User signed out.');
});
}
var userChanged = function (user) {
if(user.getId()){
// Do something here
}
};
Don't forget to change the app id
You can stringify a custom userEntity object and store it in sessionStorage where you can check it anytime you load a new page. I have not tested the following but it should work (doing something similar with WebAPI tokens in the same way)
function onSignIn(googleUser)
{
var profile = googleUser.getBasicProfile();
console.log('ID: ' + profile.getId());
console.log('Name: ' + profile.getName());
console.log('Image URL: ' + profile.getImageUrl());
console.log('Email: ' + profile.getEmail());
var myUserEntity = {};
myUserEntity.Id = profile.getId();
myUserEntity.Name = profile.getName();
//Store the entity object in sessionStorage where it will be accessible from all pages of your site.
sessionStorage.setItem('myUserEntity',JSON.stringify(myUserEntity));
alert(profile.getName());
}
function checkIfLoggedIn()
{
if(sessionStorage.getItem('myUserEntity') == null){
//Redirect to login page, no user entity available in sessionStorage
window.location.href='Login.html';
} else {
//User already logged in
var userEntity = {};
userEntity = JSON.parse(sessionStorage.getItem('myUserEntity'));
...
DoWhatever();
}
}
function logout()
{
//Don't forget to clear sessionStorage when user logs out
sessionStorage.clear();
}
Of course, you can have some internal checks if the sessionStorage object is tampered with. This approach should work with modern browsers like Chrome and Firefox.
To check is user Signed-in use:
gapi.auth2.getAuthInstance().isSignedIn.get()
Adding on to Joseph's answer above, you can then get information about the user by calling auth2.currentUser.get().getBasicProfile().
if (auth2.isSignedIn.get()) {
googleUserProfile = auth2.currentUser.get().getBasicProfile()
console.log('ID: ' + googleUserProfile.getId());
console.log('Full Name: ' + googleUserProfile.getName());
console.log('Given Name: ' + googleUserProfile.getGivenName());
console.log('Family Name: ' + googleUserProfile.getFamilyName());
console.log('Image URL: ' + googleUserProfile.getImageUrl());
console.log('Email: ' + googleUserProfile.getEmail());
}
From the docs: https://developers.google.com/identity/sign-in/web/people
according to the link from Phyrik post (https://developers.google.com/identity/sign-in/web/people) -
google stopped supporting the Sign-In Javascript web auth API:
We are discontinuing the Google Sign-In JavaScript Platform Library for web. The library will be unavailable for download after the March 31, 2023 deprecation date. Instead, use the new Google Identity Services for Web.
By default, newly created Client IDs are now blocked from using the older Platform Library, existing Client IDs are unaffected. New Client IDs created before July 29th, 2022 can set plugin_name to enable use of the Google Platform Library.
I am using session storage to grab my access token generated on the end of my URL by Instagram when a user has authenticated. This isn't working for me on my localhost, please look at the pen I have created as an example of the output. http://codepen.io/anon/pen/eHGBf#access_token=12345.67890
Here is the code I am using:
var token = window.location.hash.substr(1).split("=");
var storeToken = token[1];
if (typeof(Storage) != 'undefined') {
sessionStorage.setItem('accessToken', storeToken);
document.getElementById('access_token').innerHTML = sessionStorage.getItem('accessToken');
} else {
document.getElementById('access_token').innerHTML = 'Sorry, your browser does not support Web Storage';
}
and to display the access token:
<div id="access_token"></div>
When I refresh the page on my localhost (without the access token in the URL) or navigate to other pages and back to the homepage where the token has been displayed in the ID, it returns 'undefined' and I have to log in again. I thought it should have saved the token?
Any help is greatly appreciated.
var token = window.location.hash.substr(1).split("=");
var storeToken = token[1];
if (storeToken) {
sessionStorage.setItem('accessToken', storeToken);
}
if (sessionStorage.getItem('accessToken')) {
document.getElementById('access_token').innerHTML = sessionStorage.getItem('accessToken');
}