public IEnumerable <ValidationResult> Validate(ValidationContext validationContext) { var validator = new RoleValidator(); var result = validator.Validate(this); return(result.Errors.Select(item => new ValidationResult(item.ErrorMessage, new[] { item.PropertyName }))); }
/// <summary> /// Creates a role for the host specified in <c>role.HostId</c> or the current host if unspecified. /// </summary> /// <param name="role">The role.</param> /// <returns></returns> /// <exception cref="System.ArgumentException">Global roles must belong to system host.</exception> public override async Task <IdentityResult> CreateAsync(TRole role) { //x Helpers.ThrowIfNull(role != null, "role"); ThrowIfDisposed(); if (role.HostId.Equals(default(TKey))) { role.HostId = this.CurrentHostId; } if (role.IsGlobal && !role.HostId.Equals(this.SystemHostId)) { throw new ArgumentException("Global roles must belong to system host."); } var result = await RoleValidator.ValidateAsync(role).WithCurrentCulture(); if (!result.Succeeded) { return(result); } await HyperRoleStore.CreateAsync(role).WithCurrentCulture(); return(IdentityResult.Success); }
public void Should_Have_Error_When_Permissions_Is_Not_Unique() { //Arrange var unitOfWork = _serviceProvider.GetService <IUnitOfWork>(); var validator = new RoleValidator(unitOfWork, _localizer); var model = new RoleModel { Name = "Role1", Permissions = new List <PermissionModel> { new PermissionModel { Name = "Permission1" }, new PermissionModel { Name = "Permission1" } } }; //Act var result = validator.Validate(model); //Assert result.Errors.ShouldContain(x => x.ErrorMessage == "Role.Fields.Permissions.Unique"); }
public void RoleValidator_ValidateRole_ReturnsInvalidIfModelNotValid(string grain, string securableItem, string roleName, int errorCount) { var existingRole = new Role { Grain = "app", SecurableItem = "patientsafety", Name = "admin" }; var mockRoleStore = new Mock <IRoleStore>() .SetupGetRoles(new List <Role> { existingRole }).Create(); var mockPermissionStore = new Mock <IPermissionStore>().Create(); var roleValidator = new RoleValidator(new RoleService(mockRoleStore, mockPermissionStore)); var validationResult = roleValidator.Validate(new Role { Grain = grain, SecurableItem = securableItem, Name = roleName }); Assert.False(validationResult.IsValid); Assert.NotNull(validationResult.Errors); Assert.Equal(errorCount, validationResult.Errors.Count); }
public void RoleValidator_ValidateRole_UniqueCheckIgnoresDeleted() { var grain = "app"; var securableItem = "patientsafety"; var name = "admin"; var existingRole = new Role { Grain = grain, SecurableItem = securableItem, Name = name, IsDeleted = true }; var mockRoleStore = new Mock <IRoleStore>() .SetupGetRoles(new List <Role> { existingRole }).Create(); var mockPermissionStore = new Mock <IPermissionStore>().Create(); var roleValidator = new RoleValidator(new RoleService(mockRoleStore, mockPermissionStore)); var validationResult = roleValidator.Validate(new Role { Grain = grain, SecurableItem = securableItem, Name = name }); Assert.True(validationResult.IsValid); }
public void Should_Not_Have_Error_When_Name_Is_Unique() { //Arrange _serviceProvider.RunScoped <IUnitOfWork>(uow => { uow.Set <Role>().Add(new Role { Name = "ExistingName" }); uow.SaveChanges(); }); var unitOfWork = _serviceProvider.GetService <IUnitOfWork>(); var validator = new RoleValidator(unitOfWork, _localizer); var model = new RoleModel { Name = "NewName" }; //Act var result = validator.Validate(model); //Assert result.Errors.ShouldNotContain(x => x.ErrorMessage == "Role.Fields.Name.Unique"); }
public RolesModule(RoleService roleService, ClientService clientService, RoleValidator validator, ILogger logger) : base("/v1/roles", logger, validator) { _roleService = roleService ?? throw new ArgumentNullException(nameof(roleService)); _clientService = clientService ?? throw new ArgumentNullException(nameof(clientService)); Get("/{grain}/{securableItem}", async parameters => await this.GetRolesForSecurableItem(parameters).ConfigureAwait(false), null, "GetRolesBySecurableItem"); Get("/{grain}/{securableItem}/{roleName}", async parameters => await this.GetRoleByName(parameters).ConfigureAwait(false), null, "GetRoleByName"); Post("/", async parameters => await AddRole().ConfigureAwait(false), null, "AddRole"); Delete("/{roleId}", async parameters => await this.DeleteRole(parameters).ConfigureAwait(false), null, "DeleteRole"); Post("/{roleId}/permissions", async parameters => await this.AddPermissionsToRole(parameters).ConfigureAwait(false), null, "AddPermissionsToRole"); Delete("/{roleId}/permissions", async parameters => await this.DeletePermissionsFromRole(parameters).ConfigureAwait(false), null, "DeletePermissionsFromRole"); }
public RoleUpdateHandler(GlobalSolusindoDb db, tblM_User user, RoleValidator roleValidator, RoleFactory roleFactory, RoleQuery roleQuery, AccessControl accessControl) : base(db, user) { this.roleValidator = roleValidator; this.roleFactory = roleFactory; this.roleQuery = roleQuery; this.roleEntryDataProvider = new RoleEntryDataProvider(db, user, accessControl, roleQuery); }
public RoleController(ILoggerFactory loggerFactory, IRoleAppService appService, RoleValidator validator, IConfigurationRoot configuration) { this.logger = loggerFactory.CreateLogger <AccountController>(); this.appService = appService; this.validator = validator; this.configuration = configuration; }
public void Should_Not_Have_Error_When_Name_Is_Unique() { //Arrange _serviceProvider.RunScoped <IDbContext>(context => { context.Set <Role>().Add(new Role { Name = "ExistingName" }); context.SaveChanges(); }); var dbContext = _serviceProvider.GetService <IDbContext>(); var validator = new RoleValidator(dbContext, _translation); var model = new RoleModel { Name = "NewName" }; //Act var result = validator.Validate(model); //Assert result.Errors.ShouldNotContain(x => x.ErrorMessage == "Role.Fields.Name.Unique"); }
public void Should_Not_Have_Error_When_Permissions_Is_Not_Unique_But_Exists_In_Deleted_Permissions() { //Arrange var dbContext = _serviceProvider.GetService <IDbContext>(); var validator = new RoleValidator(dbContext, _translation); var model = new RoleModel { Name = "Role1", Permissions = new List <PermissionModel> { new PermissionModel { Id = 1, Name = "Permission1" }, new PermissionModel { Id = 2, Name = "Permission1", TrackingState = TrackingState.Deleted } } }; //Act var result = validator.Validate(model); //Assert result.Errors.ShouldNotContain(x => x.ErrorMessage == "Role.Fields.Permissions.Unique"); }
/// <summary> /// Update an existing role. /// </summary> /// <param name="role">The role.</param> /// <returns></returns> /// <exception cref="System.ArgumentException">Roles cannot be assigned a new hostId.</exception> /// <exception cref="System.ArgumentException">Roles cannot be assigned a new hostId.</exception> public override async Task <IdentityResult> UpdateAsync(TRole role) { //x Helpers.ThrowIfNull(role != null, "role"); ThrowIfDisposed(); var existing = await FindByIdAsync(role.Id); if (existing != null && !role.HostId.Equals(existing.HostId)) { throw new ArgumentException("Roles cannot be assigned a new hostId."); } if (role.IsGlobal && !role.HostId.Equals(this.SystemHostId)) { throw new ArgumentException("Global roles must belong to system host."); } var result = await RoleValidator.ValidateAsync(role).WithCurrentCulture(); if (!result.Succeeded) { return(result); } await HyperRoleStore.UpdateAsync(role).WithCurrentCulture(); return(IdentityResult.Success); }
public override void OnActionExecuting(ActionExecutingContext context) { InitializeServices(context); if (!RoleValidator.ValidatePermissions(context.HttpContext.User, Roles)) { context.Result = new UnauthorizedResult(); } }
public RoleValidatorTests() { context = new TestingContext(); validator = new RoleValidator(new UnitOfWork(context)); context.Add(role = ObjectsFactory.CreateRole()); context.SaveChanges(); }
public void SetUp() { context = new TestingContext(); validator = new RoleValidator(new UnitOfWork(context)); validator.ModelState = new ModelStateDictionary(); TearDownData(); SetUpData(); }
public RoleValidatorTests() { context = new TestingContext(); validator = new RoleValidator(new UnitOfWork(context)); context.DropData(); role = ObjectFactory.CreateRole(); context.Set <Role>().Add(role); context.SaveChanges(); }
/// <summary> ///异步验证 /// </summary> public static async Task DoValidationAsync(IRoleRespository roleRespository, Role role, string validatorType) { var roleValidator = new RoleValidator(roleRespository); var validatorReresult = await roleValidator.DoValidateAsync(role, validatorType); if (!validatorReresult.IsValid) { throw new DomainException(validatorReresult); } }
public async Task ValidateThrowsWithNull() { // Setup var validator = new RoleValidator<TestRole>(); var manager = MockHelpers.TestRoleManager<TestRole>(); // Act // Assert await Assert.ThrowsAsync<ArgumentNullException>("manager", async () => await validator.ValidateAsync(null, null)); await Assert.ThrowsAsync<ArgumentNullException>("role", async () => await validator.ValidateAsync(manager, null)); }
private static void RegisterRoleManager(IWindsorContainer container, string connectionString) { var dbContext = GetDbContext(connectionString); IRoleStore <ApplicationRole> roleStore = new RoleStore <ApplicationRole, ApplicationDbContext, Guid>(dbContext); var roleValidator = new RoleValidator <ApplicationRole>(); var roleValidators = new IRoleValidator <ApplicationRole>[] { roleValidator }; var roleManager = new RoleManager <ApplicationRole>(roleStore, roleValidators, null, null, null); container.Register(Component.For <RoleManager <ApplicationRole> >().Instance(roleManager)); }
public static void Initialize(TestContext testContext) { ApplicationUserValidator = new ApplicationUserValidator(); FollowerValidator = new FollowerValidator(); CredentialValidator = new CredentialValidator(); CredentialTypeValidator = new CredentialTypeValidator(); RoleValidator = new RoleValidator(); UserRoleValidator = new UserRoleValidator(); RolePermissionValidator = new RolePermissionValidator(); PermissionValidator = new PermissionValidator(); }
public async Task ValidateThrowsWithNull() { // Setup var validator = new RoleValidator <PocoRole>(); var manager = MockHelpers.TestRoleManager <PocoRole>(); // Act // Assert await Assert.ThrowsAsync <ArgumentNullException>("manager", async() => await validator.ValidateAsync(null, null)); await Assert.ThrowsAsync <ArgumentNullException>("role", async() => await validator.ValidateAsync(manager, null)); }
public static void Initialize(TestContext testContext) { ApplicationUserValidator = new ApplicationUserValidator(); FollowerValidator = new FollowerValidator(); CredentialValidator = new CredentialValidator(); CredentialTypeValidator = new CredentialTypeValidator(); RoleValidator = new RoleValidator(); UserRoleValidator = new UserRoleValidator(); RolePermissionValidator = new RolePermissionValidator(); PermissionValidator = new PermissionValidator(); Hasher = new Pbkdf2Hasher(); SaltGenerator = new RandomSaltGenerator(); }
public async Task ValidateFailsWithTooShortRoleName(string input) { // Setup var validator = new RoleValidator<TestRole>(); var manager = new RoleManager<TestRole>(new NoopRoleStore(), validator); var user = new TestRole {Name = input}; // Act var result = await validator.ValidateAsync(manager, user); // Assert IdentityResultAssert.IsFailure(result, "Name cannot be null or empty."); }
public async Task ValidateFailsWithTooShortRoleName(string input) { // Setup var validator = new RoleValidator<TestRole>(); var manager = MockHelpers.TestRoleManager<TestRole>(); var user = new TestRole {Name = input}; // Act var result = await validator.ValidateAsync(manager, user); // Assert IdentityResultAssert.IsFailure(result, IdentityErrorDescriber.Default.InvalidRoleName(input)); }
public void RoleValidator_ValidateRole_ReturnsValid() { var mockRoleStore = new Mock <IRoleStore>().SetupGetRoles(new List <Role>()).Create(); var mockPermissionStore = new Mock <IPermissionStore>().Create(); var roleValidator = new RoleValidator(new RoleService(mockRoleStore, mockPermissionStore)); var validationResult = roleValidator.Validate(new Role { Grain = "app", SecurableItem = "patientsafety", Name = "admin" }); Assert.True(validationResult.IsValid); }
public async Task ValidateFailsWithTooShortRoleName(string input) { // Setup var validator = new RoleValidator <PocoRole>(); var manager = MockHelpers.TestRoleManager <PocoRole>(); var user = new PocoRole { Name = input }; // Act var result = await validator.ValidateAsync(manager, user); // Assert IdentityResultAssert.IsFailure(result, new IdentityErrorDescriber().InvalidRoleName(input)); }
public async Task ValidateFailsWithTooShortRoleName(string input) { // Setup var validator = new RoleValidator <TestRole>(); var manager = new RoleManager <TestRole>(new NoopRoleStore(), null); var user = new TestRole { Name = input }; // Act var result = await validator.ValidateAsync(manager, user); // Assert IdentityResultAssert.IsFailure(result, "Name cannot be null or empty."); }
public async Task ValidateFailsWithTooShortRoleName(string input) { // Setup var validator = new RoleValidator <TestRole>(); var manager = new RoleManager <TestRole>(new NoopRoleStore()); var user = new TestRole { Name = input }; // Act var result = await validator.ValidateAsync(manager, user); // Assert IdentityResultAssert.IsFailure(result, IdentityErrorDescriber.Default.InvalidRoleName(input)); }
public void Should_Have_Error_When_Name_Is_Empty() { //Arrange var unitOfWork = _serviceProvider.GetService <IUnitOfWork>(); var validator = new RoleValidator(unitOfWork, _localizer); var model = new RoleModel { Name = null }; //Act var result = validator.Validate(model); //Assert result.Errors.ShouldContain(x => x.ErrorMessage == "Role.Fields.Name.Required"); }
public void Should_Have_Error_When_Name_Is_Empty() { //Arrange var dbContext = _serviceProvider.GetService <IDbContext>(); var validator = new RoleValidator(dbContext, _translation); var model = new RoleModel { Name = null }; //Act var result = validator.Validate(model); //Assert result.Errors.ShouldContain(x => x.ErrorMessage == "Role.Fields.Name.Required"); }
public static void Initialize(TestContext testContext) { MemeValidator = new MemeValidator(); ApplicationUserValidator = new ApplicationUserValidator(); FollowerValidator = new FollowerValidator(); CredentialValidator = new CredentialValidator(); CredentialTypeValidator = new CredentialTypeValidator(); RoleValidator = new RoleValidator(); UserRoleValidator = new UserRoleValidator(); RolePermissionValidator = new RolePermissionValidator(); PermissionValidator = new PermissionValidator(); MemeFetcherService = new LocalMemeFetcherService(); SharedMemeValidator = new SharedMemeValidator(); CommentValidator = new CommentValidator(); Hasher = new Pbkdf2Hasher(); SaltGenerator = new RandomSaltGenerator(); }
public void Should_Have_Error_When_Name_Length_More_Than_Maximum() { //Arrange var dbContext = _serviceProvider.GetService <IDbContext>(); var validator = new RoleValidator(dbContext, _translation); var model = new RoleModel { Name = new string('A', 51) }; //Act var result = validator.Validate(model); //Assert result.Errors.ShouldContain(x => x.ErrorMessage == "Role.Fields.Name.MaximumLength"); }
public void Should_Have_Error_When_Name_Length_More_Than_Maximum() { //Arrange var unitOfWork = _serviceProvider.GetService <IUnitOfWork>(); var validator = new RoleValidator(unitOfWork, _localizer); var model = new RoleModel { Name = new string('A', 51) }; //Act var result = validator.Validate(model); //Assert result.Errors.ShouldContain(x => x.ErrorMessage == "Role.Fields.Name.MaximumLength"); }
public RoleModule(ISiteService _siteService, IRoleService _roleService) : base("/role") { RoleValidator roleValidator = new RoleValidator(); Get["/list"] = x => { ViewBag.SiteId = Request.Query.siteId; ViewBag.SiteList = _siteService.GetAllSite(); if (!String.IsNullOrEmpty(Request.Query.siteId)) { return View["Role/List", _roleService.GetAllBySiteId(new Guid(Request.Query.siteId))]; } else { return View["Role/List",new List<Role>()]; } }; Get["/add"] = x => { ViewBag.SiteId = Request.Query.siteId; ViewBag.SiteList = _siteService.GetAllSite(); return View["Role/Add", new Role()]; }; Post["/add"] = x => { ViewBag.SiteId = Request.Query.siteId; ViewBag.SiteList = _siteService.GetAllSite(); ViewBag.Errored = true; var role = this.Bind<Role>(); ValidationResult results = roleValidator.Validate(role); if (!results.IsValid) { ViewBag.ErrorMsg = HtmlUtils.GetCharisma_Alert(Charisma_AlertType.error, "错误信息", results.Errors); } else if (_roleService.CreateRole(role)) { ViewBag.ErrorMsg = HtmlUtils.GetCharisma_Alert(Charisma_AlertType.success, "成功信息", "添加成功"); } else { ViewBag.ErrorMsg = HtmlUtils.GetCharisma_Alert(Charisma_AlertType.error, "错误信息", "未知错误,请联系管理员"); } return View["Role/Add", role]; }; Get["/edit/{id}"] = x => { ViewBag.SiteList = _siteService.GetAllSite(); var model = _roleService.GetByAutoId(x.id); return View["Role/Edit", model]; }; Post["/edit/{id}"] = x => { ViewBag.SiteList = _siteService.GetAllSite(); ViewBag.Errored = true; var role = this.Bind<Role>(); ValidationResult results = roleValidator.Validate(role); if (!results.IsValid) { ViewBag.ErrorMsg = HtmlUtils.GetCharisma_Alert(Charisma_AlertType.error, "错误信息", results.Errors); } else if (_roleService.ModifyRole(role)) { ViewBag.ErrorMsg = HtmlUtils.GetCharisma_Alert(Charisma_AlertType.success, "成功信息", "修改成功"); } else { ViewBag.ErrorMsg = HtmlUtils.GetCharisma_Alert(Charisma_AlertType.error, "错误信息", "未知错误,请联系管理员"); } return View["Role/Edit", role]; }; Get["/delete/{id}"] = x => { var model = _roleService.GetByAutoId((int)x.id); _roleService.DeleteRole(model.ID); return Response.AsRedirect("/role/list?siteId=" + model.ID.ToString()); }; Post["/delete"] = x => { var result = new NotyResult(); Guid[] ids; try { ids = RequestResultUtil.GetIdsByGuid(Request.Form.id); } catch { Guid strongid = new Guid(Request.Form.id); ids = new Guid[1]; ids[0] = strongid; } var list = (ids ?? new Guid[0]); if (list.Length == 0) { result.code = NotyType.warning.ToString(); result.msg = "你没有选择!"; } else if (_roleService.DeleteByIds(ids)) { result.code = NotyType.success.ToString(); result.msg = "删除成功!"; } else { result.code = NotyType.error.ToString(); result.msg = "删除失败!请联系管理员!"; } return this.Response.AsJson<NotyResult>(result); }; Get["/vieworder"] = x => { var id = new Guid(Request.Query.siteId); return View["Role/ViewOrder", _roleService.GetAllBySiteId(id)]; }; Post["/saveorder"] = x => { var result = new NotyResult(); Guid[] ids = RequestResultUtil.GetIdsByGuid(Request.Form.ids); var list = (ids ?? new Guid[0]); if (list.Length == 0) { result.code = NotyType.warning.ToString(); result.msg = "你没有选择!"; } else if (_roleService.SetOrderByIds(ids)) { result.code = NotyType.success.ToString(); result.msg = "排序成功"; } else { result.code = NotyType.error.ToString(); result.msg = "排序失败!请联系管理员!"; } return this.Response.AsJson<NotyResult>(result); }; }