summaryrefslogtreecommitdiffstats
path: root/samples/TestAzureAD/Account/Manage.aspx.cs
blob: 98ca4c74e523edf77c6fcaefa93f6787a30a95fb (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
using System;
using System.Collections.Generic;
using System.Linq;

using Microsoft.AspNet.Membership.OpenAuth;

namespace TestAzureAD.Account
{
	public partial class Manage : System.Web.UI.Page
	{
		protected string SuccessMessage
		{
			get;
			private set;
		}

		protected bool CanRemoveExternalLogins
		{
			get;
			private set;
		}

		protected void Page_Load()
		{
			if (!IsPostBack)
			{
				// Determine the sections to render
				var hasLocalPassword = OpenAuth.HasLocalPassword(User.Identity.Name);
				setPassword.Visible = !hasLocalPassword;
				changePassword.Visible = hasLocalPassword;

				CanRemoveExternalLogins = hasLocalPassword;

				// Render success message
				var message = Request.QueryString["m"];
				if (message != null)
				{
					// Strip the query string from action
					Form.Action = ResolveUrl("~/Account/Manage.aspx");

					SuccessMessage =
						message == "ChangePwdSuccess" ? "Your password has been changed."
						: message == "SetPwdSuccess" ? "Your password has been set."
						: message == "RemoveLoginSuccess" ? "The external login was removed."
						: String.Empty;
					successMessage.Visible = !String.IsNullOrEmpty(SuccessMessage);
				}
			}

		}

		protected void setPassword_Click(object sender, EventArgs e)
		{
			if (IsValid)
			{
				var result = OpenAuth.AddLocalPassword(User.Identity.Name, password.Text);
				if (result.IsSuccessful)
				{
					Response.Redirect("~/Account/Manage.aspx?m=SetPwdSuccess");
				}
				else
				{

					ModelState.AddModelError("NewPassword", result.ErrorMessage);

				}
			}
		}


		public IEnumerable<OpenAuthAccountData> GetExternalLogins()
		{
			var accounts = OpenAuth.GetAccountsForUser(User.Identity.Name);
			CanRemoveExternalLogins = CanRemoveExternalLogins || accounts.Count() > 1;
			return accounts;
		}

		public void RemoveExternalLogin(string providerName, string providerUserId)
		{
			var m = OpenAuth.DeleteAccount(User.Identity.Name, providerName, providerUserId)
				? "?m=RemoveLoginSuccess"
				: String.Empty;
			Response.Redirect("~/Account/Manage.aspx" + m);
		}


		protected static string ConvertToDisplayDateTime(DateTime? utcDateTime)
		{
			// You can change this method to convert the UTC date time into the desired display
			// offset and format. Here we're converting it to the server timezone and formatting
			// as a short date and a long time string, using the current thread culture.
			return utcDateTime.HasValue ? utcDateTime.Value.ToLocalTime().ToString("G") : "[never]";
		}
	}
}