/// <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))); } } }
/// <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)); }
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); }
private void onRequest(HttpListenerContext context) { var req = context.Request; var res = context.Response; var eventArgs = new HttpRequestEventArgs(context); if (req.HttpMethod == "GET" && !OnGet.IsNull()) { OnGet(this, eventArgs); return; } if (req.HttpMethod == "HEAD" && !OnHead.IsNull()) { OnHead(this, eventArgs); return; } if (req.HttpMethod == "POST" && !OnPost.IsNull()) { OnPost(this, eventArgs); return; } if (req.HttpMethod == "PUT" && !OnPut.IsNull()) { OnPut(this, eventArgs); return; } if (req.HttpMethod == "DELETE" && !OnDelete.IsNull()) { OnDelete(this, eventArgs); return; } if (req.HttpMethod == "OPTIONS" && !OnOptions.IsNull()) { OnOptions(this, eventArgs); return; } if (req.HttpMethod == "TRACE" && !OnTrace.IsNull()) { OnTrace(this, eventArgs); return; } if (req.HttpMethod == "CONNECT" && !OnConnect.IsNull()) { OnConnect(this, eventArgs); return; } if (req.HttpMethod == "PATCH" && !OnPatch.IsNull()) { OnPatch(this, eventArgs); return; } res.StatusCode = (int)HttpStatusCode.NotImplemented; }
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)); }
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); }
protected override void GatedTrace(string message) { OnTrace?.Invoke(message); OnLog?.Invoke(LogLevel.Trace, message); }
public static void Trace(string message, [CallerFilePath] string file = "", [CallerLineNumber] int line = 0) { OnTrace?.Invoke(message, file, line); }
private static void trace(string str) => OnTrace?.Invoke(str);