public static void Bootstrap(Container container)
        {
            _container = container;

            if (container == null)
            {
                throw new ArgumentNullException(nameof(container));
            }
            //container.RegisterSingleton<IPrincipal>(new HttpContextPrinciple());
            container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle();//new WebRequestLifestyle();
            container.RegisterSingleton <IHttpContextAccessor, HttpContextAccessor>();

            container.Register(typeof(IBaseCommand <>), new[] { Assembly.GetExecutingAssembly() }, Lifestyle.Scoped);//, Lifestyle.Scoped
            //container.RegisterCollection(typeof(ICommand), new[] { Assembly.GetExecutingAssembly()});

            container.RegisterDecorator(typeof(IBaseCommand <>), typeof(ConfirmPasswordCheckDecorator <>), Lifestyle.Scoped);
            container.RegisterDecorator(typeof(IBaseCommand <>), typeof(EmailShouldNotExistDecorator <>), Lifestyle.Scoped);
            container.RegisterDecorator(typeof(IBaseCommand <>), typeof(AuthorizationCommandDecorator <>), Lifestyle.Scoped);


            //container.Register(typeof(BaseQuery<,>), new[] { Assembly.GetExecutingAssembly() });

            container.RegisterInitializer <IBaseHandler>(handler =>
            {
                try
                {
                    var accesor  = container.GetInstance <IHttpContextAccessor>();
                    var userName = accesor.HttpContext?.User?.Identity?.Name;
                    if (string.IsNullOrEmpty(userName))
                    {
                        return;
                    }

                    handler.User = UserExtensions.GetUser(userName).User;
                }
                catch
                {
                }
            });
        }
Esempio n. 2
0
        /// <summary>
        /// Search
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public virtual IEnumerable <SearchResult> Search(Query query)
        {
            List <ContentReference> searchRoots = null;
            var searchText = query.SearchQuery;

            if (query.SearchRoots?.Any() == true)
            {
                searchRoots = new List <ContentReference>();

                foreach (var item in query.SearchRoots)
                {
                    if (ContentReference.TryParse(item, out var c))
                    {
                        searchRoots.Add(c);
                    }
                }
            }

            var typeRestriction = typeof(TContent).GetSearchTypesFor(VulcanFieldConstants.DefaultFilter);

            // Special condition for BlockData since it doesn't derive from BlockData
            if (typeof(TContent) == typeof(VulcanContentHit))
            {
                typeRestriction = typeof(BlockData).GetSearchTypesFor(VulcanFieldConstants.DefaultFilter);
            }

            var hits = new List <ISearchResponse <IContent> >();

            var clients = VulcanHandler.GetClients();

            if (clients != null)
            {
                // ReSharper disable once LoopCanBeConvertedToQuery
                foreach (var client in clients)
                {
                    if (client.Language.Equals(CultureInfo.InvariantCulture) && !IncludeInvariant)
                    {
                        continue;
                    }

                    var clientHits = client.SearchContent <IContent>(d => d
                                                                     .Take(query.MaxResults)
                                                                     .FielddataFields(fs => fs.Field(p => p.ContentLink)) // only return id for performance
                                                                     .Query(x =>
                                                                            x.SimpleQueryString(sqs =>
                                                                                                sqs.Fields(f => f
                                                                                                           .AllAnalyzed()
                                                                                                           .Field($"{VulcanFieldConstants.MediaContents}.content")
                                                                                                           .Field($"{VulcanFieldConstants.MediaContents}.content_type"))
                                                                                                .Query(searchText))
                                                                            ),
                                                                     typeFilter: typeRestriction,
                                                                     includeNeutralLanguage: client.Language.Equals(CultureInfo.InvariantCulture),
                                                                     rootReferences: searchRoots,
                                                                     principleReadFilter: UserExtensions.GetUser()
                                                                     );

                    if (clientHits?.Total > 0)
                    {
                        hits.Add(clientHits);
                    }
                }
            }

            var results = hits.SelectMany(h => h.Hits.Select(CreateSearchResult));

            return(results);
        }
Esempio n. 3
0
        protected override async Task <AuthenticateResult> HandleAuthenticateAsync()
        {
            string             token  = null;
            AuthenticateResult result = null;

            try
            {
                // Give application opportunity to find from a different location, adjust, or reject token
                var messageReceivedContext = new MessageReceivedContext(Context, Options);

                // event can set the token
                await Options.Events.MessageReceived(messageReceivedContext);

                if (messageReceivedContext.CheckEventResult(out result))
                {
                    return(result);
                }

                // If application retrieved token from somewhere else, use that.
                token = messageReceivedContext.Token;

                if (string.IsNullOrEmpty(token))
                {
                    string authorization = Request.Headers["Authorization"];

                    // If no authorization header found, nothing to process further
                    if (string.IsNullOrEmpty(authorization))
                    {
                        return(AuthenticateResult.Skip());
                    }

                    if (authorization.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
                    {
                        token = authorization.Substring("Bearer ".Length).Trim();
                    }

                    // If no token found, no further work possible
                    if (string.IsNullOrEmpty(token))
                    {
                        return(AuthenticateResult.Skip());
                    }
                }

                var validationParameters = await Param();

                List <Exception> validationFailures = null;
                SecurityToken    validatedToken;
                foreach (var validator in Options.SecurityTokenValidators)
                {
                    if (validator.CanReadToken(token))
                    {
                        ClaimsPrincipal principal;
                        try
                        {
                            principal = validator.ValidateToken(token, validationParameters, out validatedToken);
                        }
                        catch (Exception ex)
                        {
                            // Refresh the configuration for exceptions that may be caused by key rollovers. The user can also request a refresh in the event.
                            if (Options.RefreshOnIssuerKeyNotFound && Options.ConfigurationManager != null &&
                                ex is SecurityTokenSignatureKeyNotFoundException)
                            {
                                Options.ConfigurationManager.RequestRefresh();
                            }

                            if (validationFailures == null)
                            {
                                validationFailures = new List <Exception>(1);
                            }
                            validationFailures.Add(ex);
                            continue;
                        }


                        var ticket = new AuthenticationTicket(principal, new AuthenticationProperties(), Options.AuthenticationScheme);
                        var tokenValidatedContext = new TokenValidatedContext(Context, Options)
                        {
                            Ticket        = ticket,
                            SecurityToken = validatedToken,
                        };

                        await Options.Events.TokenValidated(tokenValidatedContext);

                        if (tokenValidatedContext.CheckEventResult(out result))
                        {
                            return(result);
                        }
                        ticket = tokenValidatedContext.Ticket;


                        string email = ticket.Principal.Identity.Name;
                        var    user  = UserExtensions.GetUser(ticket.Principal.Identity.Name);
                        if (user.User.Status != UserStatus.Active)
                        {
                            return(AuthenticateResult.Skip());
                        }

                        if (Options.SaveToken)
                        {
                            ticket.Properties.StoreTokens(new[]
                            {
                                new AuthenticationToken {
                                    Name = "access_token", Value = token
                                }
                            });
                        }

                        return(AuthenticateResult.Success(ticket));
                    }
                }
                if (validationFailures != null)
                {
                    var authenticationFailedContext = new AuthenticationFailedContext(Context, Options)
                    {
                        Exception = (validationFailures.Count == 1) ? validationFailures[0] : new AggregateException(validationFailures)
                    };

                    await Options.Events.AuthenticationFailed(authenticationFailedContext);

                    if (authenticationFailedContext.CheckEventResult(out result))
                    {
                        return(result);
                    }

                    return(AuthenticateResult.Fail(authenticationFailedContext.Exception));
                }

                return(AuthenticateResult.Fail("No SecurityTokenValidator available for token: " + token ?? "[null]"));
            }
            catch (Exception ex)
            {
                var authenticationFailedContext = new AuthenticationFailedContext(Context, Options)
                {
                    Exception = ex
                };

                await Options.Events.AuthenticationFailed(authenticationFailedContext);

                if (authenticationFailedContext.CheckEventResult(out result))
                {
                    return(result);
                }

                throw;
            }
        }