Exemplo n.º 1
0
        public async Task <ActionResult> LoginDirectGet(string name, string password, Guid security)
        {
            Package package  = AreaRegistration.CurrentPackage;
            Guid    batchKey = WebConfigHelper.GetValue <Guid>(package.AreaName, "BatchKey");

            if (batchKey != security)
            {
                return(NotAuthorized());
            }

            LoginConfigData config = await LoginConfigDataProvider.GetConfigAsync();

            LoginModel model = new LoginModel {
                AllowNewUser     = config.AllowUserRegistration,
                RegistrationType = config.RegistrationType,
                RememberMe       = true,
                UserName         = name,
                Password         = password
            };

            ActionResult result = await CompleteLoginAsync(model, await LoginConfigDataProvider.GetConfigAsync(), useTwoStep : false);

            if (!model.Success)
            {
                Manager.CurrentResponse.StatusCode = 401;
            }
            return(new EmptyResult());
        }
Exemplo n.º 2
0
            }                                     // for external login only

            public async Task UpdateAsync()
            {
                LoginConfigData config = await LoginConfigDataProvider.GetConfigAsync();

                RegisterModule regMod = (RegisterModule)await ModuleDefinition.CreateUniqueModuleAsync(typeof(RegisterModule));

                bool closeOnLogin;

                Manager.TryGetUrlArg <bool>("CloseOnLogin", out closeOnLogin, false);
                ForgotPasswordModule pswdMod = (ForgotPasswordModule)await ModuleDefinition.CreateUniqueModuleAsync(typeof(ForgotPasswordModule));

                ModuleAction pswdAction = await pswdMod.GetAction_ForgotPasswordAsync(config.ForgotPasswordUrl, CloseOnLogin : closeOnLogin);

                if (pswdAction != null)
                {
                    pswdAction.AddToOriginList = false;
                }
                Actions.New(pswdAction);
                ModuleAction registerAction = await regMod.GetAction_RegisterAsync(config.RegisterUrl, Force : true, CloseOnLogin : closeOnLogin);

                if (registerAction != null)
                {
                    registerAction.AddToOriginList = false;
                }
                Actions.New(registerAction);
            }
Exemplo n.º 3
0
        public async Task <ModuleAction> GetAction_RegisterAsync(string url, bool Force = false, bool CloseOnLogin = false)
        {
            LoginConfigData config = await LoginConfigDataProvider.GetConfigAsync();

            if (!config.AllowUserRegistration)
            {
                return(null);
            }
            if (!Force && Manager.HaveUser)
            {
                return(null);
            }
            return(new ModuleAction(this)
            {
                Url = string.IsNullOrWhiteSpace(url) ? ModulePermanentUrl : url,
                QueryArgs = CloseOnLogin ? new { CloseOnLogin = CloseOnLogin } : null,
                Image = await CustomIconAsync("Register.png"),
                LinkText = this.__ResStr("regLink", "Register a new user account"),
                MenuText = this.__ResStr("regText", "Register"),
                Tooltip = this.__ResStr("regTooltip", "If you don't have an account on this site, click to register"),
                Legend = this.__ResStr("regLegend", "Allows you to register on this site as a new user"),
                Style = Manager.IsInPopup ? ModuleAction.ActionStyleEnum.ForcePopup : ModuleAction.ActionStyleEnum.Normal,
                Location = ModuleAction.ActionLocationEnum.NoAuto | ModuleAction.ActionLocationEnum.InPopup | ModuleAction.ActionLocationEnum.ModuleLinks,
                Category = ModuleAction.ActionCategoryEnum.Update,
                Mode = ModuleAction.ActionModeEnum.Any,
                SaveReturnUrl = false,
                AddToOriginList = false,
            });
        }
        public async Task <ActionResult> SetupExternalAccount()
        {
            // get the registration module for some defaults
            LoginConfigData config = await LoginConfigDataProvider.GetConfigAsync();

            bool allowNewUser = config.AllowUserRegistration;

            ExtUserInfo extInfo = await GetUserInfo(config);

            if (!allowNewUser && extInfo.ExistingUser == null)
            {
                throw new Error(this.__ResStr("noInvite", "This site allows new accounts by invitation only - According to our records there is no account on this site for your {0} credentials", extInfo.LoginProviderDisplay));
            }

            SetupExternalAccountModel model = new SetupExternalAccountModel {
                AllowNewUser         = allowNewUser,
                ExistingUser         = extInfo.ExistingUser != null,
                UserName             = extInfo.Name,
                Email                = extInfo.Email,
                RegistrationType     = config.RegistrationType,
                LoginProviderDisplay = extInfo.LoginProviderDisplay,
            };

            return(View(model));
        }
Exemplo n.º 5
0
 public Model()
 {
     YetaWFManager.Syncify(async() => {  // this is needed during model validation
         ConfigData = await LoginConfigDataProvider.GetConfigAsync();
     });
     TwoStepAuth = new SerializableList <Role>();
 }
Exemplo n.º 6
0
            public async Task UpdateAsync()
            {
                LoginConfigData config = await LoginConfigDataProvider.GetConfigAsync();

                RegisterModule regMod = (RegisterModule)await ModuleDefinition.CreateUniqueModuleAsync(typeof(RegisterModule));

                LoginModule loginMod = (LoginModule)await ModuleDefinition.CreateUniqueModuleAsync(typeof(LoginModule));

                bool closeOnLogin;

                Manager.TryGetUrlArg <bool>("CloseOnLogin", out closeOnLogin, false);

                ModuleAction logAction = await loginMod.GetAction_LoginAsync(config.LoginUrl, Force : true, CloseOnLogin : closeOnLogin);

                if (logAction != null)
                {
                    logAction.AddToOriginList = false;
                }
                Actions.New(logAction);
                ModuleAction regAction = await regMod.GetAction_RegisterAsync(config.RegisterUrl, Force : true, CloseOnLogin : closeOnLogin);

                if (regAction != null)
                {
                    regAction.AddToOriginList = false;
                }
                Actions.New(regAction);
            }
Exemplo n.º 7
0
        public async Task <ActionResult> Login(string name, string pswd, string v, bool closeOnLogin = false, bool __f = false)
        {
            // add popup support for possible 2fa
            await YetaWFCoreRendering.Render.AddPopupsAddOnsAsync();

            LoginConfigData config = await LoginConfigDataProvider.GetConfigAsync();

            bool isPersistent = config.PersistentLogin;

            LoginModel model = new LoginModel {
                AllowNewUser     = config.AllowUserRegistration,
                RegistrationType = config.RegistrationType,
                UserName         = name,
                Email            = name,
                Password         = pswd,
                VerificationCode = v,
                Captcha          = new RecaptchaV2Data(),
                RememberMe       = isPersistent,
                CloseOnLogin     = closeOnLogin,
                ShowVerification = !string.IsNullOrWhiteSpace(v),
                ShowCaptcha      = config.Captcha && string.IsNullOrWhiteSpace(v) && !Manager.IsLocalHost,
            };

            if (Manager.HaveReturnToUrl)
            {
                model.ReturnUrl = Manager.ReturnToUrl;
            }

            using (LoginConfigDataProvider logConfigDP = new LoginConfigDataProvider()) {
                List <LoginConfigDataProvider.LoginProviderDescription> loginProviders = await logConfigDP.GetActiveExternalLoginProvidersAsync();

                if (loginProviders.Count > 0 && Manager.IsInPopup)
                {
                    throw new InternalError("When using external login providers, the Login module cannot be used in a popup window");
                }
                foreach (LoginConfigDataProvider.LoginProviderDescription provider in loginProviders)
                {
                    model.ExternalProviders.Add(new FormButton()
                    {
                        ButtonType = ButtonTypeEnum.Submit,
                        Name       = "provider",
                        Text       = provider.InternalName,
                        Title      = this.__ResStr("logAccountTitle", "Log in using your {0} account", provider.DisplayName),
                        CssClass   = "t_" + provider.InternalName.ToLower(),
                    });
                    YetaWF.Core.Packages.Package package = AreaRegistration.CurrentPackage;
                    string url = VersionManager.GetAddOnPackageUrl(package.AreaName);
                    model.Images.Add(Manager.GetCDNUrl(string.Format("{0}Icons/LoginProviders/{1}.png", url, provider.InternalName)));
                }
            }
            if (__f)
            {
                Manager.CurrentResponse.StatusCode = 401;
            }

            await model.UpdateAsync();

            return(View(model));
        }
Exemplo n.º 8
0
        public async Task <ActionResult> UsersAdd_Partial(AddModel model)
        {
            if (!ModelState.IsValid)
            {
                return(PartialView(model));
            }

            using (UserDefinitionDataProvider dataProvider = new UserDefinitionDataProvider()) {
                LoginConfigData config = await LoginConfigDataProvider.GetConfigAsync();

                switch (config.RegistrationType)
                {
                default:
                case RegistrationTypeEnum.NameAndEmail: {     // Email == model.Email
                    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)
                    {
                        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.UserName = model.Email;
                    break;
                }

                UserDefinition user = model.GetData();

                string hashedNewPassword;
#if MVC6
                IPasswordHasher <UserDefinition> passwordHasher = (IPasswordHasher <UserDefinition>)YetaWFManager.ServiceProvider.GetService(typeof(IPasswordHasher <UserDefinition>));
                hashedNewPassword = passwordHasher.HashPassword(user, model.Password);
#else
                UserManager <UserDefinition> userManager = Managers.GetUserManager();
                hashedNewPassword = userManager.PasswordHasher.HashPassword(model.Password);
#endif
                user.PasswordPlainText = config.SavePlainTextPassword ? model.Password : null;
                user.PasswordHash      = hashedNewPassword;

                if (!await dataProvider.AddItemAsync(user))
                {
                    throw new Error(this.__ResStr("alreadyExists", "A user named \"{0}\" already exists."), model.UserName);
                }
                return(FormProcessed(model, this.__ResStr("okSaved", "New user saved"), OnPopupClose: OnPopupCloseEnum.ReloadModule));
            }
        }
Exemplo n.º 9
0
        public async Task <ActionResult> UsersAdd()
        {
            LoginConfigData config = await LoginConfigDataProvider.GetConfigAsync();

            AddModel model = new AddModel();

            model.SetData(new UserDefinition());
            model.RegistrationType = config.RegistrationType;
            return(View(model));
        }
Exemplo n.º 10
0
        public async Task <ActionResult> ForgotPassword()
        {
            LoginConfigData config = await LoginConfigDataProvider.GetConfigAsync();

            EditModel model = new EditModel {
                ShowCaptcha      = config.CaptchaForgotPassword,
                RegistrationType = config.RegistrationType,
            };
            await model.UpdateAsync();

            return(View(model));
        }
Exemplo n.º 11
0
        public async Task <ActionResult> Register(bool closeOnLogin = false)
        {
            LoginConfigData config = await LoginConfigDataProvider.GetConfigAsync();

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

            using (LoginConfigDataProvider logConfigDP = new LoginConfigDataProvider()) {
                RegisterModel model = new RegisterModel {
                    RegistrationType = config.RegistrationType,
                    ShowCaptcha      = config.Captcha && !Manager.IsLocalHost,
                    Captcha          = new RecaptchaV2Data(),
                    CloseOnLogin     = closeOnLogin,
                    QueryString      = Manager.RequestQueryString.ToQueryString(),
                    PasswordRules    = Module.ShowPasswordRules ? logConfigDP.PasswordRules : null,
                };

                List <LoginConfigDataProvider.LoginProviderDescription> loginProviders = await logConfigDP.GetActiveExternalLoginProvidersAsync();

                if (loginProviders.Count > 0 && Manager.IsInPopup)
                {
                    throw new InternalError("When using external login providers, the Register module cannot be used in a popup window");
                }
                foreach (LoginConfigDataProvider.LoginProviderDescription provider in loginProviders)
                {
                    model.ExternalProviders.Add(new FormButton()
                    {
                        ButtonType = ButtonTypeEnum.Submit,
                        Name       = "provider",
                        Text       = provider.InternalName,
                        Title      = this.__ResStr("logAccountTitle", "Log in using your {0} account", provider.DisplayName),
                        CssClass   = "t_" + provider.InternalName.ToLower(),
                    });
                    YetaWF.Core.Packages.Package package = AreaRegistration.CurrentPackage;
                    string url = VersionManager.GetAddOnPackageUrl(package.AreaName);
                    model.Images.Add(Manager.GetCDNUrl(string.Format("{0}Icons/LoginProviders/{1}.png", url, provider.InternalName)));
                }
                if (Manager.HaveReturnToUrl)
                {
                    model.ReturnUrl = Manager.ReturnToUrl;
                }

                await model.UpdateAsync();

                return(View(model));
            }
        }
Exemplo n.º 12
0
        public async Task <ModuleAction> GetAction_ForgotPasswordAsync(string url, bool CloseOnLogin = false)
        {
            LoginConfigData config = await LoginConfigDataProvider.GetConfigAsync();

            if (config.SavePlainTextPassword)
            {
                return(new ModuleAction(this)
                {
                    Url = string.IsNullOrWhiteSpace(url) ? ModulePermanentUrl : url,
                    QueryArgs = CloseOnLogin ? new { CloseOnLogin = CloseOnLogin } : null,
                    Image = "#Help",
                    LinkText = this.__ResStr("forgotLink", "Forgot your password?"),
                    MenuText = this.__ResStr("forgotText", "Forgot your password?"),
                    Tooltip = this.__ResStr("forgotTooltip", "If you have an account and forgot your password, click to have an email sent to you with your password"),
                    Legend = this.__ResStr("forgotLegend", "Used to send an email to you with your password if you have an account and forgot your password"),
                    Style = Manager.IsInPopup ? ModuleAction.ActionStyleEnum.ForcePopup : ModuleAction.ActionStyleEnum.Normal,
                    Location = ModuleAction.ActionLocationEnum.NoAuto | ModuleAction.ActionLocationEnum.InPopup | ModuleAction.ActionLocationEnum.ModuleLinks,
                    Category = ModuleAction.ActionCategoryEnum.Update,
                    Mode = ModuleAction.ActionModeEnum.Any,
                    SaveReturnUrl = false,
                    AddToOriginList = false,
                });
            }
            else
            {
                return(new ModuleAction(this)
                {
                    Url = string.IsNullOrWhiteSpace(url) ? ModulePermanentUrl : url,
                    QueryArgs = CloseOnLogin ? new { CloseOnLogin = CloseOnLogin } : null,
                    Image = "#Help",
                    LinkText = this.__ResStr("resetLink", "Forgot your password?"),
                    MenuText = this.__ResStr("resetText", "Forgot your password?"),
                    Tooltip = this.__ResStr("resetTooltip", "If you have an account and forgot your password, click to have an email sent to you to reset your password"),
                    Legend = this.__ResStr("resetLegend", "Used to send an email to you to reset your password if you have an account and forgot your password"),
                    Style = Manager.IsInPopup ? ModuleAction.ActionStyleEnum.ForcePopup : ModuleAction.ActionStyleEnum.Normal,
                    Location = ModuleAction.ActionLocationEnum.NoAuto | ModuleAction.ActionLocationEnum.InPopup | ModuleAction.ActionLocationEnum.ModuleLinks,
                    Category = ModuleAction.ActionCategoryEnum.Update,
                    Mode = ModuleAction.ActionModeEnum.Any,
                    SaveReturnUrl = false,
                    AddToOriginList = false,
                });
            }
        }
Exemplo n.º 13
0
        public async Task <ActionResult> UsersEdit(string userName)
        {
            using (UserDefinitionDataProvider dataProvider = new UserDefinitionDataProvider()) {
                LoginConfigData config = await LoginConfigDataProvider.GetConfigAsync();

                EditModel model = new EditModel {
                    RegistrationType = config.RegistrationType,
                };
                UserDefinition data = await dataProvider.GetItemAsync(userName);

                if (data == null)
                {
                    throw new Error(this.__ResStr("notFound", "User \"{0}\" not found."), userName);
                }
                model.SetData(data);
                Module.Title = this.__ResStr("modEditTitle", "User {0}", userName);
                return(View(model));
            }
        }
Exemplo n.º 14
0
        public async Task <ActionResult> NeedNewPasswordDisplay()
        {
            if (!Manager.NeedNewPassword)
            {
                return(new EmptyResult());
            }
            if (Manager.EditMode)
            {
                return(new EmptyResult());
            }
            if (Manager.IsInPopup)
            {
                return(new EmptyResult());
            }
            using (UserLoginInfoDataProvider logInfoDP = new UserLoginInfoDataProvider()) {
                if (await logInfoDP.IsExternalUserAsync(Manager.UserId))
                {
                    return(new EmptyResult());
                }
            }

            UserPasswordModule modNewPassword = (UserPasswordModule)await ModuleDefinition.LoadAsync(ModuleDefinition.GetPermanentGuid(typeof(UserPasswordModule)));

            if (modNewPassword == null)
            {
                throw new InternalError($"nameof(UserPasswordModule) module not found");
            }

            LoginConfigData config = await LoginConfigDataProvider.GetConfigAsync();

            ModuleAction actionNewPassword = modNewPassword.GetAction_UserPassword(config.ChangePasswordUrl);

            if (actionNewPassword == null)
            {
                throw new InternalError("Change password action not found");
            }

            DisplayModel model = new DisplayModel {
                ChangePasswordAction = actionNewPassword,
            };

            return(View(model));
        }
Exemplo n.º 15
0
        public async Task <ActionResult> Login_Partial(LoginModel model)
        {
            await model.UpdateAsync();

            LoginConfigData config = await LoginConfigDataProvider.GetConfigAsync();

            model.AllowNewUser     = config.AllowUserRegistration;
            model.RegistrationType = config.RegistrationType;

            if (model.ShowCaptcha != (config.Captcha && !model.ShowVerification && !Manager.IsLocalHost))
            {
                throw new InternalError("Hidden field tampering detected");
            }

            if (!ModelState.IsValid && config.RegistrationType == RegistrationTypeEnum.EmailOnly)
            {
                if (ModelState[nameof(model.Email)] != null && ModelState[nameof(model.Email)].ValidationState == Microsoft.AspNetCore.Mvc.ModelBinding.ModelValidationState.Invalid)
                {
                    // we allow the superuser name as login in case we use email registration and the superuser name is not a valid email address
                    if (string.Compare(model.Email, SuperuserDefinitionDataProvider.SuperUserName, true) == 0)
                    {
                        ModelState.Remove(nameof(model.Email));
                    }
                }
            }
            if (!model.ShowCaptcha && ModelState[nameof(model.Captcha)] != null)
            {
                ModelState[nameof(model.Captcha)].ValidationState = Microsoft.AspNetCore.Mvc.ModelBinding.ModelValidationState.Valid;
            }

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

            if (config.RegistrationType == RegistrationTypeEnum.EmailOnly)
            {
                model.UserName = model.Email;
            }

            return(await CompleteLoginAsync(model, config, useTwoStep : true));
        }
Exemplo n.º 16
0
        /// <summary>
        /// Log off
        /// </summary>
        public async Task <ActionResult> Logoff(string nextUrl)
        {
            Manager.SetSuperUserRole(false);// explicit logoff clears superuser state
            await LoginModuleController.UserLogoffAsync();

            LoginConfigData config = await LoginConfigDataProvider.GetConfigAsync();

            string url = nextUrl;

            if (string.IsNullOrWhiteSpace(url))
            {
                url = config.LoggedOffUrl;
            }
            if (string.IsNullOrWhiteSpace(url))
            {
                url = Manager.CurrentSite.HomePageUrl;
            }
            // Because this is a plain MVC controller, this Redirect really redirects (no Unified Page Set handling) which is the desired behavior
            url = QueryHelper.AddRando(url); // to defeat client-side caching
            return(Redirect(url));
        }
Exemplo n.º 17
0
        // Change a user password
        private async Task ChangePasswordAsync(string userName, string newPassword)
        {
            using (UserDefinitionDataProvider dataProvider = new UserDefinitionDataProvider()) {
                UserDefinition user = await dataProvider.GetItemAsync(userName);

                if (user == null)
                {
                    throw new Error(this.__ResStr("notFound", "User {0} not found", userName));
                }

                UserManager <UserDefinition> userManager = Managers.GetUserManager();
                string hashedNewPassword;
#if MVC6
                IPasswordHasher <UserDefinition> passwordHasher = (IPasswordHasher <UserDefinition>)YetaWFManager.ServiceProvider.GetService(typeof(IPasswordHasher <UserDefinition>));
                hashedNewPassword = passwordHasher.HashPassword(user, newPassword);
#else
                hashedNewPassword = userManager.PasswordHasher.HashPassword(newPassword);
#endif
                //ModuleDefinition.GetPermanentGuid(typeof(RegisterModule))
                LoginConfigData config = await LoginConfigDataProvider.GetConfigAsync();

                user.PasswordPlainText = config.SavePlainTextPassword ? newPassword : null;
                user.PasswordHash      = hashedNewPassword;
                UpdateStatusEnum status = await dataProvider.UpdateItemAsync(user);

                switch (status)
                {
                default:
                case UpdateStatusEnum.NewKeyExists:
                    throw new InternalError("Unexpected status {0}", status);

                case UpdateStatusEnum.RecordDeleted:
                    throw new Error(this.__ResStr("changeUserNotFound", "The user account for user {0} no longer exists.", userName));

                case UpdateStatusEnum.OK:
                    break;
                }
            }
        }
Exemplo n.º 18
0
        // User login
        public static async Task UserLoginAsync(UserDefinition user, bool?rememberme = null)
        {
            await LoginModuleController.UserLogoffAsync();

            bool isPersistent;

            if (rememberme == null)
            {
                LoginConfigData config = await LoginConfigDataProvider.GetConfigAsync();

                isPersistent = config.PersistentLogin;
            }
            else
            {
                isPersistent = (bool)rememberme;
            }

            SignInManager <UserDefinition> _signinManager = (SignInManager <UserDefinition>)YetaWFManager.ServiceProvider.GetService(typeof(SignInManager <UserDefinition>));
            await _signinManager.SignInAsync(user, isPersistent);

            // superuser
            int superuserRole = Resource.ResourceAccess.GetSuperuserRoleId();

            if (user.RolesList != null && user.RolesList.Contains(new Role {
                RoleId = superuserRole
            }, new RoleComparer()))
            {
                Manager.SetSuperUserRole(true);
            }

            // accept user
            user.LastLoginDate    = DateTime.UtcNow;
            user.LastLoginIP      = Manager.UserHostAddress;
            user.LastActivityDate = DateTime.UtcNow;
            user.LastActivityIP   = Manager.UserHostAddress;
            user.LoginFailures    = 0;
            await Managers.GetUserManager().UpdateAsync(user);
        }
Exemplo n.º 19
0
        public async Task <ActionResult> UserAccount()
        {
            using (UserDefinitionDataProvider dataProvider = new UserDefinitionDataProvider()) {
                LoginConfigData config = await LoginConfigDataProvider.GetConfigAsync();

                EditModel model = new EditModel {
                    RegistrationType = config.RegistrationType,
                };

                // make sure this user exists
#if MVC6
                if (!Manager.CurrentContext.User.Identity.IsAuthenticated)
#else
                if (!Manager.CurrentRequest.IsAuthenticated)
#endif
                {
                    throw new Error(this.__ResStr("noUser", "There is no logged on user."));
                }
                string userName = User.Identity.Name;
                UserManager <UserDefinition> userManager = Managers.GetUserManager();
                UserDefinition user;
#if MVC6
                user = await userManager.FindByNameAsync(userName);
#else
                user = userManager.FindByName(userName);
#endif
                if (user == null)
                {
                    throw new Error(this.__ResStr("notFound", "User \"{0}\" not found."), userName);
                }
                model.SetData(user);
                model.OriginalUserName = user.UserName;

                Module.Title = this.__ResStr("modEditTitle", "User Account");
                return(View(model));
            }
        }
Exemplo n.º 20
0
        public async Task <ModuleAction> GetAction_ForceTwoStepSetupAsync(string url)
        {
            if (string.IsNullOrWhiteSpace(url))
            {
                LoginConfigData config = await LoginConfigDataProvider.GetConfigAsync();

                url = config.TwoStepAuthUrl;
            }
            return(new ModuleAction(this)
            {
                Url = string.IsNullOrWhiteSpace(url) ? ModulePermanentUrl : url,
                Image = "#Edit",
                LinkText = this.__ResStr("setupLink", "Two-Step Authentication Setup"),
                MenuText = this.__ResStr("setupText", "Two-Step Authentication Setup"),
                Tooltip = this.__ResStr("setupTooltip", "Setup Two-Step Authentication"),
                Legend = this.__ResStr("setupLegend", "Setup Two-Step Authentication"),
                Style = ModuleAction.ActionStyleEnum.ForcePopup,
                Category = ModuleAction.ActionCategoryEnum.Update,
                Mode = ModuleAction.ActionModeEnum.Any,
                Location = ModuleAction.ActionLocationEnum.NoAuto,
                SaveReturnUrl = true,
                AddToOriginList = true,
            });
        }
Exemplo n.º 21
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
        }
Exemplo n.º 22
0
        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);
            }
        }
Exemplo n.º 23
0
        public async Task <ActionResult> UserPassword_Partial(EditModel model)
        {
            // get current user we're changing
            if (!Manager.CurrentContext.User.Identity.IsAuthenticated)
            {
                throw new Error(this.__ResStr("noUser", "There is no logged on user"));
            }

            string userName = User.Identity.Name;

            using (UserLoginInfoDataProvider logInfoDP = new UserLoginInfoDataProvider()) {
                string ext = await logInfoDP.GetExternalLoginProviderAsync(Manager.UserId);

                if (ext != null)
                {
                    throw new Error(this.__ResStr("extUserPswd", "This account can only be accessed using an external login provider"));
                }
            }

            UserManager <UserDefinition> userManager = Managers.GetUserManager();
            UserDefinition user = await userManager.FindByNameAsync(userName);

            if (user == null)
            {
                throw new Error(this.__ResStr("notFound", "User \"{0}\" not found."), userName);
            }

            model.SetData(user);
            if (Module.ShowPasswordRules)
            {
                using (LoginConfigDataProvider logConfigDP = new LoginConfigDataProvider()) {
                    model.PasswordRules = logConfigDP.PasswordRules;
                }
            }

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

            // change the password
            IPasswordValidator <UserDefinition> passVal = (IPasswordValidator <UserDefinition>)YetaWFManager.ServiceProvider.GetService(typeof(IPasswordValidator <UserDefinition>));
            IdentityResult result = await passVal.ValidateAsync(userManager, user, model.NewPassword);

            if (!result.Succeeded)
            {
                foreach (var err in result.Errors)
                {
                    ModelState.AddModelError(nameof(model.NewPassword), err.Description);
                }
                return(PartialView(model));
            }

            result = await userManager.ChangePasswordAsync(user, model.OldPassword ?? "", model.NewPassword);

            if (!result.Succeeded)
            {
                foreach (var err in result.Errors)
                {
                    ModelState.AddModelError(nameof(model.OldPassword), err.Description);
                }
                return(PartialView(model));
            }

            IPasswordHasher <UserDefinition> passwordHasher = (IPasswordHasher <UserDefinition>)YetaWFManager.ServiceProvider.GetService(typeof(IPasswordHasher <UserDefinition>));

            user.PasswordHash = passwordHasher.HashPassword(user, model.NewPassword);

            // update user info
            LoginConfigData config = await LoginConfigDataProvider.GetConfigAsync();

            user.LastPasswordChangedDate = DateTime.UtcNow;
            user.PasswordChangeIP        = Manager.UserHostAddress;
            bool forceReload = false;

            if (user.NeedsNewPassword)
            {
                forceReload = true; // we need to reload the page to get rid of the warning from NeedPasswordDisplay
            }
            user.NeedsNewPassword  = false;
            user.PasswordPlainText = config.SavePlainTextPassword ? model.NewPassword : null;
            user.ResetKey          = null;
            user.ResetValidUntil   = null;

            // finally update the user definition
            result = await userManager.UpdateAsync(user);

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

            // logoff/logon for any side effects in identity (like SecurityStamp update/cookies)
            await LoginModuleController.UserLoginAsync(user);

            return(FormProcessed(model, this.__ResStr("okSaved", "Your new password has been saved"), ForceRedirect: forceReload));
        }
Exemplo n.º 24
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);
            }
        }
Exemplo n.º 25
0
        public async Task <ActionResult> ResetPassword_Partial(EditModel model)
        {
            UserManager <UserDefinition> userManager = Managers.GetUserManager();
            UserDefinition user;

#if MVC6
            user = await userManager.FindByIdAsync(model.UserId.ToString());
#else
            user = userManager.FindById(model.UserId.ToString());
#endif
            if (user == null)
            {
                throw new Error(this.__ResStr("notFound", "User account not found."));
            }
            using (UserLoginInfoDataProvider logInfoDP = new UserLoginInfoDataProvider()) {
                if (await logInfoDP.IsExternalUserAsync(model.UserId))
                {
                    throw new Error(this.__ResStr("extUser", "Your account uses an external login provider - The password (if available) must be set up using the external login provider."));
                }
            }

            if (Module.ShowPasswordRules)
            {
                using (LoginConfigDataProvider logConfigDP = new LoginConfigDataProvider()) {
                    model.PasswordRules = logConfigDP.PasswordRules;
                }
            }
            if (!ModelState.IsValid)
            {
                return(PartialView(model));
            }

            Guid?resetKey = null;
            if (user.ResetKey == null || user.ResetValidUntil == null || user.ResetValidUntil < DateTime.UtcNow)
            {
                ModelState.AddModelError(nameof(model.ResetKey), this.__ResStr("expired", "The reset key has expired and is no longer valid"));
            }
            else
            {
                try {
                    resetKey = new Guid(model.ResetKey);
                } catch (Exception) {
                    ModelState.AddModelError(nameof(model.ResetKey), this.__ResStr("invReset", "The reset key is invalid - Please make sure to copy/paste the key in its entirety"));
                }
            }
            if (resetKey != null && user.ResetKey != (Guid)resetKey)
            {
                ModelState.AddModelError(nameof(model.ResetKey), this.__ResStr("invReset", "The reset key is invalid - Please make sure to copy/paste the key in its entirety"));
            }
            if (!ModelState.IsValid)
            {
                return(PartialView(model));
            }

            // change the password
            IdentityResult result;
#if MVC6
            IPasswordValidator <UserDefinition> passVal = (IPasswordValidator <UserDefinition>)YetaWFManager.ServiceProvider.GetService(typeof(IPasswordValidator <UserDefinition>));
            result = await passVal.ValidateAsync(userManager, user, model.NewPassword);
#else
            result = await userManager.PasswordValidator.ValidateAsync(model.NewPassword);
#endif
            if (!result.Succeeded)
            {
                foreach (var err in result.Errors)
                {
                    ModelState.AddModelError(nameof(model.NewPassword), err.Description);
                }
                return(PartialView(model));
            }
#if MVC6
            await userManager.RemovePasswordAsync(user);

            result = await userManager.AddPasswordAsync(user, model.NewPassword);
#else
            await userManager.RemovePasswordAsync(user.Id);

            result = await userManager.AddPasswordAsync(user.Id, model.NewPassword);
#endif
            if (!result.Succeeded)
            {
                foreach (var err in result.Errors)
                {
#if MVC6
                    ModelState.AddModelError(nameof(model.NewPassword), err.Description);
#else
                    ModelState.AddModelError(nameof(model.NewPassword), err);
#endif
                }
                return(PartialView(model));
            }
#if MVC6
            IPasswordHasher <UserDefinition> passwordHasher = (IPasswordHasher <UserDefinition>)YetaWFManager.ServiceProvider.GetService(typeof(IPasswordHasher <UserDefinition>));
            user.PasswordHash = passwordHasher.HashPassword(user, model.NewPassword);
#else
            user.PasswordHash = userManager.PasswordHasher.HashPassword(model.NewPassword);
#endif

            // update user info
            LoginConfigData config = await LoginConfigDataProvider.GetConfigAsync();

            user.LastPasswordChangedDate = DateTime.UtcNow;
            user.PasswordChangeIP        = Manager.UserHostAddress;
            bool forceReload = false;
            if (user.NeedsNewPassword)
            {
                forceReload = true; // we need to reload the page to get rid of the warning from NeedPasswordDisplay
            }
            user.NeedsNewPassword  = false;
            user.PasswordPlainText = config.SavePlainTextPassword ? model.NewPassword : null;
            user.ResetKey          = null;
            user.ResetValidUntil   = null;

            // finally update the user definition
#if MVC6
            result = await userManager.UpdateAsync(user);
#else
            result = userManager.Update(user);
#endif
            if (!result.Succeeded)
            {
                foreach (var err in result.Errors)
                {
#if MVC6
                    ModelState.AddModelError(nameof(model.NewPassword), err.Description);
#else
                    ModelState.AddModelError(nameof(model.NewPassword), err);
#endif
                }
                return(PartialView(model));
            }

            // logoff/logon for any side effects in identity (like SecurityStamp update/cookies)
            await LoginModuleController.UserLoginAsync(user);

            return(FormProcessed(model, this.__ResStr("okSaved", "Your new password has been saved"), ForceRedirect: forceReload));
        }
Exemplo n.º 26
0
        public async Task <ActionResult> UsersEdit_Partial(EditModel model)
        {
            using (UserDefinitionDataProvider dataProvider = new UserDefinitionDataProvider()) {
                string         originalUserName = model.OriginalUserName;
                UserDefinition user             = await dataProvider.GetItemAsync(originalUserName);

                if (user == null)
                {
                    throw new Error(this.__ResStr("alreadyDeleted", "The user named \"{0}\" has been removed and can no longer be updated.", originalUserName));
                }
                if (!ModelState.IsValid)
                {
                    return(PartialView(model));
                }

                LoginConfigData config = await LoginConfigDataProvider.GetConfigAsync();

                switch (config.RegistrationType)
                {
                case RegistrationTypeEnum.NameAndEmail: {
                    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;
                }

                user = model.GetData(user); // merge new data into original
                model.SetData(user);        // and all the data back into model for final display

                switch (await dataProvider.UpdateItemAsync(originalUserName, user))
                {
                default:
                case UpdateStatusEnum.RecordDeleted:
                    throw new Error(this.__ResStr("alreadyDeleted", "The user named \"{0}\" has been removed and can no longer be updated.", originalUserName));

                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;
                }
                return(FormProcessed(model, this.__ResStr("okSaved", "User updated"), OnPopupClose: OnPopupCloseEnum.ReloadModule));
            }
        }
Exemplo n.º 27
0
        public async Task <ActionResult> ForgotPassword_Partial(EditModel model)
        {
            LoginConfigData config = await LoginConfigDataProvider.GetConfigAsync();

            if (model.ShowCaptcha != config.CaptchaForgotPassword)
            {
                throw new InternalError("Hidden field tampering detected");
            }

            await model.UpdateAsync();

            model.ShowCaptcha      = config.CaptchaForgotPassword;
            model.RegistrationType = config.RegistrationType;
            if (!ModelState.IsValid)
            {
                return(PartialView(model));
            }

            using (UserDefinitionDataProvider userDP = new UserDefinitionDataProvider()) {
                UserDefinition userDef;
                switch (model.RegistrationType)
                {
                case RegistrationTypeEnum.NameOnly:
                    userDef = await userDP.GetItemAsync(model.UserName);

                    if (userDef == null)
                    {
                        ModelState.AddModelError(nameof(model.UserName), this.__ResStr("badName", "According to our records there is no account associated with this name"));
                        return(PartialView(model));
                    }
                    break;

                case RegistrationTypeEnum.NameAndEmail:
                    userDef = await userDP.GetItemAsync(model.UserNameOrEmail);

                    if (userDef == null)
                    {
                        userDef = await userDP.GetItemByEmailAsync(model.UserNameOrEmail);

                        if (userDef == null)
                        {
                            ModelState.AddModelError(nameof(model.UserNameOrEmail), this.__ResStr("badNameEmail", "According to our records there is no account associated with this name or email address"));
                            return(PartialView(model));
                        }
                    }
                    break;

                default:
                case RegistrationTypeEnum.EmailOnly:
                    userDef = await userDP.GetItemByEmailAsync(model.Email);

                    if (userDef == null)
                    {
                        ModelState.AddModelError(nameof(model.Email), this.__ResStr("badEmail", "According to our records there is no account associated with this email address"));
                        return(PartialView(model));
                    }
                    break;
                }

                using (UserLoginInfoDataProvider logInfoDP = new UserLoginInfoDataProvider()) {
                    if (await logInfoDP.IsExternalUserAsync(userDef.UserId))
                    {
                        ModelState.AddModelError(nameof(model.Email), this.__ResStr("extEmail", "According to our records there is no account associated with this email address"));
                        ModelState.AddModelError(nameof(model.UserName), this.__ResStr("extName", "According to our records there is no account associated with this name"));
                        ModelState.AddModelError(nameof(model.UserNameOrEmail), this.__ResStr("extUser", "According to our records there is no account associated with this name or email address"));
                        return(PartialView(model));
                    }
                }
                switch (userDef.UserStatus)
                {
                case UserStatusEnum.Approved:
                    Emails emails = new Emails();
                    if (config.SavePlainTextPassword)
                    {
                        await emails.SendForgottenEmailAsync(userDef, config.BccForgottenPassword?Manager.CurrentSite.AdminEmail : null);

                        string from = emails.GetSendingEmailAddress();
                        return(FormProcessed(model, this.__ResStr("okForgot", "We just sent an email to your email address with your password information - Please allow a few minutes for delivery and make sure your spam filters allow emails from {0}", from), OnClose: OnCloseEnum.Nothing, OnPopupClose: OnPopupCloseEnum.ReloadModule));
                    }
                    else
                    {
                        if (userDef.ResetKey != null && userDef.ResetValidUntil != null && userDef.ResetValidUntil > DateTime.UtcNow)
                        {
                            // preserve existing key in case user resends
                        }
                        else
                        {
                            userDef.ResetKey        = Guid.NewGuid();
                            userDef.ResetValidUntil = DateTime.UtcNow.Add(config.ResetTimeSpan);
                            if (await userDP.UpdateItemAsync(userDef) != Core.DataProvider.UpdateStatusEnum.OK)    // update reset key info
                            {
                                throw new Error(this.__ResStr("resetUpdate", "User information could not be updated"));
                            }
                        }
                        await emails.SendPasswordResetEmailAsync(userDef, config.BccForgottenPassword?Manager.CurrentSite.AdminEmail : null);

                        string from = emails.GetSendingEmailAddress();
                        return(FormProcessed(model, this.__ResStr("okReset", "We just sent an email to your email address to reset your password - Please allow a few minutes for delivery and make sure your spam filters allow emails from {0}", from), OnClose: OnCloseEnum.Nothing, OnPopupClose: OnPopupCloseEnum.ReloadModule));
                    }

                case UserStatusEnum.NeedApproval:
                    throw new Error(this.__ResStr("needApproval", "This account has not yet been approved and is awaiting approval by the site administrator"));

                case UserStatusEnum.NeedValidation:
                    throw new Error(this.__ResStr("needValidation", "This account has not yet been verified - Please check your emails for our verification email"));

                case UserStatusEnum.Rejected:
                    throw new Error(this.__ResStr("rejected", "This account has been rejected and is not accessible"));

                case UserStatusEnum.Suspended:
                    throw new Error(this.__ResStr("suspended", "This account has been suspended and is not accessible"));

                default:
                    throw new Error(this.__ResStr("unknownState", "This account is in an undefined state and is not accessible"));
                }
            }
        }
Exemplo n.º 28
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);
            }
        }