No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 
 
 

360 líneas
12 KiB

  1. var appName;
  2. var popupMask;
  3. var popupDialog;
  4. var clientId;
  5. var realm;
  6. var redirect_uri;
  7. var clientSecret;
  8. var scopeSeparator;
  9. var additionalQueryStringParams;
  10. function handleLogin() {
  11. var scopes = [];
  12. var auths = window.swaggerUiAuth.authSchemes || window.swaggerUiAuth.securityDefinitions;
  13. if(auths) {
  14. var key;
  15. var defs = auths;
  16. for(key in defs) {
  17. var auth = defs[key];
  18. if(auth.type === 'oauth2' && auth.scopes) {
  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], OAuthSchemeKey: key});
  31. }
  32. }
  33. }
  34. }
  35. }
  36. if(window.swaggerUi.api && window.swaggerUi.api.info) {
  37. appName = window.swaggerUi.api.info.title;
  38. }
  39. $('.api-popup-dialog').remove();
  40. popupDialog = $(
  41. [
  42. '<div class="api-popup-dialog">',
  43. '<div class="api-popup-title">Select OAuth2.0 Scopes</div>',
  44. '<div class="api-popup-content">',
  45. '<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.',
  46. '<a href="#">Learn how to use</a>',
  47. '</p>',
  48. '<p><strong>' + appName + '</strong> API requires the following scopes. Select which ones you want to grant to Swagger UI.</p>',
  49. '<ul class="api-popup-scopes">',
  50. '</ul>',
  51. '<p class="error-msg"></p>',
  52. '<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>',
  53. '</div>',
  54. '</div>'].join(''));
  55. $(document.body).append(popupDialog);
  56. //TODO: only display applicable scopes (will need to pass them into handleLogin)
  57. popup = popupDialog.find('ul.api-popup-scopes').empty();
  58. for (i = 0; i < scopes.length; i ++) {
  59. scope = scopes[i];
  60. str = '<li><input type="checkbox" id="scope_' + i + '" scope="' + scope.scope + '"' +'" oauthtype="' + scope.OAuthSchemeKey +'"/>' + '<label for="scope_' + i + '">' + scope.scope ;
  61. if (scope.description) {
  62. if ($.map(auths, function(n, i) { return i; }).length > 1) //if we have more than one scheme, display schemes
  63. str += '<br/><span class="api-scope-desc">' + scope.description + ' ('+ scope.OAuthSchemeKey+')' +'</span>';
  64. else
  65. str += '<br/><span class="api-scope-desc">' + scope.description + '</span>';
  66. }
  67. str += '</label></li>';
  68. popup.append(str);
  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. popupDialog.css({
  79. top: (top < 0? 0 : top) + 'px',
  80. left: (left < 0? 0 : left) + 'px'
  81. });
  82. popupDialog.find('button.api-popup-cancel').click(function() {
  83. popupMask.hide();
  84. popupDialog.hide();
  85. popupDialog.empty();
  86. popupDialog = [];
  87. });
  88. $('button.api-popup-authbtn').unbind();
  89. popupDialog.find('button.api-popup-authbtn').click(function() {
  90. popupMask.hide();
  91. popupDialog.hide();
  92. var authSchemes = window.swaggerUi.api.authSchemes;
  93. var host = window.location;
  94. var pathname = location.pathname.substring(0, location.pathname.lastIndexOf("/"));
  95. var defaultRedirectUrl = host.protocol + '//' + host.host + pathname + '/o2c.html';
  96. var redirectUrl = window.oAuthRedirectUrl || defaultRedirectUrl;
  97. var url = null;
  98. var scopes = []
  99. var o = popup.find('input:checked');
  100. var OAuthSchemeKeys = [];
  101. var state;
  102. for(k =0; k < o.length; k++) {
  103. var scope = $(o[k]).attr('scope');
  104. if (scopes.indexOf(scope) === -1)
  105. scopes.push(scope);
  106. var OAuthSchemeKey = $(o[k]).attr('oauthtype');
  107. if (OAuthSchemeKeys.indexOf(OAuthSchemeKey) === -1)
  108. OAuthSchemeKeys.push(OAuthSchemeKey);
  109. }
  110. //TODO: merge not replace if scheme is different from any existing
  111. //(needs to be aware of schemes to do so correctly)
  112. window.enabledScopes=scopes;
  113. /**
  114. * Returns the name of the access token parameter returned by the server.
  115. *
  116. * @param dets
  117. * The authorisation scheme configuration.
  118. * @return the name of the access token parameter
  119. */
  120. function getTokenName(dets) {
  121. return dets.vendorExtensions['x-tokenName'] || dets.tokenName;
  122. }
  123. for (var key in authSchemes) {
  124. if (authSchemes.hasOwnProperty(key) && OAuthSchemeKeys.indexOf(key) != -1) { //only look at keys that match this scope.
  125. var flow = authSchemes[key].flow;
  126. if(authSchemes[key].type === 'oauth2' && flow && (flow === 'implicit' || flow === 'accessCode')) {
  127. var dets = authSchemes[key];
  128. url = dets.authorizationUrl + '?response_type=' + (flow === 'implicit' ? 'token' : 'code');
  129. window.swaggerUi.tokenName = getTokenName(dets) || 'access_token';
  130. window.swaggerUi.tokenUrl = (flow === 'accessCode' ? dets.tokenUrl : null);
  131. state = key;
  132. }
  133. else if(authSchemes[key].type === 'oauth2' && flow && (flow === 'application')) {
  134. var dets = authSchemes[key];
  135. window.swaggerUi.tokenName = getTokenName(dets) || 'access_token';
  136. clientCredentialsFlow(scopes, dets.tokenUrl, key);
  137. return;
  138. }
  139. else if(authSchemes[key].grantTypes) {
  140. // 1.2 support
  141. var o = authSchemes[key].grantTypes;
  142. for(var t in o) {
  143. if(o.hasOwnProperty(t) && t === 'implicit') {
  144. var dets = o[t];
  145. var ep = dets.loginEndpoint.url;
  146. url = dets.loginEndpoint.url + '?response_type=token';
  147. window.swaggerUi.tokenName = getTokenName(dets);
  148. }
  149. else if (o.hasOwnProperty(t) && t === 'accessCode') {
  150. var dets = o[t];
  151. var ep = dets.tokenRequestEndpoint.url;
  152. url = dets.tokenRequestEndpoint.url + '?response_type=code';
  153. window.swaggerUi.tokenName = getTokenName(dets);
  154. }
  155. }
  156. }
  157. }
  158. }
  159. redirect_uri = redirectUrl;
  160. url += '&redirect_uri=' + encodeURIComponent(redirectUrl);
  161. url += '&realm=' + encodeURIComponent(realm);
  162. url += '&client_id=' + encodeURIComponent(clientId);
  163. url += '&scope=' + encodeURIComponent(scopes.join(scopeSeparator));
  164. url += '&state=' + encodeURIComponent(state);
  165. for (var key in additionalQueryStringParams) {
  166. url += '&' + key + '=' + encodeURIComponent(additionalQueryStringParams[key]);
  167. }
  168. window.open(url);
  169. });
  170. popupMask.show();
  171. popupDialog.show();
  172. return;
  173. }
  174. function handleLogout() {
  175. for(key in window.swaggerUi.api.clientAuthorizations.authz){
  176. window.swaggerUi.api.clientAuthorizations.remove(key)
  177. }
  178. window.enabledScopes = null;
  179. $('.api-ic.ic-on').addClass('ic-off');
  180. $('.api-ic.ic-on').removeClass('ic-on');
  181. // set the info box
  182. $('.api-ic.ic-warning').addClass('ic-error');
  183. $('.api-ic.ic-warning').removeClass('ic-warning');
  184. }
  185. function initOAuth(opts) {
  186. var o = (opts||{});
  187. var errors = [];
  188. appName = (o.appName||errors.push('missing appName'));
  189. popupMask = (o.popupMask||$('#api-common-mask'));
  190. popupDialog = (o.popupDialog||$('.api-popup-dialog'));
  191. clientId = (o.clientId||errors.push('missing client id'));
  192. clientSecret = (o.clientSecret||null);
  193. realm = (o.realm||errors.push('missing realm'));
  194. scopeSeparator = (o.scopeSeparator||' ');
  195. additionalQueryStringParams = (o.additionalQueryStringParams||{});
  196. if(errors.length > 0){
  197. log('auth unable initialize oauth: ' + errors);
  198. return;
  199. }
  200. $('pre code').each(function(i, e) {hljs.highlightBlock(e)});
  201. $('.api-ic').unbind();
  202. $('.api-ic').click(function(s) {
  203. if($(s.target).hasClass('ic-off'))
  204. handleLogin();
  205. else {
  206. handleLogout();
  207. }
  208. false;
  209. });
  210. }
  211. function clientCredentialsFlow(scopes, tokenUrl, OAuthSchemeKey) {
  212. var params = {
  213. 'client_id': clientId,
  214. 'client_secret': clientSecret,
  215. 'scope': scopes.join(' '),
  216. 'grant_type': 'client_credentials'
  217. }
  218. $.ajax(
  219. {
  220. url : tokenUrl,
  221. type: "POST",
  222. data: params,
  223. success:function(data, textStatus, jqXHR)
  224. {
  225. onOAuthComplete(data,OAuthSchemeKey);
  226. },
  227. error: function(jqXHR, textStatus, errorThrown)
  228. {
  229. onOAuthComplete("");
  230. }
  231. });
  232. }
  233. window.processOAuthCode = function processOAuthCode(data) {
  234. var OAuthSchemeKey = data.state;
  235. // redirect_uri is required in auth code flow
  236. // see https://tools.ietf.org/html/draft-ietf-oauth-v2-31#section-4.1.3
  237. var host = window.location;
  238. var pathname = location.pathname.substring(0, location.pathname.lastIndexOf("/"));
  239. var defaultRedirectUrl = host.protocol + '//' + host.host + pathname + '/o2c.html';
  240. var redirectUrl = window.oAuthRedirectUrl || defaultRedirectUrl;
  241. var params = {
  242. 'client_id': clientId,
  243. 'code': data.code,
  244. 'grant_type': 'authorization_code',
  245. 'redirect_uri': redirectUrl
  246. };
  247. if (clientSecret) {
  248. params.client_secret = clientSecret;
  249. }
  250. $.ajax(
  251. {
  252. url : window.swaggerUiAuth.tokenUrl,
  253. type: "POST",
  254. data: params,
  255. success:function(data, textStatus, jqXHR)
  256. {
  257. onOAuthComplete(data, OAuthSchemeKey);
  258. },
  259. error: function(jqXHR, textStatus, errorThrown)
  260. {
  261. onOAuthComplete("");
  262. }
  263. });
  264. };
  265. window.onOAuthComplete = function onOAuthComplete(token, OAuthSchemeKey) {
  266. if(token) {
  267. if(token.error) {
  268. var checkbox = $('input[type=checkbox],.secured')
  269. checkbox.each(function(pos){
  270. checkbox[pos].checked = false;
  271. });
  272. alert(token.error);
  273. }
  274. else {
  275. var b = token[window.swaggerUiAuth.tokenName];
  276. if (!OAuthSchemeKey){
  277. OAuthSchemeKey = token.state;
  278. }
  279. if(b){
  280. // if all roles are satisfied
  281. var o = null;
  282. $.each($('.auth .api-ic .api_information_panel'), function(k, v) {
  283. var children = v;
  284. if(children && children.childNodes) {
  285. var requiredScopes = [];
  286. $.each((children.childNodes), function (k1, v1){
  287. var inner = v1.innerHTML;
  288. if(inner)
  289. requiredScopes.push(inner);
  290. });
  291. var diff = [];
  292. for(var i=0; i < requiredScopes.length; i++) {
  293. var s = requiredScopes[i];
  294. if(window.enabledScopes && window.enabledScopes.indexOf(s) == -1) {
  295. diff.push(s);
  296. }
  297. }
  298. if(diff.length > 0){
  299. o = v.parentNode.parentNode;
  300. $(o.parentNode).find('.api-ic.ic-on').addClass('ic-off');
  301. $(o.parentNode).find('.api-ic.ic-on').removeClass('ic-on');
  302. // sorry, not all scopes are satisfied
  303. $(o).find('.api-ic').addClass('ic-warning');
  304. $(o).find('.api-ic').removeClass('ic-error');
  305. }
  306. else {
  307. o = v.parentNode.parentNode;
  308. $(o.parentNode).find('.api-ic.ic-off').addClass('ic-on');
  309. $(o.parentNode).find('.api-ic.ic-off').removeClass('ic-off');
  310. // all scopes are satisfied
  311. $(o).find('.api-ic').addClass('ic-info');
  312. $(o).find('.api-ic').removeClass('ic-warning');
  313. $(o).find('.api-ic').removeClass('ic-error');
  314. }
  315. }
  316. });
  317. if(typeof window.swaggerUi !== 'undefined') {
  318. window.swaggerUi.api.clientAuthorizations.add(window.swaggerUiAuth.OAuthSchemeKey, new SwaggerClient.ApiKeyAuthorization('Authorization', 'Bearer ' + b, 'header'));
  319. window.swaggerUi.load();
  320. }
  321. }
  322. }
  323. }
  324. };