Não pode escolher mais do que 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 

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