public List <ListUsersDto> ListUserWithRolesAndDataTenant()
        {
            var result = new List <ListUsersDto>();

            foreach (var user in _userManager.Users)
            {
                var    userRoleNames = _extraContext.UserToRoles.Where(x => x.UserId == user.Id).Select(x => x.RoleName);
                var    dataEntry     = _extraContext.Find <UserDataHierarchical>(user.Id);
                string tenantName    = "no linked tenant";
                string companyName   = null;
                if (dataEntry != null)
                {
                    var linkedTenant = _extraContext.Find <TenantBase>(dataEntry.LinkedTenantId);
                    tenantName = linkedTenant?.Name ?? "tenant not found";
                    if (linkedTenant != null)
                    {
                        companyName = _extraContext.Find <TenantBase>(linkedTenant.ExtractCompanyId())?.Name;
                    }
                }

                result.Add(new ListUsersDto(user.Id, user.UserName, string.Join(", ", userRoleNames), companyName, tenantName));
            }

            return(result);
        }
        public static IStatusGeneric <UserToRole> AddRoleToUser(string userId, string roleName, ExtraAuthorizeDbContext context)
        {
            if (userId == null)
            {
                throw new ArgumentNullException(nameof(userId));
            }
            if (roleName == null)
            {
                throw new ArgumentNullException(nameof(roleName));
            }

            var status = new StatusGenericHandler <UserToRole>();

            if (context.Find <UserToRole>(userId, roleName) != null)
            {
                status.AddError($"The user already has the Role '{roleName}'.");
                return(status);
            }
            var roleToAdd = context.Find <RoleToPermissions>(roleName);

            if (roleToAdd == null)
            {
                status.AddError($"I could not find the Role '{roleName}'.");
                return(status);
            }

            return(status.SetResult(new UserToRole(userId, roleToAdd)));
        }
Пример #3
0
        /// <summary>
        /// This will update a role
        /// </summary>
        /// <param name="roleName"></param>
        /// <param name="description"></param>
        /// <param name="permissions"></param>
        public void UpdateRole(string roleName, string description, ICollection <Permissions> permissions)
        {
            var existingRole = _context.Find <RoleToPermissions>(roleName);

            if (existingRole == null)
            {
                throw new KeyNotFoundException($"Could not find the role {roleName} to update.");
            }
            existingRole.Update(description, permissions);
        }
        public void CheckAddDataAccessHierarchical(string userId, TenantBase linkedTenant)
        {
            if (linkedTenant == null)
            {
                throw new ArgumentNullException(nameof(linkedTenant));
            }

            if (_context.Find <UserDataHierarchical>(userId) == null)
            {
                var dataAccess = new UserDataHierarchical(userId, linkedTenant);
                _context.Add(dataAccess);
            }
        }
Пример #5
0
        public IStatusGeneric DeleteRole(string roleName, bool removeFromUsers,
                                         ExtraAuthorizeDbContext context)
        {
            var status = new StatusGenericHandler {
                Message = "Deleted role successfully."
            };
            var roleToUpdate = context.Find <RoleToPermissions>(roleName);

            if (roleToUpdate == null)
            {
                return(status.AddError("That role doesn't exists"));
            }

            var usersWithRoles = context.UserToRoles.Where(x => x.RoleName == roleName).ToList();

            if (usersWithRoles.Any())
            {
                if (!removeFromUsers)
                {
                    return(status.AddError($"That role is used by {usersWithRoles.Count} and you didn't ask for them to be updated."));
                }

                context.RemoveRange(usersWithRoles);
                status.Message = $"Removed role from {usersWithRoles.Count} user and then deleted role successfully.";
            }

            context.Remove(roleToUpdate);
            return(status);
        }
Пример #6
0
        public void TestUpdatePermissionsInRole()
        {
            //SETUP
            var options = SqliteInMemory.CreateOptions <ExtraAuthorizeDbContext>();

            using (var context = new ExtraAuthorizeDbContext(options, null))
            {
                context.Database.EnsureCreated();

                var createStatus = RoleToPermissions.CreateRoleWithPermissions(
                    "test", "test", new List <Permissions> {
                    Permissions.StockRead
                }, context);
                createStatus.IsValid.ShouldBeTrue(createStatus.GetAllErrors());
                context.Add(createStatus.Result);
                context.SaveChanges();

                //ATTEMPT
                var roleToUpdate = context.Find <RoleToPermissions>("test");
                roleToUpdate.UpdatePermissionsInRole(new List <Permissions> {
                    Permissions.StockAddNew, Permissions.StockRemove
                });
                context.SaveChanges();
            }
            using (var context = new ExtraAuthorizeDbContext(options, null))
            {
                //VERIFY
                context.RolesToPermissions.Single().PermissionsInRole
                .ShouldEqual(new List <Permissions> {
                    Permissions.StockAddNew, Permissions.StockRemove
                });
            }
        }
Пример #7
0
        public void TestDeleteRole()
        {
            //SETUP
            var fakeAuthChanges = new FakeAuthChanges();
            var options         = SqliteInMemory.CreateOptions <ExtraAuthorizeDbContext>();

            using (var context = new ExtraAuthorizeDbContext(options, fakeAuthChanges))
            {
                context.Database.EnsureCreated();
                var createStatus = RoleToPermissions.CreateRoleWithPermissions(
                    "test", "test", new List <Permissions> {
                    Permissions.StockRead
                }, context);
                createStatus.IsValid.ShouldBeTrue(createStatus.GetAllErrors());
                context.Add(createStatus.Result);
                context.SaveChanges();

                //ATTEMPT
                var roleToDelete = context.Find <RoleToPermissions>("test");
                context.Remove(roleToDelete);
                context.SaveChanges();

                //VERIFY
                context.RolesToPermissions.Any().ShouldBeFalse();
            }
        }
Пример #8
0
        /// <summary>
        /// This toggles whether the <see cref="Permissions.Cache2"/> permission is in the <see cref="CacheRoleName"/>.
        /// This causes the <see cref="ExtraAuthorizeDbContext"/> to update the TimeStore with the time this change happens.
        /// Then the <see cref="CodeCalledInStartup.AuthCookieValidate"/> will compare the users lastUpdated time which will
        /// cause a recalc of the logged-in user's permission claim.
        /// </summary>
        public void ToggleCacheRole()
        {
            var hasCache2Permission = _context.Find <RoleToPermissions>(CacheRoleName)
                                      .PermissionsInRole.Any(x => x == Permissions.Cache2);
            var updatedPermissions = new List <Permissions> {
                Permissions.Cache1
            };

            if (!hasCache2Permission)
            {
                updatedPermissions.Add(Permissions.Cache2);
            }

            var authUserHelper = new ExtraAuthUsersSetup(_context);

            authUserHelper.UpdateRole(CacheRoleName, $"Has {updatedPermissions.Count} permissions.", updatedPermissions);
            _context.SaveChanges();
        }
Пример #9
0
        public static IStatusGeneric <RoleToPermissions> CreateRoleWithPermissions(string roleName, string description, ICollection <Permissions> permissionInRole,
                                                                                   ExtraAuthorizeDbContext context)
        {
            var status = new StatusGenericHandler <RoleToPermissions>();

            if (context.Find <RoleToPermissions>(roleName) != null)
            {
                status.AddError("That role already exists");
                return(status);
            }

            return(status.SetResult(new RoleToPermissions(roleName, description, permissionInRole)));
        }