Last active
August 10, 2017 14:00
-
-
Save sohelrana820/7369d4a69955aa4632ea47e0b6ed9fe7 to your computer and use it in GitHub Desktop.
oAuth_login.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> | |
<script> | |
var authorizeUrl = 'http://example.com/oauth/authorize?'; | |
var accessTokenValidatorUrl = 'http://example.com/user-info'; | |
var scope = 'basic email'; | |
var clientId = 'client_id'; | |
var redirectUrl = 'http://localhost:8081'; | |
var responseType = 'token'; | |
var oAuthUrl = authorizeUrl + 'scope=' + scope + '&client_id=' + clientId + '&redirect_uri=' + redirectUrl + '&response_type=' + responseType; | |
var accessTokenInfo = []; | |
var user; | |
function login() { | |
var win = window.open(oAuthUrl, "oAuth Login", 'width=800, height=600'); | |
var pollTimer = window.setInterval(function () { | |
try { | |
var url = win.document.URL; | |
var hasCode = win.document.URL.split('#access_token'); | |
if (hasCode.length > 1) { | |
var code = hasCode[1]; | |
window.clearInterval(pollTimer); | |
var acToken = gup(url, 'access_token'); | |
var tokenType = gup(url, 'token_type'); | |
var expiresIn = gup(url, 'expires_in'); | |
getUserInfo(acToken); | |
win.close(); | |
accessTokenInfo.access_token = acToken; | |
accessTokenInfo.token_type = tokenType; | |
accessTokenInfo.expire_in = expiresIn; | |
console.log(accessTokenInfo); | |
} | |
} catch (e) { | |
console.log(e); | |
} | |
}, 500); | |
} | |
function getUserInfo(acToken) { | |
$.ajax({ | |
url: accessTokenValidatorUrl, | |
type: 'GET', | |
beforeSend: function (request) { | |
request.setRequestHeader("Authorization", 'Bearer ' + acToken); | |
}, | |
success: function (response) { | |
user = response; | |
console.log(user); | |
} | |
}); | |
} | |
/** | |
* @param url | |
* @param name | |
* @returns {*} | |
*/ | |
function gup(url, name) { | |
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]"); | |
var pattern = "[\\#&]" + name + "=([^&#]*)"; | |
var regexExp = new RegExp(pattern); | |
var results = regexExp.exec(url); | |
if (results == null) { | |
return ""; | |
} else { | |
return results[1]; | |
} | |
} | |
</script> | |
</head> | |
<body> | |
<a onClick='login();' id="loginText"> Click here to login </a> | |
<iframe name='myIFrame' id="myIFrame" style='display:none'></iframe> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment