Пример #1
0
        public async Task <AddUserInfo> AddUserAsync(string name, string email, string password, bool needsNewPassword, string comment)
        {
            AddUserInfo     info   = new AddUserInfo();
            LoginConfigData config = await LoginConfigDataProvider.GetConfigAsync();

            UserDefinition user = new UserDefinition {
                UserName          = name,
                Email             = email,
                PasswordPlainText = config.SavePlainTextPassword || needsNewPassword ? password : null,
                Comment           = comment,
            };

            if (config.RegistrationType == RegistrationTypeEnum.NameAndEmail)
            {
                using (UserDefinitionDataProvider dataProvider = new UserDefinitionDataProvider()) {
                    // Email == user.Email
                    List <DataProviderFilterInfo> filters = new List <DataProviderFilterInfo> {
                        new DataProviderFilterInfo {
                            Field = nameof(UserDefinition.Email), Operator = "==", Value = user.Email,
                        },
                    };
                    UserDefinition userExists = await dataProvider.GetItemAsync(filters);

                    if (userExists != null && user.UserName != userExists.Email)
                    {
                        info.ErrorType = AddUserInfo.ErrorTypeEnum.Email;
                        info.Errors.Add(this.__ResStr("emailUsed", "An account with email address {0} already exists.", user.Email));
                        return(info);
                    }
                }
            }
            user.UserStatus = UserStatusEnum.Approved;

            // create user
            var result = await Managers.GetUserManager().CreateAsync(user, password);

            if (!result.Succeeded)
            {
                info.ErrorType = AddUserInfo.ErrorTypeEnum.Name;
                foreach (var error in result.Errors)
                {
#if MVC6
                    info.Errors.Add(error.Description);
#else
                    info.Errors.Add(error);
#endif
                    return(info);
                }
            }
            if (needsNewPassword)
            {
                using (UserDefinitionDataProvider userDP = new UserDefinitionDataProvider()) {
                    user.NeedsNewPassword = true;
                    if (await userDP.UpdateItemAsync(user) != UpdateStatusEnum.OK)
                    {
                        throw new InternalError($"Failed to update new user to set {nameof(user.NeedsNewPassword)}");
                    }
                }
            }

            info.ErrorType = AddUserInfo.ErrorTypeEnum.None;
            info.UserId    = user.UserId;
            return(info);
        }
Пример #2
0
        public async Task <IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null)
        {
            if (remoteError != null)
            {
                throw new Error(this.__ResStr("extErr", "The external login provider reported this error: {0}", remoteError));
            }

            SignInManager <UserDefinition> _signinManager = (SignInManager <UserDefinition>)YetaWFManager.ServiceProvider.GetService(typeof(SignInManager <UserDefinition>));
            ExternalLoginInfo loginInfo = await _signinManager.GetExternalLoginInfoAsync();

            if (loginInfo == null)
            {
                Logging.AddErrorLog("AuthenticationManager.GetExternalLoginInfoAsync() returned null");
                return(Redirect(Helper.GetSafeReturnUrl(Manager.CurrentSite.LoginUrl)));
            }
            using (LoginConfigDataProvider logConfigDP = new LoginConfigDataProvider()) {
                List <LoginConfigDataProvider.LoginProviderDescription> loginProviders = await logConfigDP.GetActiveExternalLoginProvidersAsync();

                if ((from l in loginProviders where l.InternalName == loginInfo.LoginProvider select l).FirstOrDefault() == null)
                {
                    Logging.AddErrorLog("Callback from external login provider {0} which is not active", loginInfo.LoginProvider);
                    return(Redirect(Helper.GetSafeReturnUrl(Manager.CurrentSite.LoginUrl)));
                }
            }

            // get our registration defaults
            LoginConfigData config = await LoginConfigDataProvider.GetConfigAsync();

            // Sign in the user with this external login provider if the user already has a login
            UserDefinition user = await Managers.GetUserManager().FindByLoginAsync(loginInfo.LoginProvider, loginInfo.ProviderKey);

            if (user == null)
            {
                // If the user does not have an account, then prompt the user to create an account
                // we will go to a page where the user can set up a local account
                Manager.OriginList = new List <Origin>();
                if (!string.IsNullOrWhiteSpace(returnUrl))
                {
                    Manager.OriginList.Add(new Origin()
                    {
                        Url = returnUrl
                    });                                                      // where to go after setup
                }
                Manager.OriginList.Add(new Origin()
                {
                    Url = Helper.GetSafeReturnUrl(Manager.CurrentSite.ExternalAccountSetupUrl)
                });                                                                                                                  // setup
                return(Redirect(Manager.ReturnToUrl));
            }

            if (string.IsNullOrWhiteSpace(returnUrl) && Manager.HaveReturnToUrl)
            {
                returnUrl = Manager.ReturnToUrl;
            }
            if (string.IsNullOrWhiteSpace(returnUrl))
            {
                returnUrl = await Resource.ResourceAccess.GetUserPostLoginUrlAsync((from u in user.RolesList select u.RoleId).ToList());
            }
            if (string.IsNullOrWhiteSpace(returnUrl))
            {
                returnUrl = Manager.CurrentSite.PostLoginUrl;
            }
            returnUrl = Helper.GetSafeReturnUrl(returnUrl);

            // determine what to do based on account status
            if (user.UserStatus == UserStatusEnum.Approved)
            {
                await LoginModuleController.UserLoginAsync(user);

                Logging.AddLog("User {0} - logged on", user.UserName);
                returnUrl = QueryHelper.AddRando(returnUrl); // to defeat client-side caching
                return(Redirect(returnUrl));
            }
            else if (user.UserStatus == UserStatusEnum.Rejected)
            {
                await LoginModuleController.UserLogoffAsync();

                Logging.AddErrorLog("User {0} - rejected user", user.UserName);
                if (string.IsNullOrWhiteSpace(config.RejectedUrl))
                {
                    return(Redirect(MessageUrl("Your account has been rejected by the site administrator.")));
                }
                return(Redirect(Helper.GetSafeReturnUrl(config.RejectedUrl)));
            }
            else if (user.UserStatus == UserStatusEnum.Suspended)
            {
                await LoginModuleController.UserLogoffAsync();

                Logging.AddErrorLog("User {0} - suspended user", user.UserName);
                if (string.IsNullOrWhiteSpace(config.SuspendedUrl))
                {
                    return(Redirect(MessageUrl("Your account has been suspended by the site administrator.")));
                }
                return(Redirect(Helper.GetSafeReturnUrl(config.SuspendedUrl)));
            }
            else if (user.UserStatus == UserStatusEnum.NeedValidation)
            {
                await LoginModuleController.UserLogoffAsync();

                Logging.AddErrorLog("User {0} - not yet validated", user.UserName);
                if (string.IsNullOrWhiteSpace(config.VerificationPendingUrl))
                {
                    return(Redirect(MessageUrl(this.__ResStr("notValidated", "Your account has not yet been verified. You will receive an email with verification information. Once received, please use the information in the email to complete the registration."))));
                }
                return(Redirect(Helper.GetSafeReturnUrl(config.VerificationPendingUrl)));
            }
            else if (user.UserStatus == UserStatusEnum.NeedApproval)
            {
                await LoginModuleController.UserLogoffAsync();

                Logging.AddErrorLog("User {0} - not yet approved", user.UserName);
                if (string.IsNullOrWhiteSpace(config.ApprovalPendingUrl))
                {
                    return(Redirect(MessageUrl(this.__ResStr("notApproved", "Your account has not yet been approved by the site administrator. You will receive an email confirmation as soon as your account is active."))));
                }
                return(Redirect(Helper.GetSafeReturnUrl(config.ApprovalPendingUrl)));
            }
            else
            {
                await LoginModuleController.UserLogoffAsync();

                throw new InternalError("badUserStatus", "Unexpected account status {0}", user.UserStatus);
            }
        }
Пример #3
0
        private async Task <ActionResult> CompleteLoginAsync(LoginModel model, LoginConfigData config, bool useTwoStep)
        {
            Manager.SessionSettings.SiteSettings.ClearValue(LoginTwoStepController.IDENTITY_TWOSTEP_USERID);
            Manager.SessionSettings.SiteSettings.ClearValue(LoginTwoStepController.IDENTITY_TWOSTEP_NEXTURL);
            Manager.SessionSettings.SiteSettings.ClearValue(LoginTwoStepController.IDENTITY_TWOSTEP_CLOSEONLOGIN);
            Manager.SessionSettings.SiteSettings.Save();
            model.Success = false;

            // make sure it's a valid user
            UserDefinition user = await Managers.GetUserManager().FindByNameAsync(model.UserName);

            if (user == null)
            {
                Logging.AddErrorLog("User login failed: {0} - no such user", model.UserName);
                ModelState.AddModelError(nameof(LoginModel.Email), this.__ResStr("invLogin", "Invalid user name or password"));
                ModelState.AddModelError(nameof(LoginModel.UserName), this.__ResStr("invLogin", "Invalid user name or password"));
                ModelState.AddModelError(nameof(LoginModel.Password), this.__ResStr("invLogin", "Invalid user name or password"));
                return(PartialView(model));
            }
            using (UserLoginInfoDataProvider logInfoDP = new UserLoginInfoDataProvider()) {
                if (await logInfoDP.IsExternalUserAsync(user.UserId))
                {
                    throw new Error(this.__ResStr("extUser", "This account can only be accessed using an external login provider"));
                }
            }

            TwoStepAuth twoStep = new TwoStepAuth();// clear any two-step info we may have
            await twoStep.ClearTwoStepAutheticationAsync(user.UserId);

            if (config.MaxLoginFailures != 0 && user.LoginFailures >= config.MaxLoginFailures)
            {
                ModelState.AddModelError(nameof(LoginModel.Email), this.__ResStr("maxAttemps", "The maximum number of login attempts has been exceeded - Your account has been suspended"));
                ModelState.AddModelError(nameof(LoginModel.UserName), this.__ResStr("maxAttemps", "The maximum number of login attempts has been exceeded - Your account has been suspended"));
                if (user.UserStatus != UserStatusEnum.Suspended)
                {
                    user.UserStatus = UserStatusEnum.Suspended;
                    await Managers.GetUserManager().UpdateAsync(user);
                }
                return(PartialView(model));
            }

            UserDefinition foundUser = user;

            user = null;

            // Handle random super user password (only supported on Core)
            if (foundUser.UserId == SuperuserDefinitionDataProvider.SuperUserId && SuperuserDefinitionDataProvider.SuperuserAvailable && SuperuserDefinitionDataProvider.SuperUserPasswordRandom &&
                model.UserName == SuperuserDefinitionDataProvider.SuperUserName && model.Password == SuperuserDefinitionDataProvider.SuperUserPassword)
            {
                user = foundUser;
            }

            if (user == null)
            {
                user = await Managers.GetUserManager().FindByNameAsync(model.UserName);

                if (string.IsNullOrWhiteSpace(model.Password) || !await Managers.GetUserManager().CheckPasswordAsync(user, model.Password))
                {
                    user = null;
                }
            }
            if (user == null)
            {
                foundUser.LoginFailures = foundUser.LoginFailures + 1;
                await Managers.GetUserManager().UpdateAsync(foundUser);

                Logging.AddErrorLog("User login failed: {0}, {1}, {2}", model.UserName, model.Password, model.VerificationCode);
                ModelState.AddModelError(nameof(LoginModel.Email), this.__ResStr("invLogin", "Invalid user name or password"));
                ModelState.AddModelError(nameof(LoginModel.UserName), this.__ResStr("invLogin", "Invalid user name or password"));
                ModelState.AddModelError(nameof(LoginModel.Password), this.__ResStr("invLogin", "Invalid user name or password"));
                return(PartialView(model));
            }

            // if verification code valid, advance user to approved or needs approval
            if (user.UserStatus == UserStatusEnum.NeedValidation && model.VerificationCode == user.VerificationCode)
            {
                Logging.AddLog("User {0} validated ({1})", model.UserName, model.VerificationCode);

                if (config.ApproveNewUsers)
                {
                    user.UserStatus       = UserStatusEnum.NeedApproval;
                    user.LastActivityDate = DateTime.UtcNow;
                    user.LastActivityIP   = Manager.UserHostAddress;
                    await Managers.GetUserManager().UpdateAsync(user);

                    Emails emails = new Emails();
                    await emails.SendApprovalNeededAsync(user);

                    string nextPage = string.IsNullOrWhiteSpace(config.ApprovalPendingUrl) ? Manager.CurrentSite.HomePageUrl : config.ApprovalPendingUrl;
                    return(FormProcessed(model,
                                         this.__ResStr("notApproved", "You just verified your account. Now your account has to be approved by the site administrator. You will receive an email confirmation as soon as your account is active."),
                                         NextPage: nextPage));
                }
                user.UserStatus = UserStatusEnum.Approved;
                // this is saved below, before we're logged in
            }

            // check what to do based on account status
            if (user.UserStatus == UserStatusEnum.NeedValidation)
            {
                if (model.ShowVerification)
                {
                    Logging.AddErrorLog("User {0} - invalid verification code({1})", model.UserName, model.VerificationCode);
                    ModelState.AddModelError(nameof(LoginModel.VerificationCode), this.__ResStr("invVerification", "The verification code is invalid. Please make sure to copy/paste it from the email to avoid any typos."));
                    user.LoginFailures = user.LoginFailures + 1;
                    await Managers.GetUserManager().UpdateAsync(user);
                }
                else
                {
                    ModelState.AddModelError(nameof(LoginModel.VerificationCode), this.__ResStr("notValidated", "Your account has not yet been verified. You will receive an email with verification information. Please copy and enter the verification code here."));
                }
                model.ShowVerification       = true;
                model.ResendVerificationCode = await Module.GetAction_ResendVerificationEmailAsync(user.UserName);

                model.ShowCaptcha = false;
                return(PartialView(model));
            }
            else if (user.UserStatus == UserStatusEnum.NeedApproval)
            {
                Logging.AddErrorLog("User {0} - not yet approved", model.UserName);
                string nextPage = string.IsNullOrWhiteSpace(config.ApprovalPendingUrl) ? Manager.CurrentSite.HomePageUrl : config.ApprovalPendingUrl;
                return(FormProcessed(model,
                                     this.__ResStr("notApproved2", "Your account has not yet been approved by the site administrator. You will receive an email confirmation as soon as your account is active."),
                                     NextPage: nextPage));
            }
            else if (user.UserStatus == UserStatusEnum.Rejected)
            {
                Logging.AddErrorLog("User {0} - rejected user", model.UserName);
                string nextPage = string.IsNullOrWhiteSpace(config.RejectedUrl) ? Manager.CurrentSite.HomePageUrl : config.RejectedUrl;
                return(FormProcessed(model,
                                     this.__ResStr("accountRejected", "Your account has been rejected by the site administrator."),
                                     NextPage: nextPage));
            }
            else if (user.UserStatus == UserStatusEnum.Suspended)
            {
                Logging.AddErrorLog("User {0} - suspended user", model.UserName);
                string nextPage = string.IsNullOrWhiteSpace(config.SuspendedUrl) ? Manager.CurrentSite.HomePageUrl : config.SuspendedUrl;
                return(FormProcessed(model,
                                     this.__ResStr("accountSuspended", "Your account has been suspended."),
                                     NextPage: nextPage));
            }
            else if (user.UserStatus == UserStatusEnum.Approved)
            {
                string nextUrl = null;
                if (Manager.HaveReturnToUrl)
                {
                    nextUrl = Manager.ReturnToUrl;
                }
                if (string.IsNullOrWhiteSpace(nextUrl))
                {
                    nextUrl = await Resource.ResourceAccess.GetUserPostLoginUrlAsync((from u in user.RolesList select u.RoleId).ToList());
                }
                if (string.IsNullOrWhiteSpace(nextUrl))
                {
                    nextUrl = Manager.CurrentSite.PostLoginUrl;
                }
                if (string.IsNullOrWhiteSpace(nextUrl))
                {
                    nextUrl = YetaWFManager.Manager.CurrentSite.HomePageUrl;
                }

                if (useTwoStep)
                {
                    ActionResult actionResult = await TwoStepAuthetication(user);

                    if (actionResult != null)
                    {
                        Manager.SessionSettings.SiteSettings.SetValue <int>(LoginTwoStepController.IDENTITY_TWOSTEP_USERID, user.UserId);// marker that user has entered correct name/password
                        Manager.SessionSettings.SiteSettings.SetValue <string>(LoginTwoStepController.IDENTITY_TWOSTEP_NEXTURL, nextUrl);
                        Manager.SessionSettings.SiteSettings.SetValue <bool>(LoginTwoStepController.IDENTITY_TWOSTEP_CLOSEONLOGIN, model.CloseOnLogin);
                        Manager.SessionSettings.SiteSettings.Save();
                        return(actionResult);
                    }
                }
                await LoginModuleController.UserLoginAsync(user, model.RememberMe);

                model.Success = true;
                Logging.AddLog("User {0} - logged on", model.UserName);

                return(FormProcessed(model, OnClose: OnCloseEnum.GotoNewPage, OnPopupClose: OnPopupCloseEnum.GotoNewPage, NextPage: nextUrl, ForceRedirect: true));
            }
            else
            {
                throw new InternalError("badUserStatus", "Unexpected account status {0}", user.UserStatus);
            }
        }
Пример #4
0
        public async Task <ActionResult> Register_Partial(RegisterModel model)
        {
            LoginConfigData config = await LoginConfigDataProvider.GetConfigAsync();

            if (!config.AllowUserRegistration)
            {
                throw new Error(this.__ResStr("cantRegister", "This site does not allow new user registration"));
            }

            if (model.ShowCaptcha != config.Captcha && !Manager.IsLocalHost)
            {
                throw new InternalError("Hidden field tampering detected");
            }
            if (!model.ShowCaptcha && ModelState[nameof(model.Captcha)] != null)
            {
                ModelState[nameof(model.Captcha)].ValidationState = Microsoft.AspNetCore.Mvc.ModelBinding.ModelValidationState.Valid;
            }

            model.RegistrationType = config.RegistrationType;// don't trust what we get from user
            if (Module.ShowPasswordRules)
            {
                using (LoginConfigDataProvider logConfigDP = new LoginConfigDataProvider()) {
                    model.PasswordRules = logConfigDP.PasswordRules;
                }
            }

            await model.UpdateAsync();

            if (!ModelState.IsValid)
            {
                return(PartialView(model));
            }

            // Create a new user and save all info
            UserDefinition user = new UserDefinition();

            switch (config.RegistrationType)
            {
            default:
            case RegistrationTypeEnum.NameAndEmail:
                user.UserName = model.UserName;
                user.Email    = model.Email;
                break;

            case RegistrationTypeEnum.EmailOnly:
                user.UserName = user.Email = model.Email;
                break;

            case RegistrationTypeEnum.NameOnly:
                user.UserName = user.Email = model.UserName;
                break;
            }

            user.PasswordPlainText = config.SavePlainTextPassword ? model.Password : null;

            if (config.RegistrationType == RegistrationTypeEnum.NameAndEmail)
            {
                using (UserDefinitionDataProvider dataProvider = new UserDefinitionDataProvider()) {
                    // Email == user.Email
                    List <DataProviderFilterInfo> filters = new List <DataProviderFilterInfo> {
                        new DataProviderFilterInfo {
                            Field = nameof(UserDefinition.Email), Operator = "==", Value = user.Email,
                        },
                    };
                    UserDefinition userExists = await dataProvider.GetItemAsync(filters);

                    if (userExists != null && user.UserName != userExists.Email)
                    {
                        ModelState.AddModelError(nameof(model.Email), this.__ResStr("emailUsed", "An account with email address {0} already exists.", user.Email));
                        return(PartialView(model));
                    }
                }
            }

            // set account status
            if (config.VerifyNewUsers)
            {
                user.UserStatus = UserStatusEnum.NeedValidation;
            }
            else if (config.ApproveNewUsers)
            {
                user.UserStatus = UserStatusEnum.NeedApproval;
            }
            else
            {
                user.UserStatus = UserStatusEnum.Approved;
            }
            user.RegistrationIP = Manager.UserHostAddress;

            // create user
            var result = await Managers.GetUserManager().CreateAsync(user, model.Password);

            if (!result.Succeeded)
            {
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(nameof(model.UserName), error.Description);
                    ModelState.AddModelError(nameof(model.Email), error.Description);
                    ModelState.AddModelError(nameof(model.Password), error.Description);
                }
                return(PartialView(model));
            }

            // send appropriate email based on account status
            Emails emails = new Emails();

            if (user.UserStatus == UserStatusEnum.NeedValidation)
            {
                await emails.SendVerificationAsync(user, config.BccVerification?Manager.CurrentSite.AdminEmail : null);

                string nextPage = string.IsNullOrWhiteSpace(config.VerificationPendingUrl) ? Manager.CurrentSite.HomePageUrl : config.VerificationPendingUrl;
                return(FormProcessed(model, this.__ResStr("okAwaitRegistration", "An email has just been sent to your email address \"{0}\" to complete the registration. Allow a few minutes for delivery. Once received, use the information in the email to complete the registration.", model.Email),
                                     this.__ResStr("okRegTitle", "Welcome!"),
                                     NextPage: nextPage));
            }
            else if (user.UserStatus == UserStatusEnum.NeedApproval)
            {
                await emails.SendApprovalNeededAsync(user);

                string nextPage = string.IsNullOrWhiteSpace(config.ApprovalPendingUrl) ? Manager.CurrentSite.HomePageUrl : config.ApprovalPendingUrl;
                return(FormProcessed(model, this.__ResStr("okAwaitApproval", "An email has just been sent to the site administrator for approval of your new account. Once processed and approved, you will receive an email confirming your approval."),
                                     this.__ResStr("okRegTitle", "Welcome!"),
                                     NextPage: nextPage));
            }
            else if (user.UserStatus == UserStatusEnum.Approved)
            {
                if (config.NotifyAdminNewUsers)
                {
                    await emails.SendNewUserCreatedAsync(user);
                }
                await LoginModuleController.UserLoginAsync(user, config.PersistentLogin);

                string nextUrl = null;
                if (Manager.HaveReturnToUrl)
                {
                    nextUrl = Manager.ReturnToUrl;
                }
                if (string.IsNullOrWhiteSpace(nextUrl) && !string.IsNullOrWhiteSpace(Module.PostRegisterUrl))
                {
                    nextUrl = Module.PostRegisterUrl;
                    if (Module.PostRegisterQueryString)
                    {
                        nextUrl += model.QueryString.AddQSSeparator() + model.QueryString;
                    }
                }
                if (string.IsNullOrWhiteSpace(nextUrl))
                {
                    nextUrl = await Resource.ResourceAccess.GetUserPostLoginUrlAsync((from u in user.RolesList select u.RoleId).ToList());
                }
                if (string.IsNullOrWhiteSpace(nextUrl))
                {
                    nextUrl = Manager.CurrentSite.PostLoginUrl;
                }

                if (!string.IsNullOrWhiteSpace(nextUrl))
                {
                    return(FormProcessed(model, this.__ResStr("okRegText", "Your new account has been successfully registered."), this.__ResStr("okRegTitle", "Welcome!"),
                                         OnClose: OnCloseEnum.GotoNewPage, OnPopupClose: OnPopupCloseEnum.GotoNewPage, NextPage: nextUrl, ForceRedirect: true));
                }
                return(FormProcessed(model, this.__ResStr("okRegText", "Your new account has been successfully registered."), this.__ResStr("okRegTitle", "Welcome!"), ForceRedirect: true));
            }
            else
            {
                throw new InternalError("badUserStatus", "Unexpected account status {0}", user.UserStatus);
            }
        }
        public async Task <ActionResult> SetupExternalAccount_Partial(SetupExternalAccountModel model)
        {
            LoginConfigData config = await LoginConfigDataProvider.GetConfigAsync();

            bool allowNewUser = config.AllowUserRegistration;

            ExtUserInfo extInfo = await GetUserInfo(config);

            model.AllowNewUser         = allowNewUser;
            model.ExistingUser         = extInfo.ExistingUser != null;
            model.LoginProviderDisplay = extInfo.LoginProviderDisplay;
            model.RegistrationType     = config.RegistrationType;
            if (extInfo.ExistingUser != null)
            {
                model.UserName = extInfo.Name;
                model.Email    = extInfo.Email;
            }

            if (!ModelState.IsValid)
            {
                return(PartialView(model));
            }

            UserDefinition user;

            if (allowNewUser && extInfo.ExistingUser == null)
            {
                // set new user info

                user = new UserDefinition();
                switch (config.RegistrationType)
                {
                default:
                case RegistrationTypeEnum.NameAndEmail:
                    user.UserName = model.UserName;
                    user.Email    = model.Email;
                    break;

                case RegistrationTypeEnum.EmailOnly:
                    user.UserName = user.Email = model.Email;
                    break;

                case RegistrationTypeEnum.NameOnly:
                    user.UserName = user.Email = model.UserName;
                    break;
                }
                if (config.VerifyNewUsers)
                {
                    user.UserStatus = UserStatusEnum.NeedValidation;
                }
                else if (config.ApproveNewUsers)
                {
                    user.UserStatus = UserStatusEnum.NeedApproval;
                }
                else
                {
                    user.UserStatus = UserStatusEnum.Approved;
                }
                user.RegistrationIP = Manager.UserHostAddress;

                // create new local account
                var createResult = await Managers.GetUserManager().CreateAsync(user);

                if (!createResult.Succeeded)
                {
                    throw new Error(string.Join(" - ", (from e in createResult.Errors select e.Description)));
                }
            }
            else
            {
                // invited user

                // verify invitation
                if (extInfo.ExistingUser.VerificationCode != model.InvitationCode)
                {
                    ModelState.AddModelError(nameof(model.InvitationCode), this.__ResStr("badInvite", "The invitation code is invalid"));
                    return(PartialView(model));
                }
                user            = extInfo.ExistingUser;
                user.UserStatus = UserStatusEnum.Approved;
            }

            // add login provider info
            IdentityResult result = await Managers.GetUserManager().AddLoginAsync(user, extInfo.LoginInfo);

            if (!result.Succeeded)
            {
                throw new Error(string.Join(" - ", (from e in result.Errors select e.Description)));
            }

            // send appropriate email based on account status
            Emails emails = new Emails();

            if (user.UserStatus == UserStatusEnum.NeedValidation)
            {
                await emails.SendVerificationAsync(user, config.BccVerification?Manager.CurrentSite.AdminEmail : null);

                string nextPage = string.IsNullOrWhiteSpace(config.VerificationPendingUrl) ? Manager.CurrentSite.HomePageUrl : config.VerificationPendingUrl;
                return(FormProcessed(model, this.__ResStr("okAwaitRegistration", "An email has just been sent to your email address \"{0}\" to complete the registration. Allow a few minutes for delivery. Once received, please use the information in the email to complete the registration.", model.Email),
                                     this.__ResStr("okRegTitle", "Welcome!"),
                                     NextPage: nextPage));
            }
            else if (user.UserStatus == UserStatusEnum.NeedApproval)
            {
                await emails.SendApprovalNeededAsync(user);

                string nextPage = string.IsNullOrWhiteSpace(config.ApprovalPendingUrl) ? Manager.CurrentSite.HomePageUrl : config.ApprovalPendingUrl;
                return(FormProcessed(model, this.__ResStr("okAwaitApproval", "An email has just been sent to the site administrator for approval of your new account. Once processed and approved, you will receive an email confirming your approval."),
                                     this.__ResStr("okRegTitle", "Welcome!"),
                                     NextPage: nextPage));
            }
            else if (user.UserStatus == UserStatusEnum.Approved)
            {
                if (config.NotifyAdminNewUsers)
                {
                    await emails.SendNewUserCreatedAsync(user);
                }
                await LoginModuleController.UserLoginAsync(user, config.PersistentLogin);

                return(FormProcessed(model, this.__ResStr("okRegText", "Your new account has been successfully registered."), this.__ResStr("okRegTitle", "Welcome!"),
                                     NextPage: Manager.ReturnToUrl, ForceRedirect: true));
            }
            else
            {
                throw new InternalError("badUserStatus", "Unexpected account status {0}", user.UserStatus);
            }
        }
Пример #6
0
        public async Task <ActionResult> UserAccount_Partial(EditModel model)
        {
            // make sure this user exists
            UserManager <UserDefinition> userManager = Managers.GetUserManager();
            UserDefinition user;

#if MVC6
            user = await userManager.FindByNameAsync(model.OriginalUserName);
#else
            user = userManager.FindByName(model.OriginalUserName);
#endif
            if (user == null)
            {
                throw new Error(this.__ResStr("alreadyDeleted", "The user named \"{0}\" has been removed and can no longer be updated.", model.OriginalUserName));
            }
            if (!ModelState.IsValid)
            {
                return(PartialView(model));
            }

            // update email/user name - can't use an existing email address
            // get the registration module for some defaults
            LoginConfigData config = await LoginConfigDataProvider.GetConfigAsync();

            switch (config.RegistrationType)
            {
            default:
            case RegistrationTypeEnum.NameAndEmail: {
                using (UserDefinitionDataProvider dataProvider = new UserDefinitionDataProvider()) {
                    List <DataProviderFilterInfo> filters = DataProviderFilterInfo.Join(null, new DataProviderFilterInfo {
                            Field = nameof(UserDefinition.Email), Operator = "==", Value = model.Email,
                        });
                    UserDefinition userExists = await dataProvider.GetItemAsync(filters);

                    if (userExists != null && user.UserName != userExists.UserName)
                    {
                        ModelState.AddModelError(nameof(model.Email), this.__ResStr("emailUsed", "An account using email address {0} already exists.", model.Email));
                        return(PartialView(model));
                    }
                }
                break;
            }

            case RegistrationTypeEnum.EmailOnly:
                model.UserName = model.Email;
                break;

            case RegistrationTypeEnum.NameOnly:
                model.Email = model.UserName;
                break;
            }

            // save new user info
            ObjectSupport.CopyData(model, user); // merge new data into original
            model.SetData(user);                 // and all the data back into model for final display

            if (model.OriginalUserName != user.UserName)
            {
                // user name changed - change data through data provider directly
                using (UserDefinitionDataProvider dataProvider = new UserDefinitionDataProvider()) {
                    UpdateStatusEnum status = await dataProvider.UpdateItemAsync(model.OriginalUserName, user);

                    switch (status)
                    {
                    default:
                    case UpdateStatusEnum.RecordDeleted:
                        ModelState.AddModelError(nameof(model.UserName), this.__ResStr("alreadyDeleted", "The user named \"{0}\" has been removed and can no longer be updated.", model.OriginalUserName));
                        return(PartialView(model));

                    case UpdateStatusEnum.NewKeyExists:
                        ModelState.AddModelError(nameof(model.UserName), this.__ResStr("alreadyExists", "A user named \"{0}\" already exists.", model.UserName));
                        return(PartialView(model));

                    case UpdateStatusEnum.OK:
                        break;
                    }
                }
                // log the user off and back on so new name takes effect
                //IAuthenticationManager authManager = HttpContext.GetOwinContext().Authentication;
                //deleted, done in UserLogff authManager.SignOut(DefaultAuthenticationTypes.ExternalCookie, DefaultAuthenticationTypes.ApplicationCookie, DefaultAuthenticationTypes.ExternalBearer);
                await LoginModuleController.UserLogoffAsync();

                await LoginModuleController.UserLoginAsync(user);
            }
            else
            {
                IdentityResult result;
                result = await userManager.UpdateAsync(user);

                if (!result.Succeeded)
                {
                    throw new Error(string.Join(" - ", (from e in result.Errors select e.Description)));
                }
            }
            return(FormProcessed(model, this.__ResStr("okSaved", "Your account information has been saved"), OnClose: OnCloseEnum.ReloadPage, OnPopupClose: OnPopupCloseEnum.ReloadParentPage, ForceRedirect: true));// reload for tiny login module to refresh
        }