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