Esempio n. 1
0
        protected virtual async Task <SiteUser> CreateUserFromExternalLogin(
            ExternalLoginInfo externalLoginInfo,
            string providedEmail = null,
            bool?didAcceptTerms  = null
            )
        {
            var email = providedEmail;

            if (string.IsNullOrWhiteSpace(email))
            {
                email = externalLoginInfo.Principal.FindFirstValue(ClaimTypes.Email);
                if (string.IsNullOrWhiteSpace(email))
                {
                    email = externalLoginInfo.Principal.FindFirstValue("email");
                }
            }

            DateTime?termsAcceptedDate = null;

            if (didAcceptTerms == true && !string.IsNullOrWhiteSpace(_userManager.Site.RegistrationAgreement))
            {
                termsAcceptedDate = DateTime.UtcNow;
            }

            if (!string.IsNullOrWhiteSpace(email) && email.Contains("@"))
            {
                var userName = await _userManager.SuggestLoginNameFromEmail(_userManager.Site.Id, email);

                var newUser = new SiteUser
                {
                    SiteId               = _userManager.Site.Id,
                    UserName             = userName,
                    Email                = email,
                    FirstName            = externalLoginInfo.Principal.FindFirstValue(ClaimTypes.GivenName),
                    LastName             = externalLoginInfo.Principal.FindFirstValue(ClaimTypes.Surname),
                    AccountApproved      = _userManager.Site.RequireApprovalBeforeLogin ? false : true,
                    EmailConfirmed       = _socialAuthEmailVerificationPolicy.HasVerifiedEmail(externalLoginInfo),
                    AgreementAcceptedUtc = termsAcceptedDate,
                    LastLoginUtc         = DateTime.UtcNow
                };
                //https://github.com/joeaudette/cloudscribe/issues/346
                newUser.DisplayName = _displayNameResolver.ResolveDisplayName(newUser);

                var identityResult = await _userManager.CreateAsync(newUser);

                if (identityResult.Succeeded)
                {
                    identityResult = await _userManager.AddLoginAsync(newUser, externalLoginInfo);

                    return(newUser);
                }
            }
            return(null);
        }
Esempio n. 2
0
        // private ILogger log;

        private async Task <SiteUser> CreateUserFromExternalLogin(
            ExternalLoginInfo externalLoginInfo,
            string providedEmail = null,
            bool?didAcceptTerms  = null
            )
        {
            var email = providedEmail;

            if (string.IsNullOrWhiteSpace(email))
            {
                email = externalLoginInfo.Principal.FindFirstValue(ClaimTypes.Email);
            }

            DateTime?termsAcceptedDate = null;

            if (didAcceptTerms == true && !string.IsNullOrWhiteSpace(userManager.Site.RegistrationAgreement))
            {
                termsAcceptedDate = DateTime.UtcNow;
            }

            if (!string.IsNullOrWhiteSpace(email) && email.Contains("@"))
            {
                var userName = await userManager.SuggestLoginNameFromEmail(userManager.Site.Id, email);

                var newUser = new SiteUser
                {
                    SiteId               = userManager.Site.Id,
                    UserName             = userName,
                    Email                = email,
                    DisplayName          = email.Substring(0, email.IndexOf("@")),
                    FirstName            = externalLoginInfo.Principal.FindFirstValue(ClaimTypes.GivenName),
                    LastName             = externalLoginInfo.Principal.FindFirstValue(ClaimTypes.Surname),
                    AccountApproved      = userManager.Site.RequireApprovalBeforeLogin ? false : true,
                    EmailConfirmed       = socialAuthEmailVerificationPolicy.HasVerifiedEmail(externalLoginInfo),
                    AgreementAcceptedUtc = termsAcceptedDate,
                    LastLoginUtc         = DateTime.UtcNow
                };
                var identityResult = await userManager.CreateAsync(newUser);

                if (identityResult.Succeeded)
                {
                    identityResult = await userManager.AddLoginAsync(newUser, externalLoginInfo);

                    return(newUser);
                }
            }
            return(null);
        }
        public async Task <IActionResult> NewUser(NewUserViewModel model)
        {
            var selectedSite = await _siteManager.GetSiteForDataOperations(model.SiteId);

            // only server admin site can edit other sites settings
            if (selectedSite.Id != _siteManager.CurrentSite.Id)
            {
                ViewData["Title"] = string.Format(CultureInfo.CurrentUICulture, _sr["{0} - New User"], selectedSite.SiteName);
            }
            else
            {
                ViewData["Title"] = _sr["New User"];
            }

            bool isValid = ModelState.IsValid;

            bool userNameAvailable = await _userManager.LoginIsAvailable(model.UserId, model.Username);

            if (!userNameAvailable)
            {
                ModelState.AddModelError("usernameerror", _sr["Username is already in use"]);
                isValid = false;
            }

            bool customDataIsValid = await _customUserInfo.HandleNewUserValidation(
                selectedSite,
                model,
                HttpContext,
                ViewData,
                ModelState);


            if (isValid && customDataIsValid)
            {
                var user = new SiteUser()
                {
                    SiteId      = selectedSite.Id,
                    UserName    = model.Username,
                    Email       = model.Email,
                    FirstName   = model.FirstName,
                    LastName    = model.LastName,
                    DisplayName = model.DisplayName
                };

                if (model.DateOfBirth.HasValue)
                {
                    user.DateOfBirth = model.DateOfBirth.Value;
                }

                await _customUserInfo.ProcessUserBeforeCreate(user, HttpContext);

                var result = await _userManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    await _customUserInfo.HandleNewUserPostSuccess(
                        selectedSite,
                        user,
                        model,
                        HttpContext);

                    if (model.MustChangePwd)
                    {
                        user.MustChangePwd = true;
                        await _userManager.UpdateAsync(user);
                    }

                    this.AlertSuccess(string.Format(_sr["user account for {0} was successfully created."],
                                                    user.DisplayName), true);

                    return(RedirectToAction("Index", "UserAdmin", new { siteId = selectedSite.Id }));
                }
                AddErrors(result);
            }

            var viewName = await _customUserInfo.GetNewUserViewName(_userManager.Site, HttpContext);

            // If we got this far, something failed, redisplay form
            return(View(viewName, model));
        }
Esempio n. 4
0
        public async Task <IActionResult> Register(RegisterViewModel model)
        {
            ViewData["Title"] = sr["Register"];
            if ((Site.CaptchaOnRegistration) && (Site.RecaptchaPublicKey.Length > 0))
            {
                model.RecaptchaSiteKey = Site.RecaptchaPublicKey;
            }
            model.UseEmailForLogin           = Site.UseEmailForLogin;
            model.RegistrationPreamble       = Site.RegistrationPreamble;
            model.RegistrationAgreement      = Site.RegistrationAgreement;
            model.AgreementRequired          = Site.RegistrationAgreement.Length > 0;
            model.ExternalAuthenticationList = signInManager.GetExternalAuthenticationSchemes();

            bool isValid = ModelState.IsValid;

            if (isValid)
            {
                if ((Site.CaptchaOnRegistration) && (Site.RecaptchaPublicKey.Length > 0))
                {
                    string recpatchaSecretKey = Site.RecaptchaPrivateKey;

                    var captchaResponse = await this.ValidateRecaptcha(Request, recpatchaSecretKey);

                    if (!captchaResponse.Success)
                    {
                        //if (captchaResponse.ErrorCodes.Count <= 0)
                        //{
                        //    return View(model);
                        //}

                        ////TODO: log these errors rather than show them in the ui
                        //var error = captchaResponse.ErrorCodes[0].ToLower();
                        //switch (error)
                        //{
                        //    case ("missing-input-secret"):
                        //        ModelState.AddModelError("recaptchaerror", "The secret parameter is missing.");
                        //        break;
                        //    case ("invalid-input-secret"):
                        //        ModelState.AddModelError("recaptchaerror", "The secret parameter is invalid or malformed.");
                        //        break;
                        //    case ("missing-input-response"):
                        //        ModelState.AddModelError("recaptchaerror", "The response parameter is missing.");
                        //        break;
                        //    case ("invalid-input-response"):
                        //        ModelState.AddModelError("recaptchaerror", "The response parameter is invalid or malformed.");
                        //        break;
                        //    default:
                        //        ModelState.AddModelError("recaptchaerror", "Error occured. Please try again");
                        //        break;
                        //}

                        ModelState.AddModelError("recaptchaerror", "reCAPTCHA Error occured. Please try again");
                        isValid = false;
                    }
                }

                if (Site.RegistrationAgreement.Length > 0)
                {
                    if (!model.AgreeToTerms)
                    {
                        ModelState.AddModelError("agreementerror", sr["You must agree to the terms"]);
                        isValid = false;
                    }
                }

                var userName          = model.Username.Length > 0 ? model.Username : model.Email.Replace("@", string.Empty).Replace(".", string.Empty);
                var userNameAvailable = await userManager.LoginIsAvailable(Guid.Empty, userName);

                if (!userNameAvailable)
                {
                    ModelState.AddModelError("usernameerror", sr["Username not accepted please try a different value"]);
                    isValid = false;
                }

                if (!isValid)
                {
                    return(View(model));
                }

                var user = new SiteUser
                {
                    UserName        = userName,
                    Email           = model.Email,
                    FirstName       = model.FirstName,
                    LastName        = model.LastName,
                    DisplayName     = model.DisplayName,
                    AccountApproved = Site.RequireApprovalBeforeLogin ? false : true
                };

                if (model.DateOfBirth.HasValue)
                {
                    user.DateOfBirth = model.DateOfBirth.Value;
                }

                var result = await userManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    await ipAddressTracker.TackUserIpAddress(Site.Id, user.Id);

                    if (Site.RequireConfirmedEmail) // require email confirmation
                    {
                        var code = await userManager.GenerateEmailConfirmationTokenAsync(user);

                        var callbackUrl = Url.Action(new UrlActionContext {
                            Action     = "ConfirmEmail",
                            Controller = "Account",
                            Values     = new { userId = user.Id.ToString(), code = code },
                            Protocol   = HttpContext.Request.Scheme
                        });

                        emailSender.SendAccountConfirmationEmailAsync(
                            Site,
                            model.Email,
                            sr["Confirm your account"],
                            callbackUrl).Forget();

                        if (this.SessionIsAvailable())
                        {
                            this.AlertSuccess(sr["Please check your email inbox, we just sent you a link that you need to click to confirm your account"], true);

                            return(Redirect("/"));
                        }
                        else
                        {
                            return(RedirectToAction("EmailConfirmationRequired", new { userId = user.Id, didSend = true }));
                        }
                    }
                    else
                    {
                        if (Site.RequireApprovalBeforeLogin)
                        {
                            emailSender.AccountPendingApprovalAdminNotification(Site, user).Forget();
                            return(RedirectToAction("PendingApproval", new { userId = user.Id, didSend = true }));
                        }
                        else
                        {
                            await signInManager.SignInAsync(user, isPersistent : false);

                            return(this.RedirectToSiteRoot(Site));
                        }
                    }
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Esempio n. 5
0
        public async Task <IActionResult> Register(EditUserViewModel model)
        {
            ViewData["Title"] = "Register";

            if ((Site.CaptchaOnRegistration) && (Site.RecaptchaPublicKey.Length > 0))
            {
                model.RecaptchaSiteKey = Site.RecaptchaPublicKey;
            }

            model.RegistrationPreamble  = Site.RegistrationPreamble;
            model.RegistrationAgreement = Site.RegistrationAgreement;

            bool isValid = ModelState.IsValid;

            if (isValid)
            {
                if ((Site.CaptchaOnRegistration) && (Site.RecaptchaPublicKey.Length > 0))
                {
                    string recpatchaSecretKey = Site.RecaptchaPrivateKey;

                    var captchaResponse = await this.ValidateRecaptcha(Request, recpatchaSecretKey);

                    if (!captchaResponse.Success)
                    {
                        //if (captchaResponse.ErrorCodes.Count <= 0)
                        //{
                        //    return View(model);
                        //}

                        ////TODO: log these errors rather than show them in the ui
                        //var error = captchaResponse.ErrorCodes[0].ToLower();
                        //switch (error)
                        //{
                        //    case ("missing-input-secret"):
                        //        ModelState.AddModelError("recaptchaerror", "The secret parameter is missing.");
                        //        break;
                        //    case ("invalid-input-secret"):
                        //        ModelState.AddModelError("recaptchaerror", "The secret parameter is invalid or malformed.");
                        //        break;
                        //    case ("missing-input-response"):
                        //        ModelState.AddModelError("recaptchaerror", "The response parameter is missing.");
                        //        break;
                        //    case ("invalid-input-response"):
                        //        ModelState.AddModelError("recaptchaerror", "The response parameter is invalid or malformed.");
                        //        break;
                        //    default:
                        //        ModelState.AddModelError("recaptchaerror", "Error occured. Please try again");
                        //        break;
                        //}

                        ModelState.AddModelError("recaptchaerror", "reCAPTCHA Error occured. Please try again");
                        isValid = false;
                    }
                }

                //if (Site.RegistrationAgreement.Length > 0)
                //{
                //    if (!model.AgreeToTerms)
                //    {
                //        ModelState.AddModelError("agreementerror", "You must agree to the terms");
                //        isValid = false;
                //    }
                //}

                if (!isValid)
                {
                    return(View(model));
                }

                var user = new SiteUser
                {
                    UserName    = model.LoginName.Length > 0? model.LoginName : model.Email.Replace("@", string.Empty).Replace(".", string.Empty),
                    Email       = model.Email,
                    FirstName   = model.FirstName,
                    LastName    = model.LastName,
                    DisplayName = model.DisplayName
                };

                if (model.DateOfBirth.HasValue)
                {
                    user.DateOfBirth = model.DateOfBirth.Value;
                }


                var result = await userManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=532713
                    // Send an email with this link
                    //var code = await UserManager.GenerateEmailConfirmationTokenAsync(user);
                    //var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Context.Request.Scheme);
                    //await MessageServices.SendEmailAsync(model.Email, "Confirm your account",
                    //    "Please confirm your account by clicking this link: <a href=\"" + callbackUrl + "\">link</a>");
                    await signInManager.SignInAsync(user, isPersistent : false);

                    return(RedirectToAction("Index", "Home"));
                }
                AddErrors(result);
            }
            //else
            //{
            //    this.AlertDanger("model was invalid", true);
            //}

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Esempio n. 6
0
        public async Task <IActionResult> Register(RegisterViewModel model, string returnUrl = null)
        {
            ViewData["ReturnUrl"] = returnUrl;
            if (ModelState.IsValid)
            {
                var user = new SiteUser {
                    UserName = model.Email, Email = model.Email
                };
                var result = await _siteUserManager.CreateAsync(user);

                // var result = await _siteUserManager.CreateAsync(user, model.Password);

                // var user = await _userManager.FindByEmailAsync(model.Email);
                if (result.Succeeded)
                {
                    // Send an email with this link
                    var code = await _siteUserManager.GenerateEmailConfirmationTokenAsync(user);

                    var callbackUrl = Url.Action(nameof(EmailClient), "Email", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);
                    //Email from Email Template
                    string Message = "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>";
                    // string body;

                    var webRoot = _env.WebRootPath; //get wwwroot Folder

                    //Get TemplateFile located at wwwroot/Templates/EmailTemplate/Register_EmailTemplate.html
                    var pathToFile = _env.WebRootPath
                                     + Path.DirectorySeparatorChar.ToString()
                                     + "Templates"
                                     + Path.DirectorySeparatorChar.ToString()
                                     + "EmailTemplate"
                                     + Path.DirectorySeparatorChar.ToString()
                                     + "Confirm_Account_Registration.html";

                    var subject = "Confirm Account Registration";

                    var builder = new BodyBuilder();
                    using (StreamReader SourceReader = System.IO.File.OpenText(pathToFile))
                    {
                        builder.HtmlBody = SourceReader.ReadToEnd();
                    }
                    //{0} : Subject
                    //{1} : DateTime
                    //{2} : Email
                    //{3} : Username
                    //{4} : Password
                    //{5} : Message
                    //{6} : callbackURL

                    string messageBody = string.Format(builder.HtmlBody,
                                                       subject,
                                                       String.Format("{0:dddd, d MMMM yyyy}", DateTime.Now),
                                                       model.Email,
                                                       model.Email,
                                                       model.Password,
                                                       Message,
                                                       callbackUrl
                                                       );


                    await _emailSender.SendEmailAsync("*****@*****.**", model.Email, model.Email, subject, messageBody);

                    ViewData["Message"]      = $"Please confirm your account by clicking this link: <a href='{callbackUrl}' class='btn btn-primary'>Confirmation Link</a>";
                    ViewData["MessageValue"] = "1";

                    _logger.LogInformation(3, "User created a new account with password.");
                    return(LocalRedirect(returnUrl));
                }
                ViewData["Message"]      = $"Error creating user. Please try again later";
                ViewData["MessageValue"] = "0";
                // AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Esempio n. 7
0
        public async Task <IActionResult> Register(RegisterViewModel model)
        {
            ViewData["Title"] = "Register";

            if ((Site.CaptchaOnRegistration) && (Site.RecaptchaPublicKey.Length > 0))
            {
                model.RecaptchaSiteKey = Site.RecaptchaPublicKey;
            }

            model.RegistrationPreamble  = Site.RegistrationPreamble;
            model.RegistrationAgreement = Site.RegistrationAgreement;

            bool isValid = ModelState.IsValid;

            if (isValid)
            {
                if ((Site.CaptchaOnRegistration) && (Site.RecaptchaPublicKey.Length > 0))
                {
                    string recpatchaSecretKey = Site.RecaptchaPrivateKey;

                    var captchaResponse = await this.ValidateRecaptcha(Request, recpatchaSecretKey);

                    if (!captchaResponse.Success)
                    {
                        //if (captchaResponse.ErrorCodes.Count <= 0)
                        //{
                        //    return View(model);
                        //}

                        ////TODO: log these errors rather than show them in the ui
                        //var error = captchaResponse.ErrorCodes[0].ToLower();
                        //switch (error)
                        //{
                        //    case ("missing-input-secret"):
                        //        ModelState.AddModelError("recaptchaerror", "The secret parameter is missing.");
                        //        break;
                        //    case ("invalid-input-secret"):
                        //        ModelState.AddModelError("recaptchaerror", "The secret parameter is invalid or malformed.");
                        //        break;
                        //    case ("missing-input-response"):
                        //        ModelState.AddModelError("recaptchaerror", "The response parameter is missing.");
                        //        break;
                        //    case ("invalid-input-response"):
                        //        ModelState.AddModelError("recaptchaerror", "The response parameter is invalid or malformed.");
                        //        break;
                        //    default:
                        //        ModelState.AddModelError("recaptchaerror", "Error occured. Please try again");
                        //        break;
                        //}

                        ModelState.AddModelError("recaptchaerror", "reCAPTCHA Error occured. Please try again");
                        isValid = false;
                    }
                }

                //if (Site.RegistrationAgreement.Length > 0)
                //{
                //    if (!model.AgreeToTerms)
                //    {
                //        ModelState.AddModelError("agreementerror", "You must agree to the terms");
                //        isValid = false;
                //    }
                //}

                if (!isValid)
                {
                    return(View(model));
                }

                var user = new SiteUser
                {
                    UserName    = model.LoginName.Length > 0? model.LoginName : model.Email.Replace("@", string.Empty).Replace(".", string.Empty),
                    Email       = model.Email,
                    FirstName   = model.FirstName,
                    LastName    = model.LastName,
                    DisplayName = model.DisplayName
                };

                if (model.DateOfBirth.HasValue)
                {
                    user.DateOfBirth = model.DateOfBirth.Value;
                }


                var result = await userManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    if (Site.UseSecureRegistration) // require email confirmation
                    {
                        var code = await userManager.GenerateEmailConfirmationTokenAsync(user);

                        var callbackUrl = Url.Action("ConfirmEmail", "Account",
                                                     new { userId = user.Id, code = code },
                                                     protocol: HttpContext.Request.Scheme);

                        await emailSender.SendAccountConfirmationEmailAsync(
                            Site,
                            model.Email,
                            "Confirm your account",
                            callbackUrl);

                        if (this.SessionIsAvailable())
                        {
                            this.AlertSuccess("Please check your email inbox, we just sent you a link that you need to click to confirm your account", true);

                            return(Redirect("/"));
                        }
                        else
                        {
                            return(RedirectToAction("EmailConfirmationRequired", new { userGuid = user.Id, didSend = true }));
                        }
                    }
                    else
                    {
                        if (Site.RequireApprovalBeforeLogin)
                        {
                            //TODO: send notification to admins about request for approval
                        }
                        else
                        {
                            await signInManager.SignInAsync(user, isPersistent : false);

                            return(Redirect("/"));
                        }
                    }
                }
                AddErrors(result);
            }
            //else
            //{
            //    this.AlertDanger("model was invalid", true);
            //}

            // If we got this far, something failed, redisplay form
            return(View(model));
        }