Skip to content

Commit

Permalink
Get patient dashboard connected to DB and update address functionalit…
Browse files Browse the repository at this point in the history
…y working
  • Loading branch information
Matthew committed Nov 14, 2024
1 parent e84be23 commit 4b5b149
Show file tree
Hide file tree
Showing 13 changed files with 269 additions and 29 deletions.
10 changes: 6 additions & 4 deletions Controllers/AuthController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,15 @@ public class AuthController(ILogger<HomeController> logger, AuthService authServ
{
public IActionResult Login()
{
TempData["hideLogout"] = true;

return View();
}

public IActionResult Register()
{
TempData["hideLogout"] = true;

return View();
}

Expand All @@ -38,12 +42,11 @@ public IActionResult Logout()
[HttpPost]
public IActionResult Login([FromForm] LoginDetails loginDetails)
{
TempData["hideLogout"] = true;

var loginResult = authService.AttemptLogin(loginDetails);

if (!loginResult.success)
{
TempData["hideLogout"] = true;
TempData["errorMsg"] = "Invalid email or password";

return View();
Expand All @@ -57,12 +60,11 @@ public IActionResult Login([FromForm] LoginDetails loginDetails)
[HttpPost]
public IActionResult Register([FromForm] RegisterDetails registerDetails)
{
TempData["hideLogout"] = true;

var createAccountResult = authService.AttemptCreateAccount(registerDetails);

if (!createAccountResult.success)
{
TempData["hideLogout"] = true;
TempData["errorMsg"] = "Could not create account with that email.";

return View();
Expand Down
44 changes: 27 additions & 17 deletions Controllers/DashboardController.cs
Original file line number Diff line number Diff line change
@@ -1,29 +1,39 @@
using Microsoft.AspNetCore.Mvc;
using SecureDesignProject.Extensions;
using SecureDesignProject.Models;
using SecureDesignProject.Services;

namespace SecureDesignProject.Controllers;

public class DashboardController : Controller
public class DashboardController(PatientService patientService) : Controller
{
public IActionResult Patient()
{
var model = new PatientInfo
var patient = patientService.GetPatientInfoByAccountId(HttpContext.GetAccountId());

if (patient == null) return RedirectToAction("Error", "Home");


return View(patient);
}

public IActionResult UpdateAddress()
{
var address = patientService.GetAddressByAccountId(HttpContext.GetAccountId());
return View(address);
}

[HttpPost]
public IActionResult UpdateAddress(Address address)
{
var success = patientService.AttemptUpdateAddress(HttpContext.GetAccountId(), address);

if (!success)
{
AssignedCaregivers = ["Dr Steve London", "Dr Bruce Potter"],
PatientName = "John Doe",
Address = "123 Main Street\nLondon\nEC5 8BC",
Appointments = [
new AppointmentInfo
{
Caregiver = "Dr Steve London",
Patient = "John Doe",
AppointmentTime = DateTime.Now.ToString("dd/MM/yyyy HH:mm"),
AppointmentDuration = "30",
Notes = "Notes for Dr Steve London. And Dr Bruce Potter is the same time as the day. ALSO IT is the same time as the day. The day is the same time as the day. This is very strange auto complete."
}
]
};
TempData["errorMsg"] = "Failed to update address.";
return View(address);
}

return View(model);
return RedirectToAction("Patient");
}
}
5 changes: 5 additions & 0 deletions Extensions/HttpExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,9 @@ public static void SetSessionKeyCookie(this HttpResponse response, byte[] sessio
var cookie = request.Cookies["session_key"];
return cookie == null ? null : Convert.FromHexString(cookie!);
}

public static Guid GetAccountId(this HttpContext context)
{
return context.Items["accountId"] as Guid? ?? Guid.Empty;
}
}
5 changes: 4 additions & 1 deletion Middleware/AuthMiddleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,14 @@ public async Task InvokeAsync(HttpContext context)
return;
}

if (!authService.IsValidSession(sessionKey!))
var result = authService.ValidateSession(sessionKey!);
if (!result.isValid)
{
context.Response.Redirect("/auth/login");
return;
}

context.Items["accountId"] = result.accountId;

// Call the next delegate/middleware in the pipeline.
await next(context);
Expand Down
8 changes: 8 additions & 0 deletions Models/AuthModels.cs
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,14 @@ public record Patient
public string? Address { get; init; }
}

public record Caregiver
{
public Guid PatientId { get; init; } = Guid.NewGuid();
public Guid AccountId { get; init; }
public string FirstName { get; init; } = "";
public string LastName { get; init; } = "";
}

public record Session
{
public Guid SessionId { get; init; }
Expand Down
10 changes: 9 additions & 1 deletion Models/DashboardModels.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ public record PatientInfo
public string[] AssignedCaregivers { get; init; } = [];

public string PatientName { get; init; }
public string? Address { get; init; }
public Address? Address { get; init; }

public AppointmentInfo[] Appointments { get; init; } = [];
}
Expand All @@ -20,4 +20,12 @@ public record AppointmentInfo
public string AppointmentDuration { get; init; } // in minutes

public string Notes { get; init; }
}

public record Address
{
[Required] public string Line1 { get; init; } = "";
public string Line2 { get; init; } = "";
[Required] public string City { get; init; } = "";
[Required] public string Postcode { get; init; } = "";
}
2 changes: 2 additions & 0 deletions Program.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using SecureDesignProject.Middleware;
using SecureDesignProject.Models;
using SecureDesignProject.Services;

var builder = WebApplication.CreateBuilder(args);
Expand All @@ -7,6 +8,7 @@
builder.Services.AddControllersWithViews();
builder.Services.AddSingleton<DatabaseService>();
builder.Services.AddSingleton<AuthService>();
builder.Services.AddSingleton<PatientService>();

var app = builder.Build();

Expand Down
4 changes: 2 additions & 2 deletions Services/AuthService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,11 @@ public class AuthService(DatabaseService dbService)
return (true, newSession.SessionKey);
}

public bool IsValidSession(byte[] key)
public (bool isValid, Guid accountId) ValidateSession(byte[] key)
{
var session = dbService.GetSessionByKey(key);

return session != null;
return (session != null, session?.AccountId ?? Guid.Empty);
}

public (bool success, byte[] SessionKey) AttemptCreateAccount(RegisterDetails registerDetails)
Expand Down
54 changes: 54 additions & 0 deletions Services/DatabaseService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,20 @@ UPDATE Sessions

return session;
}

public Patient? UpdatePatient(Patient patient)
{
using var db = new SqlConnection(ConnectionString);

db.Execute("""
UPDATE Patients
SET FirstName=@firstName, LastName=@lastName, Address=@address
WHERE PatientId = @patientId
""",
patient);

return patient;
}

public Account InsertAccount(Account account)
{
Expand Down Expand Up @@ -86,4 +100,44 @@ FROM Sessions
""",
new {sessionKey});
}

public Patient? GetPatientByAccountId(Guid accountId)
{
using var db = new SqlConnection(ConnectionString);

return db.QuerySingleOrDefault<Patient>("""
SELECT *
FROM Patients
WHERE AccountId = @accountId
""",
new {accountId});
}
public Caregiver? GetCaregiverByAccountId(Guid accountId)
{
using var db = new SqlConnection(ConnectionString);

return db.QuerySingleOrDefault<Caregiver>("""
SELECT *
FROM Caregivers
WHERE AccountId = @accountId
""",
new {accountId});
}

public IEnumerable<Caregiver> GetCaregiversByAssignedPatient(Guid patientId)
{
using var db = new SqlConnection(ConnectionString);

return db.Query<Caregiver>("""
SELECT *
FROM Caregivers
WHERE CaregiverId IN (
SELECT Caregiver_Patients.CaregiverId
FROM Caregivers
INNER JOIN Caregiver_Patients ON Caregivers.CaregiverId = Caregiver_Patients.CaregiverId
WHERE Caregiver_Patients.PatientId = @patientId AND CurrentlyAssigned=1
)
""",
new {patientId});
}
}
69 changes: 69 additions & 0 deletions Services/PatientService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
using SecureDesignProject.Models;

namespace SecureDesignProject.Services;

public class PatientService(DatabaseService dbService)
{
public PatientInfo? GetPatientInfoByAccountId(Guid accountId)
{
var patient = dbService.GetPatientByAccountId(accountId);
if (patient == null) return null;

var caregivers = dbService
.GetCaregiversByAssignedPatient(patient.PatientId)
.Select(x => x.FirstName + " " + x.LastName)
.ToArray();


var splitAddress = patient.Address?.Split('\n');

return new PatientInfo
{
PatientName = patient.FirstName + " " + patient.LastName,
Address = splitAddress != null ?
new Address
{
Line1 = splitAddress[0],
Line2 = splitAddress[1],
City = splitAddress[2],
Postcode = splitAddress[3],
} : null,
AssignedCaregivers = caregivers,
Appointments = [] //TODO: implement appointments
};
}

public Address? GetAddressByAccountId(Guid accountId)
{
var patient = dbService.GetPatientByAccountId(accountId);

if (patient == null) return null;

var splitAddress = patient.Address?.Split('\n');

if (splitAddress == null) return new Address();

return new Address
{
Line1 = splitAddress[0],
Line2 = splitAddress[1],
City = splitAddress[2],
Postcode = splitAddress[3],
};
}

public bool AttemptUpdateAddress(Guid accountId, Address address)
{
var patient = dbService.GetPatientByAccountId(accountId);
if (patient == null) return false;

var addressString = address.Line1 + "\n" + address.Line2 + "\n" + address.City + "\n" + address.Postcode;

dbService.UpdatePatient(patient with
{
Address = addressString
});

return true;
}
}
13 changes: 10 additions & 3 deletions Views/Dashboard/Patient.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,16 @@
<h3>Address:</h3>
@if (Model.Address != null)
{
<p>@Model.Address</p>
<button type="button" class="btn btn-primary w-25 m-3">Update Address</button>
<p>@Model.Address.Line1</p>
<p>@Model.Address.Line2</p>
<p>@Model.Address.City</p>
<p>@Model.Address.Postcode</p>
<button class="btn btn-primary w-auto m-3" onclick="location.href='@Url.Action("UpdateAddress", "Dashboard")'">Update Address</button>
}
else
{
<p>You have not yet provided your address.</p>
<button type="button" class="btn btn-primary w-25 m-3">Add Address</button>
<button class="btn btn-primary w-auto m-3" onclick="location.href='@Url.Action("UpdateAddress", "Dashboard")'">Add Address</button>
}
</div>
</div>
Expand All @@ -48,6 +51,10 @@
<p>@appointment.Notes</p>
</div>
}
@if (Model.Appointments.Length == 0)
{
<p class="m-3">You don't currently have any scheduled appointments.</p>
}
</div>
</div>

Expand Down
Loading

0 comments on commit 4b5b149

Please sign in to comment.