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