class PrepPostfixForm(forms.Form): ''' Prepare postfix for GoodCrypto. ''' def clean(self): cleaned_data = super(PrepPostfixForm, self).clean() # clean up simple errors goodcrypto_private_server_ip = cleaned_data.get( 'goodcrypto_private_server_ip') if goodcrypto_private_server_ip is not None: goodcrypto_private_server_ip = goodcrypto_private_server_ip.strip() validate_ipv46_address(goodcrypto_private_server_ip) self.cleaned_data[ 'goodcrypto_private_server_ip'] = goodcrypto_private_server_ip return cleaned_data goodcrypto_private_server_ip = forms.CharField( required=True, help_text=i18n( "The IP address for your GoodCrypto private server. For example, 194.10.34.1" ), ) main_cf = forms.CharField( required=True, widget=forms.Textarea(attrs={ 'rows': 10, 'cols': 100, 'class': "input-xlarge" }), label='main.cf content', help_text=i18n( "Paste the full content of your mail server's /etc/postfix/main.cf file." ), ) master_cf = forms.CharField( required=True, widget=forms.Textarea(attrs={ 'rows': 10, 'cols': 100, 'class': "input-xlarge" }), label='master.cf content', help_text=i18n( "Paste the full content of your mail server's /etc/postfix/master.cf file." ), ) aliases = forms.CharField( required=False, widget=forms.Textarea(attrs={ 'rows': 5, 'cols': 100, 'class': "input-xlarge" }), label='aliases content', help_text=i18n( "Paste the full content of your mail server's aliases file. Leave blank if you don't use aliases." ), )
def reject_message(self, error_message, message=None): ''' Reject a message that had an unexpected error and return the to address. >>> # This message will fail if testing on dev system >>> to_address = get_admin_email() >>> filter = Filter('root', 'root', 'bad message') >>> filter.reject_message('Unknown message') == to_address True ''' try: if message is None: message = self.out_message if email_in_domain(self.sender): to_address = self.sender subject = i18n('Undelivered Mail: Unable to send message') elif email_in_domain(self.recipient): to_address = self.recipient subject = i18n('Error: Unable to receive message') else: to_address = get_admin_email() subject = i18n('Message rejected.') notice = '{}'.format(error_message) if message is not None: notice += '\n\n===================\n{}'.format(message) notify_user(to_address, subject, notice) except: raise return to_address
def import_key(email, encryption_name, public_key, id_fingerprint_pairs, plugin): ''' Import the key and return the fingerprint. ''' status = fingerprint = None result_ok = False # make sure the email address is in the key for (user_id, fingerprint) in id_fingerprint_pairs: user_name, email_address = parse_address(email) key_address = get_email(user_id) if email_address.lower() == key_address.lower(): result_ok = True break if result_ok: status = '' for (user_id, fingerprint) in id_fingerprint_pairs: result_ok = plugin.import_public(public_key, id_fingerprint_pairs) if result_ok: status += '{}\n'.format( i18n( 'Imported key successfully. Fingerprint: {fingerprint}' .format(fingerprint=fingerprint))) else: status += '{}\n'.format(i18n('Unable to import key')) else: status = i18n( "Cannot import the key because it isn't for {email}".format( email=email)) return result_ok, status
def report_db_error(to_user, from_user, encryption_name, crypto_message): ''' Report a database error to the user. >>> tag = report_db_error('*****@*****.**', '*****@*****.**', 'GPG', None) >>> tag == 'The GPG fingerprint for [email protected] could not be saved.' True ''' subject = i18n( '{warning} - Unable to save the {encryption} fingerprint in the database.' .format(warning=TAG_WARNING, encryption=encryption_name)) tag = i18n( 'The {encryption} fingerprint for {email} could not be saved.'.format( encryption=encryption_name, email=from_user)) message_lines = [] message_lines.append(tag) message_lines.append('\n') message_lines.append( i18n( 'Forward the body of this email message to your system or mail administrator immediately.' )) _notify_recipient(to_user, subject, message_lines, crypto_message) return tag
def login_user(request, user, password): ''' Login a django user. >>> error_message = login_user(None, None, None) >>> error_message == 'Unable to login user without a request and user.' True ''' error_message = None if request is None or user is None: error_message = i18n("Unable to login user without a request and user.") log_message(error_message) else: if user.is_active: try: username = user.username # you must authenticate before logging a user in user = authenticate(username=username, password=password) login(request, user) except: error_message = i18n('Unexpected error while logging in {username}.'.format( username=user.username)) log_message(error_message) record_exception() log_message('EXCEPTION - see syr.exception.log for details') else: error_message = i18n("User is not active so unable to login.") log_message(error_message) return error_message
def report_expired_key(to_user, from_user, encryption_name, expiration, crypto_message): ''' Report a key expired. >>> tag = report_expired_key('*****@*****.**', '*****@*****.**', 'GPG', None, None) >>> tag == 'The GPG key for [email protected] expired on None.' True ''' tag = i18n("The {encryption} key for {email} expired on {date}.".format( encryption=encryption_name, email=from_user, date=expiration)) subject = i18n( '{warning} - Received a message from {email} with a key that expired on {date}' .format(warning=TAG_WARNING, email=from_user, date=expiration)) message_lines = [] message_lines.append( i18n( 'First, use your GoodCrypto server to delete the {email} contact.'. format(email=from_user))) message_lines.append( i18n('Next, ask {email} to create a new key and resend the message.'. format(email=from_user))) message_lines.append( i18n( 'Finally, verify the new fingerprint with {email}. Do not use email for the verification or someone could insert a bad key.' .format(email=from_user))) _notify_recipient(to_user, subject, message_lines, crypto_message) return tag
def report_bad_header_key(to_user, from_user, user_ids, encryption_name, crypto_message): ''' Report the header's key doesn't match the sender. >>> user_ids = ['*****@*****.**'] >>> tag = report_bad_header_key('*****@*****.**', '*****@*****.**', user_ids, 'GPG', None) >>> tag == 'The message included a GPG key for [email protected], but the message was sent from [email protected].' True ''' subject = i18n("{warning} - Message contained a bad key in header".format( warning=TAG_WARNING)) if len(user_ids) == 1: tag = i18n( 'The message included a {encryption} key for {email}, but the message was sent from {from_email}.' .format(encryption=encryption_name, email=user_ids[0], from_email=from_user)) else: tag = i18n( 'The message included multiple {encryption} keys for "{ids}", but only a key from the sender, {email}, can be imported.' .format(encryption=encryption_name, ids=', '.join(user_ids), email=from_user)) message_lines = [] message_lines.append(tag) _notify_recipient(to_user, subject, message_lines, crypto_message) return tag
def authenticate_user(email, password): ''' Authenticate a django user. >>> __, __, error_message = authenticate_user(None, None) >>> error_message == 'Email or password are not defined so unable to authenticate user.' True ''' ok = False user = error_message = None if email is None or password is None: error_message = i18n("Email or password are not defined so unable to authenticate user.") log_message(error_message) else: user = authenticate(username=email, password=password) if user is not None: # the password verified for the user if user.is_active: ok = True log_message("{} is valid, active and authenticated".format(email)) else: error_message = i18n("The {} account has been disabled.".format(email)) log_message(error_message) else: # the authentication system was unable to verify the username and password error_message = i18n("The email and password do not match the previously configured account.") return ok, user, error_message
def _encrypt_message_with_all(self, encryption_names): ''' Encrypt the message with each encryption program. ''' encrypted = fatal_error = False error_message = '' encrypted_with = [] encrypted_classnames = [] to_user = self.crypto_message.smtp_recipient() original_payload = self.crypto_message.get_email_message().get_message().get_payload() self._log_message("encrypting using {} with {}'s key".format(encryption_names, to_user)) for encryption_name in encryption_names: encryption_classname = get_key_classname(encryption_name) if encryption_classname not in encrypted_classnames: try: if options.require_key_verified(): __, key_ok, __ = contacts.get_fingerprint(to_user, encryption_name) self._log_message("{} {} key verified: {}".format(to_user, encryption_name, key_ok)) else: key_ok = True if key_ok: if self._encrypt_message(encryption_name): encrypted_classnames.append(encryption_classname) encrypted_with.append(encryption_name) else: error_message += i18n('You need to verify the {encryption} key for {email} before you can use it.'.format( encryption=encryption_name, email=to_user)) self._log_message(error_message) except MessageException as message_exception: fatal_error = True error_message += message_exception.value self._log_exception(error_message) break # if the user has encryption software defined, then the message # must be encrypted or bounced to the sender if len(encrypted_classnames) > 0: encrypted = True else: MSG_NOT_SET = i18n('Message not sent to {email} because there was a problem encrypting.'.format( email=to_user)) fatal_error = True if error_message is None or len(error_message) <= 0: error_message = '{} {}\n{}'.format(MSG_NOT_SET, i18n("It's possible the recipient's key is missing."), self.POSSIBLE_ENCRYPT_SOLUTION) else: error_message = '{} {}'.format(MSG_NOT_SET, error_message) # restore the payload self.crypto_message.get_email_message().get_message().set_payload(original_payload) if fatal_error: self._log_message('raising message exception in _encrypt_message_with_all') self._log_message(error_message) raise MessageException(value=error_message) return encrypted_with
def _get_encrypt_error_message(self, users_dict, encryption_name): to_user = users_dict[encrypt_utils.TO_KEYWORD] from_user = users_dict[encrypt_utils.FROM_KEYWORD] passcode = users_dict[encrypt_utils.PASSCODE_KEYWORD] if options.clear_sign_email(): if from_user is None or passcode is None: error_message = '{} '.format( i18n("Message not sent to {email} because currently there isn't a private {encryption} key for you and your mail administrator requires all encrypted messages also be clear signed.".format( email=to_user, encryption=encryption_name))) if options.create_private_keys(): error_message += i18n("GoodCrypto is creating a private key now. You will receive email when your keys are ready so you can resend your message.") else: error_message += '\n\n{}'.format(i18n( 'Ask your mail administrator to create a private key for you and then try resending the message.')) else: error_message = '{}\n{}'.format( i18n(self.UNABLE_TO_ENCRYPT.format( from_email=from_user, to_email=to_user, encryption=encryption_name)), self.POSSIBLE_ENCRYPT_SOLUTION) else: error_message = '{}\n{}'.format( i18n(self.UNABLE_TO_ENCRYPT.format( from_email=from_user, to_email=to_user, encryption=encryption_name)), self.POSSIBLE_ENCRYPT_SOLUTION) return error_message
def export_key(request): '''Export the public key for a user.''' def get_safe_name(email): try: name = '' for letter in email: if letter == '@' or letter == '.' or letter == '-': name += '_' elif re.match('[A-Za-z0-9]', letter): name += letter except Exception: name = email record_exception() log_message('EXCEPTION - see syr.exception.log for details') return name if options.login_to_export_keys() and not request.user.is_authenticated(): context = {} context.update(csrf(request)) response = redirect('/login/?next={}'.format(request.path), context) else: response = None form = forms.ExportKeyForm() form_template = 'mail/export_key.html' if request.method == 'POST': response = None form = forms.ExportKeyForm(request.POST) if form.is_valid(): try: email = form.cleaned_data['email'] encryption_software = form.cleaned_data['encryption_software'] public_key = contacts.get_public_key(email, encryption_software) if public_key is None or len(public_key) <= 0: data = {'title': i18n("Export {encryption_software} Key Error".format( encryption_software=encryption_software)), 'result': i18n('Your GoodCrypto server does not have a public {encryption_software} key defined for {email}'.format( encryption_software=encryption_software, email=email))} template = 'mail/key_error_results.html' response = render_to_response( template, data, context_instance=RequestContext(request)) else: name = get_safe_name(email) log_message('export {} public {} key to {}'.format(email, encryption_software, name)) response = HttpResponse(public_key, content_type='application/text') response['Content-Disposition'] = 'attachment; filename="{}.asc"'.format(name) except Exception: record_exception() log_message('EXCEPTION - see syr.exception.log for details') if response is None: log_message('post: {}'.format(request.POST)) if response is None: response = render_to_response( form_template, {'form': form}, context_instance=RequestContext(request)) return response
def clean(self): '''Verify there is only 1 general info record.''' error_message = None cleaned_data = super(ImportKeyFromKeyserverForm, self).clean() email_or_fingerprint = cleaned_data.get('email_or_fingerprint') __, email = parse_address(email_or_fingerprint) if email is None: fingerprint = strip_fingerprint(email_or_fingerprint) m = re.match('^[0-9A-Fa-f]+$', fingerprint) if m: if len(fingerprint) < 16: error_message = i18n( 'Either enter a valid email address or a fingerprint that is least 16 characters' ) else: error_message = i18n( 'Either enter a valid email address or a fingerprint which must contain only numbers and the letters A through F.' ) if error_message is not None: _log.write(error_message) raise forms.ValidationError(error_message, code='invalid') return cleaned_data
class ImportKeyFromFileForm(forms.Form): from goodcrypto.mail.models import EncryptionSoftware key_file = forms.FileField( max_length=MAX_PUBLIC_KEY_FILEZISE, help_text=i18n('Select the file that contains the key.'), ) encryption_software = forms.ModelChoiceField( queryset=EncryptionSoftware.objects.filter(active=True), empty_label=None, help_text=i18n( 'Select the type of encryption software associated with the key.'), ) user_name = forms.CharField( max_length=100, required=False, help_text= 'Printable name of the contact in case the key does not contain it. Optional.' ) fingerprint = forms.CharField( max_length=100, required=False, help_text= "The fingerprint for the contact's public key, if known. Optional.") passcode = forms.CharField( max_length=PASSCODE_MAX_LENGTH, required=False, help_text= "If you're importing a private key, then you must enter its passphrase." )
def report_bad_bundled_encrypted_message(to_domain, bundled_messages): ''' Report unable to create an encrypted bundled message. ''' subject = i18n('{} - Unable to send messages to {domain}'.format( TAG_WARNING, domain=to_domain)) line1 = i18n( 'Your GoodCrypto private server tried to send messages to {domain} using the {user} keys. It was unable to do so.' .format(domain=to_domain, user=DOMAIN_USER)) line2 = i18n( "You should verify that you have a contact and key for both your domain and {domain}'s domain." .format(domain=to_domain)) line3 = i18n( "You can disable padding and packetization, but it means that your users will be easier to track." ) # leave a trailing space in case we add a 4th line admin_message = '{}\n\n{}\n\n{} '.format(line1, line2, line3) if len(bundled_messages) > 0: line4 = i18n( "Also, {} messages to {domain} will be lost if you disable padding and packetization before resolving the current problem." .format(len(bundled_messages), domain=to_domain)) admin_message += line4 admin = get_admin_email() notify_user(admin, subject, admin_message) log_message('sent bad encrypted bundle message notice to {}\n{}'.format( admin, admin_message))
def report_error_verifying_key(to_user, from_user, encryption_name, crypto_message): ''' Report the key comparison got an error during comparison. >>> tag = report_error_verifying_key('*****@*****.**', '*****@*****.**', 'GPG', None) >>> tag == 'GoodCrypto Warning - Unable to verify fingerprint for [email protected]' True ''' subject = i18n( "{warning} - Unable to verify fingerprint for {email}".format( warning=TAG_WARNING, email=from_user)) tag = subject message_lines = [] message_lines.append( i18n( 'The message arrived with a key, but unable to compare the {encryption} fingerprint.' .format(encryption=encryption_name))) message_lines.append( i18n( 'It is possible the database was just busy, but if this happens again please report it to your mail administrator immediately.' )) _notify_recipient(to_user, subject, message_lines, crypto_message) return tag
class Keyserver(models.Model): ''' List of keyservers to obtain public keys. >>> test_gpg = EncryptionSoftware.objects.get(name='TestGPG') >>> test_keyserver = Keyserver.objects.create( ... name='TestKeyserver', active=True, encryption_software=test_gpg) >>> s = str(test_keyserver) >>> s == 'TestKeyserver' True >>> s = test_gpg.__str__() >>> isinstance(s, str) True >>> x = test_keyserver.delete() ''' name = models.CharField(i18n('Name'),max_length=100, help_text=i18n('Name of keyserver.')) encryption_software = models.ForeignKey(EncryptionSoftware, default=1, help_text=i18n('Type of encryption software for this keyserver.')) active = models.BooleanField(i18n('Active?'), default=True, help_text=i18n('Should this keyserver be used to find keys?')) last_date = models.DateField(i18n('Last attempt'), blank=True, null=True, help_text=i18n('The last date attempted to use this keyserver.')) last_status = models.CharField(i18n('Status'),max_length=50, default=constants.DEFAULT_KEYSERVER_STATUS, help_text=i18n('The status of the last contact to this keyserver.')) def __str__(self): return '{}'.format(self.name)
def show_outbound_msg(request, verification_code): '''Show the outbound message with the verification code.''' try: template = 'mail/verified_encrypted.html' result_headers = [] results = [] error_message = None email = request.user.email records = history.get_outbound_messages(email) if records: # narrow the messages to those matching the verification_code records = records.filter( verification_code=url_unquote(verification_code)) if not records: try: # use the verification_code without unquoting it in case they pasted it into a url field records = records.filter(verification_code=verification_code) except: pass if records: results, private, private_signed, clear_signed, dkim_signed = summarize_outbound_messages( records) main_headline, subheadline = get_verify_msg_headlines( 'sent', private, private_signed, clear_signed, dkim_signed) else: main_headline = i18n('<font color="red">Not</font> Verified') subheadline = i18n( 'Message not sent privately from {}'.format(email)) error1 = NOT_SENT_PRIVATELY.format( email=email, verification_code=verification_code) error2 = TAMPERED_SENT_WARNING.format(email=email) error_message = '{} {}'.format(error1, error2) log_message(error_message) params = { 'email': email, 'main_headline': main_headline, 'subheadline': subheadline, 'results': results, 'error_message': error_message } response = render_to_response(template, params, context_instance=RequestContext(request)) except Exception: record_exception() log_message('EXCEPTION - see syr.exception.log for details') response = HttpResponseRedirect('/mail/show_encrypted_history/') return response
def create_superuser(admin, password=None): ''' Create a django superuser. >>> # In honor of Sergeant Michal, who publicly denounced and refused to serve in operations involving the >>> # occupied Palestinian territories because of the widespread surveillance of innocent residents. >>> email = '*****@*****.**' >>> user, password, error_message = create_superuser(email) >>> user <User: [email protected]> >>> password is not None True >>> error_message is None True >>> delete_user(email) True >>> __, __, error_message = create_superuser(None) >>> error_message == 'Email for the admin is not defined so unable to finish configuration.' True ''' user = password = error_message = None if admin is None: error_message = i18n("Email for the admin is not defined so unable to finish configuration.") log_message('admin not defined so unable to configure superuser') else: try: user = User.objects.filter(username=admin) except: record_exception() log_message('EXCEPTION - see syr.exception.log for details') if user: log_message('{} user name already exists'.format(admin)) else: try: if password is None: # create a password password = gen_passcode(max_length=24) if len(admin) > 30: user_name = admin[:30] else: user_name = admin user = User.objects.create_superuser(user_name, admin, password) log_message('created superuser: {}'.format(user)) except: user = password = None error_message = i18n('Unable to add an admin user named {}.'.format(admin)) record_exception() log_message('EXCEPTION - see syr.exception.log for details') return user, password, error_message
def report_key_creation_timedout(email): ''' Report that creating a key timed out. >>> report_key_creation_timedout('*****@*****.**') ''' subject = i18n("Creating your private key timed out.") notify_user( email, i18n("GoodCrypto - {}".format(subject)), i18n( "Your GoodCrypto server is probably very buzy. You might wait a 5-10 minutes and then try sending a message again. If that doesn't work, then ask your mail administrator to create your key manually." ))
def get_verify_msg_headlines(direction, private, private_signed, clear_signed, dkim_signed): ''' Get the headlines for a verified message. ''' main_headline = i18n('<font color="green">Verified</font>') if private and (private_signed or clear_signed or dkim_signed): subheadline = i18n('Message {} privately and signed'.format(direction)) elif private: subheadline = i18n('Message {} privately'.format(direction)) elif (private_signed or clear_signed or dkim_signed): subheadline = i18n('Message {} signed'.format(direction)) return main_headline, subheadline
def report_no_matching_fingerprint_on_keyserver(to_user, fingerprint, encryption_name): ''' Report unable to find a matching fingerprint on any of the active keyservers. >>> report_no_matching_fingerprint_on_keyserver('*****@*****.**', '12345', 'GPG') ''' subject = i18n("Unable to find key that matches the fingerprint.") notify_user( to_user, i18n("GoodCrypto - {}".format(subject)), i18n( "Your GoodCrypto server searched the active keyservers and was unable to find a {} key that matches {}." .format(encryption_name, fingerprint)))
def report_metadata_key_creation_error(email): ''' Report that an error occurred creating a metadata key. >>> report_metadata_key_creation_error('*****@*****.**') ''' subject = i18n('GoodCrypto - Error while creating a private metadata key') body = '{}.\n{}'.format( subject, i18n( "Metadata cannot be protected until you create a private key for {}@{}" .format(DOMAIN_USER, get_domain()))) notify_user(email, subject, body)
def report_key_creation_error(email): ''' Report that an error occurred creating a key. >>> report_key_creation_error('*****@*****.**') ''' subject = i18n('GoodCrypto - Error while creating a private key for you') body = '{}.\n{}'.format( subject, i18n( "Contact your mail administrator and ask them to create it for you manually." )) notify_user(email, subject, body)
def report_message_undeliverable(message, sender): ''' Report an unexpected error when delivering a message. >>> report_message_undeliverable('Serious error', None) ''' subject = i18n('Error delivering message') if sender is not None: subject += ' ' subject += i18n('from {sender}'.format(sender=sender)) error_message = i18n( 'An unexpected error was detected when trying to deliver the attached message.\n\n{}' .format(message)) notify_user(get_admin_email(), subject, error_message)
class GetFingerprintForm(forms.Form): from goodcrypto.mail.models import EncryptionSoftware email = forms.EmailField( max_length=254, help_text=i18n( 'Enter the email address whose fingerprint you want to verify.'), ) encryption_software = forms.ModelChoiceField( queryset=EncryptionSoftware.objects.filter(active=True), empty_label=None, help_text=i18n('Select the encryption software for the key.'), )
def clean(self): '''Verify there is only 1 general info record.''' cleaned_data = super(OptionsAdminForm, self).clean() # the mail_server_address should either be an ip address or a domain mail_server_address = cleaned_data.get('mail_server_address') if is_mta_ok(mail_server_address): _log.write('mail server address ok') self.cleaned_data['mail_server_address'] = mail_server_address else: del self.cleaned_data['mail_server_address'] _log.write('deleted mail server address from cleaned data') if mail_server_address is None or len( mail_server_address.strip()) <= 0: error_message = i18n( 'You need to define the mail server address (MTA).') else: error_message = i18n( 'The mail server address contains one or more bad characters or spaces.' ) _log.write(error_message) raise forms.ValidationError(error_message, code='invalid') encrypt_metadata = cleaned_data.get('encrypt_metadata') bundle_and_pad = cleaned_data.get('bundle_and_pad') if bundle_and_pad and not encrypt_metadata: del self.cleaned_data['encrypt_metadata'] _log.write('deleted encrypt_metadata from cleaned data') del self.cleaned_data['bundle_and_pad'] _log.write('deleted bundle_and_pad from cleaned data') error_message = i18n( 'You can only bundle and pad messages if you also encrypt metadata. Either add a check mark to "Encrypt metadata" or remove the check mark from "Bundle and pad".' ) _log.write(error_message) raise forms.ValidationError(error_message, code='invalid') add_dkim_sig = cleaned_data.get('add_dkim_sig') dkim_public_key = cleaned_data.get('dkim_public_key') if add_dkim_sig: if not dkim_public_key or len(dkim_public_key.strip()) <= 0: config_dkim.start(get_domain()) _log.write('starting to configure dkim') return cleaned_data
class ExportKeyForm(forms.Form): from goodcrypto.mail.models import EncryptionSoftware email = forms.EmailField( max_length=254, help_text=i18n( 'Enter the email address whose public key you want exported.'), ) encryption_software = forms.ModelChoiceField( queryset=EncryptionSoftware.objects.filter(active=True), empty_label=None, help_text=i18n( 'Select the type of encryption software associated with the key.'), )
def validate_email(email, role): if email is None: raise ValidationError( i18n('No email address specified for {role}'.format( role=role))) try: email_validator = EmailValidator() email_validator(email) except ValidationError as validation_error: self.log_message('Bad {} email address in envelope: {}'.format( role, email)) raise ValidationError( i18n('Bad {role} email address in envelope: "{email}"'. format(role=role, email=email))) return email
def show_metadata_domains(request): '''Show domains that have metadata keys.''' if not request.user.is_authenticated(): context = {} context.update(csrf(request)) response = redirect('/login/?next={}'.format(request.path), context) else: try: metadata_list = contacts.get_metadata_domains() if len(metadata_list) > 0: error_message = None else: error_message = i18n("There aren't any domains ready to protect metadata, yet.") template = 'mail/metadata_domains.html' params = {'metadata_list': metadata_list, 'encrypt_metadata': options.encrypt_metadata(), 'require_key_verified': options.require_key_verified(), 'error_message': error_message} response = render_to_response( template, params, context_instance=RequestContext(request)) except Exception: record_exception() log_message('EXCEPTION - see syr.exception.log for details') response = HttpResponseRedirect('/mail/show_metadata_domains/') return response
def _create_new_body_text(self, body): ''' Create the body text from a corrupted message. >>> from goodcrypto_tests.mail.message_utils import get_plain_message_name >>> with open(get_plain_message_name('basic.txt')) as input_file: ... email_message = EmailMessage(input_file.readlines()) ... email_message._create_new_body_text('Test new body text') ''' charset, __ = get_charset(self._message, self._last_charset) self.log_message('creating new body text with char set: {}'.format(charset)) try: body_text = '' for line in body: body_text += line.encode(charset) except Exception as body_exception: self.log_message(body_exception) record_exception() body_text = ''.join(body) if len(self.bad_header_lines) > 0: body_text += '\n\n{}\n'.format(i18n('Removed bad header lines')) for bad_header_line in self.bad_header_lines: body_text += ' {}\n'.format(bad_header_line) self._message.set_payload(body_text, charset=charset)