Esempio n. 1
0
            public async Task <RoleDto> Handle(
                Command request,
                CancellationToken cancellationToken)
            {
                if (await _dbContext.Roles.AnyAsync(
                        x => x.Name == request.Name,
                        cancellationToken))
                {
                    throw new HttpException(
                              HttpStatusCode.BadRequest,
                              new
                    {
                        Error = $"There is already a role with name {request.Name}."
                    });
                }

                var role = new Role(
                    request.Name);

                role.AddPermissions(request.Permissions);

                await _dbContext.Roles.AddAsync(
                    role,
                    cancellationToken);

                await _dbContext.SaveChangesAsync(cancellationToken);

                return(new RoleDto(
                           role.Id,
                           role.Name,
                           string.Join(
                               ", ",
                               role.PermissionsInRole)));
            }
Esempio n. 2
0
        public static async Task SeedData(
            ApplicationDbContext context,
            IPasswordHasher passwordHasher)
        {
            if (!context.Users.Any())
            {
                var salt  = Guid.NewGuid().ToByteArray();
                var user1 = new User(
                    "John",
                    "Doe",
                    "*****@*****.**",
                    "john",
                    string.Empty,
                    passwordHasher.Hash(
                        "test",
                        salt),
                    salt,
                    new Address()
                    );

                user1.CustomFields = new[] { new CustomField("Age", "35") };

                await context.Users.AddAsync(user1);

                var role1 = new Role("Base User");
                role1.AddPermissions(new List <Permissions> {
                    Permissions.ReadUsers
                });
                await context.Roles.AddAsync(role1);

                var userRole1 = new UserRole(user1, role1);
                await context.UserRoles.AddAsync(userRole1);

                var user2 = new User(
                    "Jane",
                    "Doe",
                    "*****@*****.**",
                    "jane",
                    string.Empty,
                    passwordHasher.Hash(
                        "test",
                        salt),
                    salt,
                    new Address()
                    );
                await context.Users.AddAsync(user2);

                var role2 = new Role("Super User");
                role2.AddPermissions(new List <Permissions> {
                    Permissions.SuperUser
                });
                await context.Roles.AddAsync(role2);

                var userRole2 = new UserRole(user2, role2);
                await context.UserRoles.AddAsync(userRole2);

                await context.SaveChangesAsync();
            }
        }
Esempio n. 3
0
        private Role SeedSequrity(IDatabaseContext context)
        {
            var existingPermissions = context.Set <Permission>().ToList();
            var existingRoleTypes   = context.Set <RoleType>().ToList();

            foreach (var permission in EnumExtension.ToList <PermissionEnum>())
            {
                if (!existingPermissions.Any(x => x.Id == permission.Value))
                {
                    var permissionEntity = new Permission(permission.Value, 1, permission.Description);
                    context.Attach(permissionEntity).State = EntityState.Added;
                }
            }

            foreach (var roleType in EnumExtension.ToList <RoleTypeEnum>())
            {
                if (!existingRoleTypes.Any(x => x.Id == roleType.Value))
                {
                    var roleTypeEntity = new RoleType(roleType.Value, 1, roleType.Description);
                    context.Attach(roleTypeEntity).State = EntityState.Added;
                }
            }

            var roleEntity = new Role(1, "System administrator", null, (int)RoleTypeEnum.Administrator);

            roleEntity.AddPermissions(new List <int>()
            {
                (int)PermissionEnum.OperationsOnUser,
                (int)PermissionEnum.OperationsOnUserDevice,
                (int)PermissionEnum.OperationsOnUserIdentity,
                (int)PermissionEnum.OperationsOnClient
            }, 1);

            var existingRole = context.Set <Role>().FirstOrDefault(x => x.Name.Equals(roleEntity.Name) && x.RoleTypeId == (int)RoleTypeEnum.Administrator);

            if (existingRole == null)
            {
                context.Attach(roleEntity).State = EntityState.Added;
            }

            context.SaveChanges();

            if (existingRole == null)
            {
                return(roleEntity);
            }
            else
            {
                return(existingRole);
            }
        }
Esempio n. 4
0
        static void Main()
        {
            var storage = new Dictionary <Guid, List <object> >();
            Func <Guid, Tuple <Int32, IEnumerable <object> > > reader = id => {
                List <object> events;
                if (storage.TryGetValue(id, out events))
                {
                    return(new Tuple <int, IEnumerable <object> >(events.Count, events));
                }
                return(null);
            };
            var unitOfWork = new UnitOfWork();

            var roleRepository        = new Repository <Role>(Role.Factory, unitOfWork, reader);
            var roleGroupRepository   = new Repository <RoleGroup>(RoleGroup.Factory, unitOfWork, reader);
            var userAccountRepository = new Repository <UserAccount>(UserAccount.Factory, unitOfWork, reader);

            // Setting up security (accounts, roles and authorization)
            var administratorRoleId = new RoleId(Guid.NewGuid());
            var administratorRole   = new Role(administratorRoleId, new Name("Administrator"));

            administratorRole.AddPermissions(SecurityPermissions.All);
            administratorRole.AllowPermissions(SecurityPermissions.All);
            roleRepository.Add(administratorRole.Id, administratorRole);
            var subRole1Id = new RoleId(Guid.NewGuid());
            var subRole1   = new Role(subRole1Id, new Name("SubRole1"));

            subRole1.AddPermission(SecurityPermissions.AddRole);
            subRole1.DenyPermission(SecurityPermissions.AddRole);
            roleRepository.Add(subRole1.Id, subRole1);
            var subRole2Id = new RoleId(Guid.NewGuid());
            var subRole2   = new Role(subRole2Id, new Name("SubRole2"));

            subRole2.AddPermission(SecurityPermissions.AddRole);
            subRole2.AllowPermission(SecurityPermissions.AddRole);
            roleRepository.Add(subRole2.Id, subRole2);
            var group1Id = new RoleGroupId(Guid.NewGuid());
            var group1   = new RoleGroup(group1Id, new Name("SubRole 1 & 2"));

            group1.AddRole(subRole1);
            group1.AddRole(subRole2);
            roleGroupRepository.Add(group1.Id, group1);

            var administratorId = new UserAccountId(Guid.NewGuid());
            var administrator   = new UserAccount(administratorId, new UserAccountName("Administrator"));

            administrator.GrantRole(administratorRole);
            administrator.GrantRoleGroup(group1);
            userAccountRepository.Add(administrator.Id, administrator);

            // Using security - in domain layer code
            var combinator = new AccessDecisionCombinator();

            administrator.CombineDecisions(combinator, roleRepository, roleGroupRepository);
            var decider = combinator.BuildDecider();

            Console.WriteLine(decider.IsAllowed(SecurityPermissions.AddUserAccount));

            // Using security - in application layer code

            var command = new AddUserAccount(
                new Guid("735A259F-996B-4174-9899-3D40242BF6B1"),
                "Pierke Pol");
            var resolver = new PermissionResolver();
            var service  =
                new UserAccountApplicationService(
                    userAccountRepository,
                    roleRepository,
                    roleGroupRepository);
            var authorizer =
                new MessageAuthorizer(
                    resolver,
                    userAccountRepository,
                    roleRepository,
                    roleGroupRepository);
            var commandHandler = service.Secure <AddUserAccount>(authorizer);

            commandHandler.Handle(new SecurityContext <AddUserAccount>(administratorId, command));

            // Using security - in projection code
            var builder = new SqlConnectionStringBuilder("Data Source=.\\SQLEXPRESS;Initial Catalog=<YourStoreHere>;Integrated Security=SSPI;");

            // What that table could look like ...
            //CREATE TABLE [UserAccountEffectiveRoles](
            //  [UserAccountId] [uniqueidentifier] NOT NULL,
            //  [RoleId] [uniqueidentifier] NULL,
            //  [RoleGroupId] [uniqueidentifier] NULL,
            //  [Id] [int] IDENTITY(1,1) NOT NULL,
            //  CONSTRAINT [PK_UserAccountEffectiveRoles] PRIMARY KEY CLUSTERED ( [Id] ASC )
            //)

            var observer = new SqlStatementObserver();
            // var lookup = new MemoryRoleGroupLookup(new Dictionary<Guid, HashSet<Guid>>());
            var lookupInitializer          = new SqlBasedLookupRolesOfRoleGroupInitializer(builder);
            var lookup                     = lookupInitializer.Initialize();
            var projectionHandler          = new UserAccountEffectiveRolesProjectionHandler(observer, lookup);
            var compositeProjectionHandler = new CompositeHandler(
                new IHandle <object>[] {
                new HandlerAdapter <AddedRoleToRoleGroup>(lookup),
                new HandlerAdapter <RemovedRoleFromRoleGroup>(lookup),
                new HandlerAdapter <DisabledUserAccount>(projectionHandler),
                new HandlerAdapter <RoleGrantedToUserAccount>(projectionHandler),
                new HandlerAdapter <RoleRevokedFromUserAccount>(projectionHandler),
                new HandlerAdapter <RoleGroupGrantedToUserAccount>(projectionHandler),
                new HandlerAdapter <RoleRevokedFromUserAccount>(projectionHandler),
                new HandlerAdapter <AddedRoleToRoleGroup>(projectionHandler),
                new HandlerAdapter <RemovedRoleFromRoleGroup>(projectionHandler)
            });

            foreach (var change in unitOfWork.GetChanges())
            {
                compositeProjectionHandler.Handle(change);
            }

            new BatchedSqlStatementFlusher(
                builder).
            Flush(observer.Statements);

            Console.ReadLine();
        }