Ejemplo n.º 1
0
        public void Can_publish_and_receive_messages_with_MessageFactory()
        {
            using (var mqFactory = new RabbitMqMessageFactory(Config.RabbitMQConnString))
                using (var mqClient = mqFactory.CreateMessageQueueClient())
                {
                    mqClient.Publish(new Hello {
                        Name = "Foo"
                    });
                    var msg = mqClient.Get <Hello>(QueueNames <Hello> .In);

                    Assert.That(msg.GetBody().Name, Is.EqualTo("Foo"));
                }
        }
        public void Can_Send_Email_via_MqClient()
        {
            var mqFactory = new RabbitMqMessageFactory();

            using (var mqClient = mqFactory.CreateMessageQueueClient())
            {
                mqClient.Publish(new EmailContact {
                    ContactId = 1, Subject = "UnitTest MQ Email #1", Body = "Body 1"
                });
                mqClient.Publish(new EmailContact {
                    ContactId = 1, Subject = "UnitTest MQ Email #2", Body = "Body 2"
                });
            }
        }
Ejemplo n.º 3
0
        public void Allows_MegaDto_through_RabbitMqClients()
        {
            var mqFactory = new RabbitMqMessageFactory(connectionString: Config.RabbitMQConnString);

            var request = MegaDto.Create();

            using (var mqClient = mqFactory.CreateMessageProducer())
            {
                mqClient.Publish(request);
            }

            using (var mqClient = mqFactory.CreateMessageQueueClient())
            {
                var msg      = mqClient.Get <MegaDto>(QueueNames <MegaDto> .In);
                var response = msg.GetBody();

                Assert.That(request.T01.Id, Is.EqualTo(response.T01.Id));
            }
        }
Ejemplo n.º 4
0
        public override void Configure(Container container)
        {
            var co = this.Config;

            LogManager.LogFactory = new ConsoleLogFactory(debugEnabled: true);

            var jwtprovider = new MyJwtAuthProvider(AppSettings)
            {
                HashAlgorithm = "RS256",
                PrivateKeyXml = EbLiveSettings.PrivateKeyXml,
                PublicKeyXml  = EbLiveSettings.PublicKeyXml,
#if (DEBUG)
                RequireSecureConnection = false,
                //EncryptPayload = true,
#endif
                CreatePayloadFilter = (payload, session) =>
                {
                    payload["sub"] = (session as CustomUserSession).UserAuthId;
                    payload["cid"] = (session as CustomUserSession).CId;
                    payload["uid"] = (session as CustomUserSession).Uid.ToString();
                    payload["wc"]  = (session as CustomUserSession).WhichConsole;
                },

                ExpireTokensIn        = TimeSpan.FromHours(10),
                ExpireRefreshTokensIn = TimeSpan.FromHours(12),
                PersistSession        = true,
                SessionExpiry         = TimeSpan.FromHours(12)
            };

            this.Plugins.Add(new CorsFeature(allowedHeaders: "Content-Type, Authorization, Access-Control-Allow-Origin, Access-Control-Allow-Credentials"));
            this.Plugins.Add(new ProtoBufFormat());

            Plugins.Add(new AuthFeature(() => new CustomUserSession(),
                                        new IAuthProvider[] {
                new MyFacebookAuthProvider(AppSettings)
                {
                    AppId       = "151550788692231",
                    AppSecret   = "94ec1a04342e5cf7e7a971f2eb7ad7bc",
                    Permissions = new string[] { "email, public_profile" }
                },

                new MyTwitterAuthProvider(AppSettings)
                {
                    ConsumerKey    = "6G9gaYo7DMx1OHYRAcpmkPfvu",
                    ConsumerSecret = "Jx8uUIPeo5D0agjUnqkKHGQ4o6zTrwze9EcLtjDlOgLnuBaf9x",
                    // CallbackUrl = "http://*****:*****@{1}:{2}?ssl=true",
                                                      EbLiveSettings.RedisPassword, EbLiveSettings.RedisServer, EbLiveSettings.RedisPort);

            container.Register <IRedisClientsManager>(c => new RedisManagerPool(redisConnectionString));

            container.Register <IUserAuthRepository>(c => new EbRedisAuthRepository(c.Resolve <IRedisClientsManager>()));

            container.Register <JwtAuthProvider>(jwtprovider);

            container.Register <ITenantDbFactory>(c => new TenantDbFactory(c)).ReusedWithin(ReuseScope.Request);

            RabbitMqMessageFactory rabitFactory = new RabbitMqMessageFactory();

            rabitFactory.ConnectionFactory.UserName    = EbLiveSettings.RabbitUser;
            rabitFactory.ConnectionFactory.Password    = EbLiveSettings.RabbitPassword;
            rabitFactory.ConnectionFactory.HostName    = EbLiveSettings.RabbitHost;
            rabitFactory.ConnectionFactory.Port        = EbLiveSettings.RabbitPort;
            rabitFactory.ConnectionFactory.VirtualHost = EbLiveSettings.RabbitVHost;

            var mqServer = new RabbitMqServer(rabitFactory);

            mqServer.RetryCount = 1;
            //mqServer.RegisterHandler<EmailServicesMqRequest>(base.ExecuteMessage);
            //mqServer.RegisterHandler<RefreshSolutionConnectionsMqRequestTest>(base.ExecuteMessage);
            //mqServer.RegisterHandler<UploadFileMqRequestTest>(base.ExecuteMessage);
            //mqServer.RegisterHandler<ImageResizeMqRequestTest>(base.ExecuteMessage);
            //mqServer.RegisterHandler<FileMetaPersistMqRequestTest>(base.ExecuteMessage);
            //mqServer.RegisterHandler<SlackPostMqRequest>(base.ExecuteMessage);
            ////mqServer.RegisterHandler<SlackAuthMqRequest>(base.ExecuteMessage);

            mqServer.Start();

            container.AddScoped <IMessageProducer, RabbitMqProducer>(serviceProvider =>
            {
                return(mqServer.CreateMessageProducer() as RabbitMqProducer);
            });

            container.AddScoped <IMessageQueueClient, RabbitMqQueueClient>(serviceProvider =>
            {
                return(mqServer.CreateMessageQueueClient() as RabbitMqQueueClient);
            });

            //Add a request filter to check if the user has a session initialized
            this.GlobalRequestFilters.Add((req, res, requestDto) =>
            {
                ILog log = LogManager.GetLogger(GetType());

                log.Info("In GlobalRequestFilters");
                try
                {
                    if (requestDto.GetType() == typeof(Authenticate))
                    {
                        log.Info("In Authenticate");

                        string TenantId = (requestDto as Authenticate).Meta != null ? (requestDto as Authenticate).Meta["cid"] : "expressbase";
                        log.Info(TenantId);
                        RequestContext.Instance.Items.Add("TenantAccountId", TenantId);
                    }
                }catch (Exception e)
                {
                    log.Info("ErrorStackTrace..........." + e.StackTrace);
                    log.Info("ErrorMessage..........." + e.Message);
                    log.Info("InnerException..........." + e.InnerException);
                }
                try
                {
                    if (requestDto != null && requestDto.GetType() != typeof(Authenticate) && requestDto.GetType() != typeof(GetAccessToken) && requestDto.GetType() != typeof(UniqueRequest) && requestDto.GetType() != typeof(CreateAccountRequest) && requestDto.GetType() != typeof(EmailServicesRequest) && requestDto.GetType() != typeof(RegisterRequest))
                    {
                        var auth = req.Headers[HttpHeaders.Authorization];
                        if (string.IsNullOrEmpty(auth))
                        {
                            res.ReturnAuthRequired();
                        }
                        else
                        {
                            var jwtoken = new JwtSecurityToken(auth.Replace("Bearer", string.Empty).Trim());
                            foreach (var c in jwtoken.Claims)
                            {
                                if (c.Type == "cid" && !string.IsNullOrEmpty(c.Value))
                                {
                                    RequestContext.Instance.Items.Add("TenantAccountId", c.Value);
                                    if (requestDto is IEbSSRequest)
                                    {
                                        (requestDto as IEbSSRequest).TenantAccountId = c.Value;
                                    }
                                    if (requestDto is EbServiceStackRequest)
                                    {
                                        (requestDto as EbServiceStackRequest).TenantAccountId = c.Value;
                                    }
                                    continue;
                                }
                                if (c.Type == "uid" && !string.IsNullOrEmpty(c.Value))
                                {
                                    RequestContext.Instance.Items.Add("UserId", Convert.ToInt32(c.Value));
                                    if (requestDto is IEbSSRequest)
                                    {
                                        (requestDto as IEbSSRequest).UserId = Convert.ToInt32(c.Value);
                                    }
                                    if (requestDto is EbServiceStackRequest)
                                    {
                                        (requestDto as EbServiceStackRequest).UserId = Convert.ToInt32(c.Value);
                                    }
                                    continue;
                                }
                                if (c.Type == "wc" && !string.IsNullOrEmpty(c.Value))
                                {
                                    RequestContext.Instance.Items.Add("wc", c.Value);
                                    if (requestDto is EbServiceStackRequest)
                                    {
                                        (requestDto as EbServiceStackRequest).WhichConsole = c.Value.ToString();
                                    }
                                    continue;
                                }
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    log.Info("ErrorStackTraceNontokenServices..........." + e.StackTrace);
                    log.Info("ErrorMessageNontokenServices..........." + e.Message);
                    log.Info("InnerExceptionNontokenServices..........." + e.InnerException);
                }
            });

            this.GlobalResponseFilters.Add((req, res, responseDto) =>
            {
                if (responseDto.GetResponseDto() != null)
                {
                    if (responseDto.GetResponseDto().GetType() == typeof(GetAccessTokenResponse))
                    {
                        res.SetSessionCookie("Token", (res.Dto as GetAccessTokenResponse).AccessToken);
                    }
                }
            });
        }
Ejemplo n.º 5
0
        public override void Configure(Container container)
        {
            LogManager.LogFactory = new ConsoleLogFactory(debugEnabled: true);

            var jwtprovider = new JwtAuthProviderReader
            {
                HashAlgorithm = "RS256",
                PublicKeyXml  = Environment.GetEnvironmentVariable(EnvironmentConstants.EB_JWT_PUBLIC_KEY_XML),
#if (DEBUG)
                RequireSecureConnection = false,
                //EncryptPayload = true,
#endif
            };

            this.Plugins.Add(new CorsFeature(allowedHeaders: "rToken, bToken, Content-Type, Authorization, Access-Control-Allow-Origin, Access-Control-Allow-Credentials"));
            this.Plugins.Add(new ServerEventsFeature());
            this.Plugins.Add(new AuthFeature(() => new CustomUserSession(),
                                             new IAuthProvider[] {
                jwtprovider,
            }));

#if (DEBUG)
            SetConfig(new HostConfig {
                DebugMode = true
            });
#endif
            SetConfig(new HostConfig {
                DefaultContentType = MimeTypes.Json
            });

            string env = Environment.GetEnvironmentVariable(EnvironmentConstants.ASPNETCORE_ENVIRONMENT);

            var redisServer   = Environment.GetEnvironmentVariable(EnvironmentConstants.EB_REDIS_SERVER);
            var redisPassword = Environment.GetEnvironmentVariable(EnvironmentConstants.EB_REDIS_PASSWORD);
            var redisPort     = Environment.GetEnvironmentVariable(EnvironmentConstants.EB_REDIS_PORT);

            //if (env == "Staging")
            //{
            //    container.Register<IRedisClientsManager>(c => new RedisManagerPool(redisServer));
            //}
            //else
            //{
            var redisConnectionString = string.Format("redis://{0}@{1}:{2}", redisPassword, redisServer, redisPort);
            container.Register <IRedisClientsManager>(c => new RedisManagerPool(redisConnectionString));
            //}

            container.Register <IUserAuthRepository>(c => new MyRedisAuthRepository(c.Resolve <IRedisClientsManager>()));
            container.Register <IEbMqClient>(c => new EbMqClient()).ReusedWithin(ReuseScope.Request);

            RabbitMqMessageFactory rabitFactory = new RabbitMqMessageFactory();
            rabitFactory.ConnectionFactory.UserName    = Environment.GetEnvironmentVariable(EnvironmentConstants.EB_RABBIT_USER);
            rabitFactory.ConnectionFactory.Password    = Environment.GetEnvironmentVariable(EnvironmentConstants.EB_RABBIT_PASSWORD);
            rabitFactory.ConnectionFactory.HostName    = Environment.GetEnvironmentVariable(EnvironmentConstants.EB_RABBIT_HOST);
            rabitFactory.ConnectionFactory.Port        = Convert.ToInt32(Environment.GetEnvironmentVariable(EnvironmentConstants.EB_RABBIT_PORT));
            rabitFactory.ConnectionFactory.VirtualHost = Environment.GetEnvironmentVariable(EnvironmentConstants.EB_RABBIT_VHOST);

            var mqServer = new RabbitMqServer(rabitFactory);

            container.AddScoped <IMessageProducer, RabbitMqProducer>(serviceProvider =>
            {
                return(mqServer.CreateMessageProducer() as RabbitMqProducer);
            });

            container.Register <IServerEvents>(c => new RedisServerEvents(c.Resolve <IRedisClientsManager>()));
            container.Resolve <IServerEvents>().Start();

            //Setting Assembly version in Redis
            RedisClient  client   = (container.Resolve <IRedisClientsManager>() as RedisManagerPool).GetClient() as RedisClient;
            AssemblyName assembly = Assembly.GetExecutingAssembly().GetName();
            String       version  = assembly.Name.ToString() + " - " + assembly.Version.ToString();
            client.Set("ServerEventsAssembly", version);


            this.GlobalRequestFilters.Add((req, res, requestDto) =>
            {
                ILog log = LogManager.GetLogger(GetType());

                log.Info("In GlobalRequestFilters");
                try
                {
                    log.Info("In Try");
                    if (requestDto != null)
                    {
                        log.Info("In Auth Header");
                        var auth = req.Headers[HttpHeaders.Authorization];
                        if (string.IsNullOrEmpty(auth))
                        {
                            res.ReturnAuthRequired();
                        }
                        else
                        {
                            if (req.Headers[CacheConstants.RTOKEN] != null)
                            {
                                log.Info("Req Headers Not Null");
                            }
                            var jwtoken = new JwtSecurityToken(auth.Replace("Bearer", string.Empty).Trim());
                            foreach (var c in jwtoken.Claims)
                            {
                                if (c.Type == "cid" && !string.IsNullOrEmpty(c.Value))
                                {
                                    RequestContext.Instance.Items.Add(CoreConstants.SOLUTION_ID, c.Value);
                                    if (requestDto is IEbSSRequest)
                                    {
                                        (requestDto as IEbSSRequest).SolnId = c.Value;
                                    }
                                    if (requestDto is EbServiceStackAuthRequest)
                                    {
                                        (requestDto as EbServiceStackAuthRequest).SolnId = c.Value;
                                    }
                                    continue;
                                }
                                if (c.Type == "uid" && !string.IsNullOrEmpty(c.Value))
                                {
                                    RequestContext.Instance.Items.Add("UserId", Convert.ToInt32(c.Value));
                                    if (requestDto is IEbSSRequest)
                                    {
                                        (requestDto as IEbSSRequest).UserId = Convert.ToInt32(c.Value);
                                    }
                                    if (requestDto is EbServiceStackAuthRequest)
                                    {
                                        (requestDto as EbServiceStackAuthRequest).UserId = Convert.ToInt32(c.Value);
                                    }
                                    continue;
                                }
                                if (c.Type == "wc" && !string.IsNullOrEmpty(c.Value))
                                {
                                    RequestContext.Instance.Items.Add("wc", c.Value);
                                    if (requestDto is EbServiceStackAuthRequest)
                                    {
                                        (requestDto as EbServiceStackAuthRequest).WhichConsole = c.Value.ToString();
                                    }
                                    continue;
                                }
                                if (c.Type == "sub" && !string.IsNullOrEmpty(c.Value))
                                {
                                    RequestContext.Instance.Items.Add("sub", c.Value);
                                    if (requestDto is EbServiceStackAuthRequest)
                                    {
                                        (requestDto as EbServiceStackAuthRequest).UserAuthId = c.Value.ToString();
                                    }
                                    continue;
                                }
                            }
                            log.Info("Req Filter Completed");
                        }
                    }
                }
                catch (Exception e)
                {
                    log.Info("ErrorStackTraceNontokenServices..........." + e.StackTrace);
                    log.Info("ErrorMessageNontokenServices..........." + e.Message);
                    log.Info("InnerExceptionNontokenServices..........." + e.InnerException);
                }
            });
        }
Ejemplo n.º 6
0
 public MqTest()
 {
     MqFactory = new RabbitMqMessageFactory("localhost:5672");
 }
        public override void Configure(Container container)
        {
            LogManager.LogFactory = new ConsoleLogFactory(debugEnabled: true);

            var jwtprovider = new JwtAuthProviderReader
            {
                HashAlgorithm           = "RS256",
                PublicKeyXml            = Environment.GetEnvironmentVariable(EnvironmentConstants.EB_JWT_PUBLIC_KEY_XML),
                RequireSecureConnection = false,
                //EncryptPayload = true,
            };

            this.Plugins.Add(new AuthFeature(() => new CustomUserSession(),
                                             new IAuthProvider[] {
                jwtprovider,
            }));

#if (DEBUG)
            SetConfig(new HostConfig {
                DebugMode = true
            });
#endif
            SetConfig(new HostConfig {
                DefaultContentType = MimeTypes.Json
            });

            string env = Environment.GetEnvironmentVariable(EnvironmentConstants.ASPNETCORE_ENVIRONMENT);

            var redisServer   = Environment.GetEnvironmentVariable(EnvironmentConstants.EB_REDIS_SERVER);
            var redisPassword = Environment.GetEnvironmentVariable(EnvironmentConstants.EB_REDIS_PASSWORD);
            var redisPort     = Environment.GetEnvironmentVariable(EnvironmentConstants.EB_REDIS_PORT);

            RedisClient client = null;

            string redisConnectionString = string.Format("redis://{0}@{1}:{2}", redisPassword, redisServer, redisPort);
            container.Register <IRedisClientsManager>(c => new RedisManagerPool(redisConnectionString));
            client = (container.Resolve <IRedisClientsManager>() as RedisManagerPool).GetClient() as RedisClient;

            AssemblyName assembly = Assembly.GetExecutingAssembly().GetName();
            String       version  = assembly.Name.ToString() + " - " + assembly.Version.ToString();
            client.Set("MQAssembly", version);



            container.Register <IEbServerEventClient>(c => new EbServerEventClient()).ReusedWithin(ReuseScope.Request);
            container.Register <IServiceClient>(c => new JsonServiceClient(Environment.GetEnvironmentVariable(EnvironmentConstants.EB_SERVICESTACK_EXT_URL))).ReusedWithin(ReuseScope.Request);
            container.Register <IEbConnectionFactory>(c => new EbConnectionFactory(c)).ReusedWithin(ReuseScope.Request);
            container.Register <IEbStaticFileClient>(c => new EbStaticFileClient()).ReusedWithin(ReuseScope.Request);


            RabbitMqMessageFactory rabitFactory = new RabbitMqMessageFactory();
            rabitFactory.ConnectionFactory.UserName    = Environment.GetEnvironmentVariable(EnvironmentConstants.EB_RABBIT_USER);
            rabitFactory.ConnectionFactory.Password    = Environment.GetEnvironmentVariable(EnvironmentConstants.EB_RABBIT_PASSWORD);
            rabitFactory.ConnectionFactory.HostName    = Environment.GetEnvironmentVariable(EnvironmentConstants.EB_RABBIT_HOST);
            rabitFactory.ConnectionFactory.Port        = Convert.ToInt32(Environment.GetEnvironmentVariable(EnvironmentConstants.EB_RABBIT_PORT));
            rabitFactory.ConnectionFactory.VirtualHost = Environment.GetEnvironmentVariable(EnvironmentConstants.EB_RABBIT_VHOST);

            var mqServer = new RabbitMqServer(rabitFactory);

            mqServer.RetryCount = 1;

            mqServer.RegisterHandler <RefreshSolutionConnectionsRequest>(base.ExecuteMessage);

            mqServer.RegisterHandler <UploadFileRequest>(base.ExecuteMessage);
            mqServer.RegisterHandler <UploadImageRequest>(base.ExecuteMessage);
            mqServer.RegisterHandler <UploadImageInfraMqRequest>(base.ExecuteMessage);
            mqServer.RegisterHandler <UploadDpRequest>(base.ExecuteMessage);
            mqServer.RegisterHandler <UploadLogoRequest>(base.ExecuteMessage);
            mqServer.RegisterHandler <NotificationToDBRequest>(base.ExecuteMessage);
            mqServer.RegisterHandler <SaveRoleMqRequest>(base.ExecuteMessage);
            mqServer.RegisterHandler <SaveUserMqRequest>(base.ExecuteMessage);
            mqServer.RegisterHandler <SuspendUserMqRequest>(base.ExecuteMessage);
            mqServer.RegisterHandler <BrowserExceptionRequest>(base.ExecuteMessage);
            mqServer.RegisterHandler <SaveUserGroupMqRequest>(base.ExecuteMessage);
            //mqServer.RegisterHandler<GetImageFtpRequest>(base.ExecuteMessage, 3);
            mqServer.RegisterHandler <EmailServicesRequest>(base.ExecuteMessage);
            mqServer.RegisterHandler <SMSSentRequest>(base.ExecuteMessage);
            mqServer.RegisterHandler <ApiMqRequest>(base.ExecuteMessage);
            //mqServer.RegisterHandler<SMSStatusLogMqRequest>(base.ExecuteMessage);
            //mqServer.RegisterHandler<SlackPostMqRequest>(base.ExecuteMessage);
            //mqServer.RegisterHandler<SlackAuthMqRequest>(base.ExecuteMessage);
            mqServer.RegisterHandler <ReportRenderMultipleMQRequest>(base.ExecuteMessage);

            mqServer.Start();

            container.AddScoped <IMessageProducer, RabbitMqProducer>(serviceProvider =>
            {
                return(mqServer.CreateMessageProducer() as RabbitMqProducer);
            });

            container.AddScoped <IMessageQueueClient, RabbitMqQueueClient>(serviceProvider =>
            {
                return(mqServer.CreateMessageQueueClient() as RabbitMqQueueClient);
            });

            //var quartzFeature = new QuartzFeature();

            //// create a simple job trigger to repeat every minute
            //quartzFeature.RegisterJob<MyJob>(
            //    trigger =>
            //        trigger.WithSimpleSchedule(s =>
            //                s.WithInterval(TimeSpan.FromSeconds(30))
            //                    .RepeatForever()
            //            )
            //            .Build()
            //);

            //quartzFeature.RegisterJob<MyJob>(
            //    trigger =>
            //        trigger.WithDailyTimeIntervalSchedule(s => s.WithInterval(1, IntervalUnit.Minute))
            //            .Build()
            //);

            //// register the plugin
            //Plugins.Add(quartzFeature);

            this.GlobalRequestFilters.Add((req, res, requestDto) =>
            {
                ILog log = LogManager.GetLogger(GetType());

                log.Info("In GlobalRequestFilters");
                try
                {
                    log.Info("In Try");
                    if (requestDto != null /*&& requestDto.GetType() != typeof(RefreshSolutionExtRequest)*/)
                    {
                        log.Info("In Auth Header");
                        var auth = req.Headers[HttpHeaders.Authorization];
                        if (string.IsNullOrEmpty(auth))
                        {
                            res.ReturnAuthRequired();
                        }
                        else
                        {
                            if (req.Headers[CacheConstants.RTOKEN] != null)
                            {
                                Resolve <IEbServerEventClient>().AddAuthentication(req);
                            }
                            var jwtoken = new JwtSecurityToken(auth.Replace("Bearer", string.Empty).Trim());
                            foreach (var c in jwtoken.Claims)
                            {
                                if (c.Type == "cid" && !string.IsNullOrEmpty(c.Value))
                                {
                                    RequestContext.Instance.Items.Add(CoreConstants.SOLUTION_ID, c.Value);
                                    if (requestDto is IEbSSRequest)
                                    {
                                        (requestDto as IEbSSRequest).SolnId = c.Value;
                                    }
                                    if (requestDto is EbServiceStackAuthRequest)
                                    {
                                        (requestDto as EbServiceStackAuthRequest).SolnId = c.Value;
                                    }
                                    continue;
                                }
                                if (c.Type == "uid" && !string.IsNullOrEmpty(c.Value))
                                {
                                    RequestContext.Instance.Items.Add("UserId", Convert.ToInt32(c.Value));
                                    if (requestDto is IEbSSRequest)
                                    {
                                        (requestDto as IEbSSRequest).UserId = Convert.ToInt32(c.Value);
                                    }
                                    if (requestDto is EbServiceStackAuthRequest)
                                    {
                                        (requestDto as EbServiceStackAuthRequest).UserId = Convert.ToInt32(c.Value);
                                    }
                                    continue;
                                }
                                if (c.Type == "wc" && !string.IsNullOrEmpty(c.Value))
                                {
                                    RequestContext.Instance.Items.Add("wc", c.Value);
                                    if (requestDto is EbServiceStackAuthRequest)
                                    {
                                        (requestDto as EbServiceStackAuthRequest).WhichConsole = c.Value.ToString();
                                    }
                                    continue;
                                }
                                if (c.Type == "sub" && !string.IsNullOrEmpty(c.Value))
                                {
                                    RequestContext.Instance.Items.Add("sub", c.Value);
                                    if (requestDto is EbServiceStackAuthRequest)
                                    {
                                        (requestDto as EbServiceStackAuthRequest).UserAuthId = c.Value.ToString();
                                    }
                                    continue;
                                }
                            }
                            log.Info("Req Filter Completed");
                        }
                    }
                }
                catch (Exception e)
                {
                    log.Info("ErrorStackTraceNontokenServices..........." + e.StackTrace);
                    log.Info("ErrorMessageNontokenServices..........." + e.Message);
                    log.Info("InnerExceptionNontokenServices..........." + e.InnerException);
                }
            });
        }
Ejemplo n.º 8
0
        public override void Configure(Container container)
        {
            LogManager.LogFactory = new ConsoleLogFactory(debugEnabled: true);

            var jwtprovider = new JwtAuthProviderReader
            {
                HashAlgorithm = "RS256",
                PublicKeyXml  = Environment.GetEnvironmentVariable(EnvironmentConstants.EB_JWT_PUBLIC_KEY_XML),
#if (DEBUG)
                RequireSecureConnection = false,
                //EncryptPayload = true,
#endif
            };

            this.Plugins.Add(new AuthFeature(() => new CustomUserSession(),
                                             new IAuthProvider[] {
                jwtprovider,
            }));

#if (DEBUG)
            SetConfig(new HostConfig {
                DebugMode = true
            });
#endif
            SetConfig(new HostConfig {
                DefaultContentType = MimeTypes.Json
            });



            RabbitMqMessageFactory rabitFactory = new RabbitMqMessageFactory();
            rabitFactory.ConnectionFactory.UserName    = Environment.GetEnvironmentVariable(EnvironmentConstants.EB_RABBIT_USER);
            rabitFactory.ConnectionFactory.Password    = Environment.GetEnvironmentVariable(EnvironmentConstants.EB_RABBIT_PASSWORD);
            rabitFactory.ConnectionFactory.HostName    = Environment.GetEnvironmentVariable(EnvironmentConstants.EB_RABBIT_HOST);
            rabitFactory.ConnectionFactory.Port        = Convert.ToInt32(Environment.GetEnvironmentVariable(EnvironmentConstants.EB_RABBIT_PORT));
            rabitFactory.ConnectionFactory.VirtualHost = Environment.GetEnvironmentVariable(EnvironmentConstants.EB_RABBIT_VHOST);

            var mqServer = new RabbitMqServer(rabitFactory);

            mqServer.RetryCount = 1;

            mqServer.RegisterHandler <ScheduleRequest>(base.ExecuteMessage);
            mqServer.RegisterHandler <DeleteJobRequest>(base.ExecuteMessage);
            mqServer.RegisterHandler <RescheduleRequest>(base.ExecuteMessage);

            mqServer.Start();

            container.AddScoped <IMessageProducer, RabbitMqProducer>(serviceProvider =>
            {
                return(mqServer.CreateMessageProducer() as RabbitMqProducer);
            });

            container.AddScoped <IMessageQueueClient, RabbitMqQueueClient>(serviceProvider =>
            {
                return(mqServer.CreateMessageQueueClient() as RabbitMqQueueClient);
            });

            //****************SCHEDULER********************
            string conn = string.Format("Server = {0}; Database = {1}; Uid = {2}; Pwd = {3}; Trust Server Certificate=true; Port= {4}; Use SSL Stream=true; SSL Mode=Require;",
                                        Environment.GetEnvironmentVariable(EnvironmentConstants.EB_INFRA_DB_SERVER),
                                        Environment.GetEnvironmentVariable(EnvironmentConstants.EB_INFRA_DBNAME),
                                        Environment.GetEnvironmentVariable(EnvironmentConstants.EB_INFRA_DB_RW_USER),
                                        Environment.GetEnvironmentVariable(EnvironmentConstants.EB_INFRA_DB_RW_PASSWORD),
                                        Environment.GetEnvironmentVariable(EnvironmentConstants.EB_INFRA_DB_PORT));
            var properties = new NameValueCollection
            {
                ["quartz.serializer.type"]                  = "json",
                ["quartz.scheduler.instanceName"]           = "DotnetCoreScheduler",
                ["quartz.scheduler.instanceId"]             = "instance_one",
                ["quartz.threadPool.type"]                  = "Quartz.Simpl.SimpleThreadPool, Quartz",
                ["quartz.threadPool.threadCount"]           = "5",
                ["quartz.jobStore.misfireThreshold"]        = "60000",
                ["quartz.jobStore.type"]                    = "Quartz.Impl.AdoJobStore.JobStoreTX, Quartz",
                ["quartz.jobStore.useProperties"]           = "true",
                ["quartz.jobStore.dataSource"]              = "myDS",
                ["quartz.jobStore.tablePrefix"]             = "QRTZ_",
                ["quartz.jobStore.driverDelegateType"]      = "Quartz.Impl.AdoJobStore.PostgreSQLDelegate, Quartz",
                ["quartz.dataSource.myDS.provider"]         = "Npgsql ",
                ["quartz.dataSource.myDS.connectionString"] = conn
            };


            StdSchedulerFactory factory   = new Quartz.Impl.StdSchedulerFactory(properties);
            IScheduler          scheduler = factory.GetScheduler().Result;
            scheduler.Start().Wait();

            container.AddScoped <IScheduler>(serviceProvider =>
            {
                return(scheduler);
            });

            string env = Environment.GetEnvironmentVariable(EnvironmentConstants.ASPNETCORE_ENVIRONMENT);

            var redisServer   = Environment.GetEnvironmentVariable(EnvironmentConstants.EB_REDIS_SERVER);
            var redisPassword = Environment.GetEnvironmentVariable(EnvironmentConstants.EB_REDIS_PASSWORD);
            var redisPort     = Environment.GetEnvironmentVariable(EnvironmentConstants.EB_REDIS_PORT);

            RedisClient client = null;
            //if (env == "Staging")
            //{
            //    client = new RedisClient(redisServer, Convert.ToInt32(redisPort));
            //}
            //else
            //{
            client = new RedisClient(string.Format("redis://{0}@{1}:{2}", redisPassword, redisServer, redisPort));
            //}
            //Setting Assembly version in Redis
            AssemblyName assembly = Assembly.GetExecutingAssembly().GetName();
            String       version  = assembly.Name.ToString() + " - " + assembly.Version.ToString();
            client.Set("SchedulerAssembly", version);

            this.GlobalRequestFilters.Add((req, res, requestDto) =>
            {
                ILog log = LogManager.GetLogger(GetType());

                log.Info("In GlobalRequestFilters");
                try
                {
                    log.Info("In Try");
                    if (requestDto != null)
                    {
                        log.Info("In Auth Header");
                        var auth = req.Headers[HttpHeaders.Authorization];
                        if (string.IsNullOrEmpty(auth))
                        {
                            res.ReturnAuthRequired();
                        }
                        else
                        {
                            if (req.Headers[CacheConstants.RTOKEN] != null)
                            {
                                Resolve <IEbServerEventClient>().AddAuthentication(req);
                            }
                            var jwtoken = new JwtSecurityToken(auth.Replace("Bearer", string.Empty).Trim());
                            foreach (var c in jwtoken.Claims)
                            {
                                if (c.Type == "cid" && !string.IsNullOrEmpty(c.Value))
                                {
                                    RequestContext.Instance.Items.Add(CoreConstants.SOLUTION_ID, c.Value);
                                    if (requestDto is IEbSSRequest)
                                    {
                                        (requestDto as IEbSSRequest).SolnId = c.Value;
                                    }
                                    if (requestDto is EbServiceStackAuthRequest)
                                    {
                                        (requestDto as EbServiceStackAuthRequest).SolnId = c.Value;
                                    }
                                    continue;
                                }
                                if (c.Type == "uid" && !string.IsNullOrEmpty(c.Value))
                                {
                                    RequestContext.Instance.Items.Add("UserId", Convert.ToInt32(c.Value));
                                    if (requestDto is IEbSSRequest)
                                    {
                                        (requestDto as IEbSSRequest).UserId = Convert.ToInt32(c.Value);
                                    }
                                    if (requestDto is EbServiceStackAuthRequest)
                                    {
                                        (requestDto as EbServiceStackAuthRequest).UserId = Convert.ToInt32(c.Value);
                                    }
                                    continue;
                                }
                                if (c.Type == "wc" && !string.IsNullOrEmpty(c.Value))
                                {
                                    RequestContext.Instance.Items.Add("wc", c.Value);
                                    if (requestDto is EbServiceStackAuthRequest)
                                    {
                                        (requestDto as EbServiceStackAuthRequest).WhichConsole = c.Value.ToString();
                                    }
                                    continue;
                                }
                                if (c.Type == "sub" && !string.IsNullOrEmpty(c.Value))
                                {
                                    RequestContext.Instance.Items.Add("sub", c.Value);
                                    if (requestDto is EbServiceStackAuthRequest)
                                    {
                                        (requestDto as EbServiceStackAuthRequest).UserAuthId = c.Value.ToString();
                                    }
                                    continue;
                                }
                            }
                            log.Info("Req Filter Completed");
                        }
                    }
                }
                catch (Exception e)
                {
                    log.Info("ErrorStackTraceNontokenServices..........." + e.StackTrace);
                    log.Info("ErrorMessageNontokenServices..........." + e.Message);
                    log.Info("InnerExceptionNontokenServices..........." + e.InnerException);
                }
            });
        }