Skip to content

Commit

Permalink
Update (#30)
Browse files Browse the repository at this point in the history
  • Loading branch information
atrakic authored Jan 2, 2025
1 parent 529ad65 commit c01d126
Show file tree
Hide file tree
Showing 4 changed files with 69 additions and 16 deletions.
65 changes: 57 additions & 8 deletions src/EchoApi/EndpointMappings.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
using System.Drawing;

using EchoApi.Auth;
using EchoApi.DAL;
using EchoApi.Model;
Expand All @@ -13,9 +15,11 @@ namespace EchoApi;

public static class EndpointMappings
{
private const string API_VERSION = "v1";
private const string API_BASE_PATH = "/api/" + API_VERSION;
public static void MapEchoApiV1(this IEndpointRouteBuilder group)
{
group.MapGet("/healthz", () => Results.Ok());
group.MapGet("/healthz", () => Results.Ok("Healthy")).WithOpenApi();
group.MapPost("/token", (TokenService tokenService, [FromBody] UserCredentials credentials) =>
{
bool isValidUser = AuthenticateUser(credentials);
Expand All @@ -31,11 +35,53 @@ public static void MapEchoApiV1(this IEndpointRouteBuilder group)
}
});

group.MapGet("/", GetAllMessages).RequireAuthorization().WithOpenApi();
group.MapPost("/", CreateMessage).RequireAuthorization().WithOpenApi();
group.MapGet("/api/message/{id:int}", GetMessageById).RequireAuthorization().WithOpenApi();
group.MapPut("/api/message/{id}", UpdateMessage).RequireAuthorization().WithOpenApi();
group.MapDelete("/api/message/{id}", DeleteMessage).RequireAuthorization().WithOpenApi();
group.MapGet(API_BASE_PATH, GetHttpRequestContext).WithOpenApi();
group.MapGet(API_BASE_PATH + "/message", GetAllMessages).RequireAuthorization().WithOpenApi();
group.MapPost(API_BASE_PATH + "/message", CreateMessage).RequireAuthorization().WithOpenApi();
group.MapGet(API_BASE_PATH + "/message/{id:int}", GetMessageById).RequireAuthorization().WithOpenApi();
group.MapPut(API_BASE_PATH + "/message/{id}", UpdateMessage).RequireAuthorization().WithOpenApi();
group.MapDelete(API_BASE_PATH + "/message/{id}", DeleteMessage).RequireAuthorization().WithOpenApi();
}

private static IResult GetHttpRequestContext(HttpContext context)
{
var cookies = context.Request.Cookies;
var method = context.Request.Method;
var headers = context.Request.Headers;
var path = context.Request.Path;
var subdomains = context.Request.Host;
var connectionMethods = context.Connection.RemotePort;
var protocol = context.Request.Protocol;
var query = context.Request.QueryString;
var osHostName = System.Environment.MachineName;

string ip;
string ips;
try
{
ip = context.Connection.RemoteIpAddress?.ToString() ?? "Unknown";
ips = context.Connection.RemoteIpAddress?.ToString() ?? "Unknown";
}
catch (System.Net.Sockets.SocketException)
{
ip = "Unknown";
ips = "Unknown";
}

return Results.Ok(new
{
cookies,
method,
headers,
path,
subdomains,
connectionMethods,
protocol,
query,
ip,
ips,
osHostName
});
}

private static IResult GetAllMessages(IMessageRepository msgRepository)
Expand Down Expand Up @@ -94,8 +140,11 @@ private static IResult DeleteMessage(int id, IMessageRepository msgRepository)
/// <returns>True if the user is authenticated, otherwise false.</returns>
private static bool AuthenticateUser(UserCredentials credentials)
{
var USERNAME = Environment.GetEnvironmentVariable("USERNAME") ?? "admin"; //builder.Configuration["AppSettings:Authentication:Username"];
var PASSWORD = Environment.GetEnvironmentVariable("PASSWORD") ?? "admin123"; //builder.Configuration["AppSettings:Authentication:Password"];
var USERNAME = Environment.GetEnvironmentVariable("USERNAME") ?? "admin";
//builder.Configuration["AppSettings:Authentication:Username"];

var PASSWORD = Environment.GetEnvironmentVariable("PASSWORD") ?? "admin123";
//builder.Configuration["AppSettings:Authentication:Password"];

if (credentials.Username != USERNAME || credentials.Password != PASSWORD)
{
Expand Down
5 changes: 3 additions & 2 deletions src/EchoApi/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -82,14 +82,15 @@ private static void Main(string[] args)
ValidateIssuerSigningKey = true,
ValidIssuer = builder.Configuration?["AppSettings:Jwt:Issuer"],
ValidAudience = builder.Configuration?["AppSettings:Jwt:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration?["AppSettings:Jwt:Key"]))
IssuerSigningKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(builder.Configuration?["AppSettings:Jwt:Key"])

Check warning on line 86 in src/EchoApi/Program.cs

View workflow job for this annotation

GitHub Actions / Build

Possible null reference argument for parameter 's' in 'byte[] Encoding.GetBytes(string s)'.

Check warning on line 86 in src/EchoApi/Program.cs

View workflow job for this annotation

GitHub Actions / Build

Possible null reference argument for parameter 's' in 'byte[] Encoding.GetBytes(string s)'.
)
};
}
);

var app = builder.Build();

// Configure the HTTP request pipeline
app.UseAuthentication();
app.UseAuthorization();

Expand Down
3 changes: 2 additions & 1 deletion tests/IntegrationTests/HttpEndpointTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@ public HttpEndpointTests()
public void UnauthorizedRouteExistsTest()
{
new string[] {
"/healthz" }
"/healthz",
}
.ToList()
.ForEach(async path =>
{
Expand Down
12 changes: 7 additions & 5 deletions tests/test.sh
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
#!/bin/bash

set -ex
set -euo pipefail

BEARER=$(curl -s -X POST http://localhost:5000/token \
API_URL="http://localhost:5000"

BEARER=$(curl -s -X POST "$API_URL"/token \
-H "Content-Type: application/json" \
-d '{"Username":"admin","Password":"admin123"}' | jq -r ".token")

curl -v -H "Authorization: Bearer $BEARER" http://localhost:5000/api/message/1
curl -v -H "Authorization: Bearer $BEARER" "$API_URL"/api/v1/message/1

curl -v -X "DELETE" -H "Authorization: Bearer $BEARER" http://localhost:5000/api/message/1
curl -v -X "DELETE" -H "Authorization: Bearer $BEARER" "$API_URL"/api/v1/message/1

curl -v -H "Authorization: Bearer $BEARER" -H "Content-Type: application/json" \
-d '{"message":"Hello World"}' http://localhost:5000/api/message
-d '{"message":"Hello World"}' "$API_URL"/api/v1/message

0 comments on commit c01d126

Please sign in to comment.