summaryrefslogtreecommitdiffstats
path: root/samples/OAuthClient/SampleWcf2Javascript.js
blob: 9eb945e3edc57d5cc778b31ef358c523aa9da504 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
var utilities = {
	assembleQueryString: function(args) {
		var query = '?';
		for (var key in args) {
			if (query.length > 1) query += '&';
			query += encodeURIComponent(key) + '=' + encodeURIComponent(args[key])
		};
		return query;
	},

	parseQueryString: function (query) {
		var result = new Array();
		var pairs = query.split('&');
		for (var i = 0; i < pairs.length; i++) {
			var pair = pairs[i].split('=');
			var key = decodeURIComponent(pair[0]);
			var value = decodeURIComponent(pair[1]);
			result[key] = value;
		};
		return result;
	},

	stripQueryAndFragment: function (url) {
		var index = url.indexOf('?');
		if (index < 0) index = url.indexOf('#');
		url = index < 0 ? url : url.substring(0, index);
		return url;
	}
};

$(document).ready(function () {
	var requestAuthorizationButton = $('#requestAuthorizationButton');

	function gatherRequestedScopes() {
		scopes = '';
		var scopeElements = $("input[name='scope']");
		for (var i = 0; i < scopeElements.length; i++) {
			if (scopeElements[i].checked) {
				if (scopes.length > 0) scopes += ' ';
				scopes += scopeElements[i].value;
			}
		};
		return scopes;
	};

	function requestAuthorizationButton_onClick(evt) {
		var args = new Array();
		args['scope'] = gatherRequestedScopes();
		args['redirect_uri'] = utilities.stripQueryAndFragment(document.location.href);
		args['response_type'] = 'token';
		args['client_id'] = 'sampleImplicitConsumer';

		var authorizeUrl = "http://localhost:50172/OAuth/Authorize" + utilities.assembleQueryString(args);
		document.location = authorizeUrl;
	};

	requestAuthorizationButton.click(requestAuthorizationButton_onClick);
});

$(document).ready(function () {
	var fragmentIndex = document.location.href.indexOf('#');
	if (fragmentIndex > 0) {
		var fragment = document.location.href.substring(fragmentIndex + 1);
		var args = utilities.parseQueryString(fragment);
		if (args['access_token']) {
			var authorizationLabel = $('#authorizationLabel');
			var lifetimeInSeconds = args['expires_in'];
			var suffix = '(access token expires in ' + lifetimeInSeconds + ' seconds)';
			authorizationLabel.text('Authorization received! ' + suffix);

			var scopes = args['scope'].split(' ');
			for (var scope in scopes) {
				var button = $('input[operation="' + scopes[scope] + '"]')[0];
				button.disabled = false;

				var checkbox = $('input[value="' + scopes[scope] + '"]')[0];
				checkbox.checked = true;
			}
		}
	}
});