コード例 #1
0
        public virtual async Task GeneratePasswordResetToken(User user, int expirationInMinutes)
        {
            if (user == null)
            {
                throw new ArgumentNullException("user");
            }
            if (expirationInMinutes < 1)
            {
                throw new ArgumentException(
                          "Token expiration should give the user at least a minute to change their password", "expirationInMinutes");
            }

            if (!user.Confirmed)
            {
                throw new InvalidOperationException(Strings.UserIsNotYetConfirmed);
            }

            if (!String.IsNullOrEmpty(user.PasswordResetToken) && !user.PasswordResetTokenExpirationDate.IsInThePast())
            {
                return;
            }

            user.PasswordResetToken = CryptographyService.GenerateToken();
            user.PasswordResetTokenExpirationDate = DateTime.UtcNow.AddMinutes(expirationInMinutes);

            await Auditing.SaveAuditRecord(new UserAuditRecord(user, UserAuditAction.RequestedPasswordReset));

            Entities.SaveChanges();
            return;
        }
コード例 #2
0
        public bool SetAuditPol(Auditing audit)
        {
            //MiscFunc.Exec("auditpol.exe", "/set /subcategory:{0CCE9226-69AE-11D9-BED3-505054503030} /failure:enable /success:enable");
            try
            {
                AuditPol.AUDIT_POLICY_INFORMATION pol = AuditPol.GetSystemPolicy("0CCE9226-69AE-11D9-BED3-505054503030");
                switch (audit)
                {
                case Auditing.All: pol.AuditingInformation = AuditPol.AUDIT_POLICY_INFORMATION_TYPE.Success | AuditPol.AUDIT_POLICY_INFORMATION_TYPE.Failure; break;

                case Auditing.Blocked: pol.AuditingInformation = AuditPol.AUDIT_POLICY_INFORMATION_TYPE.Failure; break;

                case Auditing.Allowed: pol.AuditingInformation = AuditPol.AUDIT_POLICY_INFORMATION_TYPE.Success; break;

                case Auditing.Off: pol.AuditingInformation = AuditPol.AUDIT_POLICY_INFORMATION_TYPE.None; break;
                }
                TokenManipulator.AddPrivilege(TokenManipulator.SE_SECURITY_NAME);
                // Note: without SeSecurityPrivilege this fails silently
                AuditPol.SetSystemPolicy(pol);
                TokenManipulator.RemovePrivilege(TokenManipulator.SE_SECURITY_NAME);
            }
            catch (Exception err)
            {
                AppLog.Line("Error in {0}: {1}", MiscFunc.GetCurrentMethod(), err.Message);
                return(false);
            }
            return(true);
        }
コード例 #3
0
        public async Task <bool> RemovePageDefinitionAsync(Guid pageGuid)
        {
            PageDefinition page;

            using (ILockObject lockObject = await LockDesignedPagesAsync()) {
                page = await LoadPageDefinitionAsync(pageGuid);

                if (page == null)
                {
                    return(false);
                }
                await Manager.StaticPageManager.RemovePageAsync(page.Url);

                await DataProvider.RemoveAsync(pageGuid);
                await RemoveCachedPageAsync(pageGuid);

                DesignedPagesDictionaryByUrl designedPagesUrl = await GetDesignedPagesWithoutLockAsync();
                await RemoveDesignedPageAsync(designedPagesUrl, page.Url);

                await lockObject.UnlockAsync();
            }
            await Auditing.AddAuditAsync($"{nameof(PageDefinitionDataProvider)}.{nameof(RemovePageDefinitionAsync)}", page.Url, page.PageGuid,
                                         "Remove Page",
                                         DataBefore : page,
                                         DataAfter : null,
                                         ExpensiveMultiInstance : true
                                         );

            return(true);
        }
コード例 #4
0
        public async Task <UpdateStatusEnum> UpdateItemAsync(UnifiedSetData unifiedSet)
        {
            UnifiedSetData origData = Auditing.Active ? await GetItemAsync(unifiedSet.UnifiedSetGuid) : null;

            unifiedSet.Updated = DateTime.UtcNow;
            if (unifiedSet.UnifiedMode == PageDefinition.UnifiedModeEnum.SkinDynamicContent)
            {
                unifiedSet.PageList = new List <string>();
            }
            else
            {
                unifiedSet.PageSkin = new SkinDefinition();
            }
            unifiedSet.PageGuids = await UpdatePageGuidsAsync(unifiedSet.UnifiedSetGuid, unifiedSet.PageList);

            UpdateStatusEnum status = await DataProvider.UpdateAsync(unifiedSet.UnifiedSetGuid, unifiedSet.UnifiedSetGuid, unifiedSet);

            if (status != UpdateStatusEnum.OK)
            {
                return(status);
            }

            await Auditing.AddAuditAsync($"{nameof(UnifiedSetDataProvider)}.{nameof(UpdateItemAsync)}", Dataset, Guid.Empty,
                                         $"Update UPS {unifiedSet.Name}",
                                         DataBefore : origData,
                                         DataAfter : unifiedSet
                                         );

            return(status);
        }
コード例 #5
0
        private async Task <PageDefinition> CreatePageDefinitionAsync(PageDefinition page)
        {
            using (ILockObject lockObject = await LockDesignedPagesAsync()) {
                PageDefinition.DesignedPage desPage = new PageDefinition.DesignedPage()
                {
                    PageGuid = page.PageGuid, Url = page.Url,
                };
                DesignedPagesDictionaryByUrl designedPagesByUrl = await GetDesignedPagesWithoutLockAsync();

                if (designedPagesByUrl.ContainsKey(desPage.Url.ToLower()))
                {
                    throw new Error(this.__ResStr("pageUrlErr", "A page with Url {0} already exists.", desPage.Url));
                }
                if (!await DataProvider.AddAsync(page))
                {
                    throw new Error(this.__ResStr("pageGuidErr", "A page with Guid {0} already exists.", desPage.PageGuid));
                }
                await SetCachedPageAsync(page);
                await AddDesignedPageAsync(designedPagesByUrl, page.Url.ToLower(), desPage);

                await lockObject.UnlockAsync();
            }
            await Auditing.AddAuditAsync($"{nameof(PageDefinitionDataProvider)}.{nameof(CreatePageDefinitionAsync)}", page.Url, page.PageGuid,
                                         "Create Page",
                                         DataBefore : null,
                                         DataAfter : page,
                                         ExpensiveMultiInstance : true
                                         );

            return(page);
        }
コード例 #6
0
        public async Task <bool> AddItemAsync(UserDefinition data)
        {
            CleanupRoles(data);

            if (!Manager.HasSuperUserRole)
            {
                int superuserRole = Resource.ResourceAccess.GetSuperuserRoleId();
                if (data.RolesList.Contains(new Role {
                    RoleId = superuserRole
                }, new RoleComparer()))
                {
                    throw new Error(this.__ResStr("noSup", "Only a superuser can assign superuser status to another user"));
                }
            }
            if (data.UserId == SuperuserDefinitionDataProvider.SuperUserId || string.Compare(data.UserName, SuperuserDefinitionDataProvider.SuperUserName, true) == 0)
            {
                using (SuperuserDefinitionDataProvider superDP = new SuperuserDefinitionDataProvider()) {
                    return(await superDP.AddItemAsync(data));
                }
            }
            bool result = await DataProvider.AddAsync(data);

            await Auditing.AddAuditAsync($"{nameof(UserDefinitionDataProvider)}.{nameof(AddItemAsync)}", data.UserName, Guid.Empty,
                                         "Add User",
                                         DataBefore : null,
                                         DataAfter : data
                                         );

            return(result);
        }
コード例 #7
0
        public async Task <bool> AddItemAsync(UnifiedSetData unifiedSet)
        {
            unifiedSet.UnifiedSetGuid = Guid.NewGuid();
            unifiedSet.Created        = DateTime.UtcNow;
            if (unifiedSet.UnifiedMode == PageDefinition.UnifiedModeEnum.SkinDynamicContent)
            {
                unifiedSet.PageList = new List <string>();
            }
            else
            {
                unifiedSet.PageSkin = new SkinDefinition();
            }
            unifiedSet.PageGuids = await UpdatePageGuidsAsync(unifiedSet.UnifiedSetGuid, unifiedSet.PageList);

            if (!await DataProvider.AddAsync(unifiedSet))
            {
                return(false);
            }

            await Auditing.AddAuditAsync($"{nameof(UnifiedSetDataProvider)}.{nameof(AddItemAsync)}", Dataset, Guid.Empty,
                                         $"Add UPS {unifiedSet.Name}",
                                         DataBefore : null,
                                         DataAfter : unifiedSet
                                         );

            return(true);
        }
コード例 #8
0
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            try
            {
                var request = actionContext.Request;

                var principal = actionContext.RequestContext.Principal as ClaimsPrincipal;
                var userName  = principal?.Claims.FirstOrDefault(x => x.Type == "preferred_username")?.Value;

                //var controllerContext = new ControllerContext(filterContext.RequestContext, filterContext.Controller);
                var controller = actionContext.ControllerContext.ControllerDescriptor.ControllerName;
                var action     = actionContext.Request.RequestUri.AbsolutePath.Remove(0, 1);
                var audit      = new Auditing
                {
                    UserName = (!userName.IsNullOrEmpty()) ? userName : "******",
                    // UserId = (request.IsAuthenticated) ? filterContext.HttpContext.User.Identity.GetUserId() : Guid.Empty.ToString(),
                    IpAddress    = request.GetClientIpAddress(),
                    AreaAccessed = JsonConvert.SerializeObject(actionContext.ActionArguments),
                    TimeAccessed = DateTime.UtcNow,
                    Action       = action,
                    Controller   = controller,
                    MachinName   = Environment.MachineName,
                    //TODO: get id from setting
                    ApplicationId = (int)Applications.WebApi
                };

                AuditingService.SaveAuditing(audit);
            }
            catch (Exception ex)
            {
                Logger.ErrorException(ex.Message, ex);
                throw;
            }
        }
コード例 #9
0
        public async Task <UpdateStatusEnum> UpdateItemAsync(Authorization data)
        {
            Authorization origData = Auditing.Active ? await GetItemAsync(data.ResourceName) : null;

            CleanupUsersAndRoles(data);
            if (data.AllowedUsers.Count > Info.MAX_USERS_IN_RESOURCE)
            {
                throw new Error(this.__ResStr("maxUsers", "Only up to {0} users can be authorized for a resource. Consider creating a role instead, and add all users to that role. There is no limit to the number of users that can be added to a role."));
            }
            UpdateStatusEnum status = await DataProvider.UpdateAsync(data.ResourceName, data.ResourceName, data);

            if (status == UpdateStatusEnum.RecordDeleted)
            {
                if (!await DataProvider.AddAsync(data))
                {
                    throw new Error(this.__ResStr("addFail", "Unexpected error adding new record - {0}", status));
                }
                status = UpdateStatusEnum.OK;
            }
            if (status != UpdateStatusEnum.OK)
            {
                throw new Error(this.__ResStr("updFail", "Unexpected error updating record - {0}", status));
            }
            await Auditing.AddAuditAsync($"{nameof(AuthorizationDataProvider)}.{nameof(UpdateItemAsync)}", data.ResourceName, Guid.Empty,
                                         "Add/Update Authorization",
                                         DataBefore : origData,
                                         DataAfter : data,
                                         ExpensiveMultiInstance : true
                                         );

            return(status);
        }
コード例 #10
0
        public virtual async Task <AuthenticatedUser> Register(string username, string emailAddress, string fullname, Credential credential)
        {
            var existingUser = UserService.GetUser(username, emailAddress);

            if (existingUser != null)
            {
                if (String.Equals(existingUser.Username, username, StringComparison.OrdinalIgnoreCase))
                {
                    throw new EntityException(Strings.UsernameNotAvailable, username);
                }
                throw new EntityException(Strings.EmailAddressBeingUsed, emailAddress);
            }

            var newUser = new User(username)
            {
                FullName     = fullname,
                EmailAllowed = true,
                EmailAddress = emailAddress,
                CreatedUtc   = DateTime.UtcNow
            };

            // Add a credential for the password
            newUser.Credentials.Add(credential);

            // Write an audit record
            await Auditing.SaveAuditRecord(new UserAuditRecord(newUser, UserAuditAction.Registered));

            UserService.CreateUser(newUser);

            return(new AuthenticatedUser(newUser, credential));
        }
コード例 #11
0
        public async Task <ActionResult> LocalizeConfig_Partial(Model model)
        {
            using (LocalizeConfigDataProvider dataProvider = new LocalizeConfigDataProvider()) {
                LocalizeConfigData origData = YetaWF.Core.Audit.Auditing.Active ? await dataProvider.GetItemAsync() : null;

                LocalizeConfigData 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

                LocalizationSupport locSupport = new LocalizationSupport();
                await locSupport.SetUseLocalizationResourcesAsync(model.UseLocalizationResources);

                await locSupport.SetAbortOnFailureAsync(model.AbortOnFailure);

                await dataProvider.UpdateConfigAsync(data);

                await Auditing.AddAuditAsync($"{nameof(LocalizeConfigModuleController)}.{nameof(LocalizeConfig)}", null, Guid.Empty, $"Localization",
                                             DataBefore : origData,
                                             DataAfter : data,
                                             RequiresRestart : true
                                             );
            }
            return(FormProcessed(model, this.__ResStr("okSaved", "Localization settings saved - These settings won't take effect until the site is restarted")));
        }
コード例 #12
0
        public virtual async Task AddCredential(User user, Credential credential)
        {
            await Auditing.SaveAuditRecord(new UserAuditRecord(user, UserAuditAction.AddedCredential, credential));

            user.Credentials.Add(credential);
            Entities.SaveChanges();
        }
コード例 #13
0
        public async Task <UpdateStatusEnum> UpdateItemAsync(string originalRole, RoleDefinition data)
        {
            if (data.RoleId == RoleDefinitionDataProvider.SuperUserId || data.Name == Globals.Role_Superuser)
            {
                throw new Error(this.__ResStr("cantUpdateSuper", "Can't update built-in superuser role"));
            }
            if (originalRole != data.Name && IsPredefinedRole(originalRole))
            {
                throw new Error(this.__ResStr("cantUpdateUser", "The {0} role can't be updated", originalRole));
            }
            if (YetaWF.Core.Support.Startup.MultiInstance)
            {
                throw new InternalError("Changing roles is not possible when distributed caching is enabled");
            }
            RoleDefinition origRole = Auditing.Active ? await GetItemAsync(originalRole) : null;

            UpdateStatusEnum status = await DataProvider.UpdateAsync(originalRole, data.Name, data);

            if (status == UpdateStatusEnum.OK)
            {
                GetAllUserRoles(true);
            }
            await Auditing.AddAuditAsync($"{nameof(RoleDefinitionDataProvider)}.{nameof(UpdateItemAsync)}", originalRole, Guid.Empty,
                                         "Update Role",
                                         DataBefore : origRole,
                                         DataAfter : data,
                                         ExpensiveMultiInstance : true
                                         );

            return(status);
        }
コード例 #14
0
ファイル: FirewallMonitor.cs プロジェクト: vlad1000/priv10
        public bool SetAuditPolicy(Auditing audit)
        {
            try
            {
                AuditPolicy.AUDIT_POLICY_INFORMATION pol = AuditPolicy.GetSystemPolicy(FirewallEventPolicyID);
                switch (audit)
                {
                case Auditing.All: pol.AuditingInformation = AuditPolicy.AUDIT_POLICY_INFORMATION_TYPE.Success | AuditPolicy.AUDIT_POLICY_INFORMATION_TYPE.Failure; break;

                case Auditing.Blocked: pol.AuditingInformation = AuditPolicy.AUDIT_POLICY_INFORMATION_TYPE.Failure; break;

                case Auditing.Allowed: pol.AuditingInformation = AuditPolicy.AUDIT_POLICY_INFORMATION_TYPE.Success; break;

                case Auditing.Off: pol.AuditingInformation = AuditPolicy.AUDIT_POLICY_INFORMATION_TYPE.None; break;
                }
                TokenManipulator.AddPrivilege(TokenManipulator.SE_SECURITY_NAME);
                // Note: without SeSecurityPrivilege this fails silently
                AuditPolicy.SetSystemPolicy(pol);
                TokenManipulator.RemovePrivilege(TokenManipulator.SE_SECURITY_NAME);
            }
            catch (Exception err)
            {
                AppLog.Exception(err);
                return(false);
            }
            return(true);
        }
コード例 #15
0
        public async Task <User> DeleteMemberAsync(Organization organization, string memberName)
        {
            organization = organization ?? throw new ArgumentNullException(nameof(organization));

            var membership = FindMembershipByUsername(organization, memberName);

            if (membership == null)
            {
                throw new EntityException(string.Format(CultureInfo.CurrentCulture,
                                                        Strings.UpdateOrDeleteMember_MemberNotFound, memberName));
            }

            var memberToRemove = membership.Member;

            // block removal of last admin
            if (membership.IsAdmin && organization.Administrators.Count() == 1)
            {
                throw new EntityException(Strings.DeleteMember_CannotRemoveLastAdmin);
            }

            organization.Members.Remove(membership);

            await Auditing.SaveAuditRecordAsync(new UserAuditRecord(organization, AuditedUserAction.RemoveOrganizationMember, membership));

            await EntitiesContext.SaveChangesAsync();

            return(memberToRemove);
        }
コード例 #16
0
        public async Task CancelChangeEmailAddress(User user)
        {
            await Auditing.SaveAuditRecordAsync(new UserAuditRecord(user, AuditedUserAction.CancelChangeEmail, user.UnconfirmedEmailAddress));

            user.CancelChangeEmailAddress();
            await UserRepository.CommitChangesAsync();
        }
コード例 #17
0
        /// <summary>
        /// Subscribe a user to one or more security policies.
        /// </summary>
        public async Task SubscribeAsync(User user, IUserSecurityPolicySubscription subscription)
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }
            if (subscription == null)
            {
                throw new ArgumentNullException(nameof(subscription));
            }

            if (IsSubscribed(user, subscription))
            {
                Diagnostics.Information($"User '{user.Username}' is already subscribed to '{subscription.SubscriptionName}'.");
            }
            else
            {
                foreach (var policy in subscription.Policies)
                {
                    user.SecurityPolicies.Add(new UserSecurityPolicy(policy));
                }

                await subscription.OnSubscribeAsync(new UserSecurityPolicySubscriptionContext(this, user));

                await Auditing.SaveAuditRecordAsync(
                    new UserAuditRecord(user, AuditedUserAction.SubscribeToPolicies, subscription.Policies));

                await EntitiesContext.SaveChangesAsync();

                Diagnostics.Information($"User '{user.Username}' is now subscribed to '{subscription.SubscriptionName}'.");
            }
        }
コード例 #18
0
        /// <summary>
        /// Look up and evaluation of security policies for the specified action.
        /// </summary>
        public async Task <SecurityPolicyResult> EvaluateAsync(SecurityPolicyAction action, HttpContextBase httpContext)
        {
            if (httpContext == null)
            {
                throw new ArgumentNullException(nameof(httpContext));
            }

            var user = httpContext.GetCurrentUser();

            foreach (var handler in UserHandlers.Where(h => h.Action == action))
            {
                var foundPolicies = user.SecurityPolicies.Where(p => p.Name.Equals(handler.Name, StringComparison.OrdinalIgnoreCase));
                if (foundPolicies.Any())
                {
                    var result = handler.Evaluate(new UserSecurityPolicyEvaluationContext(httpContext, foundPolicies));

                    await Auditing.SaveAuditRecordAsync(new UserSecurityPolicyAuditRecord(
                                                            user.Username, GetAuditAction(action), foundPolicies, result.Success, result.ErrorMessage));

                    if (!result.Success)
                    {
                        Diagnostics.Information(
                            $"Security policy '{handler.Name}' failed for user '{user.Username}' with error '{result.ErrorMessage}'.");

                        return(result);
                    }
                }
            }

            return(SecurityPolicyResult.SuccessResult);
        }
コード例 #19
0
        private async Task MigrateCredentials(User user, List <Credential> creds, string password)
        {
            var toRemove = creds.Where(c =>
                                       !String.Equals(
                                           c.Type,
                                           CredentialTypes.Password.Pbkdf2,
                                           StringComparison.OrdinalIgnoreCase))
                           .ToList();

            // Remove any non PBKDF2 credentials
            foreach (var cred in toRemove)
            {
                creds.Remove(cred);
                user.Credentials.Remove(cred);
                Entities.DeleteOnCommit(cred);
            }
            await Auditing.SaveAuditRecord(new UserAuditRecord(user, UserAuditAction.RemovedCredential, toRemove));

            // Now add one if there are no credentials left
            if (creds.Count == 0)
            {
                var newCred = CredentialBuilder.CreatePbkdf2Password(password);
                await Auditing.SaveAuditRecord(new UserAuditRecord(user, UserAuditAction.AddedCredential, newCred));

                user.Credentials.Add(newCred);
            }

            // Save changes, if any
            Entities.SaveChanges();
        }
コード例 #20
0
        private async Task MigrateCredentials(User user, List <Credential> creds, string password)
        {
            var toRemove = creds.Where(c =>
                                       !string.Equals(
                                           c.Type,
                                           CredentialBuilder.LatestPasswordType,
                                           StringComparison.OrdinalIgnoreCase))
                           .ToList();

            // Remove any non latest credentials
            foreach (var cred in toRemove)
            {
                creds.Remove(cred);
                user.Credentials.Remove(cred);
                Entities.DeleteOnCommit(cred);
            }
            await Auditing.SaveAuditRecordAsync(new UserAuditRecord(user, AuditedUserAction.RemoveCredential, toRemove));

            // Now add one if there are no credentials left
            if (creds.Count == 0)
            {
                var newCred = _credentialBuilder.CreatePasswordCredential(password);
                await Auditing.SaveAuditRecordAsync(new UserAuditRecord(user, AuditedUserAction.AddCredential, newCred));

                user.Credentials.Add(newCred);
            }

            // Save changes, if any
            await Entities.SaveChangesAsync();
        }
コード例 #21
0
        private async Task ReplaceCredentialInternal(User user, Credential credential)
        {
            // Find the credentials we're replacing, if any
            var toRemove = user.Credentials
                           .Where(cred =>
                                  // If we're replacing a password credential, remove ALL password credentials
                                  (credential.Type.StartsWith(CredentialTypes.Password.Prefix, StringComparison.OrdinalIgnoreCase) &&
                                   cred.Type.StartsWith(CredentialTypes.Password.Prefix, StringComparison.OrdinalIgnoreCase)) ||
                                  cred.Type == credential.Type)
                           .ToList();

            foreach (var cred in toRemove)
            {
                user.Credentials.Remove(cred);
                Entities.DeleteOnCommit(cred);
            }

            if (toRemove.Any())
            {
                await Auditing.SaveAuditRecord(new UserAuditRecord(
                                                   user, UserAuditAction.RemovedCredential, toRemove));
            }

            user.Credentials.Add(credential);

            await Auditing.SaveAuditRecord(new UserAuditRecord(
                                               user, UserAuditAction.AddedCredential, credential));
        }
コード例 #22
0
        internal async Task RemoveSiteDefinitionAsync()
        {
            SiteDefinition site = Manager.CurrentSite;

            if (site.IsDefaultSite)
            {
                throw new Error(this.__ResStr("cantDeleteDefault", "The default site of a YetaWF instance cannot be removed"));
            }

            using (await lockObject.LockAsync()) { // protect SiteCache locally
                // remove all saved data
                SiteCache.Remove(site.SiteDomain.ToLower());
                if (!string.IsNullOrWhiteSpace(site.StaticDomain))
                {
                    StaticSiteCache.Remove(site.StaticDomain.ToLower());
                }
                if (!string.IsNullOrWhiteSpace(site.SiteTestDomain))
                {
                    TestSiteCache.Remove(site.SiteTestDomain.ToLower());
                }

                await Package.RemoveSiteDataAsync(Manager.SiteFolder);

                await DataProvider.RemoveAsync(site.SiteDomain);// remove domain
            }
            await Auditing.AddAuditAsync($"{nameof(SiteDefinitionDataProvider)}.{nameof(SaveSiteDefinitionAsync)}", site.SiteDomain, Guid.Empty,
                                         "Remove Site",
                                         DataBefore : site,
                                         DataAfter : null,
                                         ExpensiveMultiInstance : true
                                         );
        }
コード例 #23
0
        private async Task <SecurityPolicyResult> EvaluateInternalAsync(IEnumerable <UserSecurityPolicy> policies, HttpContextBase httpContext, SecurityPolicyAction action, bool auditSuccess)
        {
            var relevantHandlers = UserHandlers.Where(h => h.Action == action).ToList();

            foreach (var handler in relevantHandlers)
            {
                var foundPolicies = policies.Where(p => p.Name.Equals(handler.Name, StringComparison.OrdinalIgnoreCase)).ToList();

                if (foundPolicies.Any())
                {
                    var user   = httpContext.GetCurrentUser();
                    var result = handler.Evaluate(new UserSecurityPolicyEvaluationContext(httpContext, foundPolicies));

                    if (auditSuccess || !result.Success)
                    {
                        await Auditing.SaveAuditRecordAsync(new UserSecurityPolicyAuditRecord(
                                                                user.Username, GetAuditAction(action), foundPolicies, result.Success, result.ErrorMessage));
                    }

                    if (!result.Success)
                    {
                        Diagnostics.Information(
                            $"Security policy from subscription '{foundPolicies.First().Subscription}' - '{handler.Name}' failed for user '{user.Username}' with error '{result.ErrorMessage}'.");

                        return(result);
                    }
                }
            }

            return(SecurityPolicyResult.SuccessResult);
        }
コード例 #24
0
        public async Task <bool> RemoveItemAsync(string role)
        {
            if (role == Globals.Role_Superuser)
            {
                throw new Error(this.__ResStr("cantRemoveSuper", "Can't remove built-in superuser role"));
            }
            if (IsPredefinedRole(role))
            {
                throw new Error(this.__ResStr("cantRemoveUser", "The {0} role can't be removed", role));
            }
            if (YetaWF.Core.Support.Startup.MultiInstance)
            {
                throw new InternalError("Removing roles is not possible when distributed caching is enabled");
            }
            RoleDefinition origRole = Auditing.Active ? await GetItemAsync(role) : null;

            if (!await DataProvider.RemoveAsync(role))
            {
                return(false);
            }
            GetAllUserRoles(true);
            await Auditing.AddAuditAsync($"{nameof(RoleDefinitionDataProvider)}.{nameof(RemoveItemAsync)}", role, Guid.Empty,
                                         "Remove Role",
                                         DataBefore : origRole,
                                         DataAfter : null,
                                         ExpensiveMultiInstance : true
                                         );

            return(true);
        }
コード例 #25
0
        public async Task <bool> ConfirmEmailAddress(User user, string token)
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }

            if (String.IsNullOrEmpty(token))
            {
                throw new ArgumentNullException(nameof(token));
            }

            if (user.EmailConfirmationToken != token)
            {
                return(false);
            }

            var conflictingUsers = FindAllByEmailAddress(user.UnconfirmedEmailAddress);

            if (conflictingUsers.AnySafe(u => u.Key != user.Key))
            {
                throw new EntityException(Strings.EmailAddressBeingUsed, user.UnconfirmedEmailAddress);
            }

            await Auditing.SaveAuditRecordAsync(new UserAuditRecord(user, AuditedUserAction.ConfirmEmail, user.UnconfirmedEmailAddress));

            user.ConfirmEmailAddress();

            await UserRepository.CommitChangesAsync();

            return(true);
        }
コード例 #26
0
        public async Task <bool> RemoveItemByIdentityAsync(int id)
        {
            VoiceMailData origData = Auditing.Active ? await GetItemByIdentityAsync(id) : null;

            if (!await DataProvider.RemoveByIdentityAsync(id))
            {
                return(false);
            }

            await SetupClient();

            try {
                if (YetaWFManager.IsSync())
                {
                    RecordingResource.Delete(pathSid: origData.RecordingSid);
                }
                else
                {
                    await RecordingResource.DeleteAsync(pathSid : origData.RecordingSid);
                }
            } catch (Exception) { }

            await Auditing.AddAuditAsync($"{nameof(VoiceMailDataProvider)}.{nameof(RemoveItemByIdentityAsync)}", Dataset, Guid.Empty,
                                         $"Remove Voice Mail Entry {id}",
                                         DataBefore : origData,
                                         DataAfter : null
                                         );

            return(true);
        }
コード例 #27
0
        public virtual async Task RemoveCredential(User user, Credential cred)
        {
            await Auditing.SaveAuditRecord(new UserAuditRecord(user, UserAuditAction.RemovedCredential, cred));

            user.Credentials.Remove(cred);
            Entities.Credentials.Remove(cred);
            Entities.SaveChanges();
        }
コード例 #28
0
 public EntityServiceBase(Auditing auditing, ILoggerFactory loggerFactory) : base(loggerFactory)
 {
     if (auditing == null)
     {
         throw new Exception("Service Base requires a non-null auditing class.");
     }
     Auditing = auditing;
 }
コード例 #29
0
        private async Task <AuthenticatedUser> AuthenticateInternal(Func <Credential, Credential> matchCredential, Credential credential)
        {
            if (credential.Type.StartsWith(CredentialTypes.Password.Prefix, StringComparison.OrdinalIgnoreCase))
            {
                // Password credentials cannot be used this way.
                throw new ArgumentException(Strings.PasswordCredentialsCannotBeUsedHere, nameof(credential));
            }

            using (_trace.Activity("Authenticate Credential: " + credential.Type))
            {
                var matched = matchCredential(credential);

                if (matched == null)
                {
                    _trace.Information("No user matches credential of type: " + credential.Type);

                    await Auditing.SaveAuditRecordAsync(
                        new FailedAuthenticatedOperationAuditRecord(null, AuditedAuthenticatedOperationAction.FailedLoginNoSuchUser, attemptedCredential : credential));

                    return(null);
                }

                if (matched.HasExpired)
                {
                    _trace.Verbose("Credential of type '" + matched.Type + "' for user '" + matched.User.Username + "' has expired on " + matched.Expires.Value.ToString("O", CultureInfo.InvariantCulture));

                    return(null);
                }

                if (matched.Type == CredentialTypes.ApiKey.V1 &&
                    !matched.HasBeenUsedInLastDays(_config.ExpirationInDaysForApiKeyV1))
                {
                    // API key credential was last used a long, long time ago - expire it
                    await Auditing.SaveAuditRecordAsync(
                        new UserAuditRecord(matched.User, AuditedUserAction.ExpireCredential, matched));

                    matched.Expires = _dateTimeProvider.UtcNow;
                    await Entities.SaveChangesAsync();

                    _trace.Verbose(
                        "Credential of type '" + matched.Type
                        + "' for user '" + matched.User.Username
                        + "' was last used on " + matched.LastUsed.Value.ToString("O", CultureInfo.InvariantCulture)
                        + " and has now expired.");

                    return(null);
                }

                // update last used timestamp
                matched.LastUsed = _dateTimeProvider.UtcNow;
                await Entities.SaveChangesAsync();

                _trace.Verbose("Successfully authenticated '" + matched.User.Username + "' with '" + matched.Type + "' credential");

                return(new AuthenticatedUser(matched.User, matched));
            }
        }
コード例 #30
0
        public virtual async Task ChangeMultiFactorAuthentication(User user, bool enableMultiFactor)
        {
            await Auditing.SaveAuditRecordAsync(new UserAuditRecord(user, enableMultiFactor ? AuditedUserAction.EnabledMultiFactorAuthentication : AuditedUserAction.DisabledMultiFactorAuthentication));

            user.EnableMultiFactorAuthentication = enableMultiFactor;
            await UserRepository.CommitChangesAsync();

            TelemetryService.TrackUserChangedMultiFactorAuthentication(user, enableMultiFactor);
        }