Пример #1
0
        public void Register(IAppHost appHost)
        {
            if (!string.IsNullOrEmpty(AtRestPath))
            {
                appHost.RegisterService <RequestLogsService>(AtRestPath);
            }

            var requestLogger = RequestLogger ?? new InMemoryRollingRequestLogger(Capacity);

            requestLogger.EnableSessionTracking     = EnableSessionTracking;
            requestLogger.EnableResponseTracking    = EnableResponseTracking;
            requestLogger.EnableRequestBodyTracking = EnableRequestBodyTracking;
            requestLogger.LimitToServiceRequests    = LimitToServiceRequests;
            requestLogger.SkipLogging                       = SkipLogging;
            requestLogger.RequiredRoles                     = RequiredRoles;
            requestLogger.EnableErrorTracking               = EnableErrorTracking;
            requestLogger.ExcludeRequestDtoTypes            = ExcludeRequestDtoTypes;
            requestLogger.HideRequestBodyForRequestDtoTypes = HideRequestBodyForRequestDtoTypes;
            requestLogger.RequestLogFilter                  = RequestLogFilter;
            requestLogger.IgnoreFilter                      = IgnoreFilter;
            requestLogger.CurrentDateFn                     = CurrentDateFn;

            appHost.Register(requestLogger);

            if (EnableRequestBodyTracking)
            {
                appHost.PreRequestFilters.Insert(0, (httpReq, httpRes) =>
                {
#if NETCORE
                    // https://forums.servicestack.net/t/unexpected-end-of-stream-when-uploading-to-aspnet-core/6478/6
                    if (httpReq.ContentType.MatchesContentType(MimeTypes.MultiPartFormData))
                    {
                        return;
                    }
#endif
                    httpReq.UseBufferedStream = EnableRequestBodyTracking;
                });
            }

            appHost.ConfigurePlugin <MetadataFeature>(
                feature => feature.AddDebugLink(AtRestPath, "Request Logs"));

            appHost.GetPlugin <MetadataFeature>()?.ExportTypes.Add(typeof(RequestLogEntry));

            appHost.AddToAppMetadata(meta => {
                meta.Plugins.RequestLogs = new RequestLogsInfo {
                    RequiredRoles = RequiredRoles,
                    ServiceRoutes = new Dictionary <string, string[]> {
                        { nameof(RequestLogsService), new[] { AtRestPath } },
                    },
                    RequestLogger = requestLogger.GetType().Name,
                };
            });
        }
Пример #2
0
        /// <summary>
        /// Activate the validation mechanism, so every request DTO with an existing validator
        /// will be validated.
        /// </summary>
        /// <param name="appHost">The app host</param>
        public void Register(IAppHost appHost)
        {
            if (TreatInfoAndWarningsAsErrors)
            {
                if (!appHost.GlobalRequestFiltersAsync.Contains(ValidationFilters.RequestFilterAsync))
                {
                    appHost.GlobalRequestFiltersAsync.Add(ValidationFilters.RequestFilterAsync);
                }

                if (!appHost.GlobalMessageRequestFiltersAsync.Contains(ValidationFilters.RequestFilterAsync))
                {
                    appHost.GlobalMessageRequestFiltersAsync.Add(ValidationFilters.RequestFilterAsync);
                }
            }
            else
            {
                if (!appHost.GlobalRequestFiltersAsync.Contains(ValidationFilters.RequestFilterAsyncIgnoreWarningsInfo))
                {
                    appHost.GlobalRequestFiltersAsync.Add(ValidationFilters.RequestFilterAsyncIgnoreWarningsInfo);
                }

                if (!appHost.GlobalMessageRequestFiltersAsync.Contains(ValidationFilters.RequestFilterAsyncIgnoreWarningsInfo))
                {
                    appHost.GlobalMessageRequestFiltersAsync.Add(ValidationFilters.RequestFilterAsyncIgnoreWarningsInfo);
                }

                if (!appHost.GlobalResponseFiltersAsync.Contains(ValidationFilters.ResponseFilterAsync))
                {
                    appHost.GlobalResponseFiltersAsync.Add(ValidationFilters.ResponseFilterAsync);
                }

                if (!appHost.GlobalMessageResponseFiltersAsync.Contains(ValidationFilters.ResponseFilterAsync))
                {
                    appHost.GlobalMessageResponseFiltersAsync.Add(ValidationFilters.ResponseFilterAsync);
                }
            }

            if (ValidationSource != null)
            {
                appHost.Register(ValidationSource);
                ValidationSource.InitSchema();
            }

            var container           = appHost.GetContainer();
            var hasValidationSource = ValidationSource != null || container.Exists <IValidationSource>();

            if (hasValidationSource && AccessRole != null)
            {
                appHost.RegisterServices(ServiceRoutes);
            }

            if (ScanAppHostAssemblies)
            {
                container.RegisterValidators(((ServiceStackHost)appHost).ServiceAssemblies.ToArray());
            }

            appHost.AddToAppMetadata(metadata => {
                metadata.Plugins.Validation = new ValidationInfo {
                    HasValidationSource      = hasValidationSource.NullIfFalse(),
                    HasValidationSourceAdmin = (container.TryResolve <IValidationSource>() is IValidationSourceAdmin).NullIfFalse(),
                    ServiceRoutes            = ServiceRoutes.ToMetadataServiceRoutes(),
                    TypeValidators           = !EnableDeclarativeValidation ? null
                        : appHost.ScriptContext.ScriptMethods.SelectMany(x =>
                                                                         ScriptMethodInfo.GetScriptMethods(x.GetType(), where : mi =>
                                                                                                           typeof(ITypeValidator).IsAssignableFrom(mi.ReturnType)))
                                               .Map(x => x.ToScriptMethodType()),
                    PropertyValidators = !EnableDeclarativeValidation ? null
                        : appHost.ScriptContext.ScriptMethods.SelectMany(x =>
                                                                         ScriptMethodInfo.GetScriptMethods(x.GetType(), where : mi =>
                                                                                                           typeof(IPropertyValidator).IsAssignableFrom(mi.ReturnType)))
                                         .Map(x => x.ToScriptMethodType()),
                    AccessRole = AccessRole,
                };
            });

            appHost.GetPlugin <MetadataFeature>()?.ExportTypes.Add(typeof(ValidationRule));
        }
Пример #3
0
        public void Register(IAppHost appHost)
        {
            hasRegistered = true;
            AuthenticateService.Init(sessionFactory, AuthProviders);

            var unitTest = appHost == null;

            if (unitTest)
            {
                return;
            }

            if (HostContext.StrictMode)
            {
                var sessionInstance = sessionFactory();
                if (TypeSerializer.HasCircularReferences(sessionInstance))
                {
                    throw new StrictModeException($"User Session {sessionInstance.GetType().Name} cannot have circular dependencies", "sessionFactory",
                                                  StrictModeCodes.CyclicalUserSession);
                }
            }

            appHost.RegisterServices(ServiceRoutes);

            var sessionFeature = RegisterPlugins.OfType <SessionFeature>().First();

            sessionFeature.SessionExpiry          = SessionExpiry;
            sessionFeature.PermanentSessionExpiry = PermanentSessionExpiry;

            appHost.LoadPlugin(RegisterPlugins.ToArray());

            if (IncludeAuthMetadataProvider && appHost.TryResolve <IAuthMetadataProvider>() == null)
            {
                appHost.Register <IAuthMetadataProvider>(new AuthMetadataProvider());
            }

            AuthProviders.OfType <IAuthPlugin>().Each(x => x.Register(appHost, this));

            AuthenticateService.HtmlRedirect               = HtmlRedirect;
            AuthenticateService.HtmlRedirectAccessDenied   = HtmlRedirectAccessDenied;
            AuthenticateService.HtmlRedirectReturnParam    = HtmlRedirectReturnParam;
            AuthenticateService.HtmlRedirectReturnPathOnly = HtmlRedirectReturnPathOnly;
            AuthenticateService.AuthResponseDecorator      = AuthResponseDecorator;
            if (ValidateFn != null)
            {
                AuthenticateService.ValidateFn = ValidateFn;
            }

            var authNavItems = AuthProviders.Select(x => (x as AuthProvider)?.NavItem).Where(x => x != null);

            if (!ViewUtils.NavItemsMap.TryGetValue("auth", out var navItems))
            {
                ViewUtils.NavItemsMap["auth"] = navItems = new List <NavItem>();
            }

            var isDefaultHtmlRedirect = HtmlRedirect == "~/" + LocalizedStrings.Login.Localize();

            if (IncludeDefaultLogin && isDefaultHtmlRedirect && !appHost.VirtualFileSources.FileExists("/login.html"))
            {
                appHost.VirtualFileSources.GetMemoryVirtualFiles().WriteFile("/login.html",
                                                                             Templates.HtmlTemplates.GetLoginTemplate());
            }

            navItems.AddRange(authNavItems);

            appHost.AddToAppMetadata(meta => {
                meta.Plugins.Auth = new AuthInfo {
                    HasAuthSecret       = (appHost.Config.AdminAuthSecret != null).NullIfFalse(),
                    HasAuthRepository   = appHost.GetContainer().Exists <IAuthRepository>().NullIfFalse(),
                    IncludesRoles       = IncludeRolesInAuthenticateResponse.NullIfFalse(),
                    IncludesOAuthTokens = IncludeOAuthTokensInAuthenticateResponse.NullIfFalse(),
                    HtmlRedirect        = HtmlRedirect?.TrimStart('~'),
                    AuthProviders       = AuthenticateService.GetAuthProviders().Map(x => new MetaAuthProvider {
                        Type    = x.Type,
                        Name    = x.Provider,
                        NavItem = (x as AuthProvider)?.NavItem,
                        Meta    = x.Meta,
                    })
                };
            });
        }