Beispiel #1
0
 public void Authorize(UserAccountId account, object message)
 {
     var decider = GetDeciderForMessage(account);
       if (!decider.AreAllAllowed(_resolver.ResolvePermission(message))) {
     throw new SecurityException(string.Format("Yo bro, u do not have permission to do {0}", message.GetType()));
       }
 }
Beispiel #2
0
 IAccessDecider GetDeciderForMessage(UserAccountId account)
 {
     var combinator = new AccessDecisionCombinator();
       var userAccount = _userAccountRepository.Get(account);
       userAccount.CombineDecisions(combinator, _roleRepository, _roleGroupRepository);
       return combinator.BuildDecider();
 }
 public UserAddedToGroup(UserGroupId userGroupId, UserAccountId userAccountId, string userGroupName, string userName)
 {
     UserGroupId   = userGroupId;
     UserAccountId = userAccountId;
     UserGroupName = userGroupName;
     UserName      = userName;
 }
Beispiel #4
0
        IAccessDecider GetDeciderForMessage(UserAccountId account)
        {
            var combinator  = new AccessDecisionCombinator();
            var userAccount = _userAccountRepository.Get(account);

            userAccount.CombineDecisions(combinator, _roleRepository, _roleGroupRepository);
            return(combinator.BuildDecider());
        }
 public AddNewTracker(
     string serialNumber, UserAccountId issuedBy,
     string?brand = null, string?model = null)
 {
     SerialNumber = serialNumber;
     IssuedBy     = issuedBy;
     Brand        = brand;
     Model        = model;
 }
Beispiel #6
0
        public void Authorize(UserAccountId account, object message)
        {
            var decider = GetDeciderForMessage(account);

            if (!decider.AreAllAllowed(_resolver.ResolvePermission(message)))
            {
                throw new SecurityException(string.Format("Yo bro, u do not have permission to do {0}", message.GetType()));
            }
        }
 public UserRoleChanged(TenantId tenantId, UserAccountId userAccountId,
                        UserRoleId oldUserRoleId,
                        UserRoleId newUserRoleId, string newUserRoleName)
 {
     TenantId        = tenantId;
     UserAccountId   = userAccountId;
     OldUserRoleId   = oldUserRoleId;
     NewUserRoleId   = newUserRoleId;
     NewUserRoleName = newUserRoleName;
 }
Beispiel #8
0
        public UserAccountCreatedEvent(UserAccountId id, string userName, EMail email)
        {
            Condition.Requires(id, "id").IsNotNull();
            Condition.Requires(userName, "userName").IsNotNull();
            Condition.Requires(email, "email").IsNotNull();

            Id       = id;
            UserName = userName;
            EMail    = email;
        }
        public UserAccountCreatedEvent(UserAccountId id, string userName, EMail email)
        {
            Condition.Requires(id, "id").IsNotNull();
              Condition.Requires(userName, "userName").IsNotNull();
              Condition.Requires(email, "email").IsNotNull();

              Id = id;
              UserName = userName;
              EMail = email;
        }
        public PasswordChangedEvent(UserAccountId id, byte[] passwordSalt, byte[] passwordHash, string passwordHashingAlgorithm)
        {
            Condition.Requires(id, "id").IsNotNull();

              if ((passwordSalt != null || passwordHash != null) && string.IsNullOrEmpty(passwordHashingAlgorithm))
            throw new InvalidOperationException("Missing passwordHashingAlgorithm");

              Id = id;
              PasswordHash = passwordHash;
              PasswordSalt = passwordSalt;
              PasswordHashAlgorithm = passwordHashingAlgorithm;
        }
Beispiel #11
0
        public void CanSerializeUserAccountId()
        {
            // Arrange
            UserAccountId id1 = new UserAccountId(Guid.NewGuid());

            // Act
            byte[]        data = Serializer.Serialize(id1);
            UserAccountId id2  = (UserAccountId)Serializer.Deserialize(data);

            // Assert
            Assert.IsNotNull(id2);
            Assert.AreEqual(id1, id2);
        }
        public PasswordChangedEvent(UserAccountId id, byte[] passwordSalt, byte[] passwordHash, string passwordHashingAlgorithm)
        {
            Condition.Requires(id, "id").IsNotNull();

            if ((passwordSalt != null || passwordHash != null) && string.IsNullOrEmpty(passwordHashingAlgorithm))
            {
                throw new InvalidOperationException("Missing passwordHashingAlgorithm");
            }

            Id                    = id;
            PasswordHash          = passwordHash;
            PasswordSalt          = passwordSalt;
            PasswordHashAlgorithm = passwordHashingAlgorithm;
        }
 public UserAccountCreated(TenantId tenantId,
                           UserAccountId userAccountId, string userName, string passwordHash,
                           UserRoleId userRoleId, string roleName,
                           string?email = null, string?name = null, string?description = null)
 {
     TenantId      = tenantId;
     UserAccountId = userAccountId;
     UserName      = userName;
     PasswordHash  = passwordHash;
     UserRoleId    = userRoleId;
     RoleName      = roleName;
     Email         = email;
     Name          = name;
     Description   = description;
 }
Beispiel #14
0
        public async Task SubscribeAsync(string networkName)
        {
            EthereumNetwork network = this.VerifyNetwork(networkName);

            UserAccountId userAccountId = this.JwtUser()
                                          .Id;

            string connectionId = this.Context.ConnectionId;

            this.Logger.LogInformation($"Client {connectionId} subscribing to network {network.Name}");

            // temporary for dummy data
            await this.SubscribeNetworkAsync(connectionId : this.Context.ConnectionId, network : network);

            this.Logger.LogInformation($"Client {connectionId} subscribed to network {network.Name} and user account id {userAccountId}");

            int playerCount = await this._playerCountManager.AddPlayerAsync(playerId : this.Context.ConnectionId, newNetwork : network);

            await this.Clients.Caller.PlayersOnline(playerCount);
        }
Beispiel #15
0
        public override int GetHashCode()
        {
            int hash = 1;

            if (Id.Length != 0)
            {
                hash ^= Id.GetHashCode();
            }
            if (subjectCase_ == SubjectOneofCase.UserAccountId)
            {
                hash ^= UserAccountId.GetHashCode();
            }
            if (subjectCase_ == SubjectOneofCase.ServiceAccountId)
            {
                hash ^= ServiceAccountId.GetHashCode();
            }
            if (createdAt_ != null)
            {
                hash ^= CreatedAt.GetHashCode();
            }
            if (Description.Length != 0)
            {
                hash ^= Description.GetHashCode();
            }
            if (KeyAlgorithm != global::Yandex.Cloud.Iam.V1.Key.Types.Algorithm.Unspecified)
            {
                hash ^= KeyAlgorithm.GetHashCode();
            }
            if (PublicKey.Length != 0)
            {
                hash ^= PublicKey.GetHashCode();
            }
            hash ^= (int)subjectCase_;
            if (_unknownFields != null)
            {
                hash ^= _unknownFields.GetHashCode();
            }
            return(hash);
        }
        public async Task SubscribeAsync(string networkName)
        {
            EthereumNetwork network = this.VerifyNetwork(networkName);

            JwtUser       user          = this.JwtUser();
            UserAccountId userAccountId = user.Id;

            string connectionId = this.Context.ConnectionId;

            this.Logger.LogInformation($"Client {connectionId} subscribing to network {network.Name}");

            await this.SubscribeNetworkAsync(connectionId : this.Context.ConnectionId, network : network);

            this.Logger.LogInformation($"Client {connectionId} subscribed to network {network.Name} and user account id {userAccountId}");

            int playerCount = await this._playerCountManager.AddPlayerAsync(playerId : this.Context.ConnectionId, newNetwork : network);

            await this.Clients.Caller.PlayersOnline(playerCount);

            INetworkBlockHeader?networkBlockHeader = this._ethereumBlockStatus.GetLatestBlockRetrievedOnNetwork(network);

            await this.PublishGameStateAsync(network : network, networkBlockHeader : networkBlockHeader);
        }
Beispiel #17
0
        public static async Task Main(string[] args)
        {
            //var upcaster = new UserAccountAggregateEventUpcaster();

            //var oldevt = new CommittedEvent<UserAccountAggregate,UserAccountId,UserAccountNameChangedEvent>(UserAccountId.New,new UserAccountNameChangedEvent("test"),null);
            //var
            //var evt1 = upcaster.FromJournal(oldevt, String.Empty);
            //Console.WriteLine("Ok");
            //var evt = upcaster.Upcast(oldevt);
            //Console.WriteLine(evt);

            //Create actor system
            var system = ActorSystem.Create("useraccount-example", Config.Postgres);

            //Create supervising aggregate manager for UserAccount aggregate root actors
            var aggregateManager = system.ActorOf(Props.Create(() => new UserAccountAggregateManager()));

            //Build create user account aggregate command
            //var aggregateId = UserAccountId.New;
            //var createUserAccountCommand = new CreateUserAccountCommand(aggregateId, "foo bar");

            //Send command, this is equivalent to command.publish() in other cqrs frameworks
            //aggregateManager.Tell(createUserAccountCommand);
            var aggregateId = UserAccountId.With("useraccount-a40e3a87-6ebf-4900-884d-7c17477ea20b");

            while (true)
            {
                var newName           = GetRandomString();
                var changeNameCommand = new UserAccountChangeNameCommand(aggregateId, newName);
                aggregateManager.Tell(changeNameCommand);
                await Task.Delay(1000);
            }

            //block end of program
            Console.WriteLine("done");
            Console.ReadLine();
        }
        protected Task SubscribeAccountAsync(string connectionId, EthereumNetwork network, UserAccountId userAccountId)
        {
            if (userAccountId == null)
            {
                return(Task.CompletedTask);
            }

            return(Task.WhenAll(this.AddToGroupAsync(connectionId: connectionId, this._groupNameGenerator.GenerateGlobal(network: network, accountAddress: userAccountId)),
                                this.AddToGroupAsync(connectionId: connectionId, this._groupNameGenerator.GenerateLocal(network: network, accountAddress: userAccountId))));
        }
Beispiel #19
0
 void When(AddedUserAccount @event)
 {
     Id = new UserAccountId(@event.UserAccountId);
       _roles = new HashSet<RoleId>();
       _roleGroups = new HashSet<RoleGroupId>();
       _disabled = false;
 }
Beispiel #20
0
 // Behavior
 public UserAccount(UserAccountId userAccountId, UserAccountName name)
     : this()
 {
     Apply(
     new AddedUserAccount(userAccountId, name));
 }
Beispiel #21
0
 public JwtUser(UserAccountId userAccountId, AccountAddress accountAddress)
 {
     this.Id             = userAccountId;
     this.AccountAddress = accountAddress;
 }
 public AddUserAccountToGroup(UserAccountId userAccountId, UserGroupId userGroupId)
 {
     UserAccountId = userAccountId;
     UserGroupId   = userGroupId;
 }
Beispiel #23
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();
        }
Beispiel #24
0
 public UserRemovedFromGroup(UserGroupId userGroupId, UserAccountId userAccountId)
 {
     UserGroupId   = userGroupId;
     UserAccountId = userAccountId;
 }
Beispiel #25
0
 public SecurityContext(UserAccountId accountId, TMessage message)
 {
     _message   = message;
     _accountId = accountId;
 }
 public UserAccountDeleted(TenantId tenantId, UserAccountId userAccountId)
 {
     TenantId      = tenantId;
     UserAccountId = userAccountId;
 }
 /// <inheritdoc />
 public string GenerateGlobal(EthereumNetwork network, UserAccountId accountAddress)
 {
     return($"{this._environment.GetName()}|{network.Name}|{accountAddress}");
 }