Skip to content

Commit

Permalink
Merge pull request #26 from SaintAngeLs/dev
Browse files Browse the repository at this point in the history
Merge with dev -- update the sign-in with respect to the blazor component  #19
  • Loading branch information
SaintAngeLs authored Mar 17, 2024
2 parents f5b16ab + e97b07e commit 8b6e214
Show file tree
Hide file tree
Showing 15 changed files with 165 additions and 74 deletions.
Empty file modified MiniSpace.APIGateway/scripts/dockerize-tag-push.sh
100644 → 100755
Empty file.
Original file line number Diff line number Diff line change
Expand Up @@ -127,8 +127,7 @@ modules:
auth: false
use: downstream
downstream: identity-service/sign-in
responseHeaders:
content-type: application/json


services:
identity-service:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ generateTraceId: true
useLocalUrl: false
loadBalancer:
enabled: false
url: fabio:9999
url: faibo:9999

extensions:
customErrors:
Expand Down
24 changes: 13 additions & 11 deletions MiniSpace.APIGateway/src/MiniSpace.APIGateway/ntrada.yml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ generateTraceId: true
useLocalUrl: true
loadBalancer:
enabled: false
url: localhost:9999
url: faibo:9999

extensions:
customErrors:
Expand All @@ -27,11 +27,13 @@ extensions:
cors:
allowCredentials: true
allowedOrigins:
- '*'
- 'http://localhost:5606'
allowedMethods:
- post
- put
- delete
- GET
- POST
- PUT
- DELETE
- OPTIONS
allowedHeaders:
- '*'
exposedHeaders:
Expand All @@ -42,10 +44,10 @@ extensions:

jwt:
issuerSigningKey: eiquief5phee9pazo0Faegaez9gohThailiur5woy2befiech1oarai4aiLi6ahVecah3ie9Aiz6Peij
validIssuer: pacco
validIssuer: minispace
validateAudience: false
validateIssuer: true
validateLifetime: true
validateIssuer: false
validateLifetime: false

swagger:
name: MiniSpace
Expand Down Expand Up @@ -73,7 +75,7 @@ modules:


identity:
path: identity
path: /identity
routes:
- upstream: /users/{userId}
method: GET
Expand Down Expand Up @@ -103,8 +105,8 @@ modules:
use: downstream
downstream: identity-service/sign-in
auth: false
responseHeaders:
content-type: application/json



services:
identity-service:
Expand Down
Empty file modified MiniSpace.Services.Identity/scripts/dockerize-tag-push.sh
100644 → 100755
Empty file.
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
"service": "identity-service",
"address": "docker.for.win.localhost",
"port": "5004",
"pingEnabled": true,
"pingEnabled": false,
"pingEndpoint": "ping",
"pingInterval": 3,
"removeAfterInterval": 3
Expand All @@ -37,10 +37,10 @@
},
"issuerSigningKey": "eiquief5phee9pazo0Faegaez9gohThailiur5woy2befiech1oarai4aiLi6ahVecah3ie9Aiz6Peij",
"expiryMinutes": 60,
"issuer": "pacco",
"issuer": "minispace",
"validateAudience": false,
"validateIssuer": false,
"validateLifetime": true,
"validateLifetime": false,
"allowAnonymousEndpoints": ["/sign-in", "/sign-up"]
},
"logger": {
Expand Down Expand Up @@ -93,7 +93,7 @@
"influxEnabled": false,
"prometheusEnabled": true,
"influxUrl": "http://localhost:8086",
"database": "pacco",
"database": "minispace",
"env": "local",
"interval": 5
},
Expand Down
22 changes: 16 additions & 6 deletions MiniSpace.Web/Dockerfile
Original file line number Diff line number Diff line change
@@ -1,11 +1,21 @@
FROM mcr.microsoft.com/dotnet/core/sdk:3.1 AS build
# Use the .NET 6 SDK for building the project
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
WORKDIR /app

# Copy everything and publish the release
COPY . .
RUN dotnet publish src/MiniSpace.Web -c release -o out
RUN dotnet publish src/MiniSpace.Web -c Release -o out

FROM mcr.microsoft.com/dotnet/core/aspnet:3.1
# Use the .NET 6 runtime for the final image
FROM mcr.microsoft.com/dotnet/aspnet:8.0
WORKDIR /app

# Copy the published app from the build stage
COPY --from=build /app/out .
ENV ASPNETCORE_URLS http://*:80
ENV ASPNETCORE_ENVIRONMENT docker
ENTRYPOINT dotnet MiniSpace.Web.dll

# Set environment variables
ENV ASPNETCORE_URLS=http://*:80
ENV ASPNETCORE_ENVIRONMENT=docker

# Start the application
ENTRYPOINT ["dotnet", "MiniSpace.Web.dll"]
Empty file modified MiniSpace.Web/scripts/dockerize-tag-push.sh
100644 → 100755
Empty file.
1 change: 1 addition & 0 deletions MiniSpace.Web/src/MiniSpace.Web/DTO/JwtDto.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ public class JwtDto
{
public string AccessToken { get; set; }
public string Role { get; set; }
public string RefreshToken { get; set; }
public long Expires { get; set; }
}
}
118 changes: 73 additions & 45 deletions MiniSpace.Web/src/MiniSpace.Web/HttpClients/CustomHttpClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Polly;
Expand All @@ -11,43 +12,51 @@ namespace MiniSpace.Web.HttpClients
{
public class CustomHttpClient : IHttpClient
{
private static readonly JsonSerializerOptions JsonSerializerOptions = new JsonSerializerOptions
private static readonly JsonSerializerSettings JsonSerializerSettings = new JsonSerializerSettings
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
PropertyNameCaseInsensitive = true,
IgnoreNullValues = true
ContractResolver = new CamelCasePropertyNamesContractResolver(),
NullValueHandling = NullValueHandling.Ignore
};

private readonly HttpClient _client;
private readonly HttpClientOptions _options;
private readonly ILogger<IHttpClient> _logger;

public CustomHttpClient(HttpClient client, HttpClientOptions options, ILogger<IHttpClient> logger)
{
_client = client;
_options = options;
_logger = logger;
_client.BaseAddress = new Uri(options.ApiUrl);
}

public void SetAccessToken(string accessToken)
=> _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

public void SetAccessToken(string token)
{
_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
}

public async Task<T> GetAsync<T>(string uri)
{
var (success, content) = await TryExecuteAsync(uri, client => client.GetAsync(uri));

return !success ? default : Parse<T>(content);
return !success ? default : JsonConvert.DeserializeObject<T>(content, JsonSerializerSettings);
}

public Task PostAsync<T>(string uri, T request)
=> TryExecuteAsync(uri, client => client.PostAsync(uri, GetPayload(request)));
{
var jsonPayload = JsonConvert.SerializeObject(request, JsonSerializerSettings);
_logger.LogDebug($"Sending HTTP POST request to URI: {uri} with payload: {jsonPayload}");
return TryExecuteAsync(uri, client => client.PostAsync(uri, GetPayload(request)));
}

public async Task<TResult> PostAsync<TRequest, TResult>(string uri, TRequest request)
{
var jsonPayload = JsonConvert.SerializeObject(request, JsonSerializerSettings);
_logger.LogDebug($"Sending HTTP POST request to URI: {uri} with payload: {jsonPayload}");

var (success, content) = await TryExecuteAsync(uri, client => client.PostAsync(uri, GetPayload(request)));

return !success ? default : Parse<TResult>(content);
return !success ? default : JsonConvert.DeserializeObject<TResult>(content, JsonSerializerSettings);
}

public Task PutAsync<T>(string uri, T request)
Expand All @@ -57,42 +66,61 @@ public async Task<TResult> PutAsync<TRequest, TResult>(string uri, TRequest requ
{
var (success, content) = await TryExecuteAsync(uri, client => client.PutAsync(uri, GetPayload(request)));

return !success ? default : Parse<TResult>(content);
return !success ? default : JsonConvert.DeserializeObject<TResult>(content, JsonSerializerSettings);
}

public Task DeleteAsync(string uri)
=> TryExecuteAsync(uri, client => client.DeleteAsync(uri));

private static StringContent GetPayload<T>(T request)
=> new StringContent(JsonSerializer.Serialize(request, JsonSerializerOptions), Encoding.UTF8,
"application/json");

private Task<(bool success, string content)> TryExecuteAsync(string uri,
Func<HttpClient, Task<HttpResponseMessage>> client)
=> Policy.Handle<Exception>()
.WaitAndRetryAsync(_options.Retries, r => TimeSpan.FromSeconds(Math.Pow(2, r)))
.ExecuteAsync(async () =>
{
var json = JsonConvert.SerializeObject(request, JsonSerializerSettings);
// Set content type with charset parameter
return new StringContent(json, Encoding.UTF8, "text/plain");
}



private Task<(bool success, string content)> TryExecuteAsync(string uri, Func<HttpClient, Task<HttpResponseMessage>> client)
=> Policy.Handle<Exception>()
.WaitAndRetryAsync(_options.Retries, r => TimeSpan.FromSeconds(Math.Pow(2, r)))
.ExecuteAsync(async () =>
{
if (_client.BaseAddress != null && !Uri.IsWellFormedUriString(uri, UriKind.Absolute))
{
if (!uri.StartsWith("/")) uri = "/" + uri;

uri = new Uri(_client.BaseAddress, uri).ToString();
}
else if (!Uri.IsWellFormedUriString(uri, UriKind.Absolute))
{
_logger.LogError($"The provided URI '{uri}' is not a valid absolute URL and no BaseAddress is set.");
return default;
}

_logger.LogDebug($"Sending HTTP request to URI: {uri}");
using (var response = await client(_client))
{
if (response.IsSuccessStatusCode)
{
uri = uri.StartsWith("http://") ? uri : $"http://{uri}";
_logger.LogDebug($"Sending HTTP request to URI: {uri}");
using (var response = await client(_client))
{
if (response.IsSuccessStatusCode)
{
_logger.LogDebug($"Received a valid response to HTTP request from URI: {uri}" +
$"{Environment.NewLine}{response}");

return (true, await response.Content.ReadAsStringAsync());
}

_logger.LogError($"Received an invalid response to HTTP request from URI: {uri}" +
$"{Environment.NewLine}{response}");

return default;
}
});

private static T Parse<T>(string content)
=> string.IsNullOrWhiteSpace(content) ? default : JsonSerializer.Deserialize<T>(content, JsonSerializerOptions);
_logger.LogDebug($"Received a valid response to HTTP request from URI: {uri}" +
$"{Environment.NewLine}{response}");

return (true, await response.Content.ReadAsStringAsync());
}

if (!response.IsSuccessStatusCode)
{
var errorContent = await response.Content.ReadAsStringAsync();
_logger.LogError($"Error response from server: {errorContent}");
}

_logger.LogError($"Received an invalid response to HTTP request from URI: {uri}" +
$"{Environment.NewLine}{response}");

return default;
}
});

}
}
}
7 changes: 5 additions & 2 deletions MiniSpace.Web/src/MiniSpace.Web/MiniSpace.Web.csproj
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
</PropertyGroup>


<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Polly" Version="7.1.1" />
<PackageReference Include="System.Net.Http.Json" Version="8.0.0" />
</ItemGroup>

</Project>
25 changes: 25 additions & 0 deletions MiniSpace.Web/src/MiniSpace.Web/Pages/Greeting.razor
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
@page "/greeting"
@using Microsoft.AspNetCore.Components.Authorization
@inject AuthenticationStateProvider AuthenticationStateProvider

<h1>Greeting</h1>


@if (userName != null)
{
<p>Hello, @userName!</p>
}
else
{
<p>Loading...</p>
}

@code {
private string userName;

protected override async Task OnInitializedAsync()
{
var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
userName = authState.User.Identity.Name;
}
}
Loading

0 comments on commit 8b6e214

Please sign in to comment.