summaryrefslogtreecommitdiffstats
path: root/source/Janrain.OpenId/Consumer/OpenIdTextBox.cs
blob: 291cdfb50aecbc27f64291828371416d20bad87a (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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
/********************************************************
 * Copyright (C) 2007 Andrew Arnott
 * Released under the New BSD License
 * License available here: http://www.opensource.org/licenses/bsd-license.php
 * For news or support on this file: http://jmpinline.nerdbank.net/
 ********************************************************/

using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Text;
using System.Net.Mail;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;

using Janrain.OpenId;
using Janrain.OpenId.Consumer;
using Janrain.OpenId.Session;
using Janrain.OpenId.RegistrationExtension;
using Janrain.OpenId.Store;

namespace NerdBank.OpenId.RegistrationExtension
{
}

namespace Janrain.OpenId.RegistrationExtension
{
}

namespace NerdBank.OpenId.Consumer
{
	[DefaultProperty("Text")]
	[ToolboxData("<{0}:OpenIdTextBox runat=\"server\"></{0}:OpenIdTextBox>")]
	public class OpenIdTextBox : CompositeControl
	{
		public OpenIdTextBox()
		{
			InitializeControls();
		}

		TextBox wrappedTextBox;
		protected TextBox WrappedTextBox
		{
			get { return wrappedTextBox; }
		}

		protected override void CreateChildControls()
		{
			base.CreateChildControls();

			Controls.Add(wrappedTextBox);
			if (ShouldBeFocused)
				WrappedTextBox.Focus();
		}

		protected virtual void InitializeControls()
		{
			wrappedTextBox = new TextBox();
			wrappedTextBox.ID = "wrappedTextBox";
			wrappedTextBox.CssClass = cssClassDefault;
			wrappedTextBox.Columns = columnsDefault;
			wrappedTextBox.Text = text;
		}

		protected bool ShouldBeFocused;
		public override void Focus()
		{
			if (Controls.Count == 0)
				ShouldBeFocused = true;
			else
				WrappedTextBox.Focus();
		}

		#region Properties
		const string textDefault = "";
		string text = textDefault;
		[Bindable(true)]
		[Category("Appearance")]
		[DefaultValue("")]
		public string Text
		{
			get { return (WrappedTextBox != null) ? WrappedTextBox.Text : text; }
			set
			{
				text = value;
				if (WrappedTextBox != null) WrappedTextBox.Text = value;
			}
		}

		const string cssClassDefault = "openid";
		[Bindable(true)]
		[Category("Appearance")]
		[DefaultValue(cssClassDefault)]
		public override string CssClass
		{
			get { return WrappedTextBox.CssClass; }
			set { WrappedTextBox.CssClass = value; }
		}

		const int columnsDefault = 40;
		[Bindable(true)]
		[Category("Appearance")]
		[DefaultValue(columnsDefault)]
		public int Columns
		{
			get { return WrappedTextBox.Columns; }
			set { WrappedTextBox.Columns = value; }
		}

		const string requestNicknameViewStateKey = "RequestNickname";
		const ProfileRequest requestNicknameDefault = ProfileRequest.NoRequest;
		[Bindable(true)]
		[Category("Profile")]
		[DefaultValue(requestNicknameDefault)]
		public ProfileRequest RequestNickname
		{
			get { return (ProfileRequest)(ViewState[requestNicknameViewStateKey] ?? requestNicknameDefault); }
			set { ViewState[requestNicknameViewStateKey] = value; }
		}

		const string requestEmailViewStateKey = "RequestEmail";
		const ProfileRequest requestEmailDefault = ProfileRequest.NoRequest;
		[Bindable(true)]
		[Category("Profile")]
		[DefaultValue(requestEmailDefault)]
		public ProfileRequest RequestEmail
		{
			get { return (ProfileRequest)(ViewState[requestEmailViewStateKey] ?? requestEmailDefault); }
			set { ViewState[requestEmailViewStateKey] = value; }
		}

		const string requestFullNameViewStateKey = "RequestFullName";
		const ProfileRequest requestFullNameDefault = ProfileRequest.NoRequest;
		[Bindable(true)]
		[Category("Profile")]
		[DefaultValue(requestFullNameDefault)]
		public ProfileRequest RequestFullName
		{
			get { return (ProfileRequest)(ViewState[requestFullNameViewStateKey] ?? requestFullNameDefault); }
			set { ViewState[requestFullNameViewStateKey] = value; }
		}

		const string requestBirthdateViewStateKey = "RequestBirthday";
		const ProfileRequest requestBirthdateDefault = ProfileRequest.NoRequest;
		[Bindable(true)]
		[Category("Profile")]
		[DefaultValue(requestBirthdateDefault)]
		public ProfileRequest RequestBirthdate
		{
			get { return (ProfileRequest)(ViewState[requestBirthdateViewStateKey] ?? requestBirthdateDefault); }
			set { ViewState[requestBirthdateViewStateKey] = value; }
		}

		const string requestGenderViewStateKey = "RequestGender";
		const ProfileRequest requestGenderDefault = ProfileRequest.NoRequest;
		[Bindable(true)]
		[Category("Profile")]
		[DefaultValue(requestGenderDefault)]
		public ProfileRequest RequestGender
		{
			get { return (ProfileRequest)(ViewState[requestGenderViewStateKey] ?? requestGenderDefault); }
			set { ViewState[requestGenderViewStateKey] = value; }
		}

		const string requestPostalCodeViewStateKey = "RequestPostalCode";
		const ProfileRequest requestPostalCodeDefault = ProfileRequest.NoRequest;
		[Bindable(true)]
		[Category("Profile")]
		[DefaultValue(requestPostalCodeDefault)]
		public ProfileRequest RequestPostalCode
		{
			get { return (ProfileRequest)(ViewState[requestPostalCodeViewStateKey] ?? requestPostalCodeDefault); }
			set { ViewState[requestPostalCodeViewStateKey] = value; }
		}

		const string requestCountryViewStateKey = "RequestCountry";
		const ProfileRequest requestCountryDefault = ProfileRequest.NoRequest;
		[Bindable(true)]
		[Category("Profile")]
		[DefaultValue(requestCountryDefault)]
		public ProfileRequest RequestCountry
		{
			get { return (ProfileRequest)(ViewState[requestCountryViewStateKey] ?? requestCountryDefault); }
			set { ViewState[requestCountryViewStateKey] = value; }
		}

		const string requestLanguageViewStateKey = "RequestLanguage";
		const ProfileRequest requestLanguageDefault = ProfileRequest.NoRequest;
		[Bindable(true)]
		[Category("Profile")]
		[DefaultValue(requestLanguageDefault)]
		public ProfileRequest RequestLanguage
		{
			get { return (ProfileRequest)(ViewState[requestLanguageViewStateKey] ?? requestLanguageDefault); }
			set { ViewState[requestLanguageViewStateKey] = value; }
		}

		const string requestTimeZoneViewStateKey = "RequestTimeZone";
		const ProfileRequest requestTimeZoneDefault = ProfileRequest.NoRequest;
		[Bindable(true)]
		[Category("Profile")]
		[DefaultValue(requestTimeZoneDefault)]
		public ProfileRequest RequestTimeZone
		{
			get { return (ProfileRequest)(ViewState[requestTimeZoneViewStateKey] ?? requestTimeZoneDefault); }
			set { ViewState[requestTimeZoneViewStateKey] = value; }
		}

		const string policyUrlViewStateKey = "PolicyUrl";
		const string policyUrlDefault = "";
		[Bindable(true)]
		[Category("Profile")]
		[DefaultValue(policyUrlDefault)]
		public string PolicyUrl
		{
			get { return (string)ViewState[policyUrlViewStateKey] ?? policyUrlDefault; }
			set { ViewState[policyUrlViewStateKey] = value; }
		}

		const string enableRequestProfileViewStateKey = "EnableRequestProfile";
		const bool enableRequestProfileDefault = true;
		[Bindable(true)]
		[Category("Profile")]
		[DefaultValue(enableRequestProfileDefault)]
		public bool EnableRequestProfile
		{
			get { return (bool)(ViewState[enableRequestProfileViewStateKey] ?? enableRequestProfileDefault); }
			set { ViewState[enableRequestProfileViewStateKey] = value; }
		}
		#endregion

		#region Properties to hide
		[Browsable(false), Bindable(false)]
		public override System.Drawing.Color ForeColor
		{
			get { throw new NotSupportedException(); }
			set { throw new NotSupportedException(); }
		}
		[Browsable(false), Bindable(false)]
		public override System.Drawing.Color BackColor
		{
			get { throw new NotSupportedException(); }
			set { throw new NotSupportedException(); }
		}
		[Browsable(false), Bindable(false)]
		public override System.Drawing.Color BorderColor
		{
			get { throw new NotSupportedException(); }
			set { throw new NotSupportedException(); }
		}
		[Browsable(false), Bindable(false)]
		public override Unit BorderWidth
		{
			get { return Unit.Empty; }
			set { throw new NotSupportedException(); }
		}
		[Browsable(false), Bindable(false)]
		public override BorderStyle BorderStyle
		{
			get { return BorderStyle.None; }
			set { throw new NotSupportedException(); }
		}
		[Browsable(false), Bindable(false)]
		public override FontInfo Font
		{
			get { return null; }
		}
		[Browsable(false), Bindable(false)]
		public override Unit Height
		{
			get { return Unit.Empty; }
			set { throw new NotSupportedException(); }
		}
		[Browsable(false), Bindable(false)]
		public override Unit Width
		{
			get { return Unit.Empty; }
			set { throw new NotSupportedException(); }
		}
		[Browsable(false), Bindable(false)]
		public override string ToolTip
		{
			get { return string.Empty; }
			set { throw new NotSupportedException(); }
		}
		[Browsable(false), Bindable(false)]
		public override string SkinID
		{
			get { return string.Empty; }
			set { throw new NotSupportedException(); }
		}
		[Browsable(false), Bindable(false)]
		public override bool EnableTheming
		{
			get { return false; }
			set { throw new NotSupportedException(); }
		}
		#endregion

		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);

			try
			{
				if (!Page.IsPostBack && Page.Request.QueryString["openid.mode"] != null)
				{
					Janrain.OpenId.Consumer.Consumer consumer =
						new Janrain.OpenId.Consumer.Consumer(new SystemHttpSessionState(Page.Session), MemoryStore.GetInstance());

					ConsumerResponse resp = consumer.Complete(Page.Request.QueryString);
					OnLoggedIn(resp.IdentityUrl, parseProfileFields(Page.Request.QueryString));
				}
			}
			catch (FailureException fexc)
			{
				OnError(fexc);
			}
			catch (CancelException cex)
			{
				OnCanceled(cex);
			}
		}

		public void Login()
		{
			if (string.IsNullOrEmpty(Text))
				throw new InvalidOperationException(Janrain.OpenId.Strings.OpenIdTextBoxEmpty);

			Janrain.OpenId.Consumer.Consumer consumer =
				new Janrain.OpenId.Consumer.Consumer(new SystemHttpSessionState(Page.Session), MemoryStore.GetInstance());

			Uri userUri = UriUtil.NormalizeUri(Text);
			// Initiate openid request
			AuthRequest request = consumer.Begin(userUri);
			if (EnableRequestProfile) addProfileArgs(request);

			// Build the trust root
			UriBuilder builder = new UriBuilder(Page.Request.Url.AbsoluteUri);
			builder.Query = null;
			builder.Password = null;
			builder.UserName = null;
			builder.Fragment = null;
			builder.Path = Page.Request.ApplicationPath;
			string trustRoot = builder.Uri.ToString();

			// Build the return_to URL
			UriBuilder return_to = new UriBuilder(Page.Request.Url);
			// Trim off any old "openid." prefixed parameters to avoid carrying
			// state from a prior login attempt.
			return_to.Query = string.Empty;
			NameValueCollection return_to_params = new NameValueCollection(Page.Request.QueryString.Count);
			foreach (string key in Page.Request.QueryString) {
				if (!key.StartsWith("openid.")) {
					return_to_params.Add(key, Page.Request.QueryString[key]);
				}
			}
			UriUtil.AppendQueryArgs(return_to, return_to_params);
			Uri redirectUrl = request.CreateRedirect(trustRoot, return_to.Uri, AuthRequest.Mode.SETUP);
			Page.Response.Redirect(redirectUrl.AbsoluteUri);
		}

		void addProfileArgs(AuthRequest request)
		{
			request.ExtraArgs.Add("openid.sreg.required", string.Join(",", assembleProfileFields(ProfileRequest.Require)));
			request.ExtraArgs.Add("openid.sreg.optional", string.Join(",", assembleProfileFields(ProfileRequest.Request)));
			request.ExtraArgs.Add("openid.sreg.policy_url", PolicyUrl);
		}

		string[] assembleProfileFields(ProfileRequest level)
		{
			List<string> fields = new List<string>(10);
			if (RequestNickname == level)
				fields.Add("nickname");
			if (RequestEmail == level)
				fields.Add("email");
			if (RequestFullName == level)
				fields.Add("fullname");
			if (RequestBirthdate == level)
				fields.Add("dob");
			if (RequestGender == level)
				fields.Add("gender");
			if (RequestPostalCode == level)
				fields.Add("postcode");
			if (RequestCountry == level)
				fields.Add("country");
			if (RequestLanguage == level)
				fields.Add("language");
			if (RequestTimeZone == level)
				fields.Add("timezone");

			return fields.ToArray();
		}
		OpenIdProfileFields parseProfileFields(NameValueCollection queryString)
		{
			OpenIdProfileFields fields = new OpenIdProfileFields();
			if (RequestNickname > ProfileRequest.NoRequest)
				fields.Nickname = queryString["openid.sreg.nickname"];
			if (RequestEmail > ProfileRequest.NoRequest)
				fields.Email = queryString["openid.sreg.email"];
			if (RequestFullName > ProfileRequest.NoRequest)
				fields.Fullname = queryString["openid.sreg.fullname"];
			if (RequestBirthdate > ProfileRequest.NoRequest && !string.IsNullOrEmpty(queryString["openid.sreg.dob"]))
			{
				DateTime birthdate;
				DateTime.TryParse(queryString["openid.sreg.dob"], out birthdate);
				fields.Birthdate = birthdate;
			}
			if (RequestGender > ProfileRequest.NoRequest)
				switch (queryString["openid.sreg.gender"])
				{
					case "M": fields.Gender = Gender.Male; break;
					case "F": fields.Gender = Gender.Female; break;
				}
			if (RequestPostalCode > ProfileRequest.NoRequest)
				fields.PostalCode = queryString["openid.sreg.postcode"];
			if (RequestCountry > ProfileRequest.NoRequest)
				fields.Country = queryString["openid.sreg.country"];
			if (RequestLanguage > ProfileRequest.NoRequest)
				fields.Language = queryString["openid.sreg.language"];
			if (RequestTimeZone > ProfileRequest.NoRequest)
				fields.TimeZone = queryString["openid.sreg.timezone"];
			return fields;
		}

		#region Events
		public class OpenIdEventArgs : EventArgs
		{
			public OpenIdEventArgs(Uri openIdUri, OpenIdProfileFields profileFields)
			{
				this.openIdUri = openIdUri;
				this.profileFields = profileFields;
			}
			private Uri openIdUri;
			/// <summary>
			/// The OpenID url of the authenticating user.
			/// </summary>
			public Uri OpenIdUri
			{
				get { return openIdUri; }
			}
			private bool cancel;
			/// <summary>
			/// Cancels the OpenID authentication and/or login process.
			/// </summary>
			public bool Cancel
			{
				get { return cancel; }
				set { cancel = value; }
			}

			private OpenIdProfileFields profileFields;
			public OpenIdProfileFields ProfileFields
			{
				get { return profileFields; }
			}
		}
		/// <summary>
		/// Fired upon completion of a successful login.
		/// </summary>
		[Description("Fired upon completion of a successful login.")]
		public event EventHandler<OpenIdEventArgs> LoggedIn;
		protected virtual void OnLoggedIn(Uri openIdUri, OpenIdProfileFields profileFields)
		{
			EventHandler<OpenIdEventArgs> loggedIn = LoggedIn;
			OpenIdEventArgs args = new OpenIdEventArgs(openIdUri, profileFields);
			if (loggedIn != null)
				loggedIn(this, args);
			if (!args.Cancel)
				FormsAuthentication.RedirectFromLoginPage(openIdUri.AbsoluteUri, false);
		}

		#endregion
		#region Error handling
		public class ErrorEventArgs : EventArgs
		{
			public ErrorEventArgs(string errorMessage, Exception errorException)
			{
				ErrorMessage = errorMessage;
				ErrorException = errorException;
			}
			public string ErrorMessage;
			public Exception ErrorException;
		}

		/// <summary>
		/// Fired when a login attempt fails or is canceled by the user.
		/// </summary>
		[Description("Fired when a login attempt fails or is canceled by the user.")]
		public event EventHandler<ErrorEventArgs> Error;
		protected virtual void OnError(Exception errorException)
		{
			if (errorException == null)
				throw new ArgumentNullException("errorException");

			EventHandler<ErrorEventArgs> error = Error;
			if (error != null)
				error(this, new ErrorEventArgs(errorException.Message, errorException));
		}

		/// <summary>
		/// Fired when an authentication attempt is canceled at the OpenID Provider.
		/// </summary>
		[Description("Fired when an authentication attempt is canceled at the OpenID Provider.")]
		public event EventHandler<ErrorEventArgs> Canceled;
		protected virtual void OnCanceled(Exception cancelException)
		{
			if (cancelException == null)
				throw new ArgumentNullException("cancelException");

			EventHandler<ErrorEventArgs> canceled = Canceled;
			if (canceled != null)
				canceled(this, new ErrorEventArgs(cancelException.Message, cancelException));
		}
		#endregion
	}
}