diff --git a/.gitignore b/.gitignore index 2608a78..3ea5d77 100644 --- a/.gitignore +++ b/.gitignore @@ -260,4 +260,6 @@ paket-files/ __pycache__/ *.pyc -SeniorAssistant/SeniorAssistant/wwwroot/* \ No newline at end of file +SeniorAssistant/SeniorAssistant/wwwroot/* +/SeniorAssistant/Controllers/TestController.cs +/SeniorAssistant/Views/Test/* diff --git a/README.md b/README.md new file mode 100644 index 0000000..05472d6 --- /dev/null +++ b/README.md @@ -0,0 +1,18 @@ +# SeniorAssistant +Parte del progetto SeniorAssistant che riguarda l'interazione con persone esterne oltre ad un server che raccoglie i dati + +## Funzionalita' +Dopo aver fatto login/essersi registrati Dottore e Paziente possono accedere alle seguenti funzionalità: + +#### Paziente +- Scegliere il proprio dottore +- Visualizzare i propri dati anagrafici +- Visualizzare i propri dati "vitali" +- Inviare messaggi al proprio dottore + +#### Dottore +- Selezionare un paziente fra i propri pazienti +- Visualizzarne dati anagrafici e vitali +- Aggiungere al paziente note (es malattie croniche, allergie ecc) +- Visualizzare notifiche prodotte dal paziente +- Inviare messaggi al paziente diff --git a/SeniorAssistant/Controllers/AccountController.cs b/SeniorAssistant/Controllers/AccountController.cs index 9edde56..6a999d4 100644 --- a/SeniorAssistant/Controllers/AccountController.cs +++ b/SeniorAssistant/Controllers/AccountController.cs @@ -4,65 +4,46 @@ using SeniorAssistant.Models; using SeniorAssistant.Controllers; using LinqToDB; using System.Linq; +using System; +using SeniorAssistant.Models.Users; namespace IdentityDemo.Controllers { - [ApiExplorerSettings(IgnoreApi = true)] [Route("[controller]/[action]")] public class AccountController : BaseController { - /* - private readonly UserManager _userManager; - private readonly SignInManager _signInManager; - private readonly ILogger _logger; - - public AccountController( - UserManager userManager, - SignInManager signInManager, - ILogger logger) - { - _userManager = userManager; - _signInManager = signInManager; - _logger = logger; - } - /* - [TempData] - public string ErrorMessage { get; set; } - - [HttpGet] - [AllowAnonymous] - public async Task Login(string returnUrl = null) - { - // Clear the existing external cookie to ensure a clean login process - await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme); - - ViewData["ReturnUrl"] = returnUrl; - return View(); - } - */ + private static readonly string NoteModified = "Il tuo dottore ha modificato la nota per te"; [HttpPost] public ActionResult _login(string username, string password) { - JsonResponse response = new JsonResponse(); - response.Success = false; - response.Message = "Username or password is invalid."; - - var strunz = Db.GetTable().Where(user => user.Username.Equals(username) && user.Password.Equals(password)).ToListAsync().Result; - - if (strunz.Count == 1) + JsonResponse response = new JsonResponse { - var loggedUser = HttpContext.Session.GetString("username"); - if (loggedUser==null || !loggedUser.Equals(username)) + Success = false, + Message = "Username or password is invalid." + }; + + var result = Db.GetTable().Where(user => user.Username.Equals(username) && user.Password.Equals(password)).ToListAsync().Result; + + if (result.Count == 1) + { + var loggedUser = HttpContext.Session.GetString(Username); + if (loggedUser==null || !loggedUser.Equals(username)) // non ha senso { - HttpContext.Session.SetString("username", username); - HttpContext.Session.SetString("email", strunz.First().Email); - HttpContext.Session.SetString("name", strunz.First().Name); - HttpContext.Session.SetString("isdoc", strunz.First().Doctor?"true":"false"); - //HttpContext.Session.SetString("lastname", strunz.First().LastName); + User user = result.First(); + HttpContext.Session.SetString(Username, username); + HttpContext.Session.SetString("email", user.Email); + HttpContext.Session.SetString("name", user.Name); + HttpContext.Session.SetString("lastname", user.LastName); + + var isDoc = (from d in Db.Doctors + where d.Username.Equals(username) + select d).ToArray().FirstOrDefault() != null; + HttpContext.Session.SetString("role", isDoc? "doctor":"patient"); + response.Success = true; - response.Message = ""; + response.Message = Request.Query["ReturnUrl"]; } else { @@ -80,28 +61,125 @@ namespace IdentityDemo.Controllers } [HttpPost] - public ActionResult _register(Register register) + public ActionResult _register(User user) { - if(ModelState.IsValid) + return Action(() => { - User user = new User() { Username = register.Username, Email = register.Email, Password = register.Password}; try { Db.Insert(user); + return _login(user.Username, user.Password); } catch { - return Json(new JsonResponse() { Success = false, Message = "Username already exist" }); + return Json(new JsonResponse(false, "Username already exists")); } - _login(user.Username, user.Password); - return Json(new JsonResponse() { Success = true }); - } - return Json(new JsonResponse() { Success = false, Message = "Modello non valido" }); + }); } - internal class JsonResponse + + [HttpPost] + public ActionResult _notification(string username, string message) { - public bool Success { get; internal set; } - public string Message { get; internal set; } + return LoggedAction(() => + { + Db.Insert(new Notification() + { + Message = message, + Username = username, + Time = DateTime.Now, + Seen = false + }); + return Json(OkJson); + }); + } + + [HttpPut] + public ActionResult _notification(int id) + { + return LoggedAction(() => + { + JsonResponse response = OkJson; + + Notification note = Db.Notifications.Where(n => n.Id == id).ToArray().FirstOrDefault(); + if(note != null) + { + note.Seen = true; + Db.Update(note); + } + else + { + response.Success = false; + response.Message = "La notifica da modificare non esiste"; + } + return Json(response); + }); + } + + [HttpPost] + public ActionResult _addDoc(string doctor) + { + return LoggedAction(() => + { + string username = HttpContext.Session.GetString(Username); + var isAlreadyPatient = Db.Patients.Where(p => p.Username.Equals(username)).ToArray().FirstOrDefault() != null; + if (isAlreadyPatient) + return Json(new JsonResponse() + { + Success = false, + Message = "You are already a patient" + }); + + var docExist = Db.Doctors.Where(d => d.Username.Equals(doctor)).ToArray().FirstOrDefault() != null; + if(!docExist) + return Json(new JsonResponse() + { + Success = false, + Message = "Doctor doesn't exist" + }); + + Db.Insert(new Patient() + { + Doctor = doctor, + Username = username + }); + + _notification(doctor, "L'utente "+username+" ti ha inserito come il suo dottore."); + return Json(new JsonResponse()); + }); + } + + [HttpPost] + public ActionResult _sendMessage(string reciver, string body) + { + return LoggedAction(() => { + string username = HttpContext.Session.GetString(Username); + Message message = new Message() + { + Reciver = reciver, + Body = body, + Time = DateTime.Now, + Username = username, + Seen = false + }; + + Db.Insert(message); + + return Json(new JsonResponse()); + }); + } + + [HttpPut] + public ActionResult _addNote(string patient, string text) + { + return LoggedAccessDataOf(patient, () => + { + var pat = Db.Patients.Where((p) => p.Username.Equals(patient)).FirstOrDefault(); + pat.Notes = text; + Db.Update(pat); + _notification(patient, NoteModified); + + return Json(OkJson); + }); } } } \ No newline at end of file diff --git a/SeniorAssistant/Controllers/HomeController.cs b/SeniorAssistant/Controllers/HomeController.cs index 4ee48c6..daefdd2 100644 --- a/SeniorAssistant/Controllers/HomeController.cs +++ b/SeniorAssistant/Controllers/HomeController.cs @@ -1,17 +1,10 @@ -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc; namespace SeniorAssistant.Controllers { [ApiExplorerSettings(IgnoreApi = true)] - public class HomeController : Controller + public class HomeController : BaseController { - private readonly ISession session; - public HomeController(IHttpContextAccessor httpContextAccessor) - { - this.session = httpContextAccessor.HttpContext.Session; - } - [Route("")] [Route("Home")] [Route("Index")] @@ -23,31 +16,47 @@ namespace SeniorAssistant.Controllers [Route("Heartbeat")] public IActionResult Heartbeat() { - return View(); + return CheckAuthorized("Heartbeat"); } [Route("Sleep")] public IActionResult Sleep() { - return View(); + return CheckAuthorized("Sleep"); } [Route("Step")] public IActionResult Step() { - return View(); + return CheckAuthorized("Step"); } [Route("Users")] public IActionResult Users() { - return View(); + return CheckAuthorized("Users"); } [Route("User/{User}")] public IActionResult SingleUser(string user) { - return View("data", user); + return CheckAuthorized("Data", user); + } + + [Route("Message/{Id}")] + public IActionResult Message(int id) + { + return CheckAuthorized("Message", id); + } + + private IActionResult CheckAuthorized(string view, object model = null) + { + if (!IsLogged()) + { + model = "/" + view; + view = "Index"; + } + return View(view, model); } } } \ No newline at end of file diff --git a/SeniorAssistant/Controllers/Services/ApiControllers.cs b/SeniorAssistant/Controllers/Services/ApiControllers.cs index 71414cf..7959e9b 100644 --- a/SeniorAssistant/Controllers/Services/ApiControllers.cs +++ b/SeniorAssistant/Controllers/Services/ApiControllers.cs @@ -1,5 +1,6 @@ using Microsoft.AspNetCore.Mvc; using SeniorAssistant.Models; +using SeniorAssistant.Models.Users; namespace SeniorAssistant.Controllers.Services { @@ -18,4 +19,12 @@ namespace SeniorAssistant.Controllers.Services [Route("api/[controller]")] public class UserController : CrudController { } + + [Route("api/[controller]")] + public class PatientController : CrudController + { } + + [Route("api/[controller]")] + public class DoctorController : CrudController + { } } diff --git a/SeniorAssistant/Controllers/Services/BaseController.cs b/SeniorAssistant/Controllers/Services/BaseController.cs index 71be656..94dc2fb 100644 --- a/SeniorAssistant/Controllers/Services/BaseController.cs +++ b/SeniorAssistant/Controllers/Services/BaseController.cs @@ -1,10 +1,19 @@ -using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; using SeniorAssistant.Data; +using System.Linq; +using System; namespace SeniorAssistant.Controllers { public abstract class BaseController : Controller { + protected static readonly string MustBeLogged = "Devi essere loggato per vedere/modificare questo dato"; + protected static readonly string InvalidModel = "Modello non valido"; + protected static readonly string NoAuthorized = "Non sei autorizzato a vedere questi dati"; + protected static readonly string Username = "username"; + protected readonly JsonResponse OkJson = new JsonResponse(); + IDataContextFactory dbFactory; SeniorDataContext db; @@ -20,5 +29,68 @@ namespace SeniorAssistant.Controllers base.Dispose(disposing); } + + protected bool IsLogged() + { + return HttpContext.Session.GetString(Username) != null; + } + + protected ActionResult Action(Func success) + { + return ModelState.IsValid ? + success.Invoke() : + Json(new JsonResponse() + { + Success = false, + Message = InvalidModel + }); + } + + protected ActionResult LoggedAction(Func success) + { + return Action(() => + { + return IsLogged() ? + success.Invoke() : + Json(new JsonResponse() + { + Success = false, + Message = MustBeLogged + }); + }); + } + + protected ActionResult LoggedAccessDataOf(string username, Func success, bool patients = true) + { + return LoggedAction(() => + { + var loggedUser = HttpContext.Session.GetString(Username); + var condition = username.Equals(loggedUser); + + condition = condition || (patients && (from patient in Db.Patients + where patient.Doctor.Equals(loggedUser) && patient.Username.Equals(username) + select patient).ToArray().FirstOrDefault() != null); + + return condition ? + success.Invoke() : + Json(new JsonResponse() + { + Success = false, + Message = NoAuthorized + }); + }); + } + } + + public class JsonResponse + { + public JsonResponse(bool success=true, string message="") + { + Success = success; + Message = message; + } + + public bool Success { get; set; } + public string Message { get; set; } } } diff --git a/SeniorAssistant/Controllers/Services/CrudController.cs b/SeniorAssistant/Controllers/Services/CrudController.cs index 7bb68b8..4ba8e87 100644 --- a/SeniorAssistant/Controllers/Services/CrudController.cs +++ b/SeniorAssistant/Controllers/Services/CrudController.cs @@ -10,24 +10,24 @@ namespace SeniorAssistant.Controllers.Services public abstract class CrudController : BaseController where TEntity : class, IHasUsername { - [HttpGet] - public async Task> Read() => await Db.GetTable().ToListAsync(); - [HttpGet("{username}")] - public async Task Read(string username) => await Db.GetTable().FirstOrDefaultAsync(c => c.Username.Equals(username)); - - [HttpPost] - public async Task Create([FromBody]TEntity item) => await Db.InsertAsync(item); - - [HttpPut("{username}")] - public async Task Update(string username, [FromBody]TEntity item) + public async Task Read(string username) { - item.Username = username; - - await Db.UpdateAsync(item); + return LoggedAccessDataOf(username, () => + { + return Json(Db.GetTable().Where((u) => u.Username.Equals(username)).ToArray()); + }); } - [HttpDelete("{username}")] - public async Task Delete(string username) => await Db.GetTable().Where(c => c.Username.Equals(username)).DeleteAsync(); + [HttpPut("{username}")] + public async Task Update(string username, [FromBody] TEntity entity) + { + return LoggedAccessDataOf(username, () => + { + entity.Username = username; + Db.Update(entity); + return Json(OkJson); + }, false); + } } } diff --git a/SeniorAssistant/Controllers/Services/CrudTimeController.cs b/SeniorAssistant/Controllers/Services/CrudTimeController.cs index 9e3d1c3..1235bdf 100644 --- a/SeniorAssistant/Controllers/Services/CrudTimeController.cs +++ b/SeniorAssistant/Controllers/Services/CrudTimeController.cs @@ -2,74 +2,86 @@ using Microsoft.AspNetCore.Mvc; using SeniorAssistant.Models; using System; -using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace SeniorAssistant.Controllers.Services { - public class CrudTimeController : BaseController + public class CrudTimeController : CrudController where TEntity : class, IHasTime { - static readonly object Empty = new { }; - - [HttpGet] - public async Task> Read() => await Db.GetTable().ToListAsync(); - - [HttpGet("{username}")] - public async Task> Read(string username) => await Db.GetTable().Where(e => e.Username.Equals(username)).ToListAsync(); + private static readonly string DateNotCorrect = "Il formato della data non e' corretto"; [HttpGet("{username}/{date:regex((today|\\d{{4}}-\\d{{2}}-\\d{{2}}))}/{hour:range(0, 23)?}")] - public async Task> Read(string username, string date, int hour = -1) => await Read(username, date, date, hour); + public async Task Read(string username, string date, int hour = -1) => await Read(username, date, date, hour); [HttpGet("{username}/{from:regex((today|\\d{{4}}-\\d{{2}}-\\d{{2}}))}/{to:regex((today|\\d{{4}}-\\d{{2}}-\\d{{2}}))}/{hour:range(0, 23)?}")] - public async Task> Read(string username, string from, string to, int hour = -1) + public async Task Read(string username, string from, string to, int hour = -1) { - try + return LoggedAccessDataOf(username, () => { - DateTime dateFrom = (from.Equals("today") ? DateTime.Now : DateTime.ParseExact(from, "yyyy-MM-dd", null)); - DateTime dateTo = (to.Equals("today") ? DateTime.Now : DateTime.ParseExact(to, "yyyy-MM-dd", null)); + try + { + DateTime dateFrom = (from.Equals("today") ? DateTime.Now : DateTime.ParseExact(from, "yyyy-MM-dd", null)); + DateTime dateTo = (to.Equals("today") ? DateTime.Now : DateTime.ParseExact(to, "yyyy-MM-dd", null)); - return await Db.GetTable().Where(e => e.Username.Equals(username) && dateFrom.Date<=e.Time.Date && dateTo.Date>=e.Time.Date && (hour < 0 || e.Time.Hour == hour)).ToListAsync(); - } - catch - { - return new List(); - } + return Json((from entity in Db.GetTable() + where entity.Username.Equals(username) + && dateFrom.Date <= entity.Time.Date + && dateTo.Date >= entity.Time.Date + && (hour < 0 || entity.Time.Hour == hour) + select entity).ToArray()); + } + catch + { + return Json(new JsonResponse(false, DateNotCorrect)); + } + }); } [HttpGet("{username}/last/{hour:min(1)}")] - public async Task> Read(string username, int hour) + public async Task Read(string username, int hour) { - DateTime date = DateTime.Now.AddHours(-hour); - return await Db.GetTable().Where(e => e.Username.Equals(username) && date <= e.Time).ToListAsync(); + return LoggedAccessDataOf(username, () => + { + DateTime date = DateTime.Now.AddHours(-hour); + return Json((from entity in Db.GetTable() + where entity.Username.Equals(username) + && date <= entity.Time + select entity).ToArray()); + }); + } + + [HttpPost] + public async Task Create([FromBody]TEntity item) + { + return Action(() => + { + Db.Insert(item); + return Json(OkJson); + }); + } + + [HttpPut] + public async Task Update([FromBody]TEntity item) + { + return LoggedAccessDataOf(item.Username, () => + { + var e = Read(item.Username, item.Time); + if (e == null) + { + Create(item); + } + else + { + Db.UpdateAsync(item); + } + + return Json(OkJson); + }, false); } [NonAction] - public async Task Read(string username, DateTime date) => await Db.GetTable().FirstOrDefaultAsync(e => e.Username.Equals(username) && date == e.Time); - - [HttpPost] - public async Task Create([FromBody]TEntity item) => await Db.InsertAsync(item); - - [HttpPut] - public async Task Update([FromBody]TEntity item) - { - var e = await Read(item.Username, item.Time); - if (e == null) - { - await Create(item); - } - else - { - await Db.UpdateAsync(item); - } - - return Empty; - } - - /* - [HttpDelete("{username}")] - public async Task Delete(string username) => await Db.GetTable().Where(c => c.Username.Equals(username)).DeleteAsync(); - */ + private TEntity Read(string username, DateTime date) => Db.GetTable().FirstOrDefault(e => e.Username.Equals(username) && date == e.Time); } } diff --git a/SeniorAssistant/Data/SeniorDataContext.cs b/SeniorAssistant/Data/SeniorDataContext.cs index 2a23935..027a32c 100644 --- a/SeniorAssistant/Data/SeniorDataContext.cs +++ b/SeniorAssistant/Data/SeniorDataContext.cs @@ -2,6 +2,7 @@ using LinqToDB.Data; using LinqToDB.DataProvider; using SeniorAssistant.Models; +using SeniorAssistant.Models.Users; namespace SeniorAssistant.Data { @@ -11,8 +12,13 @@ namespace SeniorAssistant.Data : base(dataProvider, connectionString) { } - public ITable User => GetTable(); - + public ITable Users => GetTable(); public ITable Heartbeats => GetTable(); + public ITable Sleeps => GetTable(); + public ITable Steps => GetTable(); + public ITable Doctors => GetTable(); + public ITable Patients => GetTable(); + public ITable Notifications => GetTable(); + public ITable Messages => GetTable(); } } diff --git a/SeniorAssistant/Models/Heartbeat.cs b/SeniorAssistant/Models/Heartbeat.cs index baf0622..7bcfd6d 100644 --- a/SeniorAssistant/Models/Heartbeat.cs +++ b/SeniorAssistant/Models/Heartbeat.cs @@ -7,7 +7,6 @@ namespace SeniorAssistant.Models { [PrimaryKey] [NotNull] - [Association(ThisKey = nameof(Username), OtherKey = nameof(User.Username), CanBeNull = false)] public string Username { get; set; } [PrimaryKey] @@ -15,5 +14,10 @@ namespace SeniorAssistant.Models public DateTime Time { get; set; } public double Value { get; set; } + + /* + [Association(ThisKey = nameof(Username), OtherKey = nameof(User.Username), CanBeNull = false)] + public User UserObj { get; set; } + */ } } diff --git a/SeniorAssistant/Models/Menu.cs b/SeniorAssistant/Models/Menu.cs index cafb8a2..1d4957d 100644 --- a/SeniorAssistant/Models/Menu.cs +++ b/SeniorAssistant/Models/Menu.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; +using System.Collections.Generic; namespace SeniorAssistant.Models { @@ -12,8 +9,7 @@ namespace SeniorAssistant.Models public class MenuItem : IMenuItem { - public MenuItem(string text) : this(text, "#") { } - public MenuItem(string text, string href) + public MenuItem(string text, string href = "#") { Text = text; HRef = href; @@ -25,6 +21,6 @@ namespace SeniorAssistant.Models public class SubMenu : IMenuItem { public string Text { get; set; } - public IEnumerable Items { get; set; } + public IList Items { get; set; } } } diff --git a/SeniorAssistant/Models/Message.cs b/SeniorAssistant/Models/Message.cs new file mode 100644 index 0000000..e76f056 --- /dev/null +++ b/SeniorAssistant/Models/Message.cs @@ -0,0 +1,26 @@ +using LinqToDB.Mapping; +using System; + +namespace SeniorAssistant.Models +{ + public class Message : IHasTime + { + [Column(IsPrimaryKey = true, CanBeNull = false, IsIdentity = true)] + public int Id { get; set; } + + [NotNull] + public DateTime Time { get; set; } + + [NotNull] + public string Username { get; set; } + + [NotNull] + public string Reciver { get; set; } + + [NotNull] + public string Body { get; set; } + + public bool Seen { get; set; } + + } +} diff --git a/SeniorAssistant/Models/Notification.cs b/SeniorAssistant/Models/Notification.cs new file mode 100644 index 0000000..b5c16a0 --- /dev/null +++ b/SeniorAssistant/Models/Notification.cs @@ -0,0 +1,21 @@ +using LinqToDB.Mapping; +using System; + +namespace SeniorAssistant.Models +{ + public class Notification : IHasTime + { + [Column(IsPrimaryKey = true, CanBeNull = false, IsIdentity = true)] + public int Id { get; set; } + + [NotNull] + public string Username { get; set; } + + [NotNull] + public DateTime Time { get; set; } + + public bool Seen { get; set; } + + public string Message { get; set; } + } +} diff --git a/SeniorAssistant/Models/Register.cs b/SeniorAssistant/Models/Register.cs deleted file mode 100644 index 40bdbcf..0000000 --- a/SeniorAssistant/Models/Register.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; - -namespace SeniorAssistant.Models -{ - public class Register - { - public string Username { get; set; } - public string Email { get; set; } - public string Password { get; set; } - public bool Doctor { get; set; } - } -} diff --git a/SeniorAssistant/Models/Sleep.cs b/SeniorAssistant/Models/Sleep.cs index 12ba7f9..b542d99 100644 --- a/SeniorAssistant/Models/Sleep.cs +++ b/SeniorAssistant/Models/Sleep.cs @@ -7,7 +7,6 @@ namespace SeniorAssistant.Models { [PrimaryKey] [NotNull] - [Association(ThisKey = nameof(Username), OtherKey = nameof(User.Username), CanBeNull = false)] public string Username { get; set; } [PrimaryKey] diff --git a/SeniorAssistant/Models/Step.cs b/SeniorAssistant/Models/Step.cs index 04eeab6..3385092 100644 --- a/SeniorAssistant/Models/Step.cs +++ b/SeniorAssistant/Models/Step.cs @@ -7,7 +7,6 @@ namespace SeniorAssistant.Models { [PrimaryKey] [NotNull] - [Association(ThisKey = nameof(Username), OtherKey = nameof(User.Username), CanBeNull = false)] public string Username { get; set; } [PrimaryKey] diff --git a/SeniorAssistant/Models/Users/Doctor.cs b/SeniorAssistant/Models/Users/Doctor.cs new file mode 100644 index 0000000..f2f0a7a --- /dev/null +++ b/SeniorAssistant/Models/Users/Doctor.cs @@ -0,0 +1,17 @@ +using LinqToDB.Mapping; + +namespace SeniorAssistant.Models.Users +{ + public class Doctor : IHasUsername + { + [Column(IsPrimaryKey = true, CanBeNull = false)] + public string Username { get; set; } + + [Association(ThisKey = "Username", OtherKey = nameof(User.Username), CanBeNull = false)] + public User UserData { get; set; } + + public string Location { get; set; } + + public string Schedule { get; set; } + } +} diff --git a/SeniorAssistant/Models/Users/Patient.cs b/SeniorAssistant/Models/Users/Patient.cs new file mode 100644 index 0000000..6a326e9 --- /dev/null +++ b/SeniorAssistant/Models/Users/Patient.cs @@ -0,0 +1,18 @@ +using LinqToDB.Mapping; + +namespace SeniorAssistant.Models.Users +{ + public class Patient : IHasUsername + { + [Column(IsPrimaryKey = true, CanBeNull = false)] + public string Username { get; set; } + + [Association(ThisKey = "Username", OtherKey = nameof(User.Username), CanBeNull = false)] + public User UserData { get; set; } + + [NotNull] + public string Doctor { get; set; } + + public string Notes { get; set; } + } +} diff --git a/SeniorAssistant/Models/User.cs b/SeniorAssistant/Models/Users/User.cs similarity index 72% rename from SeniorAssistant/Models/User.cs rename to SeniorAssistant/Models/Users/User.cs index dd9e25c..98f56ba 100644 --- a/SeniorAssistant/Models/User.cs +++ b/SeniorAssistant/Models/Users/User.cs @@ -1,26 +1,22 @@ using LinqToDB.Mapping; -using Microsoft.AspNetCore.Identity; +using Newtonsoft.Json; namespace SeniorAssistant.Models { public class User : IHasUsername { - [PrimaryKey] - [NotNull] + [Column(IsPrimaryKey = true, CanBeNull = false)] public string Username { get; set; } [NotNull] public string Email { get; set; } [NotNull] + [JsonIgnore] public string Password { get; set; } - - [NotNull] - public bool Doctor { get; set; } - + public string Name { get; set; } public string LastName { get; set; } - } } diff --git a/SeniorAssistant/Startup.cs b/SeniorAssistant/Startup.cs index 3d652ee..cbf2c20 100644 --- a/SeniorAssistant/Startup.cs +++ b/SeniorAssistant/Startup.cs @@ -5,7 +5,6 @@ using LinqToDB.DataProvider.SQLite; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; -using Microsoft.Data.Sqlite; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using SeniorAssistant.Configuration; @@ -13,8 +12,8 @@ using SeniorAssistant.Data; using SeniorAssistant.Models; using SeniorAssistant.Extensions; using Swashbuckle.AspNetCore.Swagger; -using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.DependencyInjection.Extensions; +using SeniorAssistant.Models.Users; namespace SeniorAssistant { @@ -31,7 +30,15 @@ namespace SeniorAssistant // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { - services.AddMvc(); + services.AddMvc();// config => +// { +// var policy = new AuthorizationPolicyBuilder() +// .RequireAuthenticatedUser() +// .Build(); +// config.Filters.Add(new AuthorizeFilter(policy)); +// }) +// .SetCompatibilityVersion(CompatibilityVersion.Version_2_1); + services.AddSession(); services.AddSwaggerGen(c => @@ -54,20 +61,30 @@ namespace SeniorAssistant services.Configure(Configuration.GetSection("kendo")); services.Configure(Configuration.GetSection("theme")); +// services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) +// .AddCookie(options => { +// options.LoginPath = "/"; +// options.AccessDeniedPath = "/"; +// }); + +// services.AddDefaultIdentity().AddRoles() +// .AddEntityFrameworkStores(); + services.TryAddSingleton(); - services.AddSingleton>(new IMenuItem[] + services.AddSingleton>(new List { - new SubMenu + new MenuItem("Index", "/"), + new SubMenu() { - Text = "Link veloci", + Text = "Raw Data", Items = new MenuItem[] { - new MenuItem("User", "/"), + new MenuItem("Users", "/users"), new MenuItem("Heartbeat", "/heartbeat"), new MenuItem("Sleep", "/sleep"), new MenuItem("Step", "/step") } - }, + } }); var dbFactory = new SeniorDataContextFactory( @@ -77,6 +94,7 @@ namespace SeniorAssistant services.AddSingleton>(dbFactory); SetupDatabase(dbFactory); + FillDatabase(dbFactory); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. @@ -90,6 +108,7 @@ namespace SeniorAssistant app.UseSession(); app.UseStaticFiles(); +// app.UseAuthentication(); // Enable middleware to serve generated Swagger as a JSON endpoint. app.UseSwagger(); @@ -120,55 +139,83 @@ namespace SeniorAssistant { using (var db = dataContext.Create()) { - const string baseUsername = "vecchio"; - string[] users = { "Mario", "Giovanni", "Aldo", "Giacomo", "Marcello", "Filippo" }; - db.CreateTableIfNotExists(); db.CreateTableIfNotExists(); db.CreateTableIfNotExists(); - try + db.CreateTableIfNotExists(); + db.CreateTableIfNotExists(); + db.CreateTableIfNotExists(); + db.CreateTableIfNotExists(); + db.CreateTableIfNotExists(); + } + } + + void FillDatabase(IDataContextFactory dataContext) + { + using (var db = dataContext.Create()) + { + Random rnd = new Random(); + + List users = new List(); + + List docs = db.Doctors.ToListAsync().Result; + if (docs.Count == 0) { - db.CreateTable(); + users.Add(new User { Name = "Alfredo", LastName = "Parise", Email = "alfred.pary@libero.it", Username = "alfredigno", Password = "alfy" }); + users.Add(new User { Name = "Edoardo", LastName = "Marzio", Email = "edo.marzio@libero.it", Username = "marzietto", Password = "edo64" }); + + docs.Add(new Doctor { Username = "alfredigno", Location = "Brasile" }); + docs.Add(new Doctor { Username = "marzietto", Location = "Uganda" }); + + foreach (var doc in docs) + db.InsertOrReplace(doc); + } + + List patients = db.Patients.ToListAsync().Result; + if (patients.Count == 0) + { + const string baseUsername = "vecchio"; + string[] names = { "Mario", "Giovanni", "Aldo", "Giacomo", "Marcello", "Filippo" }; + string[] lastnames = { "Rossi", "Storti", "Baglio", "Poretti", "Marcelli", "Martelli" }; int count = 0; - foreach (string user in users) + for (count=0; count().MaxAsync(x => x.Time).Result; TimeSpan span = now.Subtract(maxTimeInDB); totalHours = span.TotalHours; - } catch { } - - for (int i = 0; i dbFactory +@model string + @{ ViewBag.Title = "Hello Razor"; + var session = HttpContextAccessor.HttpContext.Session; + var username = session.GetString("username"); + + bool auth = username.Equals(Model); + bool isDoc = session.GetString("role").Equals("doctor"); + Patient patient = null; + if (isDoc) + { + var db = dbFactory.Create(); + patient = (from p in db.Patients + where p.Username.Equals(Model) && p.Doctor.Equals(username) + select p).ToArray().FirstOrDefault(); + auth = auth || patient != null; + } } -
- - \ No newline at end of file + }); + + } + + + + +} \ No newline at end of file diff --git a/SeniorAssistant/Views/Home/Index.cshtml b/SeniorAssistant/Views/Home/Index.cshtml index 76f15dd..9157d25 100644 --- a/SeniorAssistant/Views/Home/Index.cshtml +++ b/SeniorAssistant/Views/Home/Index.cshtml @@ -5,26 +5,32 @@ logo sito disattivare l-aside e le opzioni se non loggato deve tornare qua --> +@model string @inject IHttpContextAccessor HttpContextAccessor @{ + ViewBag.Title = "Hello Razor"; string session = HttpContextAccessor.HttpContext.Session.GetString("username"); }
@if (session == null) { + @if (Model != null) + { +

Per poter accedere alla pagina [@Model] e' necessario essere loggati

+ } + - + } else { - await Html.RenderPartialAsync("Profile"); + await Html.RenderPartialAsync("Profile"); // magari sostituire qui }
diff --git a/SeniorAssistant/Views/Home/Message.cshtml b/SeniorAssistant/Views/Home/Message.cshtml new file mode 100644 index 0000000..df40cae --- /dev/null +++ b/SeniorAssistant/Views/Home/Message.cshtml @@ -0,0 +1,30 @@ +@model int +@inject IHttpContextAccessor HttpContextAccessor +@inject IDataContextFactory dbFactory +@using LinqToDB; + +@{ + ViewBag.Title = "Hello Razor"; + string username = HttpContextAccessor.HttpContext.Session.GetString("username"); + var db = dbFactory.Create(); + var message = (from m in db.Messages + where m.Id.Equals(Model) && m.Reciver.Equals(username) + select m).ToArray().FirstOrDefault(); +} + +
+ @if (message == null) + { +

Non hai il permesso

+ } + else + { + message.Seen = true; + db.Update(message); +

Messaggio da @message.Username

+

Inviato il @message.Time

+
+ @message.Body +
+ } +
diff --git a/SeniorAssistant/Views/Home/Users.cshtml b/SeniorAssistant/Views/Home/Users.cshtml index 4c30ece..27fec0e 100644 --- a/SeniorAssistant/Views/Home/Users.cshtml +++ b/SeniorAssistant/Views/Home/Users.cshtml @@ -8,19 +8,11 @@ +} \ No newline at end of file diff --git a/SeniorAssistant/Views/Shared/Profile.cshtml b/SeniorAssistant/Views/Shared/Profile.cshtml index 187bcc8..2e277a9 100644 --- a/SeniorAssistant/Views/Shared/Profile.cshtml +++ b/SeniorAssistant/Views/Shared/Profile.cshtml @@ -1,16 +1,162 @@ -@model User -@inject IHttpContextAccessor HttpContextAccessor +@inject IHttpContextAccessor HttpContextAccessor +@inject IDataContextFactory dbFactory @{ var session = HttpContextAccessor.HttpContext.Session; + var db = dbFactory.Create(); + var username = session.GetString("username"); + var patientData = db.Patients.Where(p => p.Username.Equals(username)).ToArray().FirstOrDefault(); + var hasDoc = patientData != null; }
-

- Welcome @session.GetString("username") +
+

+ Welcome @username +

+ name: @session.GetString("name")
+ lastname: @session.GetString("lastname")
+ email: @session.GetString("email")
+
-

- name: @session.GetString("name")
- lastname: @session.GetString("lastname")
- email: @session.GetString("email") +
+ @if (hasDoc) // is patient and has doc, must show doc data + { + var doctor = (from u in db.Users + join d in db.Doctors on u.Username equals d.Username + where d.Username.Equals(patientData.Doctor) + select new { u.Username, u.Name, u.LastName, d.Location }).ToArray().First(); + +

Dottore: @doctor.Name @doctor.LastName

+

Dove mi puoi trovare? @doctor.Location

+ + +
+

Invia un messaggio al tuo dottore

+ + +

+ + +
+ } + else + { + dynamic[] data; + Type type = null; + string title = null; + var docData = db.Doctors.Where(d => d.Username.Equals(username)).ToArray().FirstOrDefault(); + + if (docData != null) // is DOC + { + // see all the patient of the doc + title = "Lista dei pazienti"; + var patients = (from u in db.Users + join p in db.Patients on u.Username equals p.Username + where p.Doctor.Equals(docData.Username) + select new { u.Username, u.Name, u.LastName, p.Notes, Profile = "Profile" }).ToArray(); + data = patients; + type = patients.FirstOrDefault().GetType(); + } + else // is a patient and need to choose a doctor + { + // choose which doc you want + title = "Scegli un Doc"; + var docs = (from u in db.Users + join d in db.Doctors on u.Username equals d.Username + select new { u.Username, u.Name, u.LastName, d.Location, Choose = "Scegli" }).ToArray(); + data = docs; + type = docs.FirstOrDefault().GetType(); + } + + var fields = new List(); + foreach (var field in type.GetProperties()) + { + fields.Add(field.Name); + } + +

@title

+
+ + } +
diff --git a/SeniorAssistant/Views/Shared/Register.cshtml b/SeniorAssistant/Views/Shared/Register.cshtml index 9cbe317..bbe41f9 100644 --- a/SeniorAssistant/Views/Shared/Register.cshtml +++ b/SeniorAssistant/Views/Shared/Register.cshtml @@ -1,8 +1,10 @@ 
  • - - - + + + + +
    @@ -13,20 +15,26 @@