SHARE
TWEET

Untitled

a guest Apr 21st, 2017 76 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. let AUTHORIZATION_URL = 'http://localhost:8010/Sitefinity/Authenticate/OpenID/connect/authorize';
  2. let PRESS_RELEASES_URL = 'http://localhost:8010/api/default/pressreleases';
  3. let ACCESS_TOKEN_KEY = 'access_token';
  4. let ACCESS_TOKEN_EXP_KEY = 'access_token_exp';
  5.  
  6. window.onload = () => {
  7.     // STS redirect URI. Access token is being received here
  8.     if (window.location.hash) {
  9.         let tokenResponse = getTokenResponse();
  10.         saveToLocalStorage(tokenResponse.access_token);
  11.     }
  12.     // Token has expired or is not present. Requests new access token
  13.     else if (hasExpired()) {
  14.         let authFrame = appendAuthFrame();
  15.         getToken(authFrame, () => {
  16.             let token = localStorage[ACCESS_TOKEN_KEY];
  17.             logPressReleases(token);
  18.             authFrame.remove();
  19.         });
  20.     }
  21.     // Token is available for use
  22.     else {
  23.         let token = localStorage[ACCESS_TOKEN_KEY];
  24.         logPressReleases(token);
  25.     }
  26. }
  27.  
  28. function getToken(authFrame, callback) {
  29.     // Prevents CSRF (Cross-Site Request Forgery) attacks
  30.     let state = rand();
  31.     let nonce = rand();
  32.     localStorage['state'] = state;
  33.     localStorage['nonce'] = nonce;
  34.  
  35.     let authorizationUrl = AUTHORIZATION_URL;
  36.     let clientId = 'sitefinity';
  37.     let redirectUri = getCurrentUri();
  38.     let responseType = 'id_token token';
  39.     let scope = 'openid email profile';
  40.     let url = authorizationUrl + '?' +
  41.         'client_id=' + encodeURI(clientId) + '&' +
  42.         'redirect_uri=' + encodeURI(redirectUri) + '&' +
  43.         'response_type=' + encodeURI(responseType) + '&' +
  44.         'scope=' + encodeURI(scope) + '&' +
  45.         'state=' + encodeURI(state) + '&' +
  46.         'nonce=' + encodeURI(nonce);
  47.     authFrame.src = url;
  48.     authFrame.addEventListener('load', () => {
  49.         callback();
  50.     });
  51. }
  52.  
  53. function getTokenResponse() {
  54.     let hash = window.location.hash.substr(1);
  55.     let result = hash.split('&').reduce((result, item) => {
  56.         let parts = item.split('=');
  57.         result[parts[0]] = parts[1];
  58.         return result;
  59.     }, {});
  60.  
  61.     return result;
  62. }
  63.  
  64. function appendAuthFrame() {
  65.     let authFrame = document.createElement('iframe');
  66.     authFrame.style.display = 'none';
  67.     document.body.appendChild(authFrame);
  68.     return authFrame;
  69. }
  70.  
  71. function hasExpired() {
  72.     if (!localStorage[ACCESS_TOKEN_KEY] || !localStorage[ACCESS_TOKEN_EXP_KEY]) {
  73.         return true;
  74.     }
  75.  
  76.     let currentDate = new Date();
  77.     let expirationDate = new Date(localStorage[ACCESS_TOKEN_EXP_KEY]);
  78.     return currentDate > expirationDate;
  79. }
  80.  
  81. function decodeJwt(token) {
  82.     let base64Url = token.split('.')[1];
  83.     let base64 = base64Url.replace('-', '+').replace('_', '/');
  84.     return JSON.parse(window.atob(base64));
  85. }
  86.  
  87. function getExpirationDate(token) {
  88.     let tokenInfo = decodeJwt(token);
  89.     let expirationDate = new Date(tokenInfo.exp * 1000);
  90.     return expirationDate;
  91. }
  92.  
  93. function saveToLocalStorage(token) {
  94.     localStorage[ACCESS_TOKEN_KEY] = token;
  95.     localStorage[ACCESS_TOKEN_EXP_KEY] = getExpirationDate(token);
  96. }
  97.  
  98. function logPressReleases(token) {
  99.     getJSON(PRESS_RELEASES_URL, token)
  100.         .then(console.log)
  101.         .catch(console.log);
  102. }
  103.  
  104. function getJSON(url, token) {
  105.     return new Promise((resolve, reject) => {
  106.         let xhr = new XMLHttpRequest();
  107.         xhr.responseType = 'json';
  108.  
  109.         xhr.onload = () => {
  110.             try {
  111.                 if (xhr.status === 200) {
  112.                     let response = xhr.response;
  113.                     if (typeof response === 'string') {
  114.                         response = JSON.parse(response);
  115.                     }
  116.                     resolve(response);
  117.                 }
  118.                 else {
  119.                     reject(Error(`${xhr.statusText} (${xhr.status})`));
  120.                 }
  121.             }
  122.             catch (err) {
  123.                 reject(err);
  124.             }
  125.         }
  126.  
  127.         xhr.onerror = () => {
  128.             reject(Error('Network error'));
  129.         }
  130.  
  131.         xhr.open('GET', url);
  132.         xhr.setRequestHeader('Authorization', `Bearer ${token}`);
  133.         xhr.send();
  134.     });
  135. }
  136.  
  137. function getCurrentUri() {
  138.     return window.location.href.split('?')[0];
  139. }
  140.  
  141. function rand() {
  142.     return (Date.now() + '' + Math.random()).replace('.', '');
  143. }
RAW Paste Data
Pastebin PRO Summer Special!
Get 40% OFF on Pastebin PRO accounts!
Top