Пример #1
0
        /// TODO: MOVE
        public static async Task <bool> MessagePatient(DbCtx ctx, string carerApiKey, string patientId, JObject messageJson)
        {
            try
            {
                var    jsonDict = JObject.FromObject(messageJson).ToObject <Dictionary <string, object> >();
                string title    = (string)jsonDict["Title"];
                string message  = (string)jsonDict["Message"];
                Carer  carer    = (Carer)GetEntityByForeignKey(ctx, carerApiKey, Collection.carers);

                if (carer != null)
                {
                    Patient patient = (Patient) await GetEntityByPrimaryKey(ctx, patientId, Collection.patients);

                    if (patient != null)
                    {
                        PatientMessage messageObj = new PatientMessage()
                        {
                            Read = null, Sent = DateTime.Now, Title = title, Message = message, CarerId = carer.Email
                        };
                        patient.Messages.Add(messageObj);
                        await ctx.SaveChangesAsync();

                        return(true);
                    }
                }

                return(false);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return(false);
            }
        }
Пример #2
0
        public IHttpActionResult PutCarer(int id, Carer carer)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != carer.CarerID)
            {
                return(BadRequest());
            }

            db.Entry(carer).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!CarerExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
Пример #3
0
 public IActionResult Delete([FromHeader(Name = "ApiKey")] string carerApiKey, [FromQuery(Name = "id")] string entryId)
 {
     try
     {
         CalendarEntry entry       = (CalendarEntry)DbService.GetEntityByPrimaryKey(_ctx, entryId, DbService.Collection.calendars).GetAwaiter().GetResult();
         bool          entryExists = DbService.GetEntityByPrimaryKey(_ctx, entryId, DbService.Collection.calendars).GetAwaiter().GetResult() != null;
         if (entryExists)
         {
             Carer carer      = (Carer)DbService.GetEntityByForeignKey(_ctx, carerApiKey, DbService.Collection.carers);
             bool  authorised = (carer.AssignedPatientIds != null && carer.AssignedPatientIds.Contains(entry.PatientId));
             if (authorised)
             {
                 bool success = DbService.DeleteEntityByPrimaryKey(_ctx, entryId, DbService.Collection.calendars).GetAwaiter().GetResult();
                 if (success)
                 {
                     return(Ok("Calendar entry deleted successfully."));
                 }
                 return(BadRequest("Failed to delete calendar entry."));
             }
             return(Unauthorized("You are not assigned to that patient."));
         }
         return(NotFound("Could not find an entry with that id."));
     }
     catch (Exception e)
     {
         return(BadRequest(e));
     }
 }
Пример #4
0
        public bool CheckUsersPassword(string username, string password)
        {
            Carer userToCheck = null;

            try
            {
                userToCheck = _carers.Find(user => user.UserName == username).FirstOrDefault();
            }
            catch (Exception e)
            {
                userToCheck = null;
            }

            if (userToCheck != null)
            {
                // Check password against a stored hash
                byte[]       hashBytes = Convert.FromBase64String(userToCheck.Password);
                PasswordHash hash      = new PasswordHash(hashBytes);
                if (!hash.Verify(password))
                {
                    throw new UnauthorizedAccessException();
                }
                return(true);
            }
            return(false);
        }
Пример #5
0
 public IActionResult Delete([FromHeader(Name = "ApiKey")] string apiKey, [FromQuery(Name = "id")] string email)
 {
     try
     {
         Carer carer       = (Carer)DbService.GetEntityByPrimaryKey(_ctx, email, DbService.Collection.carers).GetAwaiter().GetResult();
         bool  carerExists = carer != null;
         if (carerExists)
         {
             bool notDeletingSelf = carer.User.ApiKey != apiKey;
             if (notDeletingSelf)
             {
                 bool success = DbService.DeleteEntityByPrimaryKey(_ctx, email, DbService.Collection.carers).GetAwaiter().GetResult();
                 if (success)
                 {
                     return(Ok("Carer deleted successfully."));
                 }
                 return(BadRequest("Failed to delete carer."));
             }
             return(Unauthorized("Accounts must be deleted by an admin other than yourself."));
         }
         return(NotFound("Could not find a carer with that email."));
     }
     catch (Exception e)
     {
         return(BadRequest(e));
     }
 }
Пример #6
0
 public IActionResult Post([FromBody] string email)
 {
     try
     {
         bool emailValid = (!string.IsNullOrWhiteSpace(email) && email.Contains("@"));
         if (!emailValid)
         {
             return(BadRequest("Invalid email format."));
         }
         Carer carer = (Carer)DbService.GetEntityByPrimaryKey(_ctx, email, DbService.Collection.carers).GetAwaiter().GetResult();
         bool  emailAlreadyExists = carer != null;
         if (emailAlreadyExists)
         {
             return(BadRequest("Email address already in use."));
         }
         bool success = DbService.CreateUser(_ctx, email, Models.User.UserRole.informalcarer).GetAwaiter().GetResult();
         if (success)
         {
             return(Ok("New carer added successfully."));
         }
         return(BadRequest("Failed to create new carer."));
     }
     catch (Exception e)
     {
         return(BadRequest(e));
     }
 }
Пример #7
0
        public IHttpActionResult GetCarer(int id)
        {
            Carer carer = db.Carers.Find(id);

            if (carer == null)
            {
                return(NotFound());
            }

            return(Ok(carer));
        }
Пример #8
0
        public IHttpActionResult PostCarer(Carer carer)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            db.Carers.Add(carer);
            db.SaveChanges();

            return(CreatedAtRoute("DefaultApi", new { id = carer.CarerID }, carer));
        }
Пример #9
0
        public IHttpActionResult DeleteCarer(int id)
        {
            Carer carer = db.Carers.Find(id);

            if (carer == null)
            {
                return(NotFound());
            }

            db.Carers.Remove(carer);
            db.SaveChanges();

            return(Ok(carer));
        }
Пример #10
0
        public IHttpActionResult DeleteCarer(int id)
        {
            Carer carer = db.Carers.Find(id);

            if (carer == null)
            {
                return(NotFound());
            }
            db.Database.ExecuteSqlCommand("DELETE FROM CarerPatient WHERE CarerID = " + carer.CarerID + ";");
            db.Carers.Remove(carer);
            db.SaveChanges();

            return(Ok(carer));
        }
Пример #11
0
        public IHttpActionResult LoginCarer(string email, string pwd)
        {
            Carer c = (from car in db.Carers
                       where car.CarerEmail == email &&
                       car.CarerPwd == pwd
                       select car).First();

            if (c == null)
            {
                return(NotFound());
            }

            return(Ok(c));
        }
Пример #12
0
 /// TODO: MOVE
 public static bool PatientIsAssigned(DbCtx ctx, string carerId, string patientId)
 {
     try
     {
         Carer carer = (Carer)GetEntityByForeignKey(ctx, carerId, Collection.carers);
         bool  patientAssignedToThisCarer = carer.AssignedPatientIds.Contains(patientId);
         return(patientAssignedToThisCarer);
     }
     catch (Exception e)
     {
         Console.WriteLine(e);
     }
     return(false);
 }
Пример #13
0
        /// TODO: MOVE
        public static async Task <bool> AllocatePatient(DbCtx ctx, JObject patientAndCarerId)
        {
            try
            {
                string  patientId  = (string)patientAndCarerId["patient"];
                string  carerEmail = (string)patientAndCarerId["carer"];
                bool    assign     = (bool)patientAndCarerId["assign"]; // Whether to assign or unassign.
                Patient patient    = (Patient) await GetEntityByPrimaryKey(ctx, patientId, Collection.patients);

                Carer carer = (Carer) await GetEntityByPrimaryKey(ctx, carerEmail, Collection.carers);

                bool patientAlreadyAssigned = carer.AssignedPatientIds.Contains(patientId);
                if (assign)
                {
                    // Assign the patient to the carer if they are not assigned.
                    if (!patientAlreadyAssigned)
                    {
                        carer.AssignedPatientIds += "," + patientId;
                        await ctx.SaveChangesAsync();
                    }
                }
                else
                {
                    // Unassign the patient from the carer if they are assigned..
                    if (patientAlreadyAssigned)
                    {
                        if (patientId != "testpatient") // Don't remove test record.
                        {
                            // Awkward string ops because efcore doesn't allow for simply storing lists of strings.
                            carer.AssignedPatientIds = carer.AssignedPatientIds.Replace(patientId, "");
                            carer.AssignedPatientIds = carer.AssignedPatientIds.Replace(",,", ""); // Remove any residual comma pairs.
                            carer.AssignedPatientIds = carer.AssignedPatientIds.TrimEnd(',');      // Remove end comma if no value follows.
                            carer.AssignedPatientIds = carer.AssignedPatientIds.TrimStart(',');    // Remove start comma if no value follows.
                        }
                        await ctx.SaveChangesAsync();
                    }
                }
                return(true);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
            return(false);
        }
Пример #14
0
 public Carer CreateAdmin(NewUser user)
 {
     if (_carerservice.ValidateNewUser(user) != null)
     {
         var x = new Carer()
         {
             UserName     = user.UserName,
             FirstName    = user.FirstName,
             LastName     = user.LastName,
             EmailAddress = user.EmailAddress,
             Password     = user.Password,
             Role         = "Admin"
         };
         _carers.InsertOne(x);
         return(x);
     }
     return(null);
 }
Пример #15
0
        /// TODO: MOVE
        public static async Task <bool> ChangeCarerPermission(DbCtx ctx, JObject carerAndRole)
        {
            try
            {
                string carerEmail = (string)carerAndRole["email"];
                string role       = (string)carerAndRole["role"];
                Carer  carer      = (Carer) await GetEntityByPrimaryKey(ctx, carerEmail, Collection.carers);

                carer.User.Role = role;
                await ctx.SaveChangesAsync();

                return(true);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
            return(false);
        }
Пример #16
0
        public Carer CreateUser(NewUser user)
        {
            var newUserObj = ValidateNewUser(user);

            if (newUserObj != null)
            {
                var x = new Carer()
                {
                    UserName     = user.UserName,
                    FirstName    = user.FirstName,
                    LastName     = user.LastName,
                    EmailAddress = user.EmailAddress,
                    Password     = user.Password,
                    Role         = user.Role
                };
                _carers.InsertOne(x);
                return(x);
            }
            return(null);
        }
Пример #17
0
        public async Task PutPatientInfoBadRequest()
        {
            // arrange
            TestClient           testClient         = new TestClient();
            const string         endpoint           = "patientinfo/put/?id=testpatient";
            const HttpStatusCode expectedStatusCode = HttpStatusCode.BadRequest;

            testClient.AddHeader("ApiKey", "testcarer");
            Carer        carer                = new Carer();
            string       requestBody          = JsonConvert.SerializeObject(carer);
            const string expectedResponseBody = "Failed to update the patient.";

            // act
            HttpResponseMessage response = await testClient.PutRequest(endpoint, body : requestBody);

            HttpStatusCode actualStatusCode   = response.StatusCode;
            string         actualResponseBody = await response.Content.ReadAsStringAsync();

            // assert
            Assert.Equal(expectedStatusCode, actualStatusCode);
            Assert.Equal(expectedResponseBody, actualResponseBody);
        }
Пример #18
0
        public IHttpActionResult PutCarer(int id, Carer carer)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != carer.CarerID)
            {
                return(BadRequest());
            }

            db.Entry(carer).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!CarerExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    return(BadRequest());
                }
            }

            Carer car = db.Carers.Find(id);

            if (car == null)
            {
                return(NotFound());
            }

            return(Ok(carer));
        }
Пример #19
0
        public async Task StickiesPostBadRequest()
        {
            // arrange
            TestClient           testClient         = new TestClient();
            const string         endpoint           = "stickies/post";
            const HttpStatusCode expectedStatusCode = HttpStatusCode.BadRequest;
            Carer        sticky           = new Carer(); // Incorrect serialisation
            const string expectedResponse = "Failed to add sticky note.";
            string       requestBody      = JsonConvert.SerializeObject(sticky);

            testClient.AddHeader("ApiKey", "testpatient");

            // act
            HttpResponseMessage response = await testClient.PostRequest(endpoint, body : requestBody);

            HttpStatusCode actualStatusCode = response.StatusCode;
            string         actualResponse   = await response.Content.ReadAsStringAsync();

            // assert
            Assert.Equal(expectedStatusCode, actualStatusCode);
            Assert.Equal(expectedResponse, actualResponse);
        }
Пример #20
0
        public IHttpActionResult Get(string loginEmail, string loginPwd)
        {
            Carer c = null;

            try
            {
                c = (from car in db.Carers
                     where car.CarerEmail == loginEmail &&
                     car.CarerPwd == loginPwd
                     select car).First();
            }
            catch
            {
                return(NotFound());
            }

            if (c == null)
            {
                return(NotFound());
            }

            return(Ok(c));
        }
Пример #21
0
        public static async Task <List <object> > GetAssignedPatients(DbCtx ctx, string carerApiKey)
        {
            try
            {
                Carer carer = (Carer) await GetEntityByPrimaryKey(ctx, carerApiKey, Collection.carers);

                List <string> assignedPatients = carer.AssignedPatientIds.Split(',', StringSplitOptions.RemoveEmptyEntries).ToList();
                List <object> patients         = new List <object>();
                foreach (string patientId in assignedPatients)
                {
                    Patient p = (Patient) await GetEntityByPrimaryKey(ctx, patientId, Collection.patients);

                    bool logsExist = p.ActivityLogs.Count > 0;
                    if (logsExist)
                    {
                        ActivityLog lastLog = p.ActivityLogs.OrderBy(l => l.DateTime).Last();
                        patients.Add(new Dictionary <string, object>()
                        {
                            { "id", p.Id }, { "activity", lastLog.Caption }, { "when", lastLog.DateTime }, { "where", lastLog.Location }, { "status", p.Status }
                        });
                    }
                    else
                    {
                        patients.Add(new Dictionary <string, object>()
                        {
                            { "id", p.Id }, { "activity", "" }, { "when", "" }, { "where", "" }, { "status", p.Status }
                        });
                    }
                }
                return(patients);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
            return(null);
        }
Пример #22
0
        /// TODO: MOVE
        public static async Task <bool> CreateUser(DbCtx ctx, string primaryKey, User.UserRole role)
        {
            try
            {
                User user = new User()
                {
                    Role = role.ToString()
                };
                await ctx.Users.AddAsync(user);

                if (role == User.UserRole.patient)
                {
                    Patient patient = new Patient()
                    {
                        User = user, Id = primaryKey
                    };
                    await ctx.Patients.AddAsync(patient);
                }
                else
                {
                    Carer carer = new Carer()
                    {
                        User = user, Email = primaryKey
                    };
                    await ctx.Carers.AddAsync(carer);
                }

                await ctx.SaveChangesAsync();

                return(true);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
            return(false);
        }
Пример #23
0
        public IActionResult Allocate([FromBody] JObject patientAndCarerId)
        {
            try
            {
                string  patientId  = (string)patientAndCarerId["patient"];
                string  carerEmail = (string)patientAndCarerId["carer"];
                bool    assign     = (bool)patientAndCarerId["assign"]; // Whether to assign or unassign.
                Patient patient    = (Patient)DbService.GetEntityByPrimaryKey(_ctx, patientId, DbService.Collection.patients).GetAwaiter().GetResult();
                Carer   carer      = (Carer)DbService.GetEntityByPrimaryKey(_ctx, carerEmail, DbService.Collection.carers).GetAwaiter().GetResult();

                if (carer != null && patient != null)
                {
                    List <string> assignedPatients = carer.AssignedPatientIds.Split(',', StringSplitOptions.RemoveEmptyEntries).ToList();
                    bool          canAssign        = (carer.User.Role != "informalcarer" || assignedPatients.Count == 0);
                    if (canAssign)
                    {
                        bool success = DbService.AllocatePatient(_ctx, patientAndCarerId).GetAwaiter().GetResult();
                        if (success)
                        {
                            if (assign)
                            {
                                return(Ok("Assigned successfully."));
                            }
                            return(Ok("Unassigned successfully."));
                        }
                        return(BadRequest("Failed."));
                    }
                    return(BadRequest("Informal carers may only have a single assigned patient."));
                }
                return(NotFound("Either the patient or carer does not exist."));
            }
            catch (Exception e)
            {
                return(BadRequest(e));
            }
        }
Пример #24
0
 public IActionResult Role([FromBody] JObject carerAndRole)
 {
     try
     {
         string carerEmail = (string)carerAndRole["carer"];
         string roleStr    = (string)carerAndRole["role"];
         Carer  carer      = (Carer)DbService.GetEntityByPrimaryKey(_ctx, carerEmail, DbService.Collection.carers).GetAwaiter().GetResult();
         if (carer != null)
         {
             bool roleExists = Enum.GetNames(typeof(User.UserRole)).Contains(roleStr);;
             if (roleExists)
             {
                 DbService.ChangeCarerPermission(_ctx, carerAndRole).GetAwaiter().GetResult();
                 return(Ok("Role changed successfully."));
             }
             return(NotFound("Invalid role specified."));
         }
         return(NotFound("Carer does not exist."));
     }
     catch (Exception e)
     {
         return(BadRequest(e));
     }
 }
Пример #25
0
        private static void SerializePatient()
        {
            Patient patient = new Patient();

            PersonData cd = new PersonData();
            cd.ID = Guid.NewGuid();
            cd.Surname = "Androulidakis";
            cd.Name = "Aggelos";

            List<Communication> communications = new List<Communication>();

            Communication commun1 = new Communication();
            commun1.IsPrimary = true;
            commun1.Type = CommunicationType.Phone;
            commun1.Value = "+302107722453";
            communications.Add(commun1);

            Communication commun2 = new Communication();
            commun2.IsPrimary = false;
            commun2.Value = "*****@*****.**";
            commun2.Type = CommunicationType.Email;
            communications.Add(commun2);

            cd.CommunicationList = new List<Communication>(communications);

            List<Address> addresses = new List<Address>();
            Address address = new Address();
            address.Street = "Patission";
            address.StreetNo = "42";
            address.City = "Athens";
            address.Country = "GR";
            address.Notes = "3rd floor";
            address.IsPrimary = true;
            address.ZipCode = "123-45";
            address.County = "Attica";
            addresses.Add(address);
            addresses.Add(address);

            List<Identifier> ids = new List<Identifier>();
            Identifier id = new Identifier();
            id.Type = IdentifierType.PassportID;
            id.Number = "AB202825";
            id.IssueDate = "17/02/2003";
            id.IssueAuthority = "ABC";
            ids.Add(id);
            ids.Add(id);

            cd.IdentifierList = ids;

            cd.AddressList = new List<Address>(addresses);

            patient.PersonData = cd;

            SocioDemographicData sd = new SocioDemographicData();
            sd.Age = 82;
            SystemParameter maritalStatus = new SystemParameter();
            maritalStatus.Code = 1;
            maritalStatus.Description = "widow";
            sd.MaritalStatus = maritalStatus;

            sd.Children = 2;
            SystemParameter sex = new SystemParameter();
            sex.Code = 1;
            sex.Description = "Male";

            sd.Gender = sex;

            SystemParameter livingWith = new SystemParameter();
            livingWith.Code = 1;
            livingWith.Description = "with son/daughter";

            sd.LivingWith = livingWith;

            patient.SD_Data = sd;

            Carer c1 = new Carer();
            c1.PersonData = patient.PersonData;
            c1.SD_Data = patient.SD_Data;

            PatientCaregiver pc1 = new PatientCaregiver();
            pc1.Caregiver = c1;
            pc1.IsPrimary = true;

            PatientCaregiver pc2 = new PatientCaregiver();
            pc2.Caregiver = c1;
            pc2.IsPrimary = false;

            patient.PatientCaregiverList.ListOfCaregivers.Add(pc1);
            patient.PatientCaregiverList.ListOfCaregivers.Add(pc2);

            Clinician respClinician = new Clinician();
            respClinician.PersonData = patient.PersonData;

            patient.ResponsibleClinician = respClinician;

            //PatientAssessment assessment = new PatientAssessment();
            //assessment.MMSE = 22;
            //assessment.DateOfAssessment = System.DateTime.Now;

            //patient.Assessments.ListOfAssessments.Add(assessment);

            SerializeMe(patient, "Patient.xml");
        }
Пример #26
0
 public static Carer WithoutPassword(this Carer user)
 {
     user.Password = null;
     return(user);
 }
Пример #27
0
 public void UpdateUser(string id, Carer updatedUser) =>
 _carers.ReplaceOne(user => user.Id == id, updatedUser);