Esempio n. 1
0
        /// <summary>
        /// Application specific configuration
        /// This method should initialize any IoC resources utilized by your web service classes.
        /// </summary>
        public override void Configure(Container container)
        {
            SetConfig(new HostConfig
            {
                //EnableFeatures = Feature.All.Remove(Feature.Metadata),
                //DebugMode = false
            });

            JsConfig.IncludeNullValues = false;
            JsConfig.ExcludeTypeInfo   = true;
            JsConfig.DateHandler       = DateHandler.ISO8601;

            #region Database
            var dbFactory = new OrmLiteConnectionFactory(
                AppSettings.Get("dbConnectionString", ""), SqlServer2008Dialect.Provider);

            container.Register <IDbConnectionFactory>(dbFactory);

            OrmLiteConfig.StringFilter = s => s.Trim();
            #endregion

            #region Plugins
            Plugins.Add(new CorsFeature(
                            allowedHeaders: "Content-Type, Allow, Authorization"));

            Plugins.Add(new OpenApiFeature()
            {
                ApiDeclarationFilter = declaration =>
                {
                    declaration.Info.Title = "Badges Molex";
                    //declaration.Info.Contact = new ServiceStack.Api.OpenApi.Specification.OpenApiContact()
                    //{
                    //    Email = "*****@*****.**",
                    //    Name = "Alfredo Pacheco"
                    //};
                    declaration.Info.Description = "";
                },
                OperationFilter = (verb, op) =>
                {
                    switch (verb)
                    {
                    case "POST":
                        op.Parameters.RemoveAll(p => p.Name == "Id");
                        op.Parameters.RemoveAll(p => p.Name == "RowVersion");
                        break;

                    default:
                        break;
                    }
                    op.Parameters.RemoveAll(p => p.Name == "EntityName");
                    op.Parameters.RemoveAll(p => p.Name == "EF_State");
                }
            });
            #endregion

            #region Auth
            var authProviders = new List <IAuthProvider>
            {
                new JwtAuthProvider(AppSettings)
                {
                    RequireSecureConnection = false,
                    AllowInQueryString      = true
                },
                new CredentialsAuthProvider()
            };

            var authFeature = new AuthFeature(SessionFactory, authProviders.ToArray());
            Plugins.Add(authFeature);

            //var authRepo = new OrmLiteAuthRepository(dbFactory);
            //container.Register<IUserAuthRepository>(authRepo);

            //authRepo.InitSchema();

            //Plugins.Add(new RegistrationFeature());

            //var admin = authRepo.GetUserAuthByUserName("admin");
            //if (admin == null)
            //    authRepo.CreateUserAuth(new UserAuth
            //    {
            //        UserName = "******",
            //        Roles = new List<string> { RoleNames.Admin }
            //    }, "admin");
            #endregion

            //TODO:
            //Done. Global Response Filter: CommonResponse.
            //Done. Cache.
            //Done. Transactions.
            //Logging.
            //Batched requests.
            //attachments
            //Profiler.
            //Versioning.
            //Compression.
            //Autoquery.
            //stripe.com

            #region Cache
            //container.Register<ICacheClient>(new MemoryCacheClient());
            #endregion

            #region App
            //container.Register(c => dbFactory.Open());
            //container.Register(c => c.Resolve<IDbConnectionFactory>().OpenDbConnection()).ReusedWithin(ReuseScope.Request);
            container.RegisterAutoWiredType(typeof(ILogicReadOnly <>), ReuseScope.Request);
            container.RegisterAutoWiredType(typeof(ILogicWrite <>), ReuseScope.Request);
            container.RegisterAutoWiredType(typeof(IDocumentLogic <>), ReuseScope.Request);

            container.RegisterAutoWired <RevisionLogic>().ReusedWithin(ReuseScope.Request);
            container.RegisterAutoWired <TrackLogic>().ReusedWithin(ReuseScope.Request);
            container.Register <IEmailService>(i => new MailgunService()).ReusedWithin(ReuseScope.Request);

            //This App:
            ///start:generated:di<<<
            container.RegisterAutoWired <EmailLogic>().ReusedWithin(ReuseScope.Request);
            container.RegisterAutoWired <UserLogic>().ReusedWithin(ReuseScope.Request);
            container.RegisterAutoWired <AdditionalFieldLogic>().ReusedWithin(ReuseScope.Request);
            container.RegisterAutoWired <AdvancedSortLogic>().ReusedWithin(ReuseScope.Request);
            container.RegisterAutoWired <BadgeLogic>().ReusedWithin(ReuseScope.Request);
            container.RegisterAutoWired <CatalogLogic>().ReusedWithin(ReuseScope.Request);
            container.RegisterAutoWired <CatalogTypeLogic>().ReusedWithin(ReuseScope.Request);
            container.RegisterAutoWired <FilterDataLogic>().ReusedWithin(ReuseScope.Request);
            container.RegisterAutoWired <SortDataLogic>().ReusedWithin(ReuseScope.Request);
            container.RegisterAutoWired <TokenLogic>().ReusedWithin(ReuseScope.Request);
            ///end:generated:di<<<
            #endregion
        }
Esempio n. 2
0
        // 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>());
        }