Exemple #1
0
        /// <summary>
        /// Process an individual request.
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override Task Invoke(IOwinContext context)
        {
            using (var scope = DIContainer.Current.BeginLifetimeScope())
            {
                try
                {
                    // Starts execution measurement
                    scope.Container.Resolve <IStopwatchProvider>().StartMeasurement();

                    // Tracing

                    var settings = scope.Container.Resolve <ISimplifyWebSettings>();

                    if (settings.ConsoleTracing)
                    {
                        TraceToConsole(context);
                    }

                    OnTrace?.Invoke(context);

                    // Setup providers

                    var webContextProvider      = scope.Container.Resolve <IWebContextProvider>();
                    var languageManagerProvider = scope.Container.Resolve <ILanguageManagerProvider>();
                    var templateFactory         = scope.Container.Resolve <ITemplateFactory>();
                    var fileReader  = scope.Container.Resolve <IFileReader>();
                    var stringTable = scope.Container.Resolve <IStringTable>();

                    webContextProvider.Setup(context);
                    languageManagerProvider.Setup(context);
                    templateFactory.Setup();
                    fileReader.Setup();
                    stringTable.Setup();

                    // Run request process pipeline

                    var requestHandler = scope.Container.Resolve <IRequestHandler>();
                    return(requestHandler.ProcessRequest(scope.Container, context));
                }
                catch (Exception e)
                {
                    try
                    {
                        context.Response.StatusCode = 500;

                        ProcessOnException(e);
                    }
                    catch (Exception exception)
                    {
                        return
                            (context.Response.WriteAsync(ExceptionInfoPageGenerator.Generate(exception,
                                                                                             scope.Container.Resolve <ISimplifyWebSettings>().HideExceptionDetails)));
                    }

                    return
                        (context.Response.WriteAsync(ExceptionInfoPageGenerator.Generate(e,
                                                                                         scope.Container.Resolve <ISimplifyWebSettings>().HideExceptionDetails)));
                }
            }
        }
Exemple #2
0
        /// <inheritdoc cref="IAuthenticator" />
        public override Task <bool> AuthenticateAsync(HttpClient httpClient, CancellationToken ct = default)
        {
            _ = httpClient ?? throw new ArgumentNullException(nameof(httpClient));

            if (!ReplaceAuthorizationHeader && httpClient.DefaultRequestHeaders.Authorization != null)
            {
                OnTrace?.Invoke($"Request header '{nameof(httpClient.DefaultRequestHeaders.Authorization)}' already set");
                return(Task.FromResult(false));
            }

            return(GetAndSetTokenAsync(httpClient, ct));
        }
Exemple #3
0
        private async Task <bool> GetAndSetTokenAsync(HttpClient httpClient, CancellationToken ct = default)
        {
            var localToken = await GetTokenAsync(ct).ConfigureAwait(false);

            if (localToken != null)
            {
                httpClient.SetBearerToken(localToken.AccessToken);
                Header = httpClient.DefaultRequestHeaders.Authorization;
                return(true);
            }

            OnTrace?.Invoke($"{nameof(localToken)} response could not be set.");
            return(false);
        }
        /// <summary>
        /// Create a new instance of <see cref="UnlocLoader"/>.
        /// </summary>
        public UnlocLoader()
        {
            var locationParser = new LocationParser();

            _countryLoader  = new CountryLoader();
            _locationLoader = new LocationLoader(locationParser);
            _fileDownloader = new FileDownloader();

            _countryLoader.OnInfo  += (sender, s) => OnInfo?.Invoke(sender, s);
            _countryLoader.OnWarn  += (sender, s) => OnWarn?.Invoke(sender, s);
            _countryLoader.OnTrace += (sender, s) => OnTrace?.Invoke(sender, s);

            _locationLoader.OnInfo  += (sender, s) => OnInfo?.Invoke(sender, s);
            _locationLoader.OnWarn  += (sender, s) => OnWarn?.Invoke(sender, s);
            _locationLoader.OnTrace += (sender, s) => OnTrace?.Invoke(sender, s);
        }
Exemple #5
0
 private static void CopyToTrace(string directory, string message, LogLevel level)
 {
     OnTrace?.Invoke(string.Format("[{0}]:[{1}] [{2}] {3}", DateTime.Now.TimeOfDay, level.ToString(), directory,
                                   message));
 }
Exemple #6
0
        public async Task <TokenResponse?> GetTokenAsync(CancellationToken ct = default)
        {
            if (token == null || DateTime.Now >= tokenExpiry)
            {
                var discovery = await discoveryCache.GetAsync().ConfigureAwait(false);

                if (discovery.IsError)
                {
                    OnTrace?.Invoke($"{nameof(discovery)} response has errors: {discovery.Error}");
                    return(token);
                }

                if (token == null)
                {
                    switch (oidcSettings.GrantType)
                    {
                    case OidcConstants.GrantTypes.Password:
                        using (var tokenRequest = new PasswordTokenRequest
                        {
                            Address = discovery.TokenEndpoint,
                            ClientId = oidcSettings.ClientId,
                            ClientSecret = oidcSettings.ClientSecret,
                            Scope = oidcSettings.Scope,
                            UserName = oidcSettings.Username,
                            Password = oidcSettings.Password
                        })
                        {
                            token = await httpClient.RequestPasswordTokenAsync(tokenRequest, ct).ConfigureAwait(false);

                            break;
                        }

                    case OidcConstants.GrantTypes.ClientCredentials:
                        using (var tokenRequest = new ClientCredentialsTokenRequest
                        {
                            Address = discovery.TokenEndpoint,
                            ClientId = oidcSettings.ClientId,
                            ClientSecret = oidcSettings.ClientSecret,
                            Scope = oidcSettings.Scope
                        })
                        {
                            token = await httpClient.RequestClientCredentialsTokenAsync(tokenRequest, ct).ConfigureAwait(false);

                            break;
                        }

                    case OidcConstants.GrantTypes.AuthorizationCode:
                        using (var tokenRequest = new AuthorizationCodeTokenRequest
                        {
                            Address = discovery.TokenEndpoint,
                            ClientId = oidcSettings.ClientId,
                            ClientSecret = oidcSettings.ClientSecret,
                            Code = oidcSettings.Code,
                            RedirectUri = oidcSettings.RedirectUri?.ToString(),
                            CodeVerifier = oidcSettings.CodeVerifier
                        })
                        {
                            token = await httpClient.RequestAuthorizationCodeTokenAsync(tokenRequest, ct).ConfigureAwait(false);

                            break;
                        }

                    default:
                        throw new NotSupportedException($"Grant type '{oidcSettings.GrantType}' is not supported");
                    }
                }
                else
                {
                    using var request = new RefreshTokenRequest
                          {
                              Address      = discovery.TokenEndpoint,
                              ClientId     = oidcSettings.ClientId,
                              ClientSecret = oidcSettings.ClientSecret,
                              Scope        = oidcSettings.Scope,
                              RefreshToken = token.RefreshToken
                          };
                    token = await httpClient.RequestRefreshTokenAsync(request, ct).ConfigureAwait(false);
                }

                if (token.IsError)
                {
                    OnTrace?.Invoke($"{nameof(token)} response has errors: {token.Error}");
                    return(token);
                }

                tokenExpiry = DateTime.Now.AddSeconds(token.ExpiresIn - 10);
            }

            return(token);
        }
Exemple #7
0
 protected override void GatedTrace(string message)
 {
     OnTrace?.Invoke(message);
     OnLog?.Invoke(LogLevel.Trace, message);
 }
Exemple #8
0
 public static void Trace(string message, [CallerFilePath] string file = "", [CallerLineNumber] int line = 0)
 {
     OnTrace?.Invoke(message, file, line);
 }
Exemple #9
0
 private static void trace(string str) => OnTrace?.Invoke(str);