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