public override void Configure(Container container) { PreRequestFilters.Add((req, res) => { var roleHeader = req.GetHeader("X-role"); if (roleHeader == null) { return; } req.Items[Keywords.Session] = new AuthUserSession { UserAuthId = "1", UserAuthName = "test", Roles = new List <string> { roleHeader } }; }); ServiceExceptionHandlers.Add((req, dto, ex) => { return(DtoUtils.CreateErrorResponse(dto, ex)); }); }
public override void Configure(Container container) { // Global Configurations SetConfig(new HostConfig { DefaultContentType = MimeTypes.Json, EnableFeatures = Feature.Json, PreferredContentTypes = new List <string> { MimeTypes.Json }, MapExceptionToStatusCode = { { typeof(InabilityToProcessPayloadException), (int)HttpStatusCode.BadRequest }, } }); // Exception Handlers ServiceExceptionHandlers.Add((httpReq, request, exception) => { var message = exception.Message; Log.Error(message); Log.Error(exception.GetResponseBody()); Log.Info(httpReq.AbsoluteUri); return(exception is DeclinePaymentException ? new HttpResult( ProcessDto.GetErrorResponse(httpReq.AbsoluteUri, message, ((DeclinePaymentException)exception).ErrorCode), HttpStatusCode.OK) : new HttpResult(null, HttpStatusCode.BadRequest)); }); UncaughtExceptionHandlers.Add((req, res, operationName, ex) => { Log.Error(ex.GetResponseBody()); res.StatusCode = ex is SerializationException ? (int)HttpStatusCode.BadRequest : (int)HttpStatusCode.InternalServerError; res.EndRequest(true); }); // Global Filters PreRequestFilters.Add((req, res) => { Log.Info($"{HTTP_HEADER.HOST} : {req.UserHostAddress}"); Log.Info($"{HTTP_HEADER.USER_AGENT} : {req.UserAgent}"); Log.Info($"{HTTP_HEADER.CONTENT_LENGTH} : {req.ContentLength}"); Log.Info($"{HTTP_HEADER.CONTENT_TYPE} : {req.ContentType}"); Log.Info($"{HTTP_HEADER.ACCEPT} : {req.AcceptTypes}"); Simulate500Error.CallMqServer(); }); // Validations Plugins.Add(new ValidationFeature()); container.RegisterValidators(typeof(MerchantPaymentValidator).Assembly, typeof(MerchantPaymentAdviceValidator).Assembly, typeof(CashInValidator).Assembly, typeof(CashInAdviceValidator).Assembly, typeof(CashOutValidator).Assembly, typeof(CashOutAdviceValidator).Assembly); // IoC container.RegisterAutoWiredAs <AppSettings, IAppSettings>(); }
public override void Configure(Container container) { ServiceExceptionHandlers.Add((req, dto, ex) => { ServiceEx = ex; return(null); }); UncaughtExceptionHandlers.Add((req, res, op, ex) => { UnHandledEx = ex; }); }
public override void Configure(Container container) { Plugins.Add(new ServerEventsFeature { OnConnect = this.OnConnect, OnCreated = this.OnCreated, OnSubscribe = this.OnSubscribe, OnPublish = this.OnPublish, HeartbeatInterval = TimeSpan.FromSeconds(10), IdleTimeout = TimeSpan.FromMinutes(20), LimitToAuthenticatedUsers = false, NotifyChannelOfSubscriptions = false }); Plugins.Add(new BasicAuthFeature { HtmlRedirect = "~/login" }); SetConfig(new HostConfig { AllowSessionIdsInHttpParams = true, DebugMode = false, EnableFeatures = Feature.All.Remove(Feature.Metadata), HandlerFactoryPath = "api" }); Container.Register(c => new SseService(c.Resolve <IServerEvents>()) ); Container.Register <IRedisClientsManager>(c => new RedisManagerPool("localhost:6379") ); Container.Register <IServerEvents>(c => new RedisServerEvents(c.Resolve <IRedisClientsManager>()) ); Container.Resolve <IServerEvents>().Start(); ServiceExceptionHandlers.Add(HandleException); UncaughtExceptionHandlers.Add(HandleUnhandledException); }
public override void Configure(Container container) { JsConfig.DateHandler = DateHandler.ISO8601; var appSettings = new AppSettings(); ServiceExceptionHandlers.Add((httpReq, request, exception) => { var logger = LogManager.GetLogger(GetType()); logger.Error(exception); return(null); }); container.Register <ICacheClient>(new MemoryCacheClient { FlushOnDispose = false }); JsConfig.AssumeUtc = true; container.RegisterAs <FordereAuthEventHandler, IAuthEvents>(); container.Register <IDbConnectionFactory>( new OrmLiteConnectionFactory( "Server = {0}; Database = {1}; Uid = {2}; Pwd = {3}".Fmt( appSettings.Get("DB.Host"), appSettings.Get("DB.Name"), appSettings.Get("DB.User"), appSettings.Get("DB.Pass")), MySqlDialect.Provider)); container.Register <IUserAuthRepository>(c => new OrmLiteAuthRepository(c.Resolve <IDbConnectionFactory>())); var authProvider = new IAuthProvider[] { new CredentialsAuthProvider(), new JwtAuthProvider(appSettings), }.ToList(); if (appSettings.Get("Debug", false)) { authProvider.Add(new BasicAuthProvider()); } var authFeature = new AuthFeature(() => new FordereAuthUserService(), authProvider.ToArray()); this.Plugins.Add(new RegistrationFeature()); this.Plugins.Add(authFeature); this.Plugins.Add(new RequestLogsFeature { // do not log request bodies of requests containing passwords HideRequestBodyForRequestDtoTypes = new[] { typeof(Authenticate), typeof(Register), typeof(UpdateUserProfileRequest) }, }); if (appSettings.Get("CORS.Enabled", false)) { this.Plugins.Add( new CorsFeature( allowedOrigins: appSettings.GetString("CORS.AllowedOrigins"), allowedMethods: "OPTIONS,GET,POST,PUT,DELETE,PATCH", allowedHeaders: "Content-Type,Authorization,division_id", allowCredentials: true)); } if (appSettings.Get("Debug", false)) { this.Plugins.Add(new PostmanFeature()); this.Plugins.Add(new OpenApiFeature()); } if (appSettings.Get("Debug", false) == false) { this.Plugins.RemoveAll(x => x is MetadataFeature); } this.SetConfig(new HostConfig { // TODO SSH This sets ss-pid/ss-opt to NOT HttpOnly.. is this a security issue? AllowNonHttpOnlyCookies = true, DebugMode = appSettings.Get("Debug", false) }); this.RegisterTypedRequestFilter <ICaptchaRequest>(Filter.Captcha); this.RegisterTypedRequestFilter <EnterMatchAppointmentRequest>(Filter.EnterMatchAppointment); this.RegisterTypedRequestFilter <EnterMatchResultRequest>(Filter.EnterMatchResult); this.RegisterTypedResponseFilter <TeamDto>(Filter.TeamPlayerDetails); PreRequestFilters.Add((httpReq, httpRes) => { if (httpReq.Verb.ToUpper() == "PATCH") { httpReq.UseBufferedStream = true; } }); }
// Configure your AppHost with the necessary configuration and dependencies your App needs public override void Configure(Container container) { Plugins.Add(new PostmanFeature()); Plugins.Add(new OpenApiFeature()); SetConfig(new HostConfig { DebugMode = AppSettings.Get(nameof(HostConfig.DebugMode), false), #if DEBUG AdminAuthSecret = "adm1nSecret", // Enable Admin Access with ?authsecret=adm1nSecret #endif }); container.Register <IList <GroupModel> >(new List <GroupModel>()); GlobalRequestFilters.Add((req, resp, reqDto) => { req.Items.Add("BeginTimestamp", DateTime.Now); }); GlobalResponseFilters.Add((req, resp, respDto) => { Console.WriteLine(); Console.WriteLine(); Console.WriteLine($"**************** {nameof(GlobalResponseFilters)} ****************"); //Console.WriteLine($"***** req: {req.ToSafeJson()}"); Console.WriteLine(); var beginTimestamp = req.Items["BeginTimestamp"]; var endTimestamp = DateTime.Now; Console.WriteLine($"=====> Request at [{beginTimestamp}]"); if (req.IsAuthenticated()) { var session = req.SessionAs <CustomUserSession>(); var authRepo = container.Resolve <IAuthRepository>(); var manageRole = authRepo as IManageRoles; var roles = manageRole.GetRoles(session.UserAuthId); Console.WriteLine($" Username: {session.UserName}, Roles: {roles.ToSafeJson()}"); } Console.WriteLine($" {req.Verb}, {req.OperationName}, {req.Dto.ToSafeJson()}"); Console.WriteLine(); Console.WriteLine($"<===== Response at [{endTimestamp}]"); Console.WriteLine($" Type: {respDto.GetType().Name}"); // Console.WriteLine($"***** resp: {resp.ToSafeJson()}"); // Console.WriteLine(); if (respDto is HttpError) { var error = respDto as HttpError; var respStatus = error.ResponseStatus; Console.WriteLine($" Status: {error.Status}, {error.StatusCode}, {respStatus.ErrorCode}, {respStatus.Message}"); Console.WriteLine(); } else { object success = respDto is HttpResult ? (respDto as HttpResult).Response : respDto; Console.WriteLine($" respDto: {success.ToSafeJson()}"); Console.WriteLine(); } }); //Handle Exceptions occurring in Services: // ServiceExceptionHandlers.Add((httpReq, request, exception) => { //log your exceptions here... return(null); //continue with default Error Handling //or return your own custom response //return DtoUtils.CreateErrorResponse(request, exception); }); //Handle Unhandled Exceptions occurring outside of Services //E.g. Exceptions during Request binding or in filters: // UncaughtExceptionHandlers.Add((req, res, operationName, ex) => { res.Write($"Error: {ex.GetType().Name}: {ex.Message}"); res.EndRequest(skipHeaders: true); }); container.Register <IDbConnectionFactory>(c => new OrmLiteConnectionFactory(":memory:", SqliteDialect.Provider)); container.Register <IAuthRepository>(c => new OrmLiteAuthRepository(c.Resolve <IDbConnectionFactory>()) { UseDistinctRoleTables = true, }); container.Resolve <IAuthRepository>().InitSchema(); // // TODO: Replace OAuth App settings in: appsettings.Development.json Plugins.Add(new AuthFeature(() => new CustomUserSession(), new IAuthProvider[] { // new NetCoreIdentityAuthProvider(AppSettings) { // Adapter to enable ServiceStack Auth in MVC // AdminRoles = { "Manager" }, // Automatically Assign additional roles to Admin Users // }, new BasicAuthProvider(), //Allow Sign-ins with HTTP Basic Auth new CredentialsAuthProvider(AppSettings), // Sign In with Username / Password credentials // new FacebookAuthProvider(AppSettings), /* Create Facebook App at: https://developers.facebook.com/apps */ // new TwitterAuthProvider(AppSettings), /* Create Twitter App at: https://dev.twitter.com/apps */ // new GoogleAuthProvider(AppSettings), /* Create App https://console.developers.google.com/apis/credentials */ // new MicrosoftGraphAuthProvider(AppSettings), /* Create App https://apps.dev.microsoft.com */ }) { IncludeRegistrationService = true, IncludeAssignRoleServices = false, }); AddSeedUsers((IUserAuthRepository)container.Resolve <IAuthRepository>()); }
/// <summary> /// Configures the specified container. /// </summary> /// <param name="container">The container.</param> public override void Configure(Funq.Container container) { //new EnumSerializerConfigurator().WithAssemblies(new List<Assembly> { typeof(HierarchyNode).Assembly }).WithNullableEnumSerializers().Configure(); // this.Plugins.Add(new ValidationFeature()); this.ConfigureSerialization(); //var dialect = new SqlServerOrmLiteDialectProvider(); // var dialect = SqlServerDialect.Provider; //UTC nakoniec nezapinam, mame vlastny serializer vid EgovAppHost; //dialect.EnsureUtc(true); // Kvôli lepsej konfigurovatelnosti pouzijem MSSql Provider - ak bude cas, potvrdte/vyvratte mi tento nazor // SqlServerDialect.Provider container.Register <IDbConnectionFactory>(c => new MultiDbFactory(new OrmLiteConnectionFactory(AppSettings.GetString("ConnectionStrings:EsamConnString"), new SqlServerOrmLiteDialectProvider()))); var RedisUri = HostContext.AppSettings.GetString("RedisUri"); if (RedisUri.Contains(",")) { container.Register <IRedisClientsManager>(new RedisSentinel(RedisUri.Split(',')) { RedisManagerFactory = (master, slaves) => new RedisManagerPool(master), #if PROD HostFilter = host => "Der3dsTR6_56ff@{0}".Fmt(host) #endif }.Start()); } else { container.Register <IRedisClientsManager>(new RedisManagerPool(RedisUri)); } container.Register <IServerEvents>(c => new RedisServerEvents(c.Resolve <IRedisClientsManager>())); container.Resolve <IServerEvents>().Start(); ServiceExceptionHandlers.Add((httpReq, request, exception) => { //log your exceptions here var response = WebEasErrorHandling.CreateErrorResponse(httpReq, request, exception); if (response.Response is Exceptions.WebEasResponseStatus) { #if DEBUG ((Exceptions.WebEasResponseStatus)response.Response).DetailMessage += $"{Environment.NewLine}http://localhost:85/esam/api/pfe/lll/{exception.GetIdentifier()}"; #elif DEVELOP ((Exceptions.WebEasResponseStatus)response.Response).DetailMessage += $"{Environment.NewLine}https://esam-dev.datalan.sk/esam/api/pfe/lll/{exception.GetIdentifier()}"; #elif DEVELOPCRM ((Exceptions.WebEasResponseStatus)response.Response).DetailMessage += $"{Environment.NewLine}https://esam-crm.datalan.sk/esam/api/pfe/lll/{exception.GetIdentifier()}"; #elif ITP ((Exceptions.WebEasResponseStatus)response.Response).DetailMessage += $"{Environment.NewLine}https://esam-test.datalan.sk/esam/api/pfe/lll/{exception.GetIdentifier()}"; #endif } return(response); }); //Handle Unhandled Exceptions occurring outside of Services //E.g. Exceptions during Request binding or in filters: //this.UncaughtExceptionHandlers.Add((req, res, operationName, ex) => { //res.Write($"Error: {ex.GetType().Name}: {ex.Message}"); //res.EndRequest(skipHeaders: true); //}); }