This commit is contained in:
andrei-mihnea-cerbu
2024-04-08 01:03:59 +03:00
parent b48d5ee19e
commit 61a55fa735
50 changed files with 80 additions and 52 deletions
@@ -1,42 +1,39 @@
namespace API.Middlewares; using Application.Endpoints;
public class ApiKeyValidationMiddleware namespace API.Middlewares;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using System.Threading.Tasks;
public class ApiKeyMiddleware
{ {
private const string APIKEYNAME = "ApiKey";
private readonly RequestDelegate _next; private readonly RequestDelegate _next;
private const string API_KEY_HEADER_NAME = "ApiKey";
private readonly string _apiKey;
public ApiKeyValidationMiddleware(RequestDelegate next) public ApiKeyMiddleware(RequestDelegate next, IConfiguration configuration)
{ {
_next = next; _next = next;
_apiKey = configuration.GetValue<string>("ApiKeySettings:ApiKey");
} }
public async Task InvokeAsync(HttpContext context) public async Task InvokeAsync(HttpContext context)
{ {
if (!context.Request.Headers.TryGetValue(APIKEYNAME, out var extractedApiKey)) if (!context.Request.Headers.TryGetValue(API_KEY_HEADER_NAME, out var extractedApiKey))
{ {
context.Response.StatusCode = 401; context.Response.StatusCode = HttpStatusCodes.Unauthorized; // Unauthorized
await context.Response.WriteAsync("API Key was not provided."); await context.Response.WriteAsync("API Key is missing");
return; return;
} }
var appSettings = context.RequestServices.GetRequiredService<IConfiguration>(); if (!_apiKey.Equals(extractedApiKey))
var apiKey = appSettings.GetValue<string>("ApiKey");
if (string.IsNullOrEmpty(apiKey))
{ {
context.Response.StatusCode = 400; context.Response.StatusCode = HttpStatusCodes.Forbidden; // Forbidden
await context.Response.WriteAsync("Unable to retrieve API key."); await context.Response.WriteAsync("Invalid API Key");
return; return;
} }
if (!apiKey.Equals(extractedApiKey)) await _next(context); // API Key is valid, proceed to the next middleware
{
context.Response.StatusCode = 401;
await context.Response.WriteAsync("Unauthorized client.");
return;
}
await _next(context);
} }
} }
+1 -1
View File
@@ -51,7 +51,7 @@ app.UseAuthorization();
app.MapControllers(); app.MapControllers();
// Middlewares // Middlewares
app.UseMiddleware<ApiKeyValidationMiddleware>(); app.UseMiddleware<ApiKeyMiddleware>();
app.UseMiddleware<BodyCheckMiddleware>(); app.UseMiddleware<BodyCheckMiddleware>();
using (var scope = app.Services.CreateScope()) using (var scope = app.Services.CreateScope())
+4 -2
View File
@@ -9,6 +9,8 @@
"HealthcareManagerDatabase": "Host=surus.db.elephantsql.com;Database=newbwuyu;Username=newbwuyu;Password=0end9Ixqo9PeTE4HVslX7_FVwruEhFf-;", "HealthcareManagerDatabase": "Host=surus.db.elephantsql.com;Database=newbwuyu;Username=newbwuyu;Password=0end9Ixqo9PeTE4HVslX7_FVwruEhFf-;",
"MongoDBDatabase": "mongodb+srv://andrei_cerbu:andrei_cerbu@cluster0.v80skg6.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0" "MongoDBDatabase": "mongodb+srv://andrei_cerbu:andrei_cerbu@cluster0.v80skg6.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0"
}, },
"AllowedHosts": "*", "ApiKeySettings": {
"ApiKey": "testapikey" "ApiKey": "testapikey"
},
"AllowedHosts": "*"
} }
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -9,6 +9,8 @@
"HealthcareManagerDatabase": "Host=surus.db.elephantsql.com;Database=newbwuyu;Username=newbwuyu;Password=0end9Ixqo9PeTE4HVslX7_FVwruEhFf-;", "HealthcareManagerDatabase": "Host=surus.db.elephantsql.com;Database=newbwuyu;Username=newbwuyu;Password=0end9Ixqo9PeTE4HVslX7_FVwruEhFf-;",
"MongoDBDatabase": "mongodb+srv://andrei_cerbu:andrei_cerbu@cluster0.v80skg6.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0" "MongoDBDatabase": "mongodb+srv://andrei_cerbu:andrei_cerbu@cluster0.v80skg6.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0"
}, },
"AllowedHosts": "*", "ApiKeySettings": {
"ApiKey": "testapikey" "ApiKey": "testapikey"
},
"AllowedHosts": "*"
} }
@@ -13,7 +13,7 @@ using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("API")] [assembly: System.Reflection.AssemblyCompanyAttribute("API")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0+2ccec617a59a712428e67340dc46bebefb152aca")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0+b48d5ee19e5228d9bcb979f2140f996fe7a12723")]
[assembly: System.Reflection.AssemblyProductAttribute("API")] [assembly: System.Reflection.AssemblyProductAttribute("API")]
[assembly: System.Reflection.AssemblyTitleAttribute("API")] [assembly: System.Reflection.AssemblyTitleAttribute("API")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
@@ -1 +1 @@
abd09d11442616a05d74c5cf91eb2ab3a3f4e18f9d1feb34f7d619b58a9ee139 2a4e1c7096998582acfb9acc87d23cdf43dae534213aaa9d36839c4312b69e45
Binary file not shown.
Binary file not shown.
@@ -1 +1 @@
{"documents":{"C:\\Users\\Andrei Cerbu\\Documents\\FACULTATE\\CC-FinalProj\\*":"https://raw.githubusercontent.com/andrei-mihnea-cerbu/CC-FinalProj/2ccec617a59a712428e67340dc46bebefb152aca/*"}} {"documents":{"C:\\Users\\Andrei Cerbu\\Documents\\FACULTATE\\CC-FinalProj\\*":"https://raw.githubusercontent.com/andrei-mihnea-cerbu/CC-FinalProj/b48d5ee19e5228d9bcb979f2140f996fe7a12723/*"}}
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,7 @@
namespace Application.Endpoints.MedicalHistories;
public class MedicalHistoryAuthorisationModel
{
public Guid Id { get; set; }
public List<Guid> Authorisation { get; set; } = new List<Guid>();
}
@@ -84,6 +84,15 @@ public class MedicalHistoryHandler
//TODO add to MongoDB //TODO add to MongoDB
var medicalHistoryId = medicalHistory.Id;
var newMedicalHistory = new MedicalHistoryAuthorisationModel
{
Id = medicalHistoryId,
Authorisation = new List<Guid>()
};
await _mongoDbService.AddAsync("MedicalHistory", newMedicalHistory);
return new BaseResponse return new BaseResponse
{ {
StatusCode = HttpStatusCodes.Created, StatusCode = HttpStatusCodes.Created,
@@ -14,16 +14,19 @@ public class PatientRegistrationValidation : AbstractValidator<PatientRegistrati
RuleFor(x => x.Email) RuleFor(x => x.Email)
.NotEmpty().WithMessage("Email is required.").WithErrorCode(HttpStatusCodes.BadRequest.ToString()) .NotEmpty().WithMessage("Email is required.").WithErrorCode(HttpStatusCodes.BadRequest.ToString())
.EmailAddress().WithMessage("Invalid email format.").WithErrorCode(HttpStatusCodes.BadRequest.ToString()) .EmailAddress().WithMessage("Invalid email format.").WithErrorCode(HttpStatusCodes.BadRequest.ToString())
.MustAsync(BeUniqueEmail).WithMessage("Email already exists.").WithErrorCode(HttpStatusCodes.Conflict.ToString()); .MustAsync(BeUniqueEmail).WithMessage("Email already exists.")
.WithErrorCode(HttpStatusCodes.Conflict.ToString());
RuleFor(x => x.Password) RuleFor(x => x.Password)
.NotEmpty().WithMessage("Password is required.").WithErrorCode(HttpStatusCodes.BadRequest.ToString()) .NotEmpty().WithMessage("Password is required.").WithErrorCode(HttpStatusCodes.BadRequest.ToString())
.MinimumLength(8).WithMessage("Password must be at least 8 characters long.").WithErrorCode(HttpStatusCodes.BadRequest.ToString()); .MinimumLength(8).WithMessage("Password must be at least 8 characters long.")
.WithErrorCode(HttpStatusCodes.BadRequest.ToString());
RuleFor(x => x.Name) RuleFor(x => x.Name)
.NotEmpty().WithMessage("Name is required.").WithErrorCode(HttpStatusCodes.BadRequest.ToString()) .NotEmpty().WithMessage("Name is required.").WithErrorCode(HttpStatusCodes.BadRequest.ToString())
.MinimumLength(3).WithMessage("Name must be at least 3 characters long.").WithErrorCode(HttpStatusCodes.BadRequest.ToString()); .MinimumLength(3).WithMessage("Name must be at least 3 characters long.")
.WithErrorCode(HttpStatusCodes.BadRequest.ToString());
} }
private async Task<bool> BeUniqueEmail(string email, CancellationToken cancellationToken) private async Task<bool> BeUniqueEmail(string email, CancellationToken cancellationToken)
Binary file not shown.
Binary file not shown.
@@ -13,7 +13,7 @@ using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("Application")] [assembly: System.Reflection.AssemblyCompanyAttribute("Application")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0+2ccec617a59a712428e67340dc46bebefb152aca")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0+b48d5ee19e5228d9bcb979f2140f996fe7a12723")]
[assembly: System.Reflection.AssemblyProductAttribute("Application")] [assembly: System.Reflection.AssemblyProductAttribute("Application")]
[assembly: System.Reflection.AssemblyTitleAttribute("Application")] [assembly: System.Reflection.AssemblyTitleAttribute("Application")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
@@ -1 +1 @@
43c727b13400f8e89ac74c76384ddd37b5c5e6f7a0de4c00bfcc4bc65f5d856d e01bb5cb416ac609d6eb58b4e5e6dea85ea3572d0845400409f93dd3761941e3
@@ -1 +1 @@
a687c08ad227adac30cf205db23b335cafe12531e9fb53842e695d4fe5f9879a 747e745a68129206db481649de2eb8593ffa6704b63c0c2bd731c9a83a9d670a
Binary file not shown.
Binary file not shown.
@@ -1 +1 @@
{"documents":{"C:\\Users\\Andrei Cerbu\\Documents\\FACULTATE\\CC-FinalProj\\*":"https://raw.githubusercontent.com/andrei-mihnea-cerbu/CC-FinalProj/2ccec617a59a712428e67340dc46bebefb152aca/*"}} {"documents":{"C:\\Users\\Andrei Cerbu\\Documents\\FACULTATE\\CC-FinalProj\\*":"https://raw.githubusercontent.com/andrei-mihnea-cerbu/CC-FinalProj/b48d5ee19e5228d9bcb979f2140f996fe7a12723/*"}}
@@ -9,7 +9,7 @@ public class HealthcareManagerDatabase : DbContext
{ {
} }
public DbSet<Patient> Pacients { get; set; } public DbSet<Patient> Patients { get; set; }
public DbSet<MedicalHistory> MedicalHistories { get; set; } public DbSet<MedicalHistory> MedicalHistories { get; set; }
public DbSet<Doctor> Doctors { get; set; } public DbSet<Doctor> Doctors { get; set; }
@@ -32,7 +32,7 @@ namespace Infrastructure.Migrations
{ {
Id = table.Column<Guid>(type: "uuid", nullable: false), Id = table.Column<Guid>(type: "uuid", nullable: false),
UserId = table.Column<Guid>(type: "uuid", nullable: false), UserId = table.Column<Guid>(type: "uuid", nullable: false),
Description = table.Column<byte[]>(type: "bytea", nullable: false) Content = table.Column<byte[]>(type: "bytea", nullable: false)
}, },
constraints: table => constraints: table =>
{ {
@@ -40,7 +40,7 @@ namespace Infrastructure.Migrations
}); });
migrationBuilder.CreateTable( migrationBuilder.CreateTable(
name: "Pacients", name: "Patients",
columns: table => new columns: table => new
{ {
Id = table.Column<Guid>(type: "uuid", nullable: false), Id = table.Column<Guid>(type: "uuid", nullable: false),
@@ -64,7 +64,7 @@ namespace Infrastructure.Migrations
name: "MedicalHistories"); name: "MedicalHistories");
migrationBuilder.DropTable( migrationBuilder.DropTable(
name: "Pacients"); name: "Patients");
} }
} }
} }
@@ -51,7 +51,7 @@ namespace Infrastructure.Migrations
.ValueGeneratedOnAdd() .ValueGeneratedOnAdd()
.HasColumnType("uuid"); .HasColumnType("uuid");
b.Property<byte[]>("Description") b.Property<byte[]>("Content")
.IsRequired() .IsRequired()
.HasColumnType("bytea"); .HasColumnType("bytea");
@@ -63,7 +63,7 @@ namespace Infrastructure.Migrations
b.ToTable("MedicalHistories"); b.ToTable("MedicalHistories");
}); });
modelBuilder.Entity("Core.Entities.Pacient", b => modelBuilder.Entity("Core.Entities.Patient", b =>
{ {
b.Property<Guid>("Id") b.Property<Guid>("Id")
.ValueGeneratedOnAdd() .ValueGeneratedOnAdd()
@@ -80,7 +80,7 @@ namespace Infrastructure.Migrations
b.HasKey("Id"); b.HasKey("Id");
b.ToTable("Pacients"); b.ToTable("Patients");
}); });
#pragma warning restore 612, 618 #pragma warning restore 612, 618
} }
@@ -1,4 +1,5 @@
using Application.Services.Database; using Application.Services.Database;
using MongoDB.Bson;
using MongoDB.Driver; using MongoDB.Driver;
namespace Infrastructure.Services.MongoDB; namespace Infrastructure.Services.MongoDB;
@@ -9,9 +10,16 @@ public class MongoDbService : IMongoDbService
public MongoDbService(string connectionString) public MongoDbService(string connectionString)
{ {
var url = new MongoUrl(connectionString); var settings = MongoClientSettings.FromConnectionString(connectionString);
var client = new MongoClient(url); settings.ServerApi = new ServerApi(ServerApiVersion.V1);
_database = client.GetDatabase(url.DatabaseName); var _database = new MongoClient(settings);
try {
var result = _database.GetDatabase("admin").RunCommand<BsonDocument>(new BsonDocument("ping", 1));
Console.WriteLine("Pinged your deployment. You successfully connected to MongoDB!");
} catch (Exception ex) {
Console.WriteLine(ex);
}
} }
public IMongoCollection<T> GetCollection<T>(string collectionName) public IMongoCollection<T> GetCollection<T>(string collectionName)
@@ -10,6 +10,6 @@ public class PatientRepository(HealthcareManagerDatabase context)
{ {
public async Task<Patient?> FindByEmailAsync(string email) public async Task<Patient?> FindByEmailAsync(string email)
{ {
return await _context.Pacients.FirstOrDefaultAsync(d => d.Email == email); return await _context.Patients.FirstOrDefaultAsync(d => d.Email == email);
} }
} }
@@ -13,7 +13,7 @@ using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("Infrastructure")] [assembly: System.Reflection.AssemblyCompanyAttribute("Infrastructure")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0+2ccec617a59a712428e67340dc46bebefb152aca")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0+b48d5ee19e5228d9bcb979f2140f996fe7a12723")]
[assembly: System.Reflection.AssemblyProductAttribute("Infrastructure")] [assembly: System.Reflection.AssemblyProductAttribute("Infrastructure")]
[assembly: System.Reflection.AssemblyTitleAttribute("Infrastructure")] [assembly: System.Reflection.AssemblyTitleAttribute("Infrastructure")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
@@ -1 +1 @@
5c68101bdd997137e1cd8f3c58cb6d9e9b9d203289c90b0f6dca8b08cc72b5c9 1eff5085180ba5a7e0c455493bf156ab7c10e42899382b41bdf7799d2b2ca6d6
@@ -1 +1 @@
{"documents":{"C:\\Users\\Andrei Cerbu\\Documents\\FACULTATE\\CC-FinalProj\\*":"https://raw.githubusercontent.com/andrei-mihnea-cerbu/CC-FinalProj/2ccec617a59a712428e67340dc46bebefb152aca/*"}} {"documents":{"C:\\Users\\Andrei Cerbu\\Documents\\FACULTATE\\CC-FinalProj\\*":"https://raw.githubusercontent.com/andrei-mihnea-cerbu/CC-FinalProj/b48d5ee19e5228d9bcb979f2140f996fe7a12723/*"}}