public static string GenerateToken(UserCredential user, DateTime expireDate)
        {
            var claims = new List <Claim>
            {
                new Claim(ClaimTypes.Name, user.Email),
                new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name", user.Email),
                new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", user.UserId.ToString()),
                new Claim(ClaimStore.Email.ToString(), user.Email),
                new Claim(ClaimStore.UserId.ToString(), user.UserId),
                new Claim(ClaimStore.Role.ToString(), user.Roles.ToJSON()),
            };

            var key     = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(AppConfigUtilities.GetAppConfig <string>("JwtKey")));
            var creds   = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var expires = DateTime.Now.AddDays(Convert.ToDouble("8"));

            var token = new JwtSecurityToken(
                issuer: AppConfigUtilities.GetAppConfig <string>("JwtIssuer"),
                audience: AppConfigUtilities.GetAppConfig <string>("JwtAudience"),
                claims: claims,
                expires: expires,
                signingCredentials: creds
                );

            string t = new JwtSecurityTokenHandler().WriteToken(token);


            return(t);
        }
Esempio n. 2
0
        public void Publish(IntegrationEvent @event)
        {
            var env = AppConfigUtilities.GetAppConfig <string>("KAFKA_ENV");


            var eventName = @event.GetType().Name;
            var kafkaUrl  = AppConfigUtilities.GetAppConfig <string>("KAFKA_URL");
            var config    = new ProducerConfig {
                BootstrapServers = kafkaUrl
            };
            var topic = env + eventName;

            if (@event.AggregateId.IsNullOrEmpty())
            {
                @event.AggregateId = Guid.NewGuid().ToString();
            }
            var msg = new Message <string, string> {
                Key = @event.AggregateId, Value = @event.ToJSON()
            };

            using (var p = new ProducerBuilder <string, string>(config).Build())
            {
                var result = p.ProduceAsync(topic, msg).Result;

                _EventStore.Persist(@event, result.Offset.Value);
            }
        }
        public static ClaimsPrincipal GetPrincipal(string token)
        {
            try
            {
                token = token.StartsWith("Bearer ") ? token.Substring(7) : token;
                JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
                JwtSecurityToken        jwtToken     = (JwtSecurityToken)tokenHandler.ReadToken(token);

                if (jwtToken == null)
                {
                    return(null);
                }
                byte[] key = Convert.FromBase64String(Secret);

                TokenValidationParameters parameters = new TokenValidationParameters()
                {
                    ValidateIssuer           = true,
                    ValidateAudience         = true,
                    ValidateLifetime         = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer      = AppConfigUtilities.GetAppConfig <string>("JwtIssuer"),
                    ValidAudience    = AppConfigUtilities.GetAppConfig <string>("JwtAudience"),
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Secret))
                };

                SecurityToken   securityToken;
                ClaimsPrincipal principal = tokenHandler.ValidateToken(token, parameters, out securityToken);
                return(principal);
            }
            catch (Exception e)
            {
                return(null);
            }
        }
Esempio n. 4
0
        public void PublishAll(List <IntegrationEvent> @events)
        {
            if (@events.Count == 0)
            {
                return;
            }
            var env = AppConfigUtilities.GetAppConfig <string>("KAFKA_ENV");

            var publisher = Environment.MachineName;
            var eventName = @events.FirstOrDefault().GetType().Name;
            var kafkaUrl  = AppConfigUtilities.GetAppConfig <string>("KAFKA_URL");
            var config    = new ProducerConfig {
                BootstrapServers = kafkaUrl
            };
            var topic = env + eventName;
            var p     = new ProducerBuilder <string, string>(config).Build();
            List <(IntegrationEvent, long)> logs = new List <(IntegrationEvent, long)>();

            foreach (var item in @events)
            {
                if (item.AggregateId.IsNullOrEmpty())
                {
                    item.AggregateId = Guid.NewGuid().ToString();
                }
                var msg = new Message <string, string> {
                    Key = item.AggregateId, Value = item.ToJSON()
                };


                var result = p.ProduceAsync(topic, msg).Result;

                #region ----LOG ES----
                var l = new LogEventStore();
                l.AggregateId = item.AggregateId;
                l.CreateDate  = DateTime.Now.GetLocalDate();
                l.EventName   = env + item.GetType().Name;
                l.Val         = item.ToJSON();
                l.OffSet      = result.Offset;
                l.Publisher   = publisher;
                var msgLog = new Message <string, string> {
                    Key = l.AggregateId, Value = l.ToJSON()
                };
                var log = p.ProduceAsync("LogEventStore", msgLog).Result;

                #endregion

                logs.Add((item, result.Offset.Value));
            }
            _EventStore.PersistAll(logs);
        }
        public static DbContextOptions <NexusDataContext> GetNexus()
        {
            var conStr = AppConfigUtilities.GetAppConfig <string>("NexusDatabase");

            if (string.IsNullOrEmpty(conStr))
            {
                conStr = AppConfigUtilities.GetAppConfig <string>("NexusDatabase");
            }
            var builder = new DbContextOptionsBuilder <NexusDataContext>();

            DbContextConfigurer.ConfigureNexusContext(
                builder,
                conStr);

            return(builder.Options);
        }
Esempio n. 6
0
        public void Publish(object obj, string _topic)
        {
            var env = AppConfigUtilities.GetAppConfig <string>("KAFKA_ENV");

            var _config = new Config();


            using (Producer producer = new Producer(_config, AppConfigUtilities.GetAppConfig <string>("KAFKA_URL")))

                using (Topic topic = producer.Topic(_topic))
                {
                    var            id             = Encoding.UTF8.GetBytes(Guid.NewGuid().ToString());
                    byte[]         data           = Encoding.UTF8.GetBytes(obj.ToJSON());
                    DeliveryReport deliveryReport = topic.Produce(data, id).Result;
                }
        }
Esempio n. 7
0
        public void StartBasicConsume()
        {
            var env      = AppConfigUtilities.GetAppConfig <string>("KAFKA_ENV");
            var consumer = DomainEvents._Consumer;


            consumer.OnPartitionsAssigned += (obj, partitions) =>
            {
                var fromBeginning = partitions.Select(p => new RdKafka.TopicPartitionOffset(p.Topic, p.Partition, RdKafka.Offset.Stored)).ToList();
                consumer.Assign(fromBeginning);
            };
            consumer.OnMessage += Consumer_OnMessage;
            var events = this._subsManager.Events.Select(s => env + s).ToList();

            consumer.Subscribe(events);
            consumer.Start();
        }
        public static DbContextOptions <DbReadDataContext> GetDbReadContext()
        {
            var conStr = AppConfigUtilities.GetAppConfig <string>("DbReadDataContext");

            if (string.IsNullOrEmpty(conStr))
            {
                conStr = AppConfigUtilities.GetAppConfig <string>("DbReadDataContext");
            }

            var builder = new DbContextOptionsBuilder <DbReadDataContext>();

            DbContextConfigurer.ConfigureDbReadContext(
                builder,
                conStr);

            return(builder.Options);
        }
Esempio n. 9
0
        public void Publish(object obj, string _topic)
        {
            var env = AppConfigUtilities.GetAppConfig <string>("KAFKA_ENV");

            var kafkaUrl = AppConfigUtilities.GetAppConfig <string>("KAFKA_URL");
            var config   = new ProducerConfig {
                BootstrapServers = kafkaUrl
            };

            var msg = new Message <string, string> {
                Key = Guid.NewGuid().ToString(), Value = obj.ToJSON()
            };

            using (var p = new ProducerBuilder <string, string>(config).Build())
            {
                var result = p.ProduceAsync(_topic, msg).Result;
            }
        }
Esempio n. 10
0
        public void Publish(IntegrationEvent @event)
        {
            var env = AppConfigUtilities.GetAppConfig <string>("KAFKA_ENV");

            _EventStore.Persist(@event);

            var _config = new Config();

            var eventName = @event.GetType().Name;

            using (Producer producer = new Producer(_config, AppConfigUtilities.GetAppConfig <string>("KAFKA_URL")))

                using (Topic topic = producer.Topic(env + eventName))
                {
                    var            id             = Encoding.UTF8.GetBytes(@event.AggregateId);
                    byte[]         data           = Encoding.UTF8.GetBytes(@event.ToJSON());
                    DeliveryReport deliveryReport = topic.Produce(data, id).Result;
                }
        }
        public static void RegisterEvent()
        {
            #region ----------REGISTER EVENT------
            if (DomainEvents._Consumer != null)
            {
                DomainEvents._Consumer.Dispose();
            }
            var config = new Config()
            {
                GroupId = AppConfigUtilities.GetAppConfig <string>("KAFKA_CONSUMER_GROUP_ID")
            };
            config.EnableAutoCommit   = false;
            config.StatisticsInterval = TimeSpan.FromSeconds(10);
            DomainEvents._Consumer    = new EventConsumer(config, AppConfigUtilities.GetAppConfig <string>("KAFKA_URL"));

            var eventBus = DomainEvents._Container.Resolve <IEventBus>();
            eventBus.Subscribe <CustomerCreatedEvent, IIntegrationEventHandler <CustomerCreatedEvent> >();
            eventBus.StartBasicConsume();
            #endregion
        }
Esempio n. 12
0
        private void Consumer_OnMessage(object sender, Message e)
        {
            var isCommitSuccess = false;
            var i = 1;

            while (!isCommitSuccess)
            {
                if (i > 10)
                {
                    isCommitSuccess = true;
                    return;
                }
                var    env     = AppConfigUtilities.GetAppConfig <string>("KAFKA_ENV");
                var    log     = DomainEvents._Container.Resolve <ILogRepository>();
                string text    = Encoding.UTF8.GetString(e.Payload, 0, e.Payload.Length);
                var    eStore  = DomainEvents._Container.Resolve <IEventStore>();
                var    id      = Encoding.UTF8.GetString(e.Key, 0, e.Key.Length);
                var    gKafka  = AppConfigUtilities.GetAppConfig <string>("KAFKA_CONSUMER_GROUP_ID");
                var    envName = Environment.MachineName;

                try
                {
                    var topic = e.Topic.Replace(env, "");
                    ProcessEvent(topic, text).Wait();

                    DomainEvents._Consumer.Commit(e).Wait();


                    eStore.Commit(id, envName);
                    isCommitSuccess = true;
                }
                catch (Exception exception)
                {
                    eStore.CommitedFail(id, $"({i})" + exception.GetMessageError());
                    log.Error($"({i})[{e.Topic}]" + exception.GetMessageError(), exception.StackTrace, "Consumer_OnMessage", null);
                    isCommitSuccess = false;
                    i++;
                    Thread.Sleep(5000);
                }
            }
        }
Esempio n. 13
0
        public void Persist <TAggregate>(TAggregate aggregate, long offset) where TAggregate : IntegrationEvent
        {
            var l = new LogEventStore();

            using (var scope = new TransactionScope(TransactionScopeOption.Suppress))
            {
                var publisher = Environment.MachineName;
                var env       = AppConfigUtilities.GetAppConfig <string>("KAFKA_ENV");
                var date      = DateTime.Now.GetLocalDate();
                var val       = aggregate.ToJSON();

                l.AggregateId = aggregate.AggregateId;
                l.CreateDate  = date;
                l.OffSet      = offset;
                l.Publisher   = publisher;
                l.EventName   = env + aggregate.GetType().Name;
                l.Val         = val;
                _db.LogEventStores.Add(l);
                _db.SaveChanges();
            }
            Publish(l, "LogEventStore");
        }