Beispiel #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());
        }
Beispiel #2
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);
            }
Beispiel #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));
        }
Beispiel #5
0
 public Model()
 {
     YetaWFManager.Syncify(async() => {  // this is needed during model validation
         ConfigData = await LoginConfigDataProvider.GetConfigAsync();
     });
     TwoStepAuth = new SerializableList <Role>();
 }
Beispiel #6
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);
            }
Beispiel #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));
        }
    /// <summary>
    /// 检查是否要直接登录,如果是那就直接登录(默认选择筛选后的第0个登录)
    /// </summary>
    /// <param name="datas">返回可登录选项</param>
    /// <returns></returns>
    public static bool CheckAutoLoginOrGetLoginPlatforms(out List <LoginConfigData> datas)
    {
        datas = new List <LoginConfigData>();
        List <LoginConfigData> allConfigs = DataGenerateManager <LoginConfigData> .GetAllDataList();

        string sdkStr = SDKManager.GetProperties(SDKInterfaceDefine.PropertiesKey_LoginPlatform, "");

        if (!string.IsNullOrEmpty(sdkStr))
        {
            string[] arrStr = sdkStr.Split('|');
            foreach (var item in arrStr)
            {
                LoginConfigData con = DataGenerateManager <LoginConfigData> .GetData(item);

                if (con != null)
                {
                    datas.Add(con);
                }
                else
                {
                    Debug.LogError("获取登录配置失败:" + item);
                }
            }
        }
        else
        {
            //Debug.LogError("获取登录配置失败:" + item);

            foreach (var d in allConfigs)
            {
                List <string> platforms = null;
                if (d.m_SupportPlatform == null)
                {
                    platforms = new List <string>();
                }
                else
                {
                    platforms = new List <string>(d.m_SupportPlatform);
                }

                if (d.m_UseItem || platforms.Contains(Application.platform.ToString()))
                {
                    datas.Add(d);
                }
            }
        }

        string directlyLoginStr = SDKManager.GetProperties(SDKInterfaceDefine.PropertiesKey_DirectlyLogin, "false");
        bool   directlyLogin    = bool.Parse(directlyLoginStr);

        if (directlyLogin)
        {
            LoginConfigData d = datas[0];
            Login(d.m_loginName, "", "", d.m_CustomInfo);
            return(true);
        }
        return(false);
    }
Beispiel #9
0
        public static void SaveXml(LoginConfigData loginConfigData, string xmlPath)
        {
            XmlSerializer ser = new XmlSerializer(typeof(LoginConfigData));

            using (FileStream fs = File.Create(xmlPath))
            {
                ser.Serialize(fs, loginConfigData);
            }
        }
Beispiel #10
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));
            }
        }
Beispiel #11
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));
        }
Beispiel #12
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));
        }
Beispiel #13
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));
            }
        }
        private async Task <ExtUserInfo> GetUserInfo(LoginConfigData config)
        {
            ExtUserInfo info = new ExtUserInfo();

            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");
                throw new Error(this.__ResStr("noExtLogin", "No external login has been processed"));
            }
            info.LoginInfo            = loginInfo;
            info.Email                = loginInfo.Principal.FindFirstValue(ClaimTypes.Email);
            info.Name                 = loginInfo.Principal.FindFirstValue(ClaimTypes.Name);
            info.LoginProvider        = loginInfo.LoginProvider;
            info.LoginProviderDisplay = loginInfo.ProviderDisplayName;

            // Check whether this is an invited user
            using (UserDefinitionDataProvider dataProvider = new UserDefinitionDataProvider()) {
                List <DataProviderFilterInfo> filters = null;
                switch (config.RegistrationType)
                {
                default:
                case RegistrationTypeEnum.NameAndEmail:
                    filters = DataProviderFilterInfo.Join(filters, new DataProviderFilterInfo {
                        Field = nameof(UserDefinition.UserName), Operator = "==", Value = info.Name,
                    });
                    filters = DataProviderFilterInfo.Join(filters, new DataProviderFilterInfo {
                        Field = nameof(UserDefinition.Email), Operator = "==", Value = info.Email,
                    });
                    break;

                case RegistrationTypeEnum.EmailOnly:
                    filters = DataProviderFilterInfo.Join(filters, new DataProviderFilterInfo {
                        Field = nameof(UserDefinition.Email), Operator = "==", Value = info.Email,
                    });
                    break;

                case RegistrationTypeEnum.NameOnly:
                    filters = DataProviderFilterInfo.Join(filters, new DataProviderFilterInfo {
                        Field = nameof(UserDefinition.UserName), Operator = "==", Value = info.Name,
                    });
                    break;
                }
                info.ExistingUser = await dataProvider.GetItemAsync(filters);
            }
            return(info);
        }
Beispiel #15
0
        public async Task <ActionResult> LoginConfig()
        {
            using (LoginConfigDataProvider dataProvider = new LoginConfigDataProvider()) {
                Model model          = new Model {
                };
                LoginConfigData data = await dataProvider.GetItemAsync();

                if (data == null)
                {
                    throw new Error(this.__ResStr("notFound", "User login configuration was not found."));
                }
                model.SetData(data);
                return(View(model));
            }
        }
Beispiel #16
0
        private static LoginConfigData GetInitLoginConfigData()
        {
            LoginConfigData initLoginConfigData = new LoginConfigData()
            {
                dataBaseType = DataBaseType.SQLITE,
                rowsPerPage  = 20,
                mysqlConfig  = new MySQLConfig
                {
                    selectedIP           = "127.0.0.1",
                    selectedUserName     = "",
                    selectedDataBaseName = "",
                    hostIPs = new List <string>()
                    {
                        "127.0.0.1"
                    },
                    userNameAndPassWords = new List <UserNameAndPassWord>(),
                    dataBaseConfigs      = new List <DataBaseConfig>()
                },
                sqliteConfig = new SQLiteConfig
                {
                    selectedDataBasePath = SqlDataInSqlite.SqliteDefaultDateBasePath,
                    dataBaseConfigs      = new List <DataBaseConfig>()
                    {
                        new DataBaseConfig()
                        {
                            Name = SqlDataInSqlite.SqliteDefaultDateBasePath,
                            WebDataCaptureTime =
                                DateTime.MinValue.ToString("yyyy-MM-dd HHH:mm:ss")
                        }
                    }
                },
                crawlConfig = new CrawlConfig
                {
                    IsCrawl      = true,
                    IntervalDays = 10,
                    CrawlURL     = CommonString.CrawlURL
                },
                webServerConfig = new WebServerConfig
                {
                    IsStartWebServer = true,
                    Port             = 5555,
                    RowsPerPage      = 20
                }
            };

            return(initLoginConfigData);
        }
Beispiel #17
0
        public async Task <ActionResult> LoginConfig_Partial(Model model)
        {
            using (LoginConfigDataProvider dataProvider = new LoginConfigDataProvider()) {
                LoginConfigData data = await dataProvider.GetItemAsync();// get the original item

                if (!ModelState.IsValid)
                {
                    return(PartialView(model));
                }
                data = model.GetData(data); // merge new data into original
                model.SetData(data);        // and all the data back into model for final display
                await dataProvider.UpdateConfigAsync(data);

                Manager.Need2FAState = null;// we may have changed two-step auth settings, so re-evaluate
                return(FormProcessed(model, this.__ResStr("okSaved", "Configuration settings saved")));
            }
        }
Beispiel #18
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));
        }
Beispiel #19
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));
            }
        }
        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,
                });
            }
        }
Beispiel #21
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));
        }
Beispiel #22
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));
        }
Beispiel #23
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;
                }
            }
        }
Beispiel #24
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);
        }
Beispiel #25
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));
            }
        }
Beispiel #26
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,
            });
        }
Beispiel #27
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));
        }
Beispiel #28
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));
        }
Beispiel #29
0
 public LoginConfigData GetData(LoginConfigData data)
 {
     ObjectSupport.CopyData(this, data);
     return(data);
 }
Beispiel #30
0
 public void SetData(LoginConfigData data)
 {
     ObjectSupport.CopyData(data, this);
 }