def test_regen_invalid_keys(self): from MHLogin.KMS.shortcuts import regen_invalid_keys_for_users c = self.client cleartext = "I enjoy going to tax seminars." response = c.post('/login/', { 'username': '******', 'password': '******' }) self.assertEqual(response.status_code, 302) # just extra verification we can get user from django auth user = authenticate(username='******', password='******') # verify we are logged in self.assertEqual(c.session['_auth_user_id'], user.id) opub = OwnerPublicKey.objects.get_pubkey(owner=user) # NOTE: encrypt_object leaks m._key but using that fact to test this for now msg = encrypt_object(SecureTestMessage, {}, cleartext, opub) # regen key (just regen don't re-encrypt object, for another test) regen_invalid_keys_for_users(msg, [user]) msg_type = ContentType.objects.get_for_model(msg) EncryptedObject.objects.filter(object_type=msg_type, object_id=msg.id).delete() # simulate re-creation of encrypted objects and singleton cast to array regen_invalid_keys_for_users(msg, [user]) # logout. cleanup response = c.logout() self.assertTrue('_auth_user_id' not in c.session)
def save_voice_attachment(request, msg): wav_data, metadata = _download_recording(request) metadata = json.dumps(metadata) if (not wav_data): admin_email_body = ''.join([ ('Answering service recording download failed on call SID '), request.REQUEST['CallSid'], ('. Since the automatic '), ('downloader hasn\'t been implemented yet, please go and'), ('manually deal with the message.\n\n'), settings.SERVER_ADDRESS ]) admin_email_subject = _('Answering Service Message Download Failed') mail_admins(admin_email_subject, admin_email_body) return None attachment = encrypt_object( MessageAttachment, { 'message': msg, 'size': len(wav_data), 'encrypted': True, 'metadata': metadata }) attachment.encrypt_url(request, ''.join(['file://', attachment.uuid])) attachment.encrypt_filename( request, ''.join([ 'call_from_', request.session['ivr_makeRecording_callbacknumber'], '.mp3' ])) try: attachment.encrypt_file(request, [wav_data]) except Exception as e: log = AnsSvcDLFailure( practice_id=request.session.get('practice_id', 0), error_message_uuid=msg.uuid, recording_url=request.session['ivr_makeRecording_recording'], callback_number=request. session['ivr_makeRecording_callbacknumber'], failure_type='UL', ) log.init_from_post_data(request.REQUEST) log.save() admin_email_body = ''.join([ ('Answering service recording upload failed on call SID '), request.REQUEST['CallSid'], ('. Since the automatic '), ('downloader hasn\'t been implemented yet, please go and'), ('manually deal with the message.\n\n'), settings.SERVER_ADDRESS, ('\n\nException: '), repr(e) ]) admin_email_subject = _('Answering Service Message Upload Failed') mail_admins(admin_email_subject, admin_email_body) return None if (not USE_MP3): attachment.suffix = 'wav' attachment.content_type = 'audio/wav' else: attachment.suffix = 'mp3' attachment.content_type = 'audio/mp3' attachment.save() return attachment
def test_admin_API_shortcuts(self): # TODO: functions in this test to use common api from utils or shortcuts cleartext = "42: the answer to life the universe and everything." c = self.client response = c.post('/login/', { 'username': '******', 'password': '******' }) c.COOKIES = {'ss': response.cookies['ss'].value} self.assertEqual(response.status_code, 302) # just extra verification we can get user from django auth c.user = authenticate(username='******', password='******') c.user = MHLUser.objects.get(id=c.user.id) opub = OwnerPublicKey.objects.get_pubkey(owner=c.user) msg = encrypt_object(SecureTestMessage, {}, cleartext, opub) upriv = UserPrivateKey.objects.get_privkey(c.user, opub) # fetch something that shouldn't exist as encrypted data notthere = admin_decrypt_cipherkey(ADMIN_PASSWORD, c.user) self.assertTrue(notthere == None) clearkey1 = admin_decrypt_cipherkey(ADMIN_PASSWORD, msg) encobj = EncryptedObject.objects.get_object(msg, opub) # import upriv.privatekey with credentials and decrypt cipherkey clearkey2 = encobj.decrypt_cipherkey(upriv, get_user_key(c)) self.assertTrue(clearkey1 == clearkey2) clearkey = admin_decrypt_cipherkey(ADMIN_PASSWORD, msg) cleartext2 = msg.decrypt(None, clearkey) self.assertTrue(cleartext == cleartext2)
def test_encrypt_object_withIVR(self): u = User.objects.get(username="******") opub = OwnerPublicKey.objects.get_pubkey(owner=u, keytype=RSA_IVR) m = encrypt_object(SecureTestMessage, {}, self.clear_text, opub) # Set up a fake request object. request = HttpRequest() request.session = dict() response = HttpResponse() request.user = u store_user_key(request, response, self.ivr_pin) request.COOKIES['ss'] = response.cookies['ss'].value m_get = SecureTestMessage.objects.get(pk=m.pk) m_body = decrypt_object(request, m_get, ivr=True) self.assertEqual(m_body, self.clear_text) # Set up a fake IVR request object. ivr_request = HttpRequest() ivr_request.session = dict() ivr_response = HttpResponse() ivr_request.user = u store_user_key(ivr_request, ivr_response, self.ivr_pin) ivr_request.COOKIES['ss'] = ivr_response.cookies['ss'].value ivr_m_get = SecureTestMessage.objects.get(pk=m.pk) ivr_m_body = decrypt_object(ivr_request, ivr_m_get, ivr=True) self.assertEqual(ivr_m_body, self.clear_text)
def test_gen_new_keys(self): cleartext = "A sql query walks in to a bar, approaches two tables and asks 'may I join you?'" c = self.client # after successful login should get re-direct to / response = c.post('/login/', {'username': '******', 'password': '******'}) c.COOKIES = {'ss': response.cookies['ss'].value} self.assertEqual(response.status_code, 302) # just extra verification we can get user from django auth c.user = authenticate(username='******', password='******') c.user = MHLUser.objects.get(id=c.user.id) msg = encrypt_object(SecureTestMessage, {}, cleartext) gen_keys_for_users(msg, [c.user], None, c, ivr=True) generate_new_user_keys(c.user, 'monkey') c.user.set_password('monkey') c.user.save() # logout. cleanup response = c.logout() # simulate admin update invalid keys creds = strengthen_key(ADMIN_PASSWORD) admin_rsa = import_rsa(ADMIN_RESET_ENCD_RSA, creds) reset_user_invalid_keys(MHLUser.objects.get(id=c.user.id), admin_rsa) # login with new password and verify we can decrypt message response = c.post('/login/', {'username': '******', 'password': '******'}) c.COOKIES = {'ss': response.cookies['ss'].value} self.assertEqual(response.status_code, 302) # just extra verification we can get user from django auth c.user = authenticate(username='******', password='******') # verify we are logged in self.assertEqual(c.session['_auth_user_id'], c.user.id) decrypted_cleartext = decrypt_object(c, msg) self.assertEqual(decrypted_cleartext, cleartext) response = c.logout()
def test_static_reset(self): # new way will obsolete test_gen_new_keys when rm #2115 in cleartext = "We never really grow up, we only learn how to act in public." c = self.client # after successful login should get re-direct to / response = c.post('/login/', {'username': '******', 'password': '******'}) c.COOKIES = {'ss': response.cookies['ss'].value} c.user = authenticate(username='******', password='******') c.user = MHLUser.objects.get(id=c.user.id) opub = OwnerPublicKey.objects.get_pubkey(owner=c.user) msg = encrypt_object(SecureTestMessage, {}, cleartext, opub) c.user.set_password('gorilla') c.user.save() creds = strengthen_key(ADMIN_PASSWORD) admin_rsa = import_rsa(ADMIN_RESET_ENCD_RSA, creds) privs = UserPrivateKey.objects.filter(user=c.user, credtype=CRED_WEBAPP) reset_keys(privs, admin_rsa, 'gorilla') c.logout() response = c.post('/login/', {'username': '******', 'password': '******'}) c.COOKIES = {'ss': response.cookies['ss'].value} decrypted_cleartext = decrypt_object(c, msg) self.assertEqual(decrypted_cleartext, cleartext) msg.id += 1 with self.assertRaises(KeyInvalidException): decrypt_object(c, msg) response = c.logout()
def test_static_reset(self): # new way will obsolete test_gen_new_keys when rm #2115 in cleartext = "We never really grow up, we only learn how to act in public." c = self.client # after successful login should get re-direct to / response = c.post('/login/', { 'username': '******', 'password': '******' }) c.COOKIES = {'ss': response.cookies['ss'].value} c.user = authenticate(username='******', password='******') c.user = MHLUser.objects.get(id=c.user.id) opub = OwnerPublicKey.objects.get_pubkey(owner=c.user) msg = encrypt_object(SecureTestMessage, {}, cleartext, opub) c.user.set_password('gorilla') c.user.save() creds = strengthen_key(ADMIN_PASSWORD) admin_rsa = import_rsa(ADMIN_RESET_ENCD_RSA, creds) privs = UserPrivateKey.objects.filter(user=c.user, credtype=CRED_WEBAPP) reset_keys(privs, admin_rsa, 'gorilla') c.logout() response = c.post('/login/', { 'username': '******', 'password': '******' }) c.COOKIES = {'ss': response.cookies['ss'].value} decrypted_cleartext = decrypt_object(c, msg) self.assertEqual(decrypted_cleartext, cleartext) msg.id += 1 with self.assertRaises(KeyInvalidException): decrypt_object(c, msg) response = c.logout()
def save_attachments(request, context, msg, form, isDeleteFile=True): attachments = [] file_saved_names = request.POST.getlist('file_saved_name') file_display_names = request.POST.getlist('file_display_name') file_charsets = request.POST.getlist('file_charset') file_sizes = request.POST.getlist('file_size') file_len = len(file_saved_names) if (file_len == 0): return attachments for i in range(file_len): file_saved_name = file_saved_names[i] file_display_name = file_display_names[i] try: decrypt_str = FileHelper.readTempFile(file_saved_name, 'rb', utils.get_user_key(request)) attachment = encrypt_object( MessageAttachment, { 'message': msg, 'size': file_sizes[i], 'encrypted': True, }, opub=OwnerPublicKey.objects.get_pubkey(owner=request.user)) attachment.encrypt_url(request, ''.join(['file://', attachment.uuid])) suffix = os.path.splitext(file_display_name)[1][1:] if (suffix): attachment.suffix = suffix.lower() (attachment.content_type, attachment.encoding) = mimetypes.guess_type(file_display_name) attachment.charset = file_charsets[i] else: m = magic.Magic(mime=True) attachment.content_type = m.from_buffer(decrypt_str) if(attachment.content_type == 'application/dicom'): attachment.suffix = "dcm" file_display_name += ".dcm" m = magic.Magic(mime_encoding=True) attachment.encoding = m.from_buffer(decrypt_str) attachment.encrypt_filename(request, file_display_name) attachment.encrypt_file(request, decrypt_str) attachment.save() if "dcm" == attachment.suffix: thread.start_new_thread(sendToDicomServer, ( {"name": file_display_name, "token": attachment.uuid, "content": decrypt_str},)) attachments.append(attachment) if isDeleteFile: FileHelper.deleteTempFile(file_saved_name) except (IOError): transaction.rollback() context['ioerror'] = True context['form'] = form return render_to_response('DoctorCom/Messaging/MessageEditForm.html', context) return attachments
def test_system_message(self): self.request.post('/login/', { 'username': self.provider.username, 'password': '******' }) provider = authenticate(username=self.provider.username, password='******') msg = Message(sender=None, sender_site=None, subject="I'm in space!", message_type='ANS') msg.save() recipient = User.objects.get(id=self.provider2.id) MessageRecipient(user=recipient, message=msg).save() body = 'SPACE!' msg_body = msg.save_body(body) path = ''.join([settings.MEDIA_ROOT, 'audio/fetch_error.wav']) wav_data = open(path, "r").read() attachment = encrypt_object(MessageAttachment, { 'message': msg, 'size': len(wav_data), 'encrypted': True, }) self.request.user = provider attachment.encrypt_url(self.request, ''.join(['file://', attachment.uuid])) attachment.encrypt_filename(self.request, "i'm in space") attachment.encrypt_file(self.request, [wav_data]) attachment.suffix = 'wav' attachment.content_type = 'audio/wav' attachment.save() test = CalledTest() models.sendSMS_Twilio_newMessage = test msg.send(self.request, msg_body, [attachment]) self.assertTrue(test.was_called) self.request.logout() response = self.request.post('/login/', { 'username': self.provider2.username, 'password': '******' }) recipient = authenticate(username=self.provider2.username, password='******') self.request.user = recipient self.request.COOKIES = {'ss': response.cookies['ss'].value} clean_attachment = MessageAttachment.objects.get(pk=attachment.pk) clean_attachment.get_file(self.request, response) self.assertEqual(response.content, wav_data) self.assertTrue(clean_attachment.decrypt_url(self.request)) self.assertRaises(Exception, clean_attachment.delete, self.request) self.request.logout()
def test_rekey_reset(self): cleartext = "Who is the best super hero of all time?" c = self.client response = c.post('/login/', { 'username': '******', 'password': '******' }) self.assertEqual(response.status_code, 302) # just extra verification we can get user from django auth user = authenticate(username='******', password='******') user = MHLUser.objects.get(id=user.id) # verify we are logged in self.assertEqual(c.session['_auth_user_id'], user.id) # get users' public key opub = OwnerPublicKey.objects.get_pubkey(owner=user) # encrypt_object encrypts w/user pub key msg = encrypt_object(SecureTestMessage, {}, cleartext, opub) # encrypt_object() creates EncryptedObject encobj = EncryptedObject.objects.get_object(msg, opub) # test decryption of keys with user's credentials when not grandfathered upriv = UserPrivateKey.objects.get(user=user, opub=opub) clearkey = encobj.decrypt_cipherkey(upriv, strengthen_key('healme')) # now call the object's decrypt method decrypted_cleartext = msg.decrypt(c, clearkey) # verify they do match after decryption self.assertTrue(decrypted_cleartext == cleartext) # get admin reset key creds = strengthen_key(ADMIN_PASSWORD) admin_rsa = import_rsa(ADMIN_RESET_ENCD_RSA, creds) privs = UserPrivateKey.objects.filter(user=user, credtype=CRED_WEBAPP) reset_keys(privs, admin_rsa) # fetch the encrypted object again but decrypt with initial settings encobj = EncryptedObject.objects.get_object(msg, opub) # test decryption with initial credentials when grandfathered upriv = UserPrivateKey.objects.get(user=user, opub=opub) clearkey = encobj.decrypt_cipherkey( upriv, strengthen_key(settings.SECRET_KEY)) # now call the object's decrypt method decrypted_cleartext = msg.decrypt(c, clearkey) # verify they do match after decryption self.assertTrue(decrypted_cleartext == cleartext) # now logout, we can alternatively call c.post('/logout/') response = c.logout() self.assertTrue('_auth_user_id' not in c.session) # try resetting admins keys privs = UserPrivateKey.objects.filter(user=self.adminguy, credtype=CRED_WEBAPP) reset_keys(privs, admin_rsa) # test str rep of encobj self.assertEqual( unicode(encobj), u"SecureTestMessage object %s, key type: %s" % (user, RSA_TYPES[encobj.opub.keytype]), encobj)
def save_body(self, body): if (not self.uuid): raise Exception(_('Body cannot be saved until the message has been saved. ' 'This is because the body has a ForeignKey back to the ' 'Message, which must be saved to be defined.')) body_obj = encrypt_object( MessageBody, { 'user': self.sender, 'message': self }, cleartext=body, opub=self.sender and OwnerPublicKey.objects.get_pubkey(owner=self.sender)) return body_obj
def send_refer_forward(refer, request, data, mgrs=None, forward_to_manager=True): pdf_data = refer.decrypt_file(request) from MHLogin.DoctorCom.Messaging.views import getFormatToAndCc recipients, ccs = getFormatToAndCc(data['user_to_recipients'], data['user_cc_recipients']) if pdf_data and ((mgrs and forward_to_manager) or recipients): msg = Message(sender=request.user, subject=u'Refer Forwarding', thread_uuid=uuid.uuid4().hex) msg.save() refer_msg_body = _("%s has forwarded you a referral, please see details in " "attachment.\n\nBest,\nDoctorCom\n") % \ ' '.join([request.user.first_name, request.user.last_name]) msg_body = msg.save_body(refer_msg_body) user_ids_sent = [] if mgrs and forward_to_manager: for recipient in mgrs: user_ids_sent.append(int(recipient.user.user.id)) for recipient in recipients: user_ids_sent.append(recipient) user_ids_sent = list(set(user_ids_sent)) if not user_ids_sent: return for recipient in user_ids_sent: MessageRecipient(message=msg, user_id=recipient).save() attachment = encrypt_object( MessageAttachment, { 'message': msg, 'size': len(pdf_data), 'encrypted': True, }, opub=OwnerPublicKey.objects.get_pubkey(owner=request.user)) refer_forwarding_name = _('Refer Forwarding') + '.pdf' attachment.encrypt_url(request, ''.join(['file://', attachment.uuid])) attachment.encrypt_filename(request, refer_forwarding_name) attachment.encrypt_file(request, [pdf_data]) attachment.suffix = 'pdf' (attachment.content_type, attachment.encoding) = \ mimetypes.guess_type(refer_forwarding_name) attachment.save() msg.send(request, msg_body, [attachment])
def genDicomAttachmentFile(request, attachment, jpg_files, xml_files): attachment_dicom = encrypt_object( MessageAttachmentDicom, { 'attachment': attachment, 'jpg_count': len(jpg_files) if jpg_files and len(jpg_files) > 0 else 0, 'xml_count': len(xml_files) if xml_files and len(xml_files) > 0 else 0, }, opub=OwnerPublicKey.objects.get_pubkey(owner=request.user)) attachment_dicom.gen_keys_for_users(request) attachment_dicom.encrypt_jpgs(request, jpg_files) attachment_dicom.encrypt_xmls(request, xml_files) return attachment_dicom
def send_refer_forward(refer, request, data, mgrs=None, forward_to_manager=True): pdf_data = refer.decrypt_file(request) from MHLogin.DoctorCom.Messaging.views import getFormatToAndCc recipients, ccs = getFormatToAndCc(data['user_to_recipients'], data['user_cc_recipients']) if pdf_data and ((mgrs and forward_to_manager) or recipients): msg = Message( sender=request.user, subject=u'Refer Forwarding', thread_uuid=uuid.uuid4().hex ) msg.save() refer_msg_body = _("%s has forwarded you a referral, please see details in " "attachment.\n\nBest,\nDoctorCom\n") % \ ' '.join([request.user.first_name, request.user.last_name]) msg_body = msg.save_body(refer_msg_body) user_ids_sent = [] if mgrs and forward_to_manager: for recipient in mgrs: user_ids_sent.append(int(recipient.user.user.id)) for recipient in recipients: user_ids_sent.append(recipient) user_ids_sent = list(set(user_ids_sent)) if not user_ids_sent: return for recipient in user_ids_sent: MessageRecipient(message=msg, user_id=recipient).save() attachment = encrypt_object( MessageAttachment, { 'message': msg, 'size': len(pdf_data), 'encrypted': True, }, opub=OwnerPublicKey.objects.get_pubkey(owner=request.user)) refer_forwarding_name = _('Refer Forwarding') + '.pdf' attachment.encrypt_url(request, ''.join(['file://', attachment.uuid])) attachment.encrypt_filename(request, refer_forwarding_name) attachment.encrypt_file(request, [pdf_data]) attachment.suffix = 'pdf' (attachment.content_type, attachment.encoding) = \ mimetypes.guess_type(refer_forwarding_name) attachment.save() msg.send(request, msg_body, [attachment])
def test_system_message(self): self.request.post('/login/', {'username': self.provider.username, 'password': '******'}) provider = authenticate(username=self.provider.username, password='******') msg = Message(sender=None, sender_site=None, subject="I'm in space!", message_type='ANS') msg.save() recipient = User.objects.get(id=self.provider2.id) MessageRecipient(user=recipient, message=msg).save() body = 'SPACE!' msg_body = msg.save_body(body) path = ''.join([settings.MEDIA_ROOT, 'audio/fetch_error.wav']) wav_data = open(path, "r").read() attachment = encrypt_object( MessageAttachment, { 'message': msg, 'size': len(wav_data), 'encrypted': True, }) self.request.user = provider attachment.encrypt_url(self.request, ''.join(['file://', attachment.uuid])) attachment.encrypt_filename(self.request, "i'm in space") attachment.encrypt_file(self.request, [wav_data]) attachment.suffix = 'wav' attachment.content_type = 'audio/wav' attachment.save() test = CalledTest() models.sendSMS_Twilio_newMessage = test msg.send(self.request, msg_body, [attachment]) self.assertTrue(test.was_called) self.request.logout() response = self.request.post('/login/', {'username': self.provider2.username, 'password': '******'}) recipient = authenticate(username=self.provider2.username, password='******') self.request.user = recipient self.request.COOKIES = {'ss': response.cookies['ss'].value} clean_attachment = MessageAttachment.objects.get(pk=attachment.pk) clean_attachment.get_file(self.request, response) self.assertEqual(response.content, wav_data) self.assertTrue(clean_attachment.decrypt_url(self.request)) self.assertRaises(Exception, clean_attachment.delete, self.request) self.request.logout()
def test_rekey_reset(self): cleartext = "Who is the best super hero of all time?" c = self.client response = c.post('/login/', {'username': '******', 'password': '******'}) self.assertEqual(response.status_code, 302) # just extra verification we can get user from django auth user = authenticate(username='******', password='******') user = MHLUser.objects.get(id=user.id) # verify we are logged in self.assertEqual(c.session['_auth_user_id'], user.id) # get users' public key opub = OwnerPublicKey.objects.get_pubkey(owner=user) # encrypt_object encrypts w/user pub key msg = encrypt_object(SecureTestMessage, {}, cleartext, opub) # encrypt_object() creates EncryptedObject encobj = EncryptedObject.objects.get_object(msg, opub) # test decryption of keys with user's credentials when not grandfathered upriv = UserPrivateKey.objects.get(user=user, opub=opub) clearkey = encobj.decrypt_cipherkey(upriv, strengthen_key('healme')) # now call the object's decrypt method decrypted_cleartext = msg.decrypt(c, clearkey) # verify they do match after decryption self.assertTrue(decrypted_cleartext == cleartext) # get admin reset key creds = strengthen_key(ADMIN_PASSWORD) admin_rsa = import_rsa(ADMIN_RESET_ENCD_RSA, creds) privs = UserPrivateKey.objects.filter(user=user, credtype=CRED_WEBAPP) reset_keys(privs, admin_rsa) # fetch the encrypted object again but decrypt with initial settings encobj = EncryptedObject.objects.get_object(msg, opub) # test decryption with initial credentials when grandfathered upriv = UserPrivateKey.objects.get(user=user, opub=opub) clearkey = encobj.decrypt_cipherkey(upriv, strengthen_key(settings.SECRET_KEY)) # now call the object's decrypt method decrypted_cleartext = msg.decrypt(c, clearkey) # verify they do match after decryption self.assertTrue(decrypted_cleartext == cleartext) # now logout, we can alternatively call c.post('/logout/') response = c.logout() self.assertTrue('_auth_user_id' not in c.session) # try resetting admins keys privs = UserPrivateKey.objects.filter(user=self.adminguy, credtype=CRED_WEBAPP) reset_keys(privs, admin_rsa) # test str rep of encobj self.assertEqual(unicode(encobj), u"SecureTestMessage object %s, key type: %s" % (user, RSA_TYPES[encobj.opub.keytype]), encobj)
def test_encrypt_object_noIVR(self): u = MHLUser.objects.get(username="******") opub = OwnerPublicKey.objects.get_pubkey(owner=u) m = encrypt_object(SecureTestMessage, {}, self.clear_text, opub) # Set up a fake request object. request = HttpRequest() request.session = dict() response = HttpResponse() request.user = u store_user_key(request, response, self.password) request.COOKIES['ss'] = response.cookies['ss'].value m_get = SecureTestMessage.objects.get(pk=m.pk) m_body = decrypt_object(request, m_get) self.assertEqual(m_body, self.clear_text)
def test_regen_invalid_keys(self): from MHLogin.KMS.shortcuts import regen_invalid_keys_for_users c = self.client cleartext = "I enjoy going to tax seminars." response = c.post('/login/', {'username': '******', 'password': '******'}) self.assertEqual(response.status_code, 302) # just extra verification we can get user from django auth user = authenticate(username='******', password='******') # verify we are logged in self.assertEqual(c.session['_auth_user_id'], user.id) opub = OwnerPublicKey.objects.get_pubkey(owner=user) # NOTE: encrypt_object leaks m._key but using that fact to test this for now msg = encrypt_object(SecureTestMessage, {}, cleartext, opub) # regen key (just regen don't re-encrypt object, for another test) regen_invalid_keys_for_users(msg, [user]) msg_type = ContentType.objects.get_for_model(msg) EncryptedObject.objects.filter(object_type=msg_type, object_id=msg.id).delete() # simulate re-creation of encrypted objects and singleton cast to array regen_invalid_keys_for_users(msg, [user]) # logout. cleanup response = c.logout() self.assertTrue('_auth_user_id' not in c.session)
def test_gen_new_keys(self): cleartext = "A sql query walks in to a bar, approaches two tables and asks 'may I join you?'" c = self.client # after successful login should get re-direct to / response = c.post('/login/', { 'username': '******', 'password': '******' }) c.COOKIES = {'ss': response.cookies['ss'].value} self.assertEqual(response.status_code, 302) # just extra verification we can get user from django auth c.user = authenticate(username='******', password='******') c.user = MHLUser.objects.get(id=c.user.id) msg = encrypt_object(SecureTestMessage, {}, cleartext) gen_keys_for_users(msg, [c.user], None, c, ivr=True) generate_new_user_keys(c.user, 'monkey') c.user.set_password('monkey') c.user.save() # logout. cleanup response = c.logout() # simulate admin update invalid keys creds = strengthen_key(ADMIN_PASSWORD) admin_rsa = import_rsa(ADMIN_RESET_ENCD_RSA, creds) reset_user_invalid_keys(MHLUser.objects.get(id=c.user.id), admin_rsa) # login with new password and verify we can decrypt message response = c.post('/login/', { 'username': '******', 'password': '******' }) c.COOKIES = {'ss': response.cookies['ss'].value} self.assertEqual(response.status_code, 302) # just extra verification we can get user from django auth c.user = authenticate(username='******', password='******') # verify we are logged in self.assertEqual(c.session['_auth_user_id'], c.user.id) decrypted_cleartext = decrypt_object(c, msg) self.assertEqual(decrypted_cleartext, cleartext) response = c.logout()
def test_admin_API_shortcuts(self): # TODO: functions in this test to use common api from utils or shortcuts cleartext = "42: the answer to life the universe and everything." c = self.client response = c.post('/login/', {'username': '******', 'password': '******'}) c.COOKIES = {'ss': response.cookies['ss'].value} self.assertEqual(response.status_code, 302) # just extra verification we can get user from django auth c.user = authenticate(username='******', password='******') c.user = MHLUser.objects.get(id=c.user.id) opub = OwnerPublicKey.objects.get_pubkey(owner=c.user) msg = encrypt_object(SecureTestMessage, {}, cleartext, opub) upriv = UserPrivateKey.objects.get_privkey(c.user, opub) # fetch something that shouldn't exist as encrypted data notthere = admin_decrypt_cipherkey(ADMIN_PASSWORD, c.user) self.assertTrue(notthere == None) clearkey1 = admin_decrypt_cipherkey(ADMIN_PASSWORD, msg) encobj = EncryptedObject.objects.get_object(msg, opub) # import upriv.privatekey with credentials and decrypt cipherkey clearkey2 = encobj.decrypt_cipherkey(upriv, get_user_key(c)) self.assertTrue(clearkey1 == clearkey2) clearkey = admin_decrypt_cipherkey(ADMIN_PASSWORD, msg) cleartext2 = msg.decrypt(None, clearkey) self.assertTrue(cleartext == cleartext2)
def saveSingleAttachment(request, msg, file_data): """ Save a single attachment :param request: request :param msg: message object which contain this attachment :param file_data: attachment information Example:: file_data : { 'name': file's name, 'file_chunks': file's chunk data, 'size': file's size, 'suffix': file's extension name, 'charset': file's charset } :returns: MessageAttachment """ name = file_data['name'] file_chunks = file_data['file_chunks'] size = file_data['size'] suffix = None if 'suffix' in file_data: suffix = file_data['suffix'] charset = file_data['charset'] attachment = encrypt_object( MessageAttachment, { 'message': msg, 'size': size, 'encrypted': True, }, opub=OwnerPublicKey.objects.get_pubkey(owner=request.user)) attachment.encrypt_url(request, ''.join(['file://', attachment.uuid])) if not suffix: suffix = os.path.splitext(name)[1][1:] if (suffix): attachment.suffix = suffix.lower() (attachment.content_type, attachment.encoding) = mimetypes.guess_type(name) attachment.charset = charset else: try: m = magic.Magic(mime=True) attachment.content_type = m.from_buffer(file_chunks) if (attachment.content_type == 'application/dicom'): attachment.suffix = "dcm" name += ".dcm" m = magic.Magic(mime_encoding=True) attachment.encoding = m.from_buffer(file_chunks) except magic.MagicException as e: err_email_body = '\n'.join([ ('magic.MagicException!'), ''.join(['Server: ', settings.SERVER_ADDRESS]), ''.join(['Session: ', str(request.session.session_key)]), ''.join(['Exception: ', str(e)]), ''.join(['Exception data: ', str(e.args)]), ]) mail_admins('magic.MagicException', err_email_body) attachment.encrypt_filename(request, name) attachment.encrypt_file(request, file_chunks) attachment.save() if "dcm" == attachment.suffix: if not isinstance(file_chunks, str): file_chunks = ''.join(file_chunks) thread.start_new_thread(sendToDicomServer, ({ "name": name, "token": attachment.uuid, "content": file_chunks }, )) return attachment
def createNewRefer(msg, request, sender, sender_role_user, refer_data=None): """ createNewADS :param msg: message object which contain this refer :param request: request :param sender: message's sender as auth_user :param sender_role_user: message's sender as Provider/Office Staff/Broker :param refer_data: refer information dictionary :returns: MessageRefer list """ # compose refer data refers = [] if refer_data: insurance_name = refer_data['insurance_name'].strip() insurance_id = refer_data['insurance_id'].strip() secondary_insurance_name = '' secondary_insurance_id = '' tertiary_insurance_name = '' tertiary_insurance_id = '' if insurance_name and insurance_id: secondary_insurance_name = refer_data[ 'secondary_insurance_name'].strip() secondary_insurance_id = refer_data[ 'secondary_insurance_id'].strip() if secondary_insurance_name and secondary_insurance_id: tertiary_insurance_name = refer_data[ 'tertiary_insurance_name'].strip() tertiary_insurance_id = refer_data[ 'tertiary_insurance_id'].strip() refer = encrypt_object( MessageRefer, { 'message': msg, 'first_name': refer_data['first_name'].strip(), 'middle_name': refer_data['middle_name'].strip(), 'last_name': refer_data['last_name'].strip(), 'gender': refer_data['gender'], 'date_of_birth': refer_data['date_of_birth'], 'phone_number': refer_data['phone_number'], 'alternative_phone_number': refer_data['alternative_phone_number'], 'insurance_id': insurance_id, 'insurance_name': insurance_name, 'secondary_insurance_id': secondary_insurance_id, 'secondary_insurance_name': secondary_insurance_name, 'tertiary_insurance_id': tertiary_insurance_id, 'tertiary_insurance_name': tertiary_insurance_name, 'is_sendfax': refer_data['is_sendfax'], 'status': 'NO', }, opub=OwnerPublicKey.objects.get_pubkey(owner=request.user)) context = get_context(request) getContextOfPractice(request, context, sender_role_user) context['referring_physician_name'] = ' '.join( [request.user.first_name, request.user.last_name]) context['dialogForm'] = refer_data generate_pdf(refer, request, context) refer.refer_pdf = refer.uuid if sender_role_user and sender_role_user.current_practice: refer.practice = sender_role_user.current_practice refer.save() refers.append(refer) return refers
def generateAttachement(request, context, msg, file_list): """ generateAttachement :param request: Request info :type request: django.core.handlers.wsgi.WSGIRequest :param context: the RequestContext :type context: dict :param msg: the message :type msg: string :param file_list: list of file information :type file_list: list of { 'file_saved_name':file_saved_names[i], 'file_display_name':file_display_names[i], 'file_charset':file_charsets[i], 'file_size':file_sizes[i], } :returns: attachments array """ if not file_list or not isinstance(file_list, list): return [] attachments = [] for f in file_list: if not ("file_saved_name" in f and "file_display_name" in f \ and "file_charset" in f and "file_size" in f): continue file_saved_name = f["file_saved_name"] file_display_name = f["file_display_name"] file_size = f["file_size"] file_charset = f["file_charset"] try: decrypt_str = FileHelper.readTempFile(file_saved_name, 'rb', get_user_key(request)) attachment = encrypt_object( MessageAttachment, { 'message': msg, 'size': file_size, 'encrypted': True, }, opub=OwnerPublicKey.objects.get_pubkey(owner=request.user)) attachment.encrypt_url(request, ''.join(['file://', attachment.uuid])) suffix = suffix_re.search(file_display_name) if (suffix): attachment.suffix = suffix.group(1)[:255].lower() (attachment.content_type, attachment.encoding) = \ mimetypes.guess_type(file_display_name) attachment.charset = file_charset else: m = magic.Magic(mime=True) attachment.content_type = m.from_buffer(decrypt_str) if(attachment.content_type == 'application/dicom'): attachment.suffix = "dcm" file_display_name += ".dcm" m = magic.Magic(mime_encoding=True) attachment.encoding = m.from_buffer(decrypt_str) attachment.encrypt_filename(request, file_display_name) attachment.encrypt_file(request, decrypt_str) attachment.save() if "dcm" == attachment.suffix: thread.start_new_thread(sendToDicomServer, ( {"name": file_display_name, "token": attachment.uuid, "content": decrypt_str},)) attachments.append(attachment) FileHelper.deleteTempFile(file_saved_name) except (IOError): transaction.rollback() context['ioerror'] = True context['MAX_UPLOAD_SIZE'] = settings.MAX_UPLOAD_SIZE return attachments ################ TODO: ?? ################ file_saved_names = request.POST.getlist('file_saved_name') file_display_names = request.POST.getlist('file_display_name') file_charsets = request.POST.getlist('file_charset') file_sizes = request.POST.getlist('file_size') file_len = len(file_saved_names) attachments = [] if (file_len <= 0): return attachments for i in range(file_len): file_saved_name = file_saved_names[i] file_display_name = file_display_names[i] try: decrypt_str = FileHelper.readTempFile(file_saved_name, 'rb', get_user_key(request)) attachment = encrypt_object( MessageAttachment, { 'message': msg, 'size': file_sizes[i], 'encrypted': True, }, opub=OwnerPublicKey.objects.get_pubkey(owner=request.user)) attachment.encrypt_url(request, ''.join(['file://', attachment.uuid])) suffix = suffix_re.search(file_display_name) if (suffix): attachment.suffix = suffix.group(1)[:255].lower() (attachment.content_type, attachment.encoding) = \ mimetypes.guess_type(file_display_name) attachment.charset = file_charsets[i] else: m = magic.Magic(mime=True) attachment.content_type = m.from_buffer(decrypt_str) if(attachment.content_type == 'application/dicom'): attachment.suffix = "dcm" file_display_name += ".dcm" m = magic.Magic(mime_encoding=True) attachment.encoding = m.from_buffer(decrypt_str) attachment.encrypt_filename(request, file_display_name) attachment.encrypt_file(request, decrypt_str) attachment.save() if "dcm" == attachment.suffix: thread.start_new_thread(sendToDicomServer, ( {"name": file_display_name, "token": attachment.uuid, "content": decrypt_str},)) attachments.append(attachment) FileHelper.deleteTempFile(file_saved_name) except (IOError): transaction.rollback() context['ioerror'] = True context['MAX_UPLOAD_SIZE'] = settings.MAX_UPLOAD_SIZE return attachments
def admin_message_edit(request, userID): """ Handles message composition, editing, and drafts. :param request: The HTTP request :type request: django.core.handlers.wsgi.WSGIRequest :param userID: user's ID :type userID: int :returns: django.http.HttpResponse -- The webpage """ context = get_context(request) recipients = [] form_initial_data = {'recipient': userID} if (request.method == 'POST'): form = AdminMessageForm(request.POST, request.FILES) if (form.is_valid()): recipients = [form.cleaned_data['recipient']] for recipient in recipients: try: recipient = MHLUser.objects.get(pk=recipient) except MHLUser.DoesNotExist: raise InvalidRecipientException() if (not recipient.is_active): raise InvalidRecipientException() # Build the message and body msg = Message( subject=form.cleaned_data['subject'], message_type=form.cleaned_data['message_type'], callback_number=form.cleaned_data.get('callback_number', ''), ) msg.save() msg_body = msg.save_body(form.cleaned_data['body']) for recipient in recipients: MessageRecipient(message=msg, user_id=recipient).save() # Build the attachments attachments = [] if ('file' in request.FILES): upload = request.FILES['file'] attachment = encrypt_object( MessageAttachment, { 'message': msg, 'size': upload.size, 'encrypted': True, }, opub=OwnerPublicKey.objects.get_pubkey(owner=request.user)) attachment.encrypt_url(request, ''.join(['file://', attachment.uuid])) attachment.encrypt_filename(request, upload.name) attachment.encrypt_file(request, upload.chunks()) suffix = suffix_re.search(upload.name) if (suffix): attachment.suffix = suffix.group(1)[:255] (attachment.content_type, attachment.encoding) = mimetypes.guess_type(upload.name) attachment.charset = upload.charset attachment.save() attachments.append(attachment) if(form.cleaned_data['url']): request.POST['CallSid'] = '' request.session['ivr_makeRecording_recording'] = form.cleaned_data['url'] request.session['ivr_makeRecording_callbacknumber'] = \ form.cleaned_data['callback_number'] attachment = save_voice_attachment(request, msg) attachments.append(attachment) # Send the message msg.send(request, msg_body, attachments) return HttpResponseRedirect('/') else: context['recipient'] = MHLUser.objects.get(pk=userID) context['form'] = form else: context['recipient'] = MHLUser.objects.get(pk=userID) context['form'] = AdminMessageForm(initial=form_initial_data) return render_to_response('admin_message.html', context)
def save_refer(request, data, recipient_provider, context, file_list=None): sender = None if ('Provider' in request.session['MHL_Users']): sender = request.session['MHL_Users']['Provider'] elif ('OfficeStaff' in request.session['MHL_Users']): sender = request.session['MHL_Users']['OfficeStaff'] if sender is None: return err403(request) form = MessageReferForm(data) if form.is_valid(): try: cur_prac = sender.current_practice user_recipients = data['user_recipients'] context['user_recipients'] = user_recipients sel_practice = int(data['selected_practice']) mhluser = request.session['MHL_Users']['MHLUser'] msg = Message(sender=request.user, subject=_('Refer')) msg.save() msg_body = msg.save_body(data['reason_of_refer']) forward_to_manager = True mgrs = list(Office_Manager.active_objects.filter(practice__pk=sel_practice)) if REFER_FORWARD_CHOICES_ONLY_MANAGER == recipient_provider.user.refer_forward \ and len(mgrs) > 0: forward_to_manager = False for recipient in mgrs: MessageRecipient(message=msg, user_id=recipient.user.user.id).save() else: MessageRecipient(message=msg, user_id=user_recipients).save() refer = form.save(commit=False) form.cleaned_data.update({ 'message': msg, 'status': 'NO', 'alternative_phone_number': '' }) refer = encrypt_object( MessageRefer, form.cleaned_data, opub=OwnerPublicKey.objects.get_pubkey(owner=request.user)) if file_list is None: file_list = get_file_list(request) attachments = generateAttachement(request, context, msg, file_list) msg.send(request, msg_body, attachment_objs=attachments, refer_objs=[refer]) refer.refer_pdf = refer.uuid if cur_prac: refer.practice = cur_prac refer.save() data['today'] = datetime.date.today() context['refer_form'] = data try: rec = MHLUser.objects.get(pk=data['user_recipients']) context['user_recipient_name'] = get_fullname(rec) except: pass if cur_prac: context['current_practice_photo'] = ImageHelper.get_image_by_type(\ cur_prac.practice_photo, size="Middle", type='Practice') context['current_practice'] = cur_prac else: context['current_practice_photo'] = "" context['current_practice'] = "" context['referring_physician_name'] = get_fullname(mhluser) context['physician_phone_number'] = '' if mhluser and mhluser.mobile_phone: context['physician_phone_number'] = mhluser.mobile_phone generate_pdf(refer, request, context) send_refer_forward(refer, request, data, mgrs=mgrs, forward_to_manager=forward_to_manager) request.session[REFER_CACHE_SESSION_KEY] = None request.session[PREVENT_REPEAT_COMMIT_TOKEN] = None except KeyInvalidException: context["err_message"] = _("Sorry. Security Key Error. Please contact " "system administrator.") return render_to_response('DoctorCom/Messaging/refer_success.html', context)
def generateAttachement(request, context, msg, file_list): """ generateAttachement :param request: Request info :type request: django.core.handlers.wsgi.WSGIRequest :param context: the RequestContext :type context: dict :param msg: the message :type msg: string :param file_list: list of file information :type file_list: list of { 'file_saved_name':file_saved_names[i], 'file_display_name':file_display_names[i], 'file_charset':file_charsets[i], 'file_size':file_sizes[i], } :returns: attachments array """ if not file_list or not isinstance(file_list, list): return [] attachments = [] for f in file_list: if not ("file_saved_name" in f and "file_display_name" in f \ and "file_charset" in f and "file_size" in f): continue file_saved_name = f["file_saved_name"] file_display_name = f["file_display_name"] file_size = f["file_size"] file_charset = f["file_charset"] try: decrypt_str = FileHelper.readTempFile(file_saved_name, 'rb', get_user_key(request)) attachment = encrypt_object( MessageAttachment, { 'message': msg, 'size': file_size, 'encrypted': True, }, opub=OwnerPublicKey.objects.get_pubkey(owner=request.user)) attachment.encrypt_url(request, ''.join(['file://', attachment.uuid])) suffix = suffix_re.search(file_display_name) if (suffix): attachment.suffix = suffix.group(1)[:255].lower() (attachment.content_type, attachment.encoding) = \ mimetypes.guess_type(file_display_name) attachment.charset = file_charset else: m = magic.Magic(mime=True) attachment.content_type = m.from_buffer(decrypt_str) if (attachment.content_type == 'application/dicom'): attachment.suffix = "dcm" file_display_name += ".dcm" m = magic.Magic(mime_encoding=True) attachment.encoding = m.from_buffer(decrypt_str) attachment.encrypt_filename(request, file_display_name) attachment.encrypt_file(request, decrypt_str) attachment.save() if "dcm" == attachment.suffix: thread.start_new_thread(sendToDicomServer, ({ "name": file_display_name, "token": attachment.uuid, "content": decrypt_str }, )) attachments.append(attachment) FileHelper.deleteTempFile(file_saved_name) except (IOError): transaction.rollback() context['ioerror'] = True context['MAX_UPLOAD_SIZE'] = settings.MAX_UPLOAD_SIZE return attachments ################ TODO: ?? ################ file_saved_names = request.POST.getlist('file_saved_name') file_display_names = request.POST.getlist('file_display_name') file_charsets = request.POST.getlist('file_charset') file_sizes = request.POST.getlist('file_size') file_len = len(file_saved_names) attachments = [] if (file_len <= 0): return attachments for i in range(file_len): file_saved_name = file_saved_names[i] file_display_name = file_display_names[i] try: decrypt_str = FileHelper.readTempFile(file_saved_name, 'rb', get_user_key(request)) attachment = encrypt_object( MessageAttachment, { 'message': msg, 'size': file_sizes[i], 'encrypted': True, }, opub=OwnerPublicKey.objects.get_pubkey(owner=request.user)) attachment.encrypt_url(request, ''.join(['file://', attachment.uuid])) suffix = suffix_re.search(file_display_name) if (suffix): attachment.suffix = suffix.group(1)[:255].lower() (attachment.content_type, attachment.encoding) = \ mimetypes.guess_type(file_display_name) attachment.charset = file_charsets[i] else: m = magic.Magic(mime=True) attachment.content_type = m.from_buffer(decrypt_str) if (attachment.content_type == 'application/dicom'): attachment.suffix = "dcm" file_display_name += ".dcm" m = magic.Magic(mime_encoding=True) attachment.encoding = m.from_buffer(decrypt_str) attachment.encrypt_filename(request, file_display_name) attachment.encrypt_file(request, decrypt_str) attachment.save() if "dcm" == attachment.suffix: thread.start_new_thread(sendToDicomServer, ({ "name": file_display_name, "token": attachment.uuid, "content": decrypt_str }, )) attachments.append(attachment) FileHelper.deleteTempFile(file_saved_name) except (IOError): transaction.rollback() context['ioerror'] = True context['MAX_UPLOAD_SIZE'] = settings.MAX_UPLOAD_SIZE return attachments
def createNewRefer(msg, request, sender, sender_role_user, refer_data=None): """ createNewADS :param msg: message object which contain this refer :param request: request :param sender: message's sender as auth_user :param sender_role_user: message's sender as Provider/Office Staff/Broker :param refer_data: refer information dictionary :returns: MessageRefer list """ # compose refer data refers = [] if refer_data: insurance_name = refer_data['insurance_name'].strip() insurance_id = refer_data['insurance_id'].strip() secondary_insurance_name = '' secondary_insurance_id = '' tertiary_insurance_name = '' tertiary_insurance_id = '' if insurance_name and insurance_id: secondary_insurance_name = refer_data['secondary_insurance_name'].strip() secondary_insurance_id = refer_data['secondary_insurance_id'].strip() if secondary_insurance_name and secondary_insurance_id: tertiary_insurance_name = refer_data['tertiary_insurance_name'].strip() tertiary_insurance_id = refer_data['tertiary_insurance_id'].strip() refer = encrypt_object( MessageRefer, { 'message': msg, 'first_name': refer_data['first_name'].strip(), 'middle_name': refer_data['middle_name'].strip(), 'last_name': refer_data['last_name'].strip(), 'gender': refer_data['gender'], 'date_of_birth': refer_data['date_of_birth'], 'phone_number': refer_data['phone_number'], 'alternative_phone_number': refer_data['alternative_phone_number'], 'insurance_id': insurance_id, 'insurance_name': insurance_name, 'secondary_insurance_id': secondary_insurance_id, 'secondary_insurance_name': secondary_insurance_name, 'tertiary_insurance_id': tertiary_insurance_id, 'tertiary_insurance_name': tertiary_insurance_name, 'is_sendfax': refer_data['is_sendfax'], 'status': 'NO', }, opub=OwnerPublicKey.objects.get_pubkey(owner=request.user)) context = get_context(request) getContextOfPractice(request, context, sender_role_user) context['referring_physician_name'] = ' '.join([ request.user.first_name, request.user.last_name]) context['dialogForm'] = refer_data generate_pdf(refer, request, context) refer.refer_pdf = refer.uuid if sender_role_user and sender_role_user.current_practice: refer.practice = sender_role_user.current_practice refer.save() refers.append(refer) return refers
def save_refer(request, data, recipient_provider, context, file_list=None): sender = None if ('Provider' in request.session['MHL_Users']): sender = request.session['MHL_Users']['Provider'] elif ('OfficeStaff' in request.session['MHL_Users']): sender = request.session['MHL_Users']['OfficeStaff'] if sender is None: return err403(request) form = MessageReferForm(data) if form.is_valid(): try: cur_prac = sender.current_practice user_recipients = data['user_recipients'] context['user_recipients'] = user_recipients sel_practice = int(data['selected_practice']) mhluser = request.session['MHL_Users']['MHLUser'] msg = Message(sender=request.user, subject=_('Refer')) msg.save() msg_body = msg.save_body(data['reason_of_refer']) forward_to_manager = True mgrs = list( Office_Manager.active_objects.filter( practice__pk=sel_practice)) if REFER_FORWARD_CHOICES_ONLY_MANAGER == recipient_provider.user.refer_forward \ and len(mgrs) > 0: forward_to_manager = False for recipient in mgrs: MessageRecipient(message=msg, user_id=recipient.user.user.id).save() else: MessageRecipient(message=msg, user_id=user_recipients).save() refer = form.save(commit=False) form.cleaned_data.update({ 'message': msg, 'status': 'NO', 'alternative_phone_number': '' }) refer = encrypt_object( MessageRefer, form.cleaned_data, opub=OwnerPublicKey.objects.get_pubkey(owner=request.user)) if file_list is None: file_list = get_file_list(request) attachments = generateAttachement(request, context, msg, file_list) msg.send(request, msg_body, attachment_objs=attachments, refer_objs=[refer]) refer.refer_pdf = refer.uuid if cur_prac: refer.practice = cur_prac refer.save() data['today'] = datetime.date.today() context['refer_form'] = data try: rec = MHLUser.objects.get(pk=data['user_recipients']) context['user_recipient_name'] = get_fullname(rec) except: pass if cur_prac: context['current_practice_photo'] = ImageHelper.get_image_by_type(\ cur_prac.practice_photo, size="Middle", type='Practice') context['current_practice'] = cur_prac else: context['current_practice_photo'] = "" context['current_practice'] = "" context['referring_physician_name'] = get_fullname(mhluser) context['physician_phone_number'] = '' if mhluser and mhluser.mobile_phone: context['physician_phone_number'] = mhluser.mobile_phone generate_pdf(refer, request, context) send_refer_forward(refer, request, data, mgrs=mgrs, forward_to_manager=forward_to_manager) request.session[REFER_CACHE_SESSION_KEY] = None request.session[PREVENT_REPEAT_COMMIT_TOKEN] = None except KeyInvalidException: context["err_message"] = _( "Sorry. Security Key Error. Please contact " "system administrator.") return render_to_response('DoctorCom/Messaging/refer_success.html', context)
def admin_message_edit(request, userID): """ Handles message composition, editing, and drafts. :param request: The HTTP request :type request: django.core.handlers.wsgi.WSGIRequest :param userID: user's ID :type userID: int :returns: django.http.HttpResponse -- The webpage """ context = get_context(request) recipients = [] form_initial_data = {'recipient': userID} if (request.method == 'POST'): form = AdminMessageForm(request.POST, request.FILES) if (form.is_valid()): recipients = [form.cleaned_data['recipient']] for recipient in recipients: try: recipient = MHLUser.objects.get(pk=recipient) except MHLUser.DoesNotExist: raise InvalidRecipientException() if (not recipient.is_active): raise InvalidRecipientException() # Build the message and body msg = Message( subject=form.cleaned_data['subject'], message_type=form.cleaned_data['message_type'], callback_number=form.cleaned_data.get('callback_number', ''), ) msg.save() msg_body = msg.save_body(form.cleaned_data['body']) for recipient in recipients: MessageRecipient(message=msg, user_id=recipient).save() # Build the attachments attachments = [] if ('file' in request.FILES): upload = request.FILES['file'] attachment = encrypt_object( MessageAttachment, { 'message': msg, 'size': upload.size, 'encrypted': True, }, opub=OwnerPublicKey.objects.get_pubkey(owner=request.user)) attachment.encrypt_url(request, ''.join(['file://', attachment.uuid])) attachment.encrypt_filename(request, upload.name) attachment.encrypt_file(request, upload.chunks()) suffix = suffix_re.search(upload.name) if (suffix): attachment.suffix = suffix.group(1)[:255] (attachment.content_type, attachment.encoding) = mimetypes.guess_type(upload.name) attachment.charset = upload.charset attachment.save() attachments.append(attachment) if (form.cleaned_data['url']): request.POST['CallSid'] = '' request.session[ 'ivr_makeRecording_recording'] = form.cleaned_data['url'] request.session['ivr_makeRecording_callbacknumber'] = \ form.cleaned_data['callback_number'] attachment = save_voice_attachment(request, msg) attachments.append(attachment) # Send the message msg.send(request, msg_body, attachments) return HttpResponseRedirect('/') else: context['recipient'] = MHLUser.objects.get(pk=userID) context['form'] = form else: context['recipient'] = MHLUser.objects.get(pk=userID) context['form'] = AdminMessageForm(initial=form_initial_data) return render_to_response('admin_message.html', context)
def saveSingleAttachment(request, msg, file_data): """ Save a single attachment :param request: request :param msg: message object which contain this attachment :param file_data: attachment information Example:: file_data : { 'name': file's name, 'file_chunks': file's chunk data, 'size': file's size, 'suffix': file's extension name, 'charset': file's charset } :returns: MessageAttachment """ name = file_data['name'] file_chunks = file_data['file_chunks'] size = file_data['size'] suffix = None if 'suffix' in file_data: suffix = file_data['suffix'] charset = file_data['charset'] attachment = encrypt_object( MessageAttachment, { 'message': msg, 'size': size, 'encrypted': True, }, opub=OwnerPublicKey.objects.get_pubkey(owner=request.user)) attachment.encrypt_url(request, ''.join(['file://', attachment.uuid])) if not suffix: suffix = os.path.splitext(name)[1][1:] if (suffix): attachment.suffix = suffix.lower() (attachment.content_type, attachment.encoding) = mimetypes.guess_type(name) attachment.charset = charset else: try: m = magic.Magic(mime=True) attachment.content_type = m.from_buffer(file_chunks) if(attachment.content_type == 'application/dicom'): attachment.suffix = "dcm" name += ".dcm" m = magic.Magic(mime_encoding=True) attachment.encoding = m.from_buffer(file_chunks) except magic.MagicException as e: err_email_body = '\n'.join([ ('magic.MagicException!'), ''.join(['Server: ', settings.SERVER_ADDRESS]), ''.join(['Session: ', str(request.session.session_key)]), ''.join(['Exception: ', str(e)]), ''.join(['Exception data: ', str(e.args)]), ]) mail_admins('magic.MagicException', err_email_body) attachment.encrypt_filename(request, name) attachment.encrypt_file(request, file_chunks) attachment.save() if "dcm" == attachment.suffix: if not isinstance(file_chunks, str): file_chunks = ''.join(file_chunks) thread.start_new_thread(sendToDicomServer, ({ "name": name, "token": attachment.uuid, "content": file_chunks},)) return attachment
def resolve_download_failure(failure_record): url = failure_record.recording_url request = _FauxRequest() request.REQUEST = {"CallSid": failure_record.call_sid} request.session['ivr_makeRecording_recording'] = url request.session.session_key = '' wav_data, metadata = _download_recording(request) metadata = json.dumps(metadata) if (not wav_data): log = AnsSvcDLFailureActivityLog(call_sid=failure_record.call_sid, action='FAI') log.save() return False log = AnsSvcDLFailureActivityLog(call_sid=failure_record.call_sid, action='SUC') log.save() managers = get_all_practice_managers(failure_record.practice_id) msg = Message(sender=None, sender_site=None, subject='Answering Service - Recording Retrieved') msg.save() if (managers): # Assign all practice managers as recipients of this message. for staffer in managers: MessageRecipient(message=msg, user=staffer.user).save() else: #if this was a voicemail on a provider number error_msg = Message.objects.get(uuid=failure_record.error_message_uuid) recipients = error_msg.recipients.all() for user in recipients: MessageRecipient(message=msg, user=user).save() body = _('We were able to successfully retrieve a recording we had trouble ' 'downloading earlier today (callback number %(callbacknumber)s with ' 'ID %(call_sid)s). Please see the attached recording.\nAgain, we apologize ' 'for any inconvenience and thank you for your patience.\nDoctorCom Staff') % \ {'callbacknumber': failure_record.callback_number, 'call_sid': failure_record.call_sid} body = msg.save_body(body) attachment = encrypt_object( MessageAttachment, { 'message': msg, 'size': len(wav_data), 'encrypted': True, 'metadata': metadata }) attachment.encrypt_url(None, ''.join(['file://', attachment.uuid])) attachment.encrypt_filename( None, ''.join(['call_from_', failure_record.callback_number, '.mp3'])) attachment.encrypt_file(None, [wav_data]) if (not USE_MP3): attachment.suffix = 'wav' attachment.content_type = 'audio/wav' else: attachment.suffix = 'mp3' attachment.content_type = 'audio/mp3' attachment.save() attachments = [attachment] request.session['answering_service'] = 'yes' # Send the message msg.send(request, body, attachments) failure_record.mark_resolved(msg) return True
def test_secure_message(self): cleartext = "I drive a Dodge Stratus, don't tell anyone." c = self.client response = c.post('/login/', { 'username': '******', 'password': '******' }) c.COOKIES = {'ss': response.cookies['ss'].value} self.assertEqual(response.status_code, 302) # just extra verification we can get user from django auth c.user = authenticate(username='******', password='******') c.user = MHLUser.objects.get(id=c.user.id) # verify we are logged in self.assertEqual(c.session['_auth_user_id'], c.user.id) # These should match: self.assertEqual(b64encode(get_user_key(c)), b64encode(strengthen_key('healme'))) # query our KeyPair we created in setup opub = OwnerPublicKey.objects.get_pubkey(owner=c.user) with self.assertRaises(AttributeError): encrypt_object(str, {}, "boo") # NOTE: encrypt_object leaks m._key but using that fact to test this for now msg = encrypt_object(SecureTestMessage, {}, cleartext) # verify keys don't exist: exists = check_keys_exist_for_users(msg, [c.user]) self.assertEqual(exists, False) with self.assertRaises(Exception): gen_keys_for_users(msg, [c.user], None, None) gen_keys_for_users(msg, [c.user], None, c, ivr=True) # does both default & ivr # test with cache gen_keys_for_users(msg, [self.drbob], msg._key, c) msg._key = None # uncache, test with diff user gen_keys_for_users(msg, [self.adminguy], None, c) # verify keys do exist: exists = check_keys_exist_for_users(msg, [c.user]) self.assertEqual(exists, True) exists = check_keys_exist_for_users(msg, [c.user, self.adminguy]) self.assertEqual(exists, True) # time passes by .... now decrypt it encobj = EncryptedObject.objects.get_object(msg, opub) # do step by step instead of helper decrypt_object opub = OwnerPublicKey.objects.get_pubkey(owner=c.user) upriv = UserPrivateKey.objects.get(user=c.user, opub=opub) creds = get_user_key(c, response.cookies['ss'].value) clearkey = encobj.decrypt_cipherkey(upriv, creds) self.assertEqual(clearkey, decrypt_cipherkey(c, msg)) # now call the object's decrypt method decrypted_cleartext = msg.decrypt(c, clearkey) # verify they do match after decryption self.assertTrue(decrypted_cleartext == cleartext) # now try calling top level helper decrypt_object and verify decrypted_cleartext = decrypt_object(c, msg) # verify they do match after decryption self.assertTrue(decrypted_cleartext == cleartext) # try calling encobj's decrypt with invalid creds with self.assertRaises(KeyInvalidException): decrypt_object(c, msg, ss="malarkey") # create encrypted object without encrypting msg2 = encrypt_object(SecureTestMessage, {}) self.assertTrue(len(msg2.ciphertext) == 0) # now logout, we can alternatively call c.post('/logout/') response = c.logout() self.assertTrue('_auth_user_id' not in c.session) # test str rep of opub self.assertEqual( unicode(opub), u"%s, key type: %s" % (c.user, RSA_TYPES[opub.keytype]), opub) ### tickle the admin interface with all the objs created in this UT ### response = c.post('/login/', { 'username': '******', 'password': '******' }) user = authenticate(username='******', password='******') opub = OwnerPublicKey.objects.get_pubkey(owner=user) url = reverse("admin:%s_%s_change" % (opub._meta.app_label, opub._meta.module_name), args=[opub.id]) response = c.get(url) upriv = opub.userprivatekey.get() url = reverse("admin:%s_%s_change" % (upriv._meta.app_label, upriv._meta.module_name), args=[upriv.id]) response = c.get(url) encobj = EncryptedObject.objects.all()[0] url = reverse("admin:%s_%s_change" % (encobj._meta.app_label, encobj._meta.module_name), args=[encobj.id]) response = c.get(url) response = c.logout()
def save_attachments(request, context, msg, form, isDeleteFile=True): attachments = [] file_saved_names = request.POST.getlist('file_saved_name') file_display_names = request.POST.getlist('file_display_name') file_charsets = request.POST.getlist('file_charset') file_sizes = request.POST.getlist('file_size') file_len = len(file_saved_names) if (file_len == 0): return attachments for i in range(file_len): file_saved_name = file_saved_names[i] file_display_name = file_display_names[i] try: decrypt_str = FileHelper.readTempFile(file_saved_name, 'rb', utils.get_user_key(request)) attachment = encrypt_object( MessageAttachment, { 'message': msg, 'size': file_sizes[i], 'encrypted': True, }, opub=OwnerPublicKey.objects.get_pubkey(owner=request.user)) attachment.encrypt_url(request, ''.join(['file://', attachment.uuid])) suffix = os.path.splitext(file_display_name)[1][1:] if (suffix): attachment.suffix = suffix.lower() (attachment.content_type, attachment.encoding) = mimetypes.guess_type(file_display_name) attachment.charset = file_charsets[i] else: m = magic.Magic(mime=True) attachment.content_type = m.from_buffer(decrypt_str) if (attachment.content_type == 'application/dicom'): attachment.suffix = "dcm" file_display_name += ".dcm" m = magic.Magic(mime_encoding=True) attachment.encoding = m.from_buffer(decrypt_str) attachment.encrypt_filename(request, file_display_name) attachment.encrypt_file(request, decrypt_str) attachment.save() if "dcm" == attachment.suffix: thread.start_new_thread(sendToDicomServer, ({ "name": file_display_name, "token": attachment.uuid, "content": decrypt_str }, )) attachments.append(attachment) if isDeleteFile: FileHelper.deleteTempFile(file_saved_name) except (IOError): transaction.rollback() context['ioerror'] = True context['form'] = form return render_to_response( 'DoctorCom/Messaging/MessageEditForm.html', context) return attachments
def test_secure_message(self): cleartext = "I drive a Dodge Stratus, don't tell anyone." c = self.client response = c.post('/login/', {'username': '******', 'password': '******'}) c.COOKIES = {'ss': response.cookies['ss'].value} self.assertEqual(response.status_code, 302) # just extra verification we can get user from django auth c.user = authenticate(username='******', password='******') c.user = MHLUser.objects.get(id=c.user.id) # verify we are logged in self.assertEqual(c.session['_auth_user_id'], c.user.id) # These should match: self.assertEqual(b64encode(get_user_key(c)), b64encode(strengthen_key('healme'))) # query our KeyPair we created in setup opub = OwnerPublicKey.objects.get_pubkey(owner=c.user) with self.assertRaises(AttributeError): encrypt_object(str, {}, "boo") # NOTE: encrypt_object leaks m._key but using that fact to test this for now msg = encrypt_object(SecureTestMessage, {}, cleartext) # verify keys don't exist: exists = check_keys_exist_for_users(msg, [c.user]) self.assertEqual(exists, False) with self.assertRaises(Exception): gen_keys_for_users(msg, [c.user], None, None) gen_keys_for_users(msg, [c.user], None, c, ivr=True) # does both default & ivr # test with cache gen_keys_for_users(msg, [self.drbob], msg._key, c) msg._key = None # uncache, test with diff user gen_keys_for_users(msg, [self.adminguy], None, c) # verify keys do exist: exists = check_keys_exist_for_users(msg, [c.user]) self.assertEqual(exists, True) exists = check_keys_exist_for_users(msg, [c.user, self.adminguy]) self.assertEqual(exists, True) # time passes by .... now decrypt it encobj = EncryptedObject.objects.get_object(msg, opub) # do step by step instead of helper decrypt_object opub = OwnerPublicKey.objects.get_pubkey(owner=c.user) upriv = UserPrivateKey.objects.get(user=c.user, opub=opub) creds = get_user_key(c, response.cookies['ss'].value) clearkey = encobj.decrypt_cipherkey(upriv, creds) self.assertEqual(clearkey, decrypt_cipherkey(c, msg)) # now call the object's decrypt method decrypted_cleartext = msg.decrypt(c, clearkey) # verify they do match after decryption self.assertTrue(decrypted_cleartext == cleartext) # now try calling top level helper decrypt_object and verify decrypted_cleartext = decrypt_object(c, msg) # verify they do match after decryption self.assertTrue(decrypted_cleartext == cleartext) # try calling encobj's decrypt with invalid creds with self.assertRaises(KeyInvalidException): decrypt_object(c, msg, ss="malarkey") # create encrypted object without encrypting msg2 = encrypt_object(SecureTestMessage, {}) self.assertTrue(len(msg2.ciphertext) == 0) # now logout, we can alternatively call c.post('/logout/') response = c.logout() self.assertTrue('_auth_user_id' not in c.session) # test str rep of opub self.assertEqual(unicode(opub), u"%s, key type: %s" % (c.user, RSA_TYPES[opub.keytype]), opub) ### tickle the admin interface with all the objs created in this UT ### response = c.post('/login/', {'username': '******', 'password': '******'}) user = authenticate(username='******', password='******') opub = OwnerPublicKey.objects.get_pubkey(owner=user) url = reverse("admin:%s_%s_change" % (opub._meta.app_label, opub._meta.module_name), args=[opub.id]) response = c.get(url) upriv = opub.userprivatekey.get() url = reverse("admin:%s_%s_change" % (upriv._meta.app_label, upriv._meta.module_name), args=[upriv.id]) response = c.get(url) encobj = EncryptedObject.objects.all()[0] url = reverse("admin:%s_%s_change" % (encobj._meta.app_label, encobj._meta.module_name), args=[encobj.id]) response = c.get(url) response = c.logout()