示例#1
0
        public virtual async Task <IActionResult> OnGetAsync()
        {
            if (CurrentUser.IsAuthenticated)
            {
                ToastHelper.ToastSuccess(this, $"{L["Welcome back!"]}, {CurrentUser.Name}");
                if (ReturnUrl.IsNullOrEmpty())
                {
                    return(Redirect("/"));
                }
                else
                {
                    return(RedirectSafely(ReturnUrl, ReturnUrlHash));
                }
            }

            ActionHelper.AddTitle(this, "Login");

            LoginInput = new LoginInputModel();

            ExternalProviders = await GetExternalProviders();

            EnableLocalLogin = await SettingProvider.IsTrueAsync(AccountSettingNames.EnableLocalLogin);

            if (IsExternalLoginOnly)
            {
                //return await ExternalLogin(vm.ExternalLoginScheme, returnUrl);
                throw new NotImplementedException();
            }

            return(Page());
        }
        private CreatePaymentRequest PrepareCardPaymentRequest(CodeActivityContext executionContext)
        {
            string description = Description.Get(executionContext);
            CreatePaymentRequest apiRequest = new CreatePaymentRequest
            {
                amount      = (int)(Amount.Get(executionContext).Value *100),
                description = description?.Replace("<", "'").Replace(">", "'").Replace("\"", "'"),
                reference   = Reference.Get(executionContext),
                return_url  = ReturnUrl.Get(executionContext),
            };

            if (apiRequest.amount <= 0)
            {
                throw new ArgumentException(Messages.InvalidArgument, nameof(Amount));
            }
            if (string.IsNullOrWhiteSpace(apiRequest.description))
            {
                throw new ArgumentException(Messages.InvalidArgument, nameof(Description));
            }
            if (string.IsNullOrWhiteSpace(apiRequest.reference))
            {
                throw new ArgumentException(Messages.InvalidArgument, nameof(Reference));
            }
            if (string.IsNullOrWhiteSpace(apiRequest.return_url))
            {
                throw new ArgumentException(Messages.InvalidArgument, nameof(ReturnUrl));
            }
            return(apiRequest);
        }
示例#3
0
        public IActionResult OutLogin([FromBody] OutLoginInfo info)
        {
            var returnUrl = HttpContext.Request.Cookies["returnUrl"];

            using (var db = new ShopDBContext())
            {
                var user = db.Users.FirstOrDefault(u => u.UserID.Equals(info.email));

                if (user == null)
                {
                    user = new User()
                    {
                        UserID   = info.email,
                        Facebook = "Y"
                    };

                    db.Users.Add(user);
                    db.SaveChanges();
                }

                user = db.Users.FirstOrDefault(u => u.UserID.Equals(info.email));

                HttpContext.Session.SetInt32("Login_User", user.UserNo);

                ReturnUrl rUrl = new ReturnUrl {
                    url = returnUrl
                };

                return(Json(rUrl));

                //return Ok(Json(new {url = returnUrl }));
            }
        }
        // GET: /F2/LoginOk?uid=panda&return_url=http://52xyj.cn&msg=测试
        public ActionResult LoginOk(string uid, string return_url, string msg = "", string uName = "未设置")
        {
            var accountContext = new AccountContext();

            //DataContext.UserId =
            //    accountContext.UserID = uid;
            //DataContext.UserName =
            // accountContext.UserName = uName;
            DataContext = new DataContext(HttpContext, uid, "", uName);
            Session["AccountContext"] = accountContext;
            if (return_url.HasValue())
            {
                //加入参数
                return_url += (return_url.Contains("?") ? "&" : "?") + "uid=" + uid + "&msg=" + msg;
                return(Redirect(return_url));
            }
            else if (ReturnUrl.HasValue() && ReturnUrl != "/" && !return_url.ToLower().Contains("login"))
            {
                return(Redirect(ReturnUrl));
            }
            else
            {
                return(RedirectToAction("Index", new { msg = "用户[" + uid + "]登录成功!" }));
            }
        }
示例#5
0
        public async Task <bool> Validate()
        {
            if (_setupUrl != null)
            {
                return(false);
            }
            if (Mode != "id_res")
            {
                return(false);
            }
            // isset($this->data['openid_claimed_id']) ?$this->data['openid_claimed_id']:$this->data['openid_identity'];
            ClaimedID = _queryParams.GetValues("openid.claimed_id")?.Single() ?? _queryParams.GetValues("openid.identity")?.Single();

            //Build the request to validate with the openid server
            var args = new Dictionary <string, string>();

            args.Add("openid.assoc_handle", _queryParams.GetValues("openid.assoc_handle")?.Single());
            args.Add("openid.signed", _queryParams.GetValues("openid.signed")?.Single());
            args.Add("openid.sig", _queryParams.GetValues("openid.sig")?.Single());

            if (_queryParams.GetValues("openid.ns") != null)
            {
                //OpenID 2.0 server, find endpoint using discovery
                args.Add("openid.ns", "http://specs.openid.net/auth/2.0");
            }

            if (!ReturnUrl.Equals(_queryParams.GetValues("openid.return_to").Single()))
            {
                return(false);
            }

            string server = await Discover(ClaimedID);

            var items = _queryParams.GetValues("openid.signed")[0];

            var claims = items.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

            foreach (string claim in claims)
            {
                string key   = $"openid.{claim}";
                string value = _queryParams.GetValues(key).Single();
                if (!args.ContainsKey(key))
                {
                    args.Add(key, value);
                }
            }

            args.Add("openid.mode", "check_authentication");

            var        content = new FormUrlEncodedContent(args);
            HttpClient client  = new HttpClient();

            var response = await client.PostAsync(server, content);

            var text = await response.Content.ReadAsStringAsync();

            return(text.Contains("is_valid:true"));
        }
示例#6
0
        /// <summary>
        /// Returns true if HostedCheckoutSpecificInput instances are equal
        /// </summary>
        /// <param name="other">Instance of HostedCheckoutSpecificInput to be compared</param>
        /// <returns>Boolean</returns>
        public bool Equals(HostedCheckoutSpecificInput other)
        {
            if (ReferenceEquals(null, other))
            {
                return(false);
            }
            if (ReferenceEquals(this, other))
            {
                return(true);
            }

            return
                ((
                     IsRecurring == other.IsRecurring ||
                     IsRecurring != null &&
                     IsRecurring.Equals(other.IsRecurring)
                     ) &&
                 (
                     Locale == other.Locale ||
                     Locale != null &&
                     Locale.Equals(other.Locale)
                 ) &&
                 (
                     PaymentProductFilters == other.PaymentProductFilters ||
                     PaymentProductFilters != null &&
                     PaymentProductFilters.Equals(other.PaymentProductFilters)
                 ) &&
                 (
                     ReturnCancelState == other.ReturnCancelState ||
                     ReturnCancelState != null &&
                     ReturnCancelState.Equals(other.ReturnCancelState)
                 ) &&
                 (
                     ReturnUrl == other.ReturnUrl ||
                     ReturnUrl != null &&
                     ReturnUrl.Equals(other.ReturnUrl)
                 ) &&
                 (
                     ShowResultPage == other.ShowResultPage ||
                     ShowResultPage != null &&
                     ShowResultPage.Equals(other.ShowResultPage)
                 ) &&
                 (
                     Tokens == other.Tokens ||
                     Tokens != null &&
                     Tokens.Equals(other.Tokens)
                 ) &&
                 (
                     ValidateShoppingCart == other.ValidateShoppingCart ||
                     ValidateShoppingCart != null &&
                     ValidateShoppingCart.Equals(other.ValidateShoppingCart)
                 ) &&
                 (
                     Variant == other.Variant ||
                     Variant != null &&
                     Variant.Equals(other.Variant)
                 ));
        }
示例#7
0
        async Task <string> GenerateInbox()
        {
            var r = new StringBuilder();

            var emails = await GetEmails();

            r.AppendLine("<h2>Emails sent to <u>" + To.Or("ALL") + "</u></h2>");
            r.AppendLine("<table cellspacing='0'>");
            r.AppendLine("<tr>");
            r.AppendLine("<th>Date</th>");
            r.AppendLine("<th>Time</th>");
            r.AppendLine("<th>From</th>");
            r.AppendLine("<th>ReplyTo</th>");
            r.AppendLine("<th>To</th>");
            r.AppendLine("<th>Cc</th>");
            r.AppendLine("<th>Bcc</th>");
            r.AppendLine("<th>Subject</th>");
            r.AppendLine("<th>Attachments</th>");
            r.AppendLine("</tr>");

            if (emails.None())
            {
                r.AppendLine("<tr>");
                r.AppendLine("<td colspan='8'>No emails in the system</td>");
                r.AppendLine("</tr>");
            }
            else
            {
                foreach (var item in emails)
                {
                    r.AppendLine("<tr>");
                    r.AddFormattedLine("<td>{0}</td>", item.SendableDate.ToString("yyyy-MM-dd"));
                    r.AddFormattedLine("<td>{0}</td>", item.SendableDate.ToSmallTime());
                    r.AddFormattedLine("<td>{0}</td>",
                                       item.GetEffectiveFromName() + "(" + item.GetEffectiveFromAddress() + ")");
                    r.AddFormattedLine("<td>{0}</td>",
                                       item.GetEffectiveReplyToName() + "(" + item.GetEffectiveReplyToAddress() + ")");
                    r.AddFormattedLine("<td>{0}</td>", item.To);
                    r.AddFormattedLine("<td>{0}</td>", item.Cc);
                    r.AddFormattedLine("<td>{0}</td>", item.Bcc);

                    r.AddFormattedLine("<td><a href='/?Web.Test.Command=testEmail&id={0}&to={1}&ReturnUrl={2}'>{3}</a></td>",
                                       item.GetId(), To, ReturnUrl.UrlEncode(), item.Subject.Or("[NO SUBJECT]").HtmlEncode());

                    r.AddFormattedLine("<td>{0}</td>", GetAttachmentLinks(item));

                    r.AppendLine("</tr>");
                }
            }

            r.AppendLine("</table>");

            return(r.ToString());
        }
示例#8
0
        private void SetUrls()
        {
            if (!_googleAuthUrl.IsNullOrEmpty())
            {
                return;
            }

            var client    = _auth0Helper.CreateAuthenticationApiClientIfNotExists();
            var returnUrl = $"{WebUtils.GetApplicationUrlPath(HttpContext.Current)}{CurrentUser.LanguageCode}/account/login-register/";

            if (!ReturnUrl.IsNullOrEmpty())
            {
                returnUrl = $"{returnUrl}?returnUrl={ReturnUrl}";
            }

            var google_authorizationUrl = client.BuildAuthorizationUrl()
                                          .WithResponseType(AuthorizationResponseType.Code)
                                          .WithClient(Auth0Helper.Auth0ClientId)
                                          .WithConnection("google-oauth2")
                                          .WithRedirectUrl(returnUrl)
                                          .WithScope("openid profile email")
                                          .Build();

            _googleAuthUrl = google_authorizationUrl.ToString();

            var facebook_authorizationUrl = client.BuildAuthorizationUrl()
                                            .WithResponseType(AuthorizationResponseType.Code)
                                            .WithClient(Auth0Helper.Auth0ClientId)
                                            .WithConnection("facebook")
                                            .WithRedirectUrl(returnUrl)
                                            .WithScope("openid profile email")
                                            .Build();

            _facebookAuthUrl = facebook_authorizationUrl.ToString();

            //var twitter_authorizationUrl = client.BuildAuthorizationUrl()
            //    .WithResponseType(AuthorizationResponseType.Code)
            //    .WithClient(Auth0Helper.Auth0ClientId)
            //    .WithConnection("twitter")
            //    .WithRedirectUrl(returnUrl)
            //    .WithScope("openid profile email")
            //    .Build();
            //_twitterAuthUrl = twitter_authorizationUrl.ToString();

            var linkedIn_authorizationUrl = client.BuildAuthorizationUrl()
                                            .WithResponseType(AuthorizationResponseType.Code)
                                            .WithClient(Auth0Helper.Auth0ClientId)
                                            .WithConnection("linkedin")
                                            .WithRedirectUrl(returnUrl)
                                            .WithScope("openid profile email")
                                            .Build();

            _linkedInAuthUrl = linkedIn_authorizationUrl.ToString();
        }
示例#9
0
        /// <summary>
        ///     Formats an init request before its sent to Paynow
        /// </summary>
        /// <param name="payment"></param>
        /// <returns></returns>
        private Dictionary <string, string> FormatInitRequest(Payment payment)
        {
            var items = payment.ToDictionary();

            items["returnurl"] = ReturnUrl.Trim();
            items["resulturl"] = ResultUrl.Trim();
            items["id"]        = IntegrationId;

            items.Add("hash", Hash.Make(items, IntegrationKey));

            return(items);
        }
        public ActionResult Regist(Regist_M model)
        {
            model.UserId   = F("UserId");
            model.UserPsw  = F("UserPsw"); model.UserPsw2 = F("UserPsw2");
            model.NickName = F("NickName");
            model.Phone    = F("Phone");
            model.Email    = F("Email");

            if (model.UserPsw != model.UserPsw2 ||
                !model.UserPsw.HasValue() ||
                !model.UserPsw2.HasValue())
            {
                return(Alert("两次密码不一致!", -1));
            }

            if (!model.UserId.HasValue() ||
                !model.NickName.HasValue())
            {
                return(Alert("注册信息不完整!", -1));
            }



            if (ModelState.IsValid)
            {
                if (_permissionProvider.Regist(model.UserId, model.UserPsw,
                                               model.NickName, model.Email, model.Phone
                                               ))
                {
                    var accountContext = new AccountContext();
                    DataContext.UserID        =
                        accountContext.UserID = model.UserId;
                    DataContext.UserUnit      = "1577668579";
                    Session["AccountContext"] = accountContext;
                    if (ReturnUrl.HasValue())
                    {
                        return(Redirect(ReturnUrl));
                    }
                    else
                    {
                        return(RedirectToAction("Index", new { msg = "用户[" + model.UserId + "]登录成功!" }));
                    }
                }
                else
                {
                    return(Alert("注册失败!", -1));
                }
            }
            else
            {
                return(View(model));
            }
        }
示例#11
0
        /// <summary>
        ///     Initiate a new Paynow transaction
        /// </summary>
        /// <remarks>
        ///     Currently, only eccocash is supported
        /// </remarks>
        /// <param name="payment">The transaction to be sent to Paynow</param>
        /// <param name="phone">The user's phone number</param>
        /// <param name="method">The mobile transaction method i.e ecocash, telecash</param>
        /// <returns></returns>
        private Dictionary <string, string> FormatMobileInitRequest(Payment payment, string phone, string method)
        {
            var items = payment.ToDictionary();

            items["returnurl"] = ReturnUrl.Trim();
            items["resulturl"] = ResultUrl.Trim();
            items["id"]        = IntegrationId;
            items["phone"]     = phone;
            items["method"]    = method;

            items.Add("hash", Hash.Make(items, IntegrationKey));

            return(items);
        }
        public ActionResult MarkAsAnswer(int questionId, int postId, ReturnUrl url)
        {
            var question = _repositories.Questions.Get().WithId(questionId);

            if (!_security.CanMarkAsAnswer(question, UserModel.Current.UserName))
            {
                TempData["message"] = _security.ErrorMessage;
                return(RedirectToAction("Details", new { id = questionId }));
            }

            var post = question.Responses.WithId(postId);

            return(View(post));
        }
示例#13
0
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            var cont             = filterContext.HttpContext;
            var contextReturnUrl = "";

            if (cont.Request.Url != null)
            {
                contextReturnUrl = cont.Request.Url.ToString();
            }
            var retUrl = string.IsNullOrWhiteSpace(ReturnUrl) ? contextReturnUrl : ReturnUrl.Replace("~/", "/");

            SessionManager.Set(Keys.Session.AfterLoginReturnUrl, retUrl);
            base.HandleUnauthorizedRequest(filterContext);
            filterContext.Result = new RedirectResult(Keys.PageUrl.AccountLogin);
        }
        public ActionResult MarkAsAnswer(Post post, ReturnUrl url)
        {
            var question = _repositories.Questions.Get().WithId(post.QuestionId);

            if (!_security.CanMarkAsAnswer(question, UserModel.Current.UserName))
            {
                TempData["message"] = _security.ErrorMessage;
                return(RedirectToAction("Details", new { id = question.Id }));
            }

            question.MarkAsAnswer(post.Id, UserModel.Current.UserName);
            _repositories.Questions.SaveChanges();

            TempData["message"] = "You have successfully marked this question as answered. The question is now closed.";

            return(RedirectToAction("Details", new { id = question.Id }));
        }
示例#15
0
 /// <summary>
 /// Gets the hash code
 /// </summary>
 /// <returns>Hash code</returns>
 public override int GetHashCode()
 {
     unchecked // Overflow is fine, just wrap
     {
         var hashCode = 41;
         // Suitable nullity checks etc, of course :)
         if (IsRecurring != null)
         {
             hashCode = hashCode * 59 + IsRecurring.GetHashCode();
         }
         if (Locale != null)
         {
             hashCode = hashCode * 59 + Locale.GetHashCode();
         }
         if (PaymentProductFilters != null)
         {
             hashCode = hashCode * 59 + PaymentProductFilters.GetHashCode();
         }
         if (ReturnCancelState != null)
         {
             hashCode = hashCode * 59 + ReturnCancelState.GetHashCode();
         }
         if (ReturnUrl != null)
         {
             hashCode = hashCode * 59 + ReturnUrl.GetHashCode();
         }
         if (ShowResultPage != null)
         {
             hashCode = hashCode * 59 + ShowResultPage.GetHashCode();
         }
         if (Tokens != null)
         {
             hashCode = hashCode * 59 + Tokens.GetHashCode();
         }
         if (ValidateShoppingCart != null)
         {
             hashCode = hashCode * 59 + ValidateShoppingCart.GetHashCode();
         }
         if (Variant != null)
         {
             hashCode = hashCode * 59 + Variant.GetHashCode();
         }
         return(hashCode);
     }
 }
        public string ToJwt(string issuer, string audience, string key, int ttl)
        {
            var claims = new List <Claim>();

            if (ReturnUrl.IsPresent())
            {
                claims.Add(new Claim("returnUrl", ReturnUrl));
            }

            var token = new JwtSecurityToken(
                issuer,
                audience,
                claims,
                new Lifetime(DateTime.UtcNow, DateTime.UtcNow.AddSeconds(ttl)),
                new HmacSigningCredentials(key));

            return(new JwtSecurityTokenHandler().WriteToken(token));
        }
        public ActionResult Reply(Post reply, int id, ReturnUrl url)
        {
            var question = _repositories.Questions.Get().WithId(id);

            if (question == null)
            {
                return(View("NotFound"));
            }

            if (!_security.HasReplyAccess(question, UserModel.Current.UserName))
            {
                TempData["message"] = _security.ErrorMessage;
                return(RedirectToAction("Details", new { id = id, r = url.Url }));
            }

            if (this.ModelState.IsValid)
            {
                try
                {
                    reply.CreatedBy   = UserModel.Current.UserName;
                    reply.CreatedDate = DateTime.Now;

                    question.AddReply(reply);

                    _repositories.Questions.SaveChanges();

                    var user = Membership.GetUser(question.CreatedBy);
                    if (user != null)
                    {
                        _emailService.SendEmailTo(user.Email,
                                                  new StandardEmail(StandardEmail.EmailTemplate.LawyerReply));
                    }

                    return(RedirectToAction("Details", new { id, r = url.Url }));
                }
                catch (Exception e)
                {
                    this.ModelState.AddModelError("*", e.ToString());
                }
            }

            return(View(new ReplyViewModel(question)));
        }
示例#18
0
    public virtual async Task <IActionResult> OnGetAsync()
    {
        ProfileManagementPageCreationContext = new ProfileManagementPageCreationContext(ServiceProvider);

        foreach (var contributor in Options.Contributors)
        {
            await contributor.ConfigureAsync(ProfileManagementPageCreationContext);
        }

        if (ReturnUrl != null)
        {
            if (!Url.IsLocalUrl(ReturnUrl) &&
                !ReturnUrl.StartsWith(UriHelper.BuildAbsolute(Request.Scheme, Request.Host, Request.PathBase).RemovePostFix("/")) &&
                !AppUrlProvider.IsRedirectAllowedUrl(ReturnUrl))
            {
                ReturnUrl = null;
            }
        }

        return(Page());
    }
        // GET: /Account/LoginOk?uid=panda&return_url=http://52xyj.cn&msg=测试
        public ActionResult LoginOk(string uid, string return_url, string msg = "", string uName = "未设置")
        {
            var accountContext = new AccountContext();

            DataContext.UserID          =
                accountContext.UserID   = uid;
            DataContext.UserName        =
                accountContext.UserName = uName;
            Session["AccountContext"]   = accountContext;
            if (return_url.HasValue())
            {
                return(Redirect(return_url));
            }
            else if (ReturnUrl.HasValue())
            {
                return(Redirect(ReturnUrl));
            }
            else
            {
                return(RedirectToAction("Index", new { msg = "用户[" + uid + "]登录成功!" }));
            }
        }
示例#20
0
 async Task <string> GetAttachmentLinks(IEmailQueueItem email)
 {
     return((await email.Attachments.OrEmpty().Split('|').Trim()
             .Select(async f => $"<form action='/?Web.Test.Command=testEmail&To={To}&ReturnUrl={ReturnUrl.UrlEncode()}' " +
                     $"method='post'><input type=hidden name='attachmentInfo' value='{f.HtmlEncode()}'/><a href='#' " +
                     $"onclick='this.parentElement.submit()'>{(await EmailService.ParseAttachment(f))?.Name.HtmlEncode()}</a></form>")
             .AwaitAll()).ToString(""));
 }
示例#21
0
        public async Task <IActionResult> OnPostAsync(string button)
        {
            var context = await m_IdsInteraction.GetAuthorizationContextAsync(ReturnUrl);

            if (button != "login")
            {
                if (context != null)
                {
                    /*
                     * 如果用户点击取消,则向IdentityServer发送一个结果(类似于用户拒绝同意)】
                     * 然后Oidc错误会被发回给客户端
                     */
                    await m_IdsInteraction.DenyAuthorizationAsync(context, IdentityServer4.Models.AuthorizationError.AccessDenied);

                    if (context.IsNativeClient())
                    {
                        //The client is native, so this change in how to return the response is for better UX for the end user.
                        //客户端是本地客户端,因此此更改返回响应的方式是为最终用户提供更好的UX。
                        //TODO : 这边跳转往后有时间再写
                    }

                    return(Redirect("/Index"));
                }
            }

            if (ModelState.IsValid)
            {
                var result = await m_SignInManager.PasswordSignInAsync(LoginDto.Username, LoginDto.Password, LoginDto.RememberLogin, lockoutOnFailure : true);

                if (result.Succeeded)
                {
                    var user = await m_UserManager.FindByNameAsync(LoginDto.Username);

                    await m_IdsEvent.RaiseAsync(new UserLoginSuccessEvent(user.UserName, user.Id, user.UserName, clientId : context?.Client.ClientId));

                    if (context != null)
                    {
                        if (context.IsNativeClient())
                        {
                            //The client is native, so this change in how to return the response is for better UX for the end user.
                            //客户端是本地客户端,因此此更改返回响应的方式是为最终用户提供更好的UX。
                            //TODO : 这边跳转往后有时间再写
                        }

                        return(Redirect(ReturnUrl));
                    }

                    //请求来自本地页面
                    if (Url.IsLocalUrl(ReturnUrl))
                    {
                        return(Redirect(ReturnUrl));
                    }
                    else if (ReturnUrl.IsNullOrEmpty())
                    {
                        return(Redirect("/"));
                    }
                    else
                    {
                        // user might have clicked on a malicious link - should be logged
                        throw new Exception(L["invalid_return_URL", ReturnUrl]);
                    }
                }

                await m_IdsEvent.RaiseAsync(new UserLoginFailureEvent(LoginDto.Username, "invalid credentials", clientId : context?.Client.ClientId));

                ModelState.AddModelError(string.Empty, L["invalid_credentials_error_message"]);
            }


            return(Page());
        }
示例#22
0
        protected override PageContent getContent()
        {
            if (User.Any())
            {
                return(new BasicPageContent(
                           bodyClasses: elementClass,
                           pageLoadPostBack: PostBack.CreateFull(
                               modificationMethod: () => UserImpersonationStatics.BeginImpersonation(UserObject),
                               actionGetter: () => new PostBackAction(new ExternalResource(ReturnUrl)))).Add(new Paragraph("Please wait.".ToComponents())));
            }

            var content = new BasicPageContent(bodyClasses: elementClass);

            content.Add(new PageName());

            if (ConfigurationStatics.IsLiveInstallation)
            {
                content.Add(
                    new Paragraph(
                        new ImportantContent("Warning:".ToComponents()).ToCollection()
                        .Concat(
                            " Do not impersonate a user without permission. Your actions will be attributed to the user you are impersonating, not to you.".ToComponents())
                        .Materialize()));
            }

            var user = new DataValue <User>();
            var pb   = PostBack.CreateFull(
                modificationMethod: () => UserImpersonationStatics.BeginImpersonation(user.Value),
                actionGetter: () => new PostBackAction(
                    new ExternalResource(
                        ReturnUrl.Any()
                                                        ? ReturnUrl
                                                        : EwfConfigurationStatics.AppConfiguration.DefaultBaseUrl.GetUrlString(EwfConfigurationStatics.AppSupportsSecureConnections))));

            FormState.ExecuteWithDataModificationsAndDefaultAction(
                pb.ToCollection(),
                () => {
                content.Add(
                    new EmailAddressControl(
                        "",
                        true,
                        validationMethod: (postBackValue, validator) => {
                    if (!postBackValue.Any())
                    {
                        user.Value = null;
                        return;
                    }
                    user.Value = UserManagementStatics.SystemProvider.GetUser(postBackValue);
                    if (user.Value == null)
                    {
                        validator.NoteErrorAndAddMessage("The email address you entered does not match a user.");
                    }
                }).ToFormItem(label: "User's email address (leave blank for anonymous)".ToComponents())
                    .ToComponentCollection()
                    .Append(
                        new Paragraph(
                            new EwfButton(
                                new StandardButtonStyle(
                                    AppRequestState.Instance.ImpersonatorExists ? "Change User" : "Begin Impersonation",
                                    buttonSize: ButtonSize.Large))
                            .ToCollection()))
                    .Materialize());
            });

            return(content);
        }