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