コード例 #1
0
        private string EncryptedUserEmail()
        {
            TwoStepAuth testObj    = new TwoStepAuth();
            var         encryption = testObj.GetEncryptionDecryption;
            string      result     = encryption.EncryptText("*****@*****.**", ATMConstants.emailEncKey);

            return(result);
        }
コード例 #2
0
        public async Task <ActionResult> SelectTwoStepSetup()
        {
            EditModel model = new EditModel();

            Manager.NeedUser();
            using (UserDefinitionDataProvider userDP = new UserDefinitionDataProvider()) {
                UserDefinition user = await userDP.GetItemByUserIdAsync(Manager.UserId);

                if (user == null)
                {
                    throw new InternalError("User with id {0} not found", Manager.UserId);
                }
                using (UserLoginInfoDataProvider logInfoDP = new UserLoginInfoDataProvider()) {
                    string ext = await logInfoDP.GetExternalLoginProviderAsync(Manager.UserId);

                    if (ext != null)
                    {
                        return(View("ShowMessage", this.__ResStr("extUser", "Your account uses a {0} account - Two-step authentication must be set up using your {0} account.", ext), UseAreaViewName: false));
                    }
                }
                TwoStepAuth         twoStep = new TwoStepAuth();
                List <ITwoStepAuth> list    = await twoStep.GetTwoStepAuthProcessorsAsync();

                List <string> procs = (from p in list select p.Name).ToList();
                List <string> enabledTwoStepAuths = (from e in user.EnabledTwoStepAuthentications select e.Name).ToList();
                foreach (string proc in procs)
                {
                    ITwoStepAuth auth = await twoStep.GetTwoStepAuthProcessorByNameAsync(proc);

                    if (auth != null)
                    {
                        ModuleAction action = await auth.GetSetupActionAsync();

                        if (action != null)
                        {
                            string status;
                            if (enabledTwoStepAuths.Contains(auth.Name))
                            {
                                status = this.__ResStr("enabled", "(Enabled)");
                            }
                            else
                            {
                                status = this.__ResStr("notEnabled", "(Not Enabled)");
                            }
                            model.AuthMethods.Add(new Controllers.SelectTwoStepSetupModuleController.EditModel.AuthMethod {
                                Action      = action,
                                Status      = status,
                                Description = auth.GetDescription()
                            });
                        }
                    }
                }
                model.AuthMethods = (from a in model.AuthMethods orderby a.Action.LinkText select a).ToList();
            }
            return(View(model));
        }
コード例 #3
0
        public async Task <List <string> > GetEnabledAndAvailableTwoStepAuthenticationsAsync()
        {
            TwoStepAuth         twoStep = new TwoStepAuth();
            List <ITwoStepAuth> list    = await twoStep.GetTwoStepAuthProcessorsAsync();

            List <string> procs = (from p in list select p.Name).ToList();
            List <string> enabledTwoStepAuths = (from e in EnabledTwoStepAuthentications select e.Name).ToList();

            procs = procs.Intersect(enabledTwoStepAuths).ToList();
            return(procs);
        }
コード例 #4
0
        /// <summary>
        /// Returns an action result to start the two-step authentication process (if any).
        /// </summary>
        private async Task <ActionResult> TwoStepAuthetication(UserDefinition user)
        {
            TwoStepAuth   twoStep = new TwoStepAuth();
            List <string> enabledTwoStepAuthentications = (from e in user.EnabledTwoStepAuthentications select e.Name).ToList();
            ModuleAction  action = await twoStep.GetLoginActionAsync(enabledTwoStepAuthentications, user.UserId, user.UserName, user.Email);

            if (action == null)
            {
                return(null);
            }
            return(Redirect(action));
        }
コード例 #5
0
        public async Task <ActionResult> RecoveryCodes()
        {
            using (UserDefinitionDataProvider userDP = new UserDefinitionDataProvider()) {
                UserDefinition user = await userDP.GetItemByUserIdAsync(Manager.UserId);

                if (user == null)
                {
                    throw new InternalError("User with id {0} not found", Manager.UserId);
                }
                // Make sure this user is not using an external account
                using (UserLoginInfoDataProvider logInfoDP = new UserLoginInfoDataProvider()) {
                    if (await logInfoDP.IsExternalUserAsync(Manager.UserId))
                    {
                        return(new EmptyResult());
                    }
                }
                // Make sure there are any 2fa processors
                TwoStepAuth         twoStep = new TwoStepAuth();
                List <ITwoStepAuth> list    = await twoStep.GetTwoStepAuthProcessorsAsync();

                if (list.Count == 0)
                {
                    return(new EmptyResult());
                }

                // If there is no recovery code, generate one (upgraded system)
                if (user.RecoveryCode == null)
                {
                    await GenerateRecoveryCodeAsync(userDP, user);
                }

                EditModel.ModelProgressEnum progress = (EditModel.ModelProgressEnum)Manager.SessionSettings.SiteSettings.GetValue <int>(IDENTITY_RECOVERY_PROGRESS, (int)EditModel.ModelProgressEnum.New);

                EditModel model = new EditModel()
                {
                    ModelProgress = progress,
                };
                model.UpdateData(user);

                await Manager.AddOnManager.AddAddOnNamedAsync("YetaWF_ComponentsHTML", "clipboardjs.com.clipboard");// add clipboard support which is needed later (after partial form update)

                return(View(model));
            }
        }
コード例 #6
0
        public async Task <ActionResult> SelectTwoStepAuth(int userId, string userName, string userEmail)
        {
            EditModel model = new EditModel {
                UserId    = userId,
                UserName  = userName,
                UserEmail = userEmail,
            };

            using (UserDefinitionDataProvider userDP = new UserDefinitionDataProvider()) {
                UserDefinition user = await userDP.GetItemByUserIdAsync(userId);

                if (user == null)
                {
                    throw new InternalError("User with id {0} not found", userId);
                }
                TwoStepAuth         twoStep = new TwoStepAuth();
                List <ITwoStepAuth> list    = await twoStep.GetTwoStepAuthProcessorsAsync();

                List <string> procs = (from p in list select p.Name).ToList();
                List <string> enabledTwoStepAuths = (from e in user.EnabledTwoStepAuthentications select e.Name).ToList();
                procs = procs.Intersect(enabledTwoStepAuths).ToList();
                foreach (string proc in procs)
                {
                    ITwoStepAuth auth = await twoStep.GetTwoStepAuthProcessorByNameAsync(proc);

                    if (auth != null)
                    {
                        model.Actions.New(await auth.GetLoginActionAsync(userId, userName, userEmail));
                    }
                }
                if (model.Actions.Count == 0)
                {
                    throw new InternalError("There are no two-step authentication providers installed");
                }
            }
            return(View(model));
        }
コード例 #7
0
        public async Task <ActionResult> Login()
        {
            // verify that the user already entered the name/password correctly
            int    userId       = Manager.SessionSettings.SiteSettings.GetValue <int>(IDENTITY_TWOSTEP_USERID, 0);
            bool   closeOnLogin = Manager.SessionSettings.SiteSettings.GetValue <bool>(IDENTITY_TWOSTEP_CLOSEONLOGIN, false);
            string returnUrl    = Manager.SessionSettings.SiteSettings.GetValue <string>(IDENTITY_TWOSTEP_NEXTURL);

            Manager.SessionSettings.SiteSettings.ClearValue(LoginTwoStepController.IDENTITY_TWOSTEP_USERID);
            Manager.SessionSettings.SiteSettings.ClearValue(LoginTwoStepController.IDENTITY_TWOSTEP_NEXTURL);
            Manager.SessionSettings.SiteSettings.ClearValue(LoginTwoStepController.IDENTITY_TWOSTEP_CLOSEONLOGIN);
            Manager.SessionSettings.SiteSettings.Save();
            if (userId == 0)
            {
                return(Redirect(Manager.CurrentSite.HomePageUrl));
            }

            // verify that the TwoStepAuthorization provider just verified this user
            TwoStepAuth twoStep = new TwoStepAuth();

            if (!await twoStep.VerifyTwoStepAutheticationDoneAsync(userId))
            {
                return(Redirect(Manager.CurrentSite.HomePageUrl));
            }
            await twoStep.ClearTwoStepAutheticationAsync(userId);

            await Resource.ResourceAccess.LoginAsAsync(userId);

            if (closeOnLogin)
            {
                return(View("YetaWF_Identity_TwoStepDone"));
            }
            else
            {
                returnUrl = QueryHelper.AddRando(returnUrl); // to defeat client-side caching
                return(Redirect(returnUrl));
            }
        }
コード例 #8
0
        private async Task <ActionResult> CompleteLoginAsync(LoginModel model, LoginConfigData config, bool useTwoStep)
        {
            Manager.SessionSettings.SiteSettings.ClearValue(LoginTwoStepController.IDENTITY_TWOSTEP_USERID);
            Manager.SessionSettings.SiteSettings.ClearValue(LoginTwoStepController.IDENTITY_TWOSTEP_NEXTURL);
            Manager.SessionSettings.SiteSettings.ClearValue(LoginTwoStepController.IDENTITY_TWOSTEP_CLOSEONLOGIN);
            Manager.SessionSettings.SiteSettings.Save();
            model.Success = false;

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

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

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

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

            UserDefinition foundUser = user;

            user = null;

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

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

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

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

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

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

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

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

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

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

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

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

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

                return(FormProcessed(model, OnClose: OnCloseEnum.GotoNewPage, OnPopupClose: OnPopupCloseEnum.GotoNewPage, NextPage: nextUrl, ForceRedirect: true));
            }
            else
            {
                throw new InternalError("badUserStatus", "Unexpected account status {0}", user.UserStatus);
            }
        }