private HttpResponseMessage handleBasicAuth(string nric, string password, string deviceID)
        {
            var    response = Request.CreateResponse(HttpStatusCode.Unauthorized);
            JWTBLL jwtBll   = new JWTBLL();

            // Ensure nric, password, deviceID exists
            if (!(AccountBLL.IsNRICValid(nric) && AccountBLL.IsPasswordValid(password) && AccountBLL.IsDeviceIDValid(deviceID)))
            {
                return(response);
            }

            // Authorize if the account is valid
            Account account = accountBLL.GetStatus(nric, password, deviceID);

            if (account.status == 1)
            {
                string role   = account.patientStatus.ToString() + account.therapistStatus.ToString();
                string newJwt = accountBLL.LoginDevice(nric, role);
                response = Request.CreateResponse(HttpStatusCode.OK);
                response.Headers.Add("Authorization", "Bearer " + newJwt);
                return(response);
            }

            return(response);
        }
        private HttpResponseMessage handleJwtAuth(string jwt, string deviceID)
        {
            var    response = Request.CreateResponse(HttpStatusCode.Unauthorized);
            string retrievedNRIC;

            JWTBLL jwtBll = new JWTBLL();

            // Ensure jwt, deviceID exists
            if (!(!string.IsNullOrEmpty(jwt) && AccountBLL.IsDeviceIDValid(deviceID)))
            {
                return(response);
            }

            // Validate jwt
            if (!jwtBll.ValidateJWT(jwt))
            {
                return(response);
            }
            else
            {
                retrievedNRIC = jwtBll.getNRIC(jwt);
            }

            // Authorize if the account is valid
            if (accountBLL.IsValid(retrievedNRIC, deviceID))
            {
                string newJwt = jwtBll.UpdateJWT(jwt);
                response = Request.CreateResponse(HttpStatusCode.OK);
                response.Headers.Add("Authorization", "Bearer " + newJwt);
                return(response);
            }

            return(response);
        }
        public HttpResponseMessage TherapistUpload([FromBody] dynamic credentials)
        {
            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Unauthorized);
            string jwt;
            string deviceID;
            string retrievedNRIC;

            AccountBLL accountBLL = new AccountBLL();
            JWTBLL     jwtBll     = new JWTBLL();

            HttpContext httpContext = HttpContext.Current;
            string      authHeader  = httpContext.Request.Headers["Authorization"];

            // Ensure Authorization Header exists
            if (authHeader != null && authHeader.StartsWith("Bearer"))
            {
                string   authHeaderValue        = authHeader.Substring("Bearer ".Length).Trim();
                string   authHeaderValueDecoded = Encoding.UTF8.GetString(Convert.FromBase64String(authHeaderValue));
                string[] authHeaderParts        = authHeaderValueDecoded.Split(':');
                jwt      = authHeaderParts[0];
                deviceID = authHeaderParts[1];
            }
            else
            {
                return(response);
            }

            // Ensure jwt, deviceID exists
            if (!(!string.IsNullOrEmpty(jwt) && AccountBLL.IsDeviceIDValid(deviceID)))
            {
                return(response);
            }

            // Validate jwt
            if (!jwtBll.ValidateJWT(jwt))
            {
                return(response);
            }
            else
            {
                retrievedNRIC = jwtBll.getNRIC(jwt);
            }

            // Validate deviceID for retrievedNRIC
            if (!(accountBLL.IsValid(retrievedNRIC, deviceID)))
            {
                return(response);
            }

            // Upload record
            accountBLL.SetRole(retrievedNRIC, "Therapist");
            Account account = accountBLL.GetStatus(retrievedNRIC);

            if (account.status == 1)
            {
                try
                {
                    Classes.Entity.Patient patient = new TherapistBLL().GetPatientPermissions(Convert.ToString(credentials.patientNRIC));

                    Record record = new Record();
                    record.patientNRIC = credentials.patientNRIC;
                    record.creatorNRIC = retrievedNRIC;
                    record.title       = System.Text.Encoding.Default.GetString(Convert.FromBase64String(Convert.ToString(credentials.title)));
                    record.description = System.Text.Encoding.Default.GetString(Convert.FromBase64String(Convert.ToString(credentials.description)));
                    record.type        = RecordType.Get(Convert.ToString(credentials.type));
                    record.isEmergency = patient.isEmergency;
                    record.content     = string.Empty;

                    if (!record.IsTitleValid())
                    {
                        return(Request.CreateResponse(HttpStatusCode.Forbidden, "Invalid record title"));
                    }

                    if (!record.IsDescriptionValid())
                    {
                        return(Request.CreateResponse(HttpStatusCode.Forbidden, "Invalid record description"));
                    }

                    if (record.type.isContent)
                    {
                        record.content = credentials.content;

                        if (!record.IsContentValid())
                        {
                            return(Request.CreateResponse(HttpStatusCode.Forbidden, "Invalid record content"));
                        }
                    }
                    else
                    {
                        record.fileName      = System.Text.Encoding.Default.GetString(Convert.FromBase64String(Convert.ToString(credentials.fileName)));
                        record.fileExtension = System.Text.Encoding.Default.GetString(Convert.FromBase64String(Convert.ToString(credentials.fileExtension)));
                        byte[] fileContent = Convert.FromBase64String(Convert.ToString(credentials.fileContent));
                        record.fileSize = fileContent.Length;

                        if (Convert.ToInt64(record.fileSize) > Convert.ToInt64(credentials.fileSize))
                        {
                            return(Request.CreateResponse(HttpStatusCode.Forbidden, "Record file size mismatch"));
                        }

                        if (!record.IsFileValid())
                        {
                            return(Request.CreateResponse(HttpStatusCode.Forbidden, "Invalid record file"));
                        }

                        record.createTime = DateTime.Now;

                        Directory.CreateDirectory(record.GetFileServerPath() + "\\" + record.GetFileDirectoryNameHash());

                        File.WriteAllBytes(record.fullpath, fileContent);
                    }

                    recordBLL.AddRecord(record);

                    response = Request.CreateResponse(HttpStatusCode.OK);
                    response.Headers.Add("Authorization", "Bearer " + jwtBll.UpdateJWT(jwt));
                }
                catch
                {
                    response = Request.CreateResponse(HttpStatusCode.InternalServerError);
                }

                return(response);
            }

            return(response);
        }
        public HttpResponseMessage TherapistScanPatient()
        {
            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Unauthorized);
            string jwt;
            string deviceID;
            string tokenID;
            string retrievedNRIC;

            AccountBLL accountBLL = new AccountBLL();
            JWTBLL     jwtBll     = new JWTBLL();

            HttpContext httpContext = HttpContext.Current;
            string      authHeader  = httpContext.Request.Headers["Authorization"];

            // Ensure Authorization Header exists
            if (authHeader != null && authHeader.StartsWith("Bearer"))
            {
                string   authHeaderValue        = authHeader.Substring("Bearer ".Length).Trim();
                string   authHeaderValueDecoded = Encoding.UTF8.GetString(Convert.FromBase64String(authHeaderValue));
                string[] authHeaderParts        = authHeaderValueDecoded.Split(':');
                jwt      = authHeaderParts[0];
                deviceID = authHeaderParts[1];
                tokenID  = authHeaderParts[2];
            }
            else
            {
                return(response);
            }

            // Ensure jwt, deviceID, tokenID exists
            if (!(!string.IsNullOrEmpty(jwt) && AccountBLL.IsDeviceIDValid(deviceID) && AccountBLL.IsTokenIDValid(tokenID)))
            {
                return(response);
            }

            // Validate jwt
            if (!jwtBll.ValidateJWT(jwt))
            {
                return(response);
            }
            else
            {
                retrievedNRIC = jwtBll.getNRIC(jwt);
            }

            // Validate deviceID for retrievedNRIC
            if (!(accountBLL.IsValid(retrievedNRIC, deviceID)))
            {
                return(response);
            }

            // Accept emergency patient and update JWT
            accountBLL.SetRole(retrievedNRIC, "Therapist");
            Account account = accountBLL.GetStatus(retrievedNRIC);

            if (account.status == 1)
            {
                try
                {
                    TherapistBLL therapistBLL = new TherapistBLL();
                    bool         check        = therapistBLL.AcceptEmergencyPatient(tokenID);

                    if (check)
                    {
                        response = Request.CreateResponse(HttpStatusCode.OK);
                        response.Headers.Add("Authorization", "Bearer " + jwtBll.UpdateJWT(jwt));
                    }
                    else
                    {
                        response = Request.CreateResponse(HttpStatusCode.Forbidden);
                    }
                }
                catch
                {
                    response = Request.CreateResponse(HttpStatusCode.InternalServerError);
                }
                return(response);
            }

            return(response);
        }
        public HttpResponseMessage TherapistGetPermissions()
        {
            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Unauthorized);
            string jwt;
            string deviceID;
            string patientNRIC;
            string retrievedNRIC;

            AccountBLL accountBLL = new AccountBLL();
            JWTBLL     jwtBll     = new JWTBLL();

            HttpContext httpContext = HttpContext.Current;
            string      authHeader  = httpContext.Request.Headers["Authorization"];

            // Ensure Authorization Header exists
            if (authHeader != null && authHeader.StartsWith("Bearer"))
            {
                string   authHeaderValue        = authHeader.Substring("Bearer ".Length).Trim();
                string   authHeaderValueDecoded = Encoding.UTF8.GetString(Convert.FromBase64String(authHeaderValue));
                string[] authHeaderParts        = authHeaderValueDecoded.Split(':');
                jwt         = authHeaderParts[0];
                deviceID    = authHeaderParts[1];
                patientNRIC = authHeaderParts[2];
            }
            else
            {
                return(response);
            }

            // Ensure jwt, deviceID, patientNRIC exists
            if (!(!string.IsNullOrEmpty(jwt) && AccountBLL.IsDeviceIDValid(deviceID) && !string.IsNullOrEmpty(patientNRIC)))
            {
                return(response);
            }

            // Validate jwt
            if (!jwtBll.ValidateJWT(jwt))
            {
                return(response);
            }
            else
            {
                retrievedNRIC = jwtBll.getNRIC(jwt);
            }

            // Validate deviceID for retrievedNRIC
            if (!(accountBLL.IsValid(retrievedNRIC, deviceID)))
            {
                return(response);
            }

            // Get permissions
            accountBLL.SetRole(retrievedNRIC, "Therapist");
            Account account = accountBLL.GetStatus(retrievedNRIC);

            if (account.status == 1)
            {
                try
                {
                    Classes.Entity.Patient patient = new TherapistBLL().GetPatientPermissions(Convert.ToString(patientNRIC));

                    response = Request.CreateResponse(HttpStatusCode.OK, System.Convert.ToBase64String(Encoding.ASCII.GetBytes(patient.permissionApproved.ToString())));
                }
                catch
                {
                    response = Request.CreateResponse(HttpStatusCode.InternalServerError);
                }

                return(response);
            }

            return(response);
        }
        public HttpResponseMessage TherapistGetPatients()
        {
            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Unauthorized);
            string jwt;
            string deviceID;
            string retrievedNRIC;

            AccountBLL accountBLL = new AccountBLL();
            JWTBLL     jwtBll     = new JWTBLL();

            HttpContext httpContext = HttpContext.Current;
            string      authHeader  = httpContext.Request.Headers["Authorization"];

            // Ensure Authorization Header exists
            if (authHeader != null && authHeader.StartsWith("Bearer"))
            {
                string   authHeaderValue        = authHeader.Substring("Bearer ".Length).Trim();
                string   authHeaderValueDecoded = Encoding.UTF8.GetString(Convert.FromBase64String(authHeaderValue));
                string[] authHeaderParts        = authHeaderValueDecoded.Split(':');
                jwt      = authHeaderParts[0];
                deviceID = authHeaderParts[1];
            }
            else
            {
                return(response);
            }

            // Ensure jwt, deviceID exists
            if (!(!string.IsNullOrEmpty(jwt) && AccountBLL.IsDeviceIDValid(deviceID)))
            {
                return(response);
            }

            // Validate jwt
            if (!jwtBll.ValidateJWT(jwt))
            {
                return(response);
            }
            else
            {
                retrievedNRIC = jwtBll.getNRIC(jwt);
            }

            // Validate deviceID for retrievedNRIC
            if (!(accountBLL.IsValid(retrievedNRIC, deviceID)))
            {
                return(response);
            }

            // Get all associated patients
            accountBLL.SetRole(retrievedNRIC, "Therapist");
            Account account = accountBLL.GetStatus(retrievedNRIC);

            if (account.status == 1)
            {
                try
                {
                    TherapistBLL therapistBLL = new TherapistBLL();
                    List <Classes.Entity.Patient> patients = therapistBLL.GetCurrentPatients("");

                    string names = "";
                    for (int i = 0; i < patients.Count; i++)
                    {
                        names += patients[i].nric + "  " + patients[i].firstName + " " + patients[i].lastName;

                        if (i != patients.Count - 1)
                        {
                            names += "\r";
                        }
                    }

                    response = Request.CreateResponse(HttpStatusCode.OK, System.Convert.ToBase64String(Encoding.ASCII.GetBytes(names)));
                }
                catch
                {
                    response = Request.CreateResponse(HttpStatusCode.InternalServerError);
                }

                return(response);
            }

            return(response);
        }
        public HttpResponseMessage UpdateJWT()
        {
            var    response = Request.CreateResponse(HttpStatusCode.Unauthorized);
            string jwt;
            string deviceID;
            string retrievedNRIC;

            JWTBLL jwtBll = new JWTBLL();

            HttpContext httpContext = HttpContext.Current;
            string      authHeader  = httpContext.Request.Headers["Authorization"];

            // Ensure Authorization Header exists
            if (authHeader != null && authHeader.StartsWith("Bearer"))
            {
                string   authHeaderValue        = authHeader.Substring("Bearer ".Length).Trim();
                string   authHeaderValueDecoded = Encoding.UTF8.GetString(Convert.FromBase64String(authHeaderValue));
                string[] authHeaderParts        = authHeaderValueDecoded.Split(':');
                jwt      = authHeaderParts[0];
                deviceID = authHeaderParts[1];
            }
            else
            {
                return(response);
            }

            // Ensure jwt, deviceID exists
            if (!(!string.IsNullOrEmpty(jwt) && AccountBLL.IsDeviceIDValid(deviceID)))
            {
                return(response);
            }

            // Validate jwt
            if (!jwtBll.ValidateJWT(jwt))
            {
                return(response);
            }
            else
            {
                retrievedNRIC = jwtBll.getNRIC(jwt);
            }

            // Validate deviceID for retrievedNRIC
            if (!(accountBLL.IsValid(retrievedNRIC, deviceID)))
            {
                return(response);
            }

            // Issue updated JWT for the client
            Account account = accountBLL.GetStatus(retrievedNRIC);

            if (account.status == 1)
            {
                string newJwt = jwtBll.UpdateJWT(jwt);
                response = Request.CreateResponse(HttpStatusCode.OK);
                response.Headers.Add("Authorization", "Bearer " + newJwt);
                return(response);
            }

            return(response);
        }
        public HttpResponseMessage WebLogin()
        {
            var    response = Request.CreateResponse(HttpStatusCode.Unauthorized);
            string jwt;
            string deviceID;
            string tokenID;
            string retrievedNRIC;

            JWTBLL jwtBll = new JWTBLL();

            HttpContext httpContext = HttpContext.Current;
            string      authHeader  = httpContext.Request.Headers["Authorization"];

            // Ensure Authorization Header exists
            if (authHeader != null && authHeader.StartsWith("Bearer"))
            {
                string   authHeaderValue        = authHeader.Substring("Bearer ".Length).Trim();
                string   authHeaderValueDecoded = Encoding.UTF8.GetString(Convert.FromBase64String(authHeaderValue));
                string[] authHeaderParts        = authHeaderValueDecoded.Split(':');
                jwt      = authHeaderParts[0];
                deviceID = authHeaderParts[1];
                tokenID  = authHeaderParts[2];
            }
            else
            {
                return(response);
            }

            // Ensure jwt, deviceID, tokenID exists
            if (!(!string.IsNullOrEmpty(jwt) && AccountBLL.IsDeviceIDValid(deviceID) && AccountBLL.IsTokenIDValid(tokenID)))
            {
                return(response);
            }

            // Validate jwt
            if (!jwtBll.ValidateJWT(jwt))
            {
                return(response);
            }
            else
            {
                retrievedNRIC = jwtBll.getNRIC(jwt);
            }

            // Validate deviceID and tokenID for retrievedNRIC
            if (accountBLL.IsValid(retrievedNRIC, tokenID, deviceID))
            {
                if (HttpContext.Current.Cache[retrievedNRIC + "_MFAAttempt"] != null &&
                    HttpContext.Current.Cache.Get(retrievedNRIC + "_MFAAttempt").ToString().Equals("Awaiting"))
                {
                    // MFA login was triggered, cache inserted
                    Account account = new Account();
                    account.associatedDeviceID = deviceID;
                    account.associatedTokenID  = tokenID;
                    HttpContext.Current.Cache.Insert(retrievedNRIC + "_MFAAttempt", account, null, DateTime.Now.AddSeconds(30), Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, null);

                    string newJwt = jwtBll.UpdateJWT(jwt);
                    response = Request.CreateResponse(HttpStatusCode.OK);
                    response.Headers.Add("Authorization", "Bearer " + newJwt);
                }
                else
                {
                    // MFA login was not triggered before this request, cache not inserted
                    response = Request.CreateResponse(HttpStatusCode.BadRequest);
                }
            }

            return(response);
        }