github.com/enmand/kubernetes@v1.2.0-alpha.0/third_party/swagger-ui/lib/swagger-oauth.js (about)

     1  var appName;
     2  var popupMask;
     3  var popupDialog;
     4  var clientId;
     5  var realm;
     6  var oauth2KeyName;
     7  
     8  function handleLogin() {
     9    var scopes = [];
    10  
    11    var auths = window.swaggerUi.api.authSchemes || window.swaggerUi.api.securityDefinitions;
    12    if(auths) {
    13      var key;
    14      var defs = auths;
    15      for(key in defs) {
    16        var auth = defs[key];
    17        if(auth.type === 'oauth2' && auth.scopes) {
    18          oauth2KeyName = key;
    19          var scope;
    20          if(Array.isArray(auth.scopes)) {
    21            // 1.2 support
    22            var i;
    23            for(i = 0; i < auth.scopes.length; i++) {
    24              scopes.push(auth.scopes[i]);
    25            }
    26          }
    27          else {
    28            // 2.0 support
    29            for(scope in auth.scopes) {
    30              scopes.push({scope: scope, description: auth.scopes[scope]});
    31            }
    32          }
    33        }
    34      }
    35    }
    36  
    37    if(window.swaggerUi.api
    38      && window.swaggerUi.api.info) {
    39      appName = window.swaggerUi.api.info.title;
    40    }
    41  
    42    popupDialog = $(
    43      [
    44        '<div class="api-popup-dialog">',
    45        '<div class="api-popup-title">Select OAuth2.0 Scopes</div>',
    46        '<div class="api-popup-content">',
    47          '<p>Scopes are used to grant an application different levels of access to data on behalf of the end user. Each API may declare one or more scopes.',
    48            '<a href="#">Learn how to use</a>',
    49          '</p>',
    50          '<p><strong>' + appName + '</strong> API requires the following scopes. Select which ones you want to grant to Swagger UI.</p>',
    51          '<ul class="api-popup-scopes">',
    52          '</ul>',
    53          '<p class="error-msg"></p>',
    54          '<div class="api-popup-actions"><button class="api-popup-authbtn api-button green" type="button">Authorize</button><button class="api-popup-cancel api-button gray" type="button">Cancel</button></div>',
    55        '</div>',
    56        '</div>'].join(''));
    57    $(document.body).append(popupDialog);
    58  
    59    popup = popupDialog.find('ul.api-popup-scopes').empty();
    60    for (i = 0; i < scopes.length; i ++) {
    61      scope = scopes[i];
    62      str = '<li><input type="checkbox" id="scope_' + i + '" scope="' + scope.scope + '"/>' + '<label for="scope_' + i + '">' + scope.scope;
    63      if (scope.description) {
    64        str += '<br/><span class="api-scope-desc">' + scope.description + '</span>';
    65      }
    66      str += '</label></li>';
    67      popup.append(str);
    68    }
    69  
    70    var $win = $(window),
    71      dw = $win.width(),
    72      dh = $win.height(),
    73      st = $win.scrollTop(),
    74      dlgWd = popupDialog.outerWidth(),
    75      dlgHt = popupDialog.outerHeight(),
    76      top = (dh -dlgHt)/2 + st,
    77      left = (dw - dlgWd)/2;
    78  
    79    popupDialog.css({
    80      top: (top < 0? 0 : top) + 'px',
    81      left: (left < 0? 0 : left) + 'px'
    82    });
    83  
    84    popupDialog.find('button.api-popup-cancel').click(function() {
    85      popupMask.hide();
    86      popupDialog.hide();
    87      popupDialog.empty();
    88      popupDialog = [];
    89    });
    90  
    91    $('button.api-popup-authbtn').unbind();
    92    popupDialog.find('button.api-popup-authbtn').click(function() {
    93      popupMask.hide();
    94      popupDialog.hide();
    95  
    96      var authSchemes = window.swaggerUi.api.authSchemes;
    97      var host = window.location;
    98      var pathname = location.pathname.substring(0, location.pathname.lastIndexOf("/"));
    99      var redirectUrl = host.protocol + '//' + host.host + pathname + '/o2c.html';
   100      var url = null;
   101  
   102      for (var key in authSchemes) {
   103        if (authSchemes.hasOwnProperty(key)) {
   104          var flow = authSchemes[key].flow;
   105          
   106          if(authSchemes[key].type === 'oauth2' && flow && (flow === 'implicit' || flow === 'accessCode')) {
   107            var dets = authSchemes[key];
   108            url = dets.authorizationUrl + '?response_type=' + (flow === 'implicit' ? 'token' : 'code');
   109            window.swaggerUi.tokenName = dets.tokenName || 'access_token';
   110            window.swaggerUi.tokenUrl = (flow === 'accessCode' ? dets.tokenUrl : null);          
   111          }
   112          else if(authSchemes[key].grantTypes) {
   113            // 1.2 support
   114            var o = authSchemes[key].grantTypes;
   115            for(var t in o) {
   116              if(o.hasOwnProperty(t) && t === 'implicit') {
   117                var dets = o[t];
   118                var ep = dets.loginEndpoint.url;
   119                url = dets.loginEndpoint.url + '?response_type=token';
   120                window.swaggerUi.tokenName = dets.tokenName;
   121              }
   122              else if (o.hasOwnProperty(t) && t === 'accessCode') {
   123                var dets = o[t];
   124                var ep = dets.tokenRequestEndpoint.url;
   125                url = dets.tokenRequestEndpoint.url + '?response_type=code';
   126                window.swaggerUi.tokenName = dets.tokenName;
   127              }
   128            }
   129          }
   130        }
   131      }
   132      var scopes = []
   133      var o = $('.api-popup-scopes').find('input:checked');
   134  
   135      for(k =0; k < o.length; k++) {
   136        var scope = $(o[k]).attr('scope');
   137        
   138        if (scopes.indexOf(scope) === -1)
   139          scopes.push(scope);
   140      }
   141  
   142      window.enabledScopes=scopes;
   143  
   144      url += '&redirect_uri=' + encodeURIComponent(redirectUrl);
   145      url += '&realm=' + encodeURIComponent(realm);
   146      url += '&client_id=' + encodeURIComponent(clientId);
   147      url += '&scope=' + encodeURIComponent(scopes);
   148  
   149      window.open(url);
   150    });
   151  
   152    popupMask.show();
   153    popupDialog.show();
   154    return;
   155  }
   156  
   157  
   158  function handleLogout() {
   159    for(key in window.authorizations.authz){
   160      window.authorizations.remove(key)
   161    }
   162    window.enabledScopes = null;
   163    $('.api-ic.ic-on').addClass('ic-off');
   164    $('.api-ic.ic-on').removeClass('ic-on');
   165  
   166    // set the info box
   167    $('.api-ic.ic-warning').addClass('ic-error');
   168    $('.api-ic.ic-warning').removeClass('ic-warning');
   169  }
   170  
   171  function initOAuth(opts) {
   172    var o = (opts||{});
   173    var errors = [];
   174  
   175    appName = (o.appName||errors.push('missing appName'));
   176    popupMask = (o.popupMask||$('#api-common-mask'));
   177    popupDialog = (o.popupDialog||$('.api-popup-dialog'));
   178    clientId = (o.clientId||errors.push('missing client id'));
   179    realm = (o.realm||errors.push('missing realm'));
   180  
   181    if(errors.length > 0){
   182      log('auth unable initialize oauth: ' + errors);
   183      return;
   184    }
   185  
   186    $('pre code').each(function(i, e) {hljs.highlightBlock(e)});
   187    $('.api-ic').unbind();
   188    $('.api-ic').click(function(s) {
   189      if($(s.target).hasClass('ic-off'))
   190        handleLogin();
   191      else {
   192        handleLogout();
   193      }
   194      false;
   195    });
   196  }
   197  
   198  function processOAuthCode(data) {
   199    var params = {
   200      'client_id': clientId,
   201      'code': data.code,
   202      'grant_type': 'authorization_code'
   203    }
   204    $.ajax(
   205    {
   206      url : window.swaggerUi.tokenUrl,
   207      type: "POST",
   208      data: params,
   209      success:function(data, textStatus, jqXHR) 
   210      {
   211        onOAuthComplete(data);
   212      },
   213      error: function(jqXHR, textStatus, errorThrown) 
   214      {
   215        onOAuthComplete("");
   216      }
   217    });
   218  }
   219  
   220  function onOAuthComplete(token) {
   221    if(token) {
   222      if(token.error) {
   223        var checkbox = $('input[type=checkbox],.secured')
   224        checkbox.each(function(pos){
   225          checkbox[pos].checked = false;
   226        });
   227        alert(token.error);
   228      }
   229      else {
   230        var b = token[window.swaggerUi.tokenName];
   231        if(b){
   232          // if all roles are satisfied
   233          var o = null;
   234          $.each($('.auth #api_information_panel'), function(k, v) {
   235            var children = v;
   236            if(children && children.childNodes) {
   237              var requiredScopes = [];
   238              $.each((children.childNodes), function (k1, v1){
   239                var inner = v1.innerHTML;
   240                if(inner)
   241                  requiredScopes.push(inner);
   242              });
   243              var diff = [];
   244              for(var i=0; i < requiredScopes.length; i++) {
   245                var s = requiredScopes[i];
   246                if(window.enabledScopes && window.enabledScopes.indexOf(s) == -1) {
   247                  diff.push(s);
   248                }
   249              }
   250              if(diff.length > 0){
   251                o = v.parentNode;
   252                $(o.parentNode).find('.api-ic.ic-on').addClass('ic-off');
   253                $(o.parentNode).find('.api-ic.ic-on').removeClass('ic-on');
   254  
   255                // sorry, not all scopes are satisfied
   256                $(o).find('.api-ic').addClass('ic-warning');
   257                $(o).find('.api-ic').removeClass('ic-error');
   258              }
   259              else {
   260                o = v.parentNode;
   261                $(o.parentNode).find('.api-ic.ic-off').addClass('ic-on');
   262                $(o.parentNode).find('.api-ic.ic-off').removeClass('ic-off');
   263  
   264                // all scopes are satisfied
   265                $(o).find('.api-ic').addClass('ic-info');
   266                $(o).find('.api-ic').removeClass('ic-warning');
   267                $(o).find('.api-ic').removeClass('ic-error');          
   268              }
   269            }
   270          });
   271          window.authorizations.add(oauth2KeyName, new ApiKeyAuthorization('Authorization', 'Bearer ' + b, 'header'));
   272        }
   273      }
   274    }
   275  }