public string SendTransferTransactionToDataBase <M>(string assetID, MetaDataSaved <M> metaData,
                                                            string senderPrivateSignKey, string recieverPublicSignKey, string inputTransID)
        {
            var senderSignPrivateKey  = EncryptionService.getSignKeyFromPrivate(senderPrivateSignKey);
            var recieverSignPublicKey = EncryptionService.getSignPublicKeyFromString(recieverPublicSignKey);

            // Using TRANSFER: START
            // add input
            var input = new Omnibasis.BigchainCSharp.Model.FulFill();

            input.TransactionId = inputTransID;
            input.OutputIndex   = 0;
            Details details = null;

            // transfer transaction
            // assetId is the transactionId to the asset we want to change
            var transaction = BigchainDbTransactionBuilder <Asset <string>, MetaDataSaved <M> >
                              .init()
                              .addAssets(assetID)
                              .addMetaData(metaData)
                              .addInput(details, input, senderSignPrivateKey.PublicKey)
                              .addOutput("1", recieverSignPublicKey)
                              .operation(Operations.TRANSFER)
                              .buildAndSignOnly(senderSignPrivateKey.PublicKey, senderSignPrivateKey);

            var createTransaction = TransactionsApi <Asset <string>, MetaDataSaved <M> > .sendTransactionAsync(transaction).GetAwaiter().GetResult();

            return(createTransaction.Data.Id);
        }
        public M GetMetadataFromAssetPublicKey <M>(string assetID, string signPublicKey)
        {
            var rawPublicKey      = EncryptionService.getRawBase58PublicKey(signPublicKey);
            var unspentOutsList   = OutputsApi.getUnspentOutputsAsync(rawPublicKey).GetAwaiter().GetResult();
            var assetTransactions = TransactionsApi <object, object> .getTransactionsByAssetIdAsync(assetID).GetAwaiter().GetResult();

            var neededTransaction = from a in unspentOutsList.AsQueryable()
                                    join b in assetTransactions.AsQueryable()
                                    on a.TransactionId equals b.Id
                                    select b.MetaData.Metadata;
            MetaDataSaved <M> result = JsonConvert.DeserializeObject <MetaDataSaved <M> >(neededTransaction.FirstOrDefault().ToString());

            return(result.data);
        }
        public string SendCreateTransactionToDataBase <A, M>(AssetSaved <A> asset, MetaDataSaved <M> metaData, string privateSignKey)
        {
            var signPrivateKey = EncryptionService.getSignKeyFromPrivate(privateSignKey);

            var transaction = BigchainDbTransactionBuilder <AssetSaved <A>, MetaDataSaved <M> >
                              .init()
                              .addAssets(asset)
                              .addMetaData(metaData)
                              .operation(Operations.CREATE)
                              .buildAndSignOnly(signPrivateKey.PublicKey, signPrivateKey);

            var createTransaction = TransactionsApi <AssetSaved <A>, MetaDataSaved <M> > .sendTransactionAsync(transaction).GetAwaiter().GetResult();

            return(createTransaction.Data.Id);
        }
        public IActionResult EditProfile(PatientCredMetadata patientCredMetadata)
        {
            Assets <PatientCredAssetData> userAsset = _bigChainDbService.GetPatientAssetFromID(HttpContext.Session.GetString(Globals.currentUserID));
            var patientSignPublicKey  = HttpContext.Session.GetString(Globals.currentPSPubK);
            var patientSignPrivateKey = HttpContext.Session.GetString(Globals.currentPSPriK);
            var transaction           = _bigChainDbService.GetMetadataIDFromAssetPublicKey <PatientCredMetadata>(userAsset.id, patientSignPublicKey);
            var transID = transaction.Id ?? userAsset.id;

            patientCredMetadata.hashedPassword = transaction.Metadata.data.hashedPassword;
            var newMetadata = new MetaDataSaved <PatientCredMetadata>
            {
                data = patientCredMetadata
            };

            _bigChainDbService.SendTransferTransactionToDataBase(userAsset.id, newMetadata,
                                                                 patientSignPrivateKey, patientSignPublicKey, transID);
            return(RedirectToAction("PatientOverview"));
        }
Exemple #5
0
        public IActionResult SignUp(mltSignUpViewModel mltSignUpViewModel)
        {
            string signPrivateKey = null, agreePrivateKey = null, signPublicKey = null, agreePublicKey = null;
            Assets <UserCredAssetData> userAsset = _bigChainDbService.GetUserAssetFromTypeID(AssetType.Doctor, mltSignUpViewModel.CSMLSID);

            if (userAsset != null)
            {
                ModelState.AddModelError("", "A Doctor profile with that MINC already exists");
                return(View(mltSignUpViewModel));
            }
            var passphrase = mltSignUpViewModel.MLTKeyWord;
            var password   = mltSignUpViewModel.Password;

            EncryptionService.getNewBlockchainUser(out signPrivateKey, out signPublicKey, out agreePrivateKey, out agreePublicKey);
            var userAssetData = new UserCredAssetData
            {
                FirstName       = mltSignUpViewModel.FirstName,
                LastName        = mltSignUpViewModel.LastName,
                ID              = mltSignUpViewModel.CSMLSID,
                Email           = mltSignUpViewModel.Email,
                PrivateKeys     = EncryptionService.encryptPrivateKeys(mltSignUpViewModel.CSMLSID, passphrase, signPrivateKey, agreePrivateKey),
                DateOfRecord    = DateTime.Now,
                SignPublicKey   = signPublicKey,
                AgreePublicKey  = agreePublicKey,
                FingerprintData = new List <string>(),
            };
            var userMetadata = new UserCredMetadata
            {
                hashedPassword = EncryptionService.hashPassword(password)
            };
            var asset = new AssetSaved <UserCredAssetData>
            {
                Type     = AssetType.MLT,
                Data     = userAssetData,
                RandomId = _random.Next(0, 100000)
            };
            var metadata = new MetaDataSaved <UserCredMetadata>
            {
                data = userMetadata
            };

            _bigChainDbService.SendCreateTransactionToDataBase(asset, metadata, signPrivateKey);
            return(RedirectToAction("Login"));
        }
Exemple #6
0
        public IActionResult UploadResult(UploadResultViewModel uploadResultViewModel)
        {
            // Get's the Doctor's information for current session
            ViewBag.DoctorName = HttpContext.Session.GetString(Globals.currentUserName);
            var oldViewModel = JsonConvert.DeserializeObject <UploadResultViewModel>(TempData["viewModel"] as string);

            uploadResultViewModel.TestData        = oldViewModel.TestData;
            uploadResultViewModel.PatientAsset    = oldViewModel.PatientAsset;
            uploadResultViewModel.PatientMetadata = oldViewModel.PatientMetadata;
            TempData["viewModel"] = JsonConvert.SerializeObject(uploadResultViewModel);

            if (!ModelState.IsValid)
            {
                return(View(uploadResultViewModel));
            }

            var doctorSignPrivateKey  = HttpContext.Session.GetString(Globals.currentDSPriK);
            var doctorAgreePrivateKey = HttpContext.Session.GetString(Globals.currentDAPriK);
            var doctorSignPublicKey   = EncryptionService.getSignPublicKeyStringFromPrivate(doctorSignPrivateKey);
            var patientSignPublicKey  = HttpContext.Session.GetString(Globals.currentPSPubK);

            var transID         = uploadResultViewModel.TestData.transID;
            var testRequisition = _bigChainDbService.GetMetaDataAndAssetFromTransactionId <string, double>(transID);

            //Check MLT has access to upload data
            if (testRequisition.metadata.AccessList.Keys.Contains(doctorSignPublicKey))
            {
                //Get hash key for requisition. We will use the same key for result
                var hashedKey         = testRequisition.metadata.AccessList[doctorSignPublicKey];
                var dataDecryptionKey = EncryptionService.getDecryptedEncryptionKey(hashedKey, doctorAgreePrivateKey);
                if (uploadResultViewModel.ResultFile != null)
                {
                    var    file             = uploadResultViewModel.ResultFile;
                    string base64FileString = "";

                    // Convert "file" into base64 string "base64FileString" to save into database
                    using (var ms = new MemoryStream())
                    {
                        file.CopyTo(ms);
                        var fileBytes = ms.ToArray();
                        base64FileString = Convert.ToBase64String(fileBytes);
                    }
                    //encrypt file data and save to ipfs
                    var encryptFileData = EncryptionService.getEncryptedAssetDataKey(base64FileString, dataDecryptionKey);
                    var cid             = _bigChainDbService.UploadTextToIPFS(encryptFileData);
                    var resultFile      = new FileData()
                    {
                        Data      = cid,
                        Type      = file.ContentType,
                        Extension = file.ContentType.Split('/').Last(),
                        Name      = file.FileName
                    };
                    //Encrypt the file using the same key
                    var encryptedFile = EncryptionService.getEncryptedAssetDataKey(JsonConvert.SerializeObject(resultFile), dataDecryptionKey);

                    var asset = new AssetSaved <TestResultAsset>
                    {
                        Data = new TestResultAsset
                        {
                            RequisitionAssetID = testRequisition.id,
                            EncryptedResult    = encryptedFile
                        },
                        RandomId = _random.Next(0, 100000),
                        Type     = AssetType.TestResult
                    };
                    //Access is managed by requisition asset
                    var metadata = new MetaDataSaved <double>();
                    metadata.AccessList = new Dictionary <string, string>();

                    _bigChainDbService.SendCreateTransferTransactionToDataBase(asset, metadata, doctorSignPrivateKey, patientSignPublicKey);
                    return(RedirectToAction("PatientRecords"));
                }
                else
                {
                    ModelState.AddModelError("", "Missing test result file.");
                    return(View(uploadResultViewModel));
                }
            }
            else
            {
                ModelState.AddModelError("", "You do not have permission to upload test result.");
                return(View(uploadResultViewModel));
            }
        }
Exemple #7
0
        public IActionResult RequestAccess(RequestAccessViewModel requestAccessViewModel)
        {
            // Description: Authenticates a patient's identity when a Doctor requests access to their medical information
            // Get's the Doctor's information for current session
            ViewBag.DoctorName = HttpContext.Session.GetString(Globals.currentUserName);
            if (!ModelState.IsValid)
            {
                return(View(requestAccessViewModel));
            }
            string PHN = HttpContext.Session.GetString(Globals.currentPPHN);
            string patientSignPublicKey  = HttpContext.Session.GetString(Globals.currentPSPubK);
            string doctorSignPrivatekey  = HttpContext.Session.GetString(Globals.currentDSPriK);
            string doctorSignPublicKey   = EncryptionService.getSignPublicKeyStringFromPrivate(doctorSignPrivatekey);
            string doctorAgreePrivatekey = HttpContext.Session.GetString(Globals.currentDAPriK);
            string doctorAgreePublicKey  = EncryptionService.getAgreePublicKeyStringFromPrivate(doctorAgreePrivatekey);
            string keyword = requestAccessViewModel.keyword;

            // Searches for a patient with the specified PHN
            Assets <UserCredAssetData> userAsset = _bigChainDbService.GetUserAssetFromTypeID(AssetType.Patient, PHN);

            if (userAsset == null)
            {
                ModelState.AddModelError("", "Could not find a patient profile with PHN: " + PHN);
                return(View(requestAccessViewModel));
            }

            // Decrypt the patient's fingerprint data stored in the Blockchain
            byte[]        dbFpData = null;
            string        patientSignPrivateKey, patientAgreePrivateKey;
            List <string> dbList   = userAsset.data.Data.FingerprintData;
            List <Image>  dbfpList = new List <Image>();

            try
            {
                foreach (string db in dbList)
                {
                    EncryptionService.decryptFingerprintData(PHN, keyword, db, out dbFpData);
                    dbfpList.Add(FingerprintService.byteToImg(dbFpData));
                }
                EncryptionService.getPrivateKeyFromIDKeyword(PHN, keyword, userAsset.data.Data.PrivateKeys, out patientSignPrivateKey, out patientAgreePrivateKey);
            }
            catch
            {
                ModelState.AddModelError("", "Keyword may be incorrect");
                return(View(requestAccessViewModel));
            }

            // Send request to the Client Computer to authenticate with fingerprint
            int          numScans = 1;
            List <Image> fpList   = FingerprintService.authenticateFP("24.84.225.22", numScans); // DEBUG: Jacob's Computer

            // Check if fingerprint data is valid
            if (fpList.Count < numScans)
            {
                ModelState.AddModelError("", "Something went wrong with the fingerprint scan, try again.");
                return(View(requestAccessViewModel));
            }
            Image fpImg = fpList[0];

            // Compare the scanned fingerprint with the one saved in the database
            if (!FingerprintService.compareFP(fpImg, dbfpList))
            {
                ModelState.AddModelError("", "The fingerprint did not match, try again.");
                return(View(requestAccessViewModel));
            }

            // Choose the types of records we want to get
            AssetType[] typeList   = { AssetType.TestRequisition };
            var         recordList = _bigChainDbService.GetAllTypeRecordsFromPPublicKey <string>
                                         (typeList, patientSignPublicKey);

            foreach (var record in recordList)
            {
                MetaDataSaved <object> metadata = record.metadata;
                if (!metadata.AccessList.Keys.Contains(doctorSignPublicKey))
                {
                    var hashedKey         = metadata.AccessList[patientSignPublicKey];
                    var dataDecryptionKey = EncryptionService.getDecryptedEncryptionKey(hashedKey, patientAgreePrivateKey);
                    var newHash           = EncryptionService.getEncryptedEncryptionKey(dataDecryptionKey, patientAgreePrivateKey, doctorAgreePublicKey);
                    metadata.AccessList[doctorSignPublicKey] = newHash;
                    _bigChainDbService.SendTransferTransactionToDataBase(record.id, metadata,
                                                                         patientSignPrivateKey, patientSignPublicKey, record.transID);
                }
            }
            return(RedirectToAction("PatientRecords"));
        }
Exemple #8
0
        public IActionResult AddNewPatientRecord(AddNewPatientRecordViewModel addNewPatientRecordViewModel)
        {
            ViewBag.DoctorName = HttpContext.Session.GetString(Globals.currentUserName);
            if (!string.IsNullOrEmpty(addNewPatientRecordViewModel.DoctorsNote.PurposeOfVisit))
            {
                var noteViewModel = addNewPatientRecordViewModel.DoctorsNote;
                var doctorNote    = new DoctorNote
                {
                    PurposeOfVisit      = noteViewModel.PurposeOfVisit,
                    Description         = noteViewModel.Description,
                    FinalDiagnosis      = noteViewModel.FinalDiagnosis,
                    FurtherInstructions = noteViewModel.FurtherInstructions,
                    DoctorName          = HttpContext.Session.GetString(Globals.currentUserName),
                    DoctorMinsc         = HttpContext.Session.GetString(Globals.currentUserID),
                    DateOfRecord        = DateTime.Now
                };
                string encryptionKey;
                var    encryptedData = EncryptionService.getEncryptedAssetData(JsonConvert.SerializeObject(doctorNote), out encryptionKey);

                var asset = new AssetSaved <string>
                {
                    Data     = encryptedData,
                    RandomId = _random.Next(0, 100000),
                    Type     = AssetType.DoctorNote
                };

                var metadata = new MetaDataSaved <double>();
                metadata.AccessList = new Dictionary <string, string>();

                //store the data encryption key in metadata encrypted with sender and reciever agree key
                var doctorSignPrivateKey  = HttpContext.Session.GetString(Globals.currentDSPriK);
                var doctorAgreePrivateKey = HttpContext.Session.GetString(Globals.currentDAPriK);
                var patientAgreePublicKey = HttpContext.Session.GetString(Globals.currentPAPubK);
                var patientSignPublicKey  = HttpContext.Session.GetString(Globals.currentPSPubK);
                var doctorSignPublicKey   = EncryptionService.getSignPublicKeyStringFromPrivate(doctorSignPrivateKey);
                var doctorAgreePublicKey  = EncryptionService.getAgreePublicKeyStringFromPrivate(doctorAgreePrivateKey);
                metadata.AccessList[doctorSignPublicKey] =
                    EncryptionService.getEncryptedEncryptionKey(encryptionKey, doctorAgreePrivateKey, doctorAgreePublicKey);
                metadata.AccessList[patientSignPublicKey] =
                    EncryptionService.getEncryptedEncryptionKey(encryptionKey, doctorAgreePrivateKey, patientAgreePublicKey);

                _bigChainDbService.SendCreateTransferTransactionToDataBase <string, double>(asset, metadata, doctorSignPrivateKey, patientSignPublicKey);
            }

            if (!string.IsNullOrEmpty(addNewPatientRecordViewModel.Prescription.DrugName))
            {
                var prescriptionViewModel = addNewPatientRecordViewModel.Prescription;
                var prescription          = new Prescription
                {
                    PrescribingDate = prescriptionViewModel.PrescribingDate,
                    Superscription  = prescriptionViewModel.Superscription,
                    DrugName        = prescriptionViewModel.DrugName,
                    Dosage          = prescriptionViewModel.Dosage,
                    //StartDate = prescriptionViewModel.StartDate,
                    EndDate         = prescriptionViewModel.EndDate,
                    Refill          = prescriptionViewModel.Refill,
                    Substitution    = prescriptionViewModel.Substitution,
                    DoctorName      = HttpContext.Session.GetString(Globals.currentUserName),
                    DoctorMinsc     = HttpContext.Session.GetString(Globals.currentUserID),
                    DirectionForUse = prescriptionViewModel.DirectionForUse
                };

                string encryptionKey;
                var    encryptedData = EncryptionService.getEncryptedAssetData(JsonConvert.SerializeObject(prescription), out encryptionKey);

                var asset = new AssetSaved <string>
                {
                    Data     = encryptedData,
                    RandomId = _random.Next(0, 100000),
                    Type     = AssetType.Prescription
                };

                var metadata = new MetaDataSaved <PrescriptionMetadata>
                {
                    AccessList = new Dictionary <string, string>(),
                    data       = new PrescriptionMetadata
                    {
                        RefillRemaining = prescription.Refill,
                        LastIssueQty    = -1
                    }
                };

                //store the data encryption key in metadata encrypted with sender and reciever agree key
                var doctorSignPrivateKey  = HttpContext.Session.GetString(Globals.currentDSPriK);
                var doctorAgreePrivateKey = HttpContext.Session.GetString(Globals.currentDAPriK);
                var patientAgreePublicKey = HttpContext.Session.GetString(Globals.currentPAPubK);
                var patientSignPublicKey  = HttpContext.Session.GetString(Globals.currentPSPubK);
                var doctorSignPublicKey   = EncryptionService.getSignPublicKeyStringFromPrivate(doctorSignPrivateKey);
                var doctorAgreePublicKey  = EncryptionService.getAgreePublicKeyStringFromPrivate(doctorAgreePrivateKey);
                metadata.AccessList[doctorSignPublicKey] =
                    EncryptionService.getEncryptedEncryptionKey(encryptionKey, doctorAgreePrivateKey, doctorAgreePublicKey);
                metadata.AccessList[patientSignPublicKey] =
                    EncryptionService.getEncryptedEncryptionKey(encryptionKey, doctorAgreePrivateKey, patientAgreePublicKey);

                _bigChainDbService.SendCreateTransferTransactionToDataBase <string, PrescriptionMetadata>(asset, metadata, doctorSignPrivateKey, patientSignPublicKey);
            }

            //There is a test result that exists
            if (!string.IsNullOrEmpty(addNewPatientRecordViewModel.TestRequisition.ReasonForTest))
            {
                //File exists
                if (addNewPatientRecordViewModel.TestRequisition.AttachedFile != null)
                {
                    var    file             = addNewPatientRecordViewModel.TestRequisition.AttachedFile;
                    string base64FileString = "";

                    // Convert "file" into base64 string "base64FileString" to save into database
                    using (var ms = new MemoryStream())
                    {
                        file.CopyTo(ms);
                        var fileBytes = ms.ToArray();
                        base64FileString = Convert.ToBase64String(fileBytes);
                    }
                    //encrypt file and store in ipfs
                    var encryptionKey = EncryptionService.getNewAESEncryptionKey();
                    var encryptedFile = EncryptionService.getEncryptedAssetDataKey(base64FileString, encryptionKey);
                    var id            = _bigChainDbService.UploadTextToIPFS(encryptedFile);

                    var testRequisition = new TestRequisitionAsset
                    {
                        AttachedFile = new FileData
                        {
                            Data      = id,
                            Type      = file.ContentType,
                            Extension = file.ContentType.Split('/').Last(),
                            Name      = file.FileName
                        },
                        ReasonForTest = addNewPatientRecordViewModel.TestRequisition.ReasonForTest,
                        TestType      = addNewPatientRecordViewModel.TestRequisition.TestType,
                        DateOrdered   = DateTime.Now
                    };
                    var encryptedData = EncryptionService.getEncryptedAssetDataKey(JsonConvert.SerializeObject(testRequisition), encryptionKey);

                    var asset = new AssetSaved <string>
                    {
                        Data     = encryptedData,
                        RandomId = _random.Next(0, 100000),
                        Type     = AssetType.TestRequisition
                    };

                    var metadata = new MetaDataSaved <double>();
                    metadata.AccessList = new Dictionary <string, string>();

                    //store the data encryption key in metadata encrypted with sender and reciever agree key
                    var doctorSignPrivateKey  = HttpContext.Session.GetString(Globals.currentDSPriK);
                    var doctorAgreePrivateKey = HttpContext.Session.GetString(Globals.currentDAPriK);
                    var patientAgreePublicKey = HttpContext.Session.GetString(Globals.currentPAPubK);
                    var patientSignPublicKey  = HttpContext.Session.GetString(Globals.currentPSPubK);
                    var doctorSignPublicKey   = EncryptionService.getSignPublicKeyStringFromPrivate(doctorSignPrivateKey);
                    var doctorAgreePublicKey  = EncryptionService.getAgreePublicKeyStringFromPrivate(doctorAgreePrivateKey);
                    metadata.AccessList[doctorSignPublicKey] =
                        EncryptionService.getEncryptedEncryptionKey(encryptionKey, doctorAgreePrivateKey, doctorAgreePublicKey);
                    metadata.AccessList[patientSignPublicKey] =
                        EncryptionService.getEncryptedEncryptionKey(encryptionKey, doctorAgreePrivateKey, patientAgreePublicKey);

                    _bigChainDbService.SendCreateTransferTransactionToDataBase <string, double>(asset, metadata, doctorSignPrivateKey, patientSignPublicKey);
                }
            }

            return(RedirectToAction("PatientOverview"));
        }
Exemple #9
0
        public IActionResult PatientSignUp(PatientSignUpViewModel patientSignUpViewModel)
        {
            // Description: Registers a patient up for a MedNet account
            ViewBag.DoctorName = HttpContext.Session.GetString(Globals.currentUserName);
            string signPrivateKey = null, agreePrivateKey = null, signPublicKey = null, agreePublicKey = null;
            Assets <PatientCredAssetData> userAsset = _bigChainDbService.GetPatientAssetFromID(patientSignUpViewModel.PHN);

            // Check if PHN is already in use
            if (userAsset != null)
            {
                ModelState.AddModelError("", "A Patient profile with that PHN already exists");
                return(View(patientSignUpViewModel));
            }

            // Register fingerprint information
            int           numScans = 5;
            List <Image>  fpList   = FingerprintService.authenticateFP("24.84.225.22", numScans);
            List <byte[]> fpdb     = new List <byte[]>();

            if (fpList.Count > numScans)
            {
                ModelState.AddModelError("", "Something went wrong with the fingerprint scan, try again.");
                return(View(patientSignUpViewModel));
            }

            // Parse the input data for user registration
            var passphrase = patientSignUpViewModel.KeyWord;
            var password   = patientSignUpViewModel.Password;

            // Encrypt fingerprint data
            List <string> encrList = new List <string>();

            foreach (var fp in fpList)
            {
                byte[] fpByte  = FingerprintService.imgToByte(fp);
                string encrStr = EncryptionService.encryptFingerprintData(patientSignUpViewModel.PHN, passphrase, fpByte);
                encrList.Add(encrStr);
            }

            // Create a user for the Blockchain
            EncryptionService.getNewBlockchainUser(out signPrivateKey, out signPublicKey, out agreePrivateKey, out agreePublicKey);

            // Create the user Asset
            var userAssetData = new PatientCredAssetData
            {
                ID              = patientSignUpViewModel.PHN,
                DateOfBirth     = patientSignUpViewModel.DateOfBirth,
                PrivateKeys     = EncryptionService.encryptPrivateKeys(patientSignUpViewModel.PHN, passphrase, signPrivateKey, agreePrivateKey),
                DateOfRecord    = DateTime.Now,
                SignPublicKey   = signPublicKey,
                AgreePublicKey  = agreePublicKey,
                FingerprintData = encrList,
            };

            // Encrypt the user's password in the metadata
            var userMetadata = new PatientCredMetadata
            {
                FirstName      = patientSignUpViewModel.FirstName,
                LastName       = patientSignUpViewModel.LastName,
                Email          = patientSignUpViewModel.Email,
                hashedPassword = EncryptionService.hashPassword(password)
            };

            // Save the user Asset and Metadata
            var asset = new AssetSaved <PatientCredAssetData>
            {
                Type     = AssetType.Patient,
                Data     = userAssetData,
                RandomId = _random.Next(0, 100000)
            };
            var metadata = new MetaDataSaved <PatientCredMetadata>
            {
                data = userMetadata
            };

            // Send the user's information to the Blockchain database
            _bigChainDbService.SendCreateTransactionToDataBase(asset, metadata, signPrivateKey);
            return(RedirectToAction("PatientLookUp"));
        }
        public JsonResult RevokeAccessFromUser(EditAccessViewModel editAccessViewModel)
        {
            if (editAccessViewModel.UserType == null || editAccessViewModel.UserType == "")
            {
                return(Json(new { message = "Please select a user type." }));
            }
            // Searches for a patient with the specified PHN
            AssetType type = editAccessViewModel.UserType == "Doctor" ? AssetType.Doctor :
                             editAccessViewModel.UserType == "Pharmacist" ? AssetType.Pharmacist : AssetType.MLT;
            Assets <UserCredAssetData> userAsset = _bigChainDbService.GetUserAssetFromTypeID(type, editAccessViewModel.UserID);

            if (userAsset == null)
            {
                return(Json(new { message = ("We could not find a " + editAccessViewModel.UserType + " with ID: " + editAccessViewModel.UserID) }));
            }

            string patientSignPublicKey  = HttpContext.Session.GetString(Globals.currentPSPubK);
            string patientSignPrivateKey = HttpContext.Session.GetString(Globals.currentPSPriK);
            string doctorSignPublicKey   = userAsset.data.Data.SignPublicKey;
            string userName = userAsset.data.Data.FirstName + " " + userAsset.data.Data.LastName;

            if (editAccessViewModel.TransID != null && editAccessViewModel.TransID != "")
            {
                var result = _bigChainDbService.GetMetaDataAndAssetFromTransactionId <string, object>(editAccessViewModel.TransID);
                MetaDataSaved <object> metadata = result.metadata;
                if (metadata.AccessList.Keys.Contains(doctorSignPublicKey))
                {
                    metadata.AccessList.Remove(doctorSignPublicKey);
                    var newTransID = _bigChainDbService.SendTransferTransactionToDataBase(result.id, metadata,
                                                                                          patientSignPrivateKey, patientSignPublicKey, result.transID);
                    return(Json(new { message = (userName + " (" + editAccessViewModel.UserID + ") was removed from the record."), newtransid = newTransID }));
                }
                else
                {
                    return(Json(new { message = (userName + " (" + editAccessViewModel.UserID + ") was already removed from the record.") }));
                }
            }

            // Choose the types of records we want to get
            List <AssetType> typeList = new List <AssetType>();

            if (type == AssetType.Doctor)
            {
                typeList.AddRange(new List <AssetType> {
                    AssetType.DoctorNote, AssetType.Prescription, AssetType.TestRequisition
                });
            }
            else if (type == AssetType.Pharmacist)
            {
                typeList.AddRange(new List <AssetType> {
                    AssetType.Prescription
                });
            }
            else
            {
                typeList.AddRange(new List <AssetType> {
                    AssetType.TestRequisition
                });
            }

            var recordList = _bigChainDbService.GetAllTypeRecordsFromPPublicKey <string>
                                 (typeList.ToArray(), patientSignPublicKey);
            int counter = 0;

            foreach (var record in recordList)
            {
                MetaDataSaved <object> metadata = record.metadata;
                if (metadata.AccessList.Keys.Contains(doctorSignPublicKey))
                {
                    metadata.AccessList.Remove(doctorSignPublicKey);
                    _bigChainDbService.SendTransferTransactionToDataBase(record.id, metadata,
                                                                         patientSignPrivateKey, patientSignPublicKey, record.transID);
                    counter++;
                }
            }

            return(Json(new { message = (userName + " (" + editAccessViewModel.UserID + ") was removed from " + counter.ToString() + " records.") }));
        }
Exemple #11
0
        public IActionResult FillPrescription(FillPrescriptionViewModel fillPrescriptionViewModel)
        {
            // Get's the Doctor's information for current session
            ViewBag.DoctorName = HttpContext.Session.GetString(Globals.currentUserName);
            var oldViewModel = JsonConvert.DeserializeObject <FillPrescriptionViewModel>(TempData["viewModel"] as string);

            fillPrescriptionViewModel.PrescriptionData = oldViewModel.PrescriptionData;
            fillPrescriptionViewModel.PatientAsset     = oldViewModel.PatientAsset;
            fillPrescriptionViewModel.PatientMetadata  = oldViewModel.PatientMetadata;
            TempData["viewModel"] = JsonConvert.SerializeObject(fillPrescriptionViewModel);

            if (!ModelState.IsValid)
            {
                return(View(fillPrescriptionViewModel));
            }
            string PHN = HttpContext.Session.GetString(Globals.currentPPHN);
            string patientSignPublicKey = HttpContext.Session.GetString(Globals.currentPSPubK);
            string keyword = fillPrescriptionViewModel.PatientKeyword;

            // Searches for a patient with the specified PHN
            Assets <UserCredAssetData> userAsset = _bigChainDbService.GetUserAssetFromTypeID(AssetType.Patient, PHN);

            if (userAsset == null)
            {
                ModelState.AddModelError("", "Could not find a patient profile with PHN: " + PHN);
                return(View(fillPrescriptionViewModel));
            }

            // Send request to the Client Computer to authenticate with fingerprint
            int          numScans = 1;
            List <Image> fpList   = FingerprintService.authenticateFP("24.84.225.22", numScans); // DEBUG: Jacob's Computer

            // Check if fingerprint data is valid
            if (fpList.Count < numScans)
            {
                ModelState.AddModelError("", "Something went wrong with the fingerprint scan, try again.");
                return(View(fillPrescriptionViewModel));
            }
            Image fpImg = fpList[0];

            // Decrypt the patient's fingerprint data stored in the Blockchain
            byte[]        dbFpData = null;
            string        patientSignPrivateKey, patientAgreePrivateKey;
            List <string> dbList   = userAsset.data.Data.FingerprintData;
            List <Image>  dbfpList = new List <Image>();

            try
            {
                foreach (string db in dbList)
                {
                    EncryptionService.decryptFingerprintData(PHN, keyword, db, out dbFpData);
                    dbfpList.Add(FingerprintService.byteToImg(dbFpData));
                }
                EncryptionService.getPrivateKeyFromIDKeyword(PHN, keyword, userAsset.data.Data.PrivateKeys, out patientSignPrivateKey, out patientAgreePrivateKey);
            }
            catch
            {
                ModelState.AddModelError("", "Keyword may be incorrect");
                return(View(fillPrescriptionViewModel));
            }

            // Compare the scanned fingerprint with the one saved in the database
            if (!FingerprintService.compareFP(fpImg, dbfpList))
            {
                ModelState.AddModelError("", "The fingerprint did not match, try again.");
                return(View(fillPrescriptionViewModel));
            }

            var prescriptionData = _bigChainDbService.GetMetaDataAndAssetFromTransactionId <string, PrescriptionMetadata>
                                       (fillPrescriptionViewModel.PrescriptionData.transID);
            var oldMetadata = prescriptionData.metadata;

            if (fillPrescriptionViewModel.PrescriptionData.assetData.EndDate.CompareTo(DateTime.Now) < 0)
            {
                ModelState.AddModelError("", "The Prescription seems to have expired. Cannot fill this prescription.");
                return(View(fillPrescriptionViewModel));
            }

            if (fillPrescriptionViewModel.PrescriptionData.Metadata.RefillRemaining < fillPrescriptionViewModel.QtyFilled)
            {
                ModelState.AddModelError("", "Connot issue more than remaining refills.");
            }

            MetaDataSaved <PrescriptionMetadata> newMetadata = oldMetadata;

            newMetadata.data.LastIssueQty    = fillPrescriptionViewModel.QtyFilled;
            newMetadata.data.LastIssueDate   = DateTime.Now;
            newMetadata.data.RefillRemaining = fillPrescriptionViewModel.PrescriptionData.Metadata.RefillRemaining - fillPrescriptionViewModel.QtyFilled;

            _bigChainDbService.SendTransferTransactionToDataBase <PrescriptionMetadata>(fillPrescriptionViewModel.PrescriptionData.assetID,
                                                                                        newMetadata, patientSignPrivateKey, patientSignPublicKey, fillPrescriptionViewModel.PrescriptionData.transID);
            return(RedirectToAction("PatientRecords"));
        }