Skip to content

Instantly share code, notes, and snippets.

@lablnet
Created September 1, 2019 05:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lablnet/987422e770fdfbb6a47391e977863883 to your computer and use it in GitHub Desktop.
Save lablnet/987422e770fdfbb6a47391e977863883 to your computer and use it in GitHub Desktop.
Cordova auth
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
<link rel="stylesheet" type="text/css" href="css/index.css" />
<title>Google OAuth with PhoneGap</title>
</head>
<body>
<div class="app">
<div id="login">
<span id="loginT"></span>
<a href="#!">Sign In With PratialValue!</a>
<p></p>
</div>
<div id="greet">
<span id="loginS"></span>
<h1></h1>
</div>
<span id="test"></span>
</div>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/jquery-1.10.1.min.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript">
var login = localStorage.getItem('data');
$("#loginT").text(login);
$("#loginS").text(login);
$("#test").text(localStorage.access_token);
</script>
</body>
</html>
var practicalValueapi = {
setToken: function(data) {
//Cache the token
localStorage.access_token = data.access_token;
//Cache the refresh token, if there is one
localStorage.refresh_token = data.refresh_token || localStorage.refresh_token;
//Figure out when the token will expire by using the current
//time, plus the valid time (in seconds), minus a 1 minute buffer
var expiresAt = new Date().getTime() + parseInt(data.expires_in, 10) * 1000 - 60000;
localStorage.expires_at = expiresAt;
},
authorize: function(options) {
var deferred = $.Deferred();
//Build the OAuth consent page URL
var authUrl = 'https://api.practicalvalue.com/authorization?' + $.param({
client_id: options.client_id,
redirect_uri: options.redirect_uri,
response_type: 'code',
scope: options.scope,
state: 'state',
});
//Open the OAuth consent page in the InAppBrowser
var authWindow = window.open(authUrl, '_blank', 'location=no,toolbar=no');
//The recommendation is to use the redirect_uri "urn:ietf:wg:oauth:2.0:oob"
//which sets the authorization code in the browser's title. However, we can't
//access the title of the InAppBrowser.
//
//Instead, we pass a bogus redirect_uri of "http://localhost", which means the
//authorization code will get set in the url. We can access the url in the
//loadstart and loadstop events. So if we bind the loadstart event, we can
//find the authorization code and close the InAppBrowser after the user
//has granted us access to their data.
authWindow.addEventListener('loadstart', praticalValueCallback);
function praticalValueCallback(e){
var url = (typeof e.url !== 'undefined' ? e.url : e.originalEvent.url);
var code = /\?code=(.+)$/.exec(url);
var error = /\?error=(.+)$/.exec(url);
if (code || error) {
//Always close the browser when match is found
authWindow.close();
}
if (code) {
//Exchange the authorization code for an access token
$.post('https://api.practicalvalue.com/token', {
code: code[1],
client_id: options.client_id,
client_secret: options.client_secret,
redirect_uri: options.redirect_uri,
grant_type: 'authorization_code'
}).done(function(data) {
localStorage.setItem('data', data);
practicalValueapi.setToken(data);
deferred.resolve(data);
}).fail(function(response) {
deferred.reject(response.responseJSON);
});
} else if (error) {
//The user denied access to the app
deferred.reject({
error: error[1]
});
}
}
return deferred.promise();
},
getToken: function(options) {
var deferred = $.Deferred();
if (new Date().getTime() < localStorage.expires_at) {
deferred.resolve({
access_token: localStorage.access_token
});
} else if (localStorage.refresh_token) {
$.post('https://api.practicalvalue.com/token', {
refresh_token: localStorage.refresh_token,
client_id: options.client_id,
client_secret: options.client_secret,
grant_type: 'refresh_token'
}).done(function(data) {
practicalValueapi.setToken(data);
deferred.resolve(data);
}).fail(function(response) {
deferred.reject(response.responseJSON);
});
} else {
deferred.reject();
}
return deferred.promise();
},
userInfo: function(token) {
return $.getJSON('https://api.practicalvalue.com/1/user?format=json&access_token='+token);
}
};
var app = {
client_id: 'XPTO',
client_secret: 'SECRET',
redirect_uri: 'http://localhost',
scope: '',
init: function() {
$('#login a').on('click', function() {
app.onLoginButtonClick();
});
//Check if we have a valid token
//cached or if we can get a new
//one using a refresh token.
practicalValueapi.getToken({
client_id: app.client_id,
client_secret: app.client_secret
}).done(function() {
//Show the greet view if we get a valid token
app.showGreetView();
}).fail(function() {
//Show the login view if we have no valid token
app.showLoginView();
});
},
showLoginView: function() {
$('#login').show();
$('#greet').hide();
},
showGreetView: function() {
$('#login').hide();
$('#greet').show();
//Get the token, either from the cache
//or by using the refresh token.
practicalValueapi.getToken({
client_id: app.client_id,
client_secret: app.client_secret
}).then(function(data) {
//Pass the token to the API call and return a new promise object
localStorage.setItem('login', data);
return practicalValueapi.userInfo(data.access_token);
}).done(function(user) {
//Display a greeting if the API call was successful
$('#greet h1').html('Hello ' + user.name + '!');
}).fail(function() {
//If getting the token fails, or the token has been
//revoked, show the login view.
app.showLoginView();
});
},
onLoginButtonClick: function() {
//Show the consent page
practicalValueapi.authorize({
client_id: app.client_id,
client_secret: app.client_secret,
redirect_uri: app.redirect_uri,
scope: app.scope
}).done(function() {
//Show the greet view if access is granted
app.showGreetView();
}).fail(function(data) {
//Show an error message if access was denied
$('#login p').html(data.error);
});
}
};
$(document).on('deviceready', function() {
app.init();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment