def team_invite(request, organization_slug, team_id ): organization = get_object_or_404(Organization, slug=organization_slug) if not organization.hasStaffAccess( request.user ): raise PermissionDenied() team = get_object_or_404(Team, id=team_id) if team.organization != organization: raise PermissionDenied() # Shenanigans! userinput = request.POST.get("invitee") users = User.objects.filter(username__iexact=userinput) if len(users) == 0: users = User.objects.filter(email__iexact=userinput) if len(users) > 0: new_member = users[0] team.members.add( new_member ) team.save() return team_detail(request, organization_slug, team_id) if email_re.match( userinput ): key = ''.join(random.choice(string.letters + string.digits) for i in xrange(8)) invite = TeamInvite(email_address=userinput, team=team, key=key) invite.save() subject = _("Invtation to ScrumDo team") message = render_to_string("organizations/team_invite_email.txt", { "invite": invite, "inviter": request.user }) send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [userinput]) return team_detail(request, organization_slug, team_id)
def is_valid_email(email): """ Is the string a valid email? (We use the regex Django uses to define an email address) """ return True if email_re.match(email) else False
def clean(self): """ Validates the quarantine form """ cleaned_data = self.cleaned_data use_alt = cleaned_data.get("use_alt") altrecipients = cleaned_data.get("altrecipients") learn = cleaned_data.get("learn") release = cleaned_data.get("release") todelete = cleaned_data.get("todelete") if not learn and not release and not todelete: raise forms.ValidationError( _("Select atleast one action to perform")) else: if altrecipients in EMPTY_VALUES and use_alt and release: raise forms.ValidationError( _("Provide atleast one alternative recipient")) else: if use_alt and release: emails = altrecipients.split(',') for email in emails: if not email_re.match(email.strip()): raise forms.ValidationError( _('%(email)s is not a valid e-mail address.') % {'email': force_escape(email)}) return cleaned_data
def clean(self): """ Validates the quarantine form """ cleaned_data = self.cleaned_data use_alt = cleaned_data.get("use_alt") altrecipients = cleaned_data.get("altrecipients") salearn = cleaned_data.get("salearn") release = cleaned_data.get("release") todelete = cleaned_data.get("todelete") if not salearn and not release and not todelete: raise forms.ValidationError("Select atleast one action to perform") else: if altrecipients in EMPTY_VALUES and use_alt and release: raise forms.ValidationError( "Provide atleast one alternative recipient") else: if use_alt and release: emails = altrecipients.split(',') for email in emails: if not email_re.match(email.strip()): raise forms.ValidationError( '%s is not a valid e-mail address.' % force_escape(email)) return cleaned_data
def clean(self, value): if not value: raise forms.ValidationError('Enter at least one e-mail address.') emails = set(re.split('\s*,?\s*', value)) for email in emails: if not email_re.match(email): raise forms.ValidationError('%s is not a valid e-mail address.' % email) return ','.join(list(emails))
def validate(self): # See explanation of validate() on ApiModel class self.errors = {} self.build_errors(['email'], ['practice_name']) # As long as email hasn't yet come back as Empty or Duplicate, check it is a valid address now if not self.errors.get('email'): if not email_re.match(self.email): self.errors['email'] = 'Invalid'
def clean_emails(self): data = self.cleaned_data['emails'] bad_emails = [] for email in data.split(): if not email_re.match(email): bad_emails.append(email) if bad_emails: raise forms.ValidationError('\n'.join(['%s is not a valid email.' % bad_email for bad_email in bad_emails])) return data
def clean_from_address(self): from_address = self.cleaned_data['from_address'] from_address = from_address.strip() if (not email_re.match(from_address) and not DOM_RE.match(from_address) and not IPV4_RE.match(from_address) and not IPV4_NET_OR_RANGE_RE.match(from_address)): raise forms.ValidationError(_("Provide either a valid IPv4, email," " Domain address, or IPv4 network or range")) return from_address
def gen_email(pdf, user, owner): "generate and return email" text_content = render_to_string('reports/pdf_report.txt', {'user': user, 'url': url}) subject = _('Baruwa usage report for: %(user)s') % { 'user': owner} if email_re.match(user.username): toaddr = user.username if email_re.match(user.email): toaddr = user.email if admin_addrs: msg = EmailMessage(subject, text_content, from_email, [toaddr], admin_addrs) else: msg = EmailMessage(subject, text_content, from_email, [toaddr]) msg.attach('baruwa.pdf', pdf.getvalue(), "application/pdf") print _("* Queue %(user)s's report to: %(addr)s") % { 'user': owner, 'addr': toaddr} pdf.close() return msg
def clean_to_address(self): to_address = self.cleaned_data['to_address'] if not email_re.match(to_address): raise forms.ValidationError( '%s provide a valid e-mail address' % force_escape(to_address)) if to_address not in self.request.session['user_filter']['addresses'] \ and not self.request.user.is_superuser(): raise forms.ValidationError( "The address: %s does not belong to you." % force_escape( to_address)) return to_address
def clean_from_address(self): from_address = self.cleaned_data['from_address'] from_address = from_address.strip() if (not email_re.match(from_address) and not DOM_RE.match(from_address) and not IPV4_RE.match(from_address) and not IPV4_NET_OR_RANGE_RE.match(from_address) and not ipaddr_is_valid(from_address)): raise forms.ValidationError(_("Provide either a valid IPv4/IPv6, email," " Domain address, or IPv4/IPv6 network or range")) return from_address
def _send_invitation(request, confirmation_key, email, content): from django.forms.fields import email_re if email_re.match(email): try: invitation = Invitation.objects.get(email=email) except Invitation.DoesNotExist: invitation = get_object_or_404(Invitation, confirmation_key=confirmation_key) invitation.email = email invitation.content = content invitation.save() return invitation return False
def clean_to_address(self): to_address = self.cleaned_data['to_address'] if not email_re.match(to_address): raise forms.ValidationError( _('%(email)s provide a valid e-mail address') % {'email': force_escape(to_address)}) if to_address not in self.request.session['user_filter']['addresses'] \ and not self.request.user.is_superuser(): raise forms.ValidationError( _("The address: %(email)s does not belong to you.") % {'email': force_escape(to_address)}) return to_address
def clean_emails(self): data = self.cleaned_data['emails'] bad_emails = [] for email in data.split(): if not email_re.match(email): bad_emails.append(email) if bad_emails: raise forms.ValidationError('\n'.join([ '%s is not a valid email.' % bad_email for bad_email in bad_emails ])) return data
def get_code(request): email = request.GET.get('email').strip() print email if email_re.match(email): new_code = create_code(email) em, created = M.EmailCode.objects.get_or_create(email=email, defaults={'code': new_code}) em = em.code if created: user = User.objects.create_user(username=email, email=email, password=em) send_mail([email], '*****@*****.**', 'Your QuoteBin Password', em) return JsonResponse(json.dumps({'success': True})) return JsonResponse(json.dumps({'success': False, 'reason': 'Invalid Email'}))
def subscribe(request): if request.method == 'POST': from django.forms.fields import email_re if email_re.match(request.POST['email']): sub = Subscription(email=request.POST['email']) sub.save() create_message(request, "Dodano do newslettera") return conditional_redirect(request, '/') else: create_message(request, "Błędny adres e-mail") return conditional_redirect(request, '/') else: return conditional_redirect(request, '/')
def set_user_addresses(request): """ set addresses in the session """ if not request.user.is_superuser: profile = retrieve_profile(request.user) addresses = [addr.address for addr in UserAddresses.objects.filter( user=request.user).exclude(enabled__exact=0)] if profile.account_type == 3: if email_re.match(request.user.username): addresses.append(request.user.username) request.session['user_filter'] = {'account_type': profile.account_type, 'addresses': addresses}
def clean(self, value): """ Check that the field contains one or more comma-separated emails and normalizes the data to a list of the email strings. """ if not value: raise forms.ValidationError("Enter at least one e-mail address.") emails = [e.strip() for e in value.split(",") if e.strip() != ""] for email in emails: if not email_re.match(email): raise forms.ValidationError(_("%(email)s is not a valid e-mail address." % {"email": email})) # Always return the cleaned data. return emails
def clean(self, value): super(EmailListField, self).clean(value) emails = email_separator_re.split(value) if not emails: raise forms.ValidationError( _(u'Enter at least one e-mail address.')) for email in emails: if not email_re.match(email): raise forms.ValidationError( _('%s is not a valid e-mail address.') % email) if self.max_emails is not None and len(emails) > self.max_emails: raise forms.ValidationError( _('Cannot send to more than %i addresses: %i') % ( self.max_emails, len(emails))) return emails
def updateEmail(request): ''' Updates a users e-mail address @pre request.POST["form"] == "Change E-mail" @post request.user.email = email @author John Hartquist ''' email = request.POST["email"] if (email_re.match(email)): request.user.email = email request.user.save() #success return 0 else: #failure return 1
def authenticate(self, username=None, password=None): if not '@' in username: return None login_user, domain = username.split('@') dom = UserAddresses.objects.filter(address=domain, address_type=1) if not dom: return None hosts = MailAuthHost.objects.filter(useraddress=dom) if not hosts: return None for host in hosts: if not host.split_address: login_user = username if self.mail_auth(host.protocol, login_user, password, host.address, host.port): try: user = User.objects.get(username=username) except User.DoesNotExist: user = User(username=username) user.set_unusable_password() user.is_staff = False user.is_superuser = False try: from django.forms.fields import email_re except ImportError: from django.core.validators import email_re if email_re.match(username): user.email = username user.save() try: profile = user.get_profile() except UserProfile.DoesNotExist: profile = UserProfile(user=user, account_type=3) profile.save() return user return None
def validate(self): # See explanation of validate() on ApiModel class # Basic requirement for all users unique = ['name'] required = ['type'] # Add in other required fields where necessary # NOTE: pin is not, at this time, added because we must allow dups if self.type.startswith('_'): # System users can never be site users -- API enforces this self.is_site_user = False self.email = None self.password = None else: # Non-system users should always have a color and pin required.append('color') required.append('pin') if self.is_site_user: # User is NOT system user & IS site user: email/password required unique.append('email') required.append('password') # Reset self.errors & check for Empty & Duplicate values first self.errors = {} self.build_errors(unique, required) if not self.type.startswith('_'): try: pin = int(self.pin) except ValueError: self.errors['pin'] = 'Invalid' else: if not len(self.pin) == 4: self.errors['pin'] = 'Invalid' if self.is_site_user and not self.errors.get('email'): # Validate email address via regexp if not email_re.match(self.email): self.errors['email'] = 'Invalid'
def clean(self): """clean_address""" if self._errors: return self.cleaned_data cleaned_data = self.cleaned_data address = cleaned_data['address'] user = cleaned_data['user'] if user.is_superuser: error_msg = _('Super users do not use addresses') self._errors["address"] = ErrorList([error_msg]) del cleaned_data['address'] account = UserProfile.objects.get(user=user) if account.account_type == 2: if not DOM_RE.match(address): error_msg = _('provide a valid domain address') self._errors["address"] = ErrorList([error_msg]) del cleaned_data['address'] else: if not email_re.match(address): error_msg = _('provide a valid email address') self._errors["address"] = ErrorList([error_msg]) del cleaned_data['address'] return cleaned_data
def is_valid_email(email): return True if email_re.match(email) else False
def authenticate(self, username=None, password=None): try: from pyrad import packet from pyrad.client import Client, Timeout from pyrad.dictionary import Dictionary except ImportError: return None if not '@' in username: return None username = username.decode('utf-8') password = password.decode('utf-8') login_user, domain = username.split('@') dom = UserAddresses.objects.filter(address=domain, address_type=1) if not dom: return None hosts = MailAuthHost.objects.filter(useraddress=dom, protocol=3) if not hosts: return None for host in hosts: if not host.split_address: login_user = username try: client = Client(server=host.address, authport=host.port, secret=settings.RADIUS_SECRET[host.address].encode('utf-8'), dict=Dictionary(StringIO(DICTIONARY)),) except AttributeError: return None request = client.CreateAuthPacket(code=packet.Accessrequestuest, User_Name=login_user,) request["User-Password"] = request.PwCrypt(password) try: reply = client.SendPacket(request) except Timeout: return None except Exception: return None if reply.code == packet.AccessReject: return None if reply.code != packet.AccessAccept: return None try: user = User.objects.get(username=username) except User.DoesNotExist: user = User(username=username) user.set_unusable_password() user.is_staff = False user.is_superuser = False if email_re.match(username): user.email = username user.save() try: profile = user.get_profile() except UserProfile.DoesNotExist: profile = UserProfile(user=user, account_type=3) profile.save() return user return None
def handle_noargs(self, **options): from django.db.models import Count, Sum from django.template.defaultfilters import filesizeformat from django.core.mail import EmailMessage, SMTPConnection from django.conf import settings from django.template.loader import render_to_string from baruwa.accounts.models import UserProfile, UserAddresses from baruwa.messages.models import Message from baruwa.messages.templatetags.messages_extras import tds_trunc from baruwa.messages.models import MessageTotals from baruwa.utils.graphs import PieChart, PIE_CHART_COLORS, BarChart from reportlab.lib import colors from reportlab.lib.styles import getSampleStyleSheet from reportlab.lib.units import inch from reportlab.platypus import SimpleDocTemplate, Spacer, Table, \ TableStyle, Paragraph, Image, PageBreak try: from django.forms.fields import email_re except ImportError: from django.core.validators import email_re try: from cStringIO import StringIO except: from StringIO import StringIO table_style = TableStyle([ ('FONT', (0, 0), (-1, -1), 'Helvetica'), ('FONT', (0, 0), (-1, 0), 'Helvetica-Bold'), ('FONTSIZE', (0, 0), (-1, -1), 8), ('GRID', (0, 0), (-1, -1), 0.15, colors.black), ('ALIGN', (0, 0), (-1, 0), 'CENTER'), ('ALIGN', (4, 1), (-1, -1), 'CENTER'), ('ALIGN', (0, 0), (0, -1), 'CENTER'), ('VALIGN', (4, 1), (-1, -1), 'MIDDLE'), ('SPAN', (4, 1), (-1, -1)), ]) styles = getSampleStyleSheet() reports = [ [ 'from_address', {'from_address__exact':""}, 'num_count', 'Top senders by quantity'], [ 'from_address', {'from_address__exact':""}, 'size', 'Top senders by volume'], [ 'from_domain', {'from_domain__exact':""}, 'num_count', 'Top sender domains by quantity'], [ 'from_domain', {'from_domain__exact':""}, 'size', 'Top sender domains by volume'], [ 'to_address', {'to_address__exact':""}, 'num_count', 'Top recipients by quantity'], [ 'to_address', {'to_address__exact':""}, 'size', 'Top recipients by volume'], [ 'to_domain', {'to_domain__exact':"", 'to_domain__isnull':False}, 'num_count', 'Top recipient domains by quantity'], [ 'to_domain', {'to_domain__exact':"", 'to_domain__isnull':False}, 'size', 'Top recipient domains by volume'], ] emails = [] from_email = getattr(settings, 'DEFAULT_FROM_EMAIL', 'postmaster@localhost') url = getattr(settings, 'QUARANTINE_REPORT_HOSTURL','') logo_dir = getattr(settings, 'MEDIA_ROOT', '') img = Image(logo_dir + '/imgs/css/logo.jpg') profiles = UserProfile.objects.filter(send_report=1) print "=================== Processing reports ======================" for profile in profiles: user = profile.user if email_re.match(user.email) or email_re.match(user.username): pdf = StringIO() doc = SimpleDocTemplate(pdf, topMargin=50, bottomMargin=18) logo = [(img, 'Baruwa mail report')] logo_table = Table(logo, [2.0 * inch, 5.4 * inch]) logo_table.setStyle(TableStyle([ ('FONT', (0, 0), (-1, 0), 'Helvetica-Bold'), ('ALIGN', (0, 0), (-1, 0), 'LEFT'), ('ALIGN', (1, 0), (-1, 0), 'RIGHT'), ('FONTSIZE', (1, 0), (-1, 0), 10), ('LINEBELOW', (0, 0),(-1, -1), 0.15, colors.black), ])) parts = [logo_table] parts.append(Spacer(1, 20)) sentry = 0 for report in reports: column = report[0] exclude_kwargs = report[1] order_by = "-%s" % report[2] order = report[2] title = report[3] data = Message.report.all(user).values(column).\ exclude(**exclude_kwargs).annotate( num_count=Count(column), size=Sum('size') ).order_by(order_by)[:10] if data: sentry += 1 headings = [('', 'Address', 'Count', 'Volume', '')] rows = [[draw_square(PIE_CHART_COLORS[index]), tds_trunc(row[column], 45), row['num_count'], filesizeformat(row['size']),''] for index,row in enumerate(data)] if len(rows) != 10: missing = 10 - len(rows) add_rows = [ ('', '', '', '', '') for ind in range(missing) ] rows.extend(add_rows) headings.extend(rows) dat = [row[order] for row in data] total = sum(dat) labels = [ ("%.1f%%" % ((1.0 * row[order] / total) * 100)) for row in data ] pie = PieChart() pie.chart.labels = labels pie.chart.data = dat headings[1][4] = pie table_with_style = Table(headings, [0.2 * inch, 2.8 * inch, 0.5 * inch, 0.7 * inch, 3.2 * inch]) table_with_style.setStyle(table_style) paragraph = Paragraph(title, styles['Heading1']) parts.append(paragraph) parts.append(table_with_style) parts.append(Spacer(1, 70)) if (sentry % 2) == 0: parts.append(PageBreak()) # parts.append(Paragraph('Message Totals', styles['Heading1'])) addrs = [ addr.address for addr in UserAddresses.objects.filter( user=user ).exclude(enabled__exact=0)] msg_totals = MessageTotals.objects.all( user, [], addrs, profile.account_type) mail_total = [] spam_total = [] virus_total = [] dates = [] for ind, msgt in enumerate(msg_totals): if ind % 10: dates.append('') else: dates.append(str(msgt.date)) mail_total.append(int(msgt.mail_total)) spam_total.append(int(msgt.spam_total)) virus_total.append(int(msgt.virus_total)) #graph = MessageTotalsGraph() graph = BarChart() graph.chart.data = [ tuple(mail_total), tuple(spam_total), tuple(virus_total) ] graph.chart.categoryAxis.categoryNames = dates graph_table = Table([[graph],], [7.4 * inch]) parts.append(graph_table) if not sentry: sentry += 1 if sentry: doc.build(parts) text_content = render_to_string('reports/pdf_report.txt', {'user':user, 'url':url}) subject = 'Baruwa usage report for: %s' % user.username if email_re.match(user.username): toaddr = user.username if email_re.match(user.email): toaddr = user.email msg = EmailMessage(subject, text_content, from_email, [toaddr]) msg.attach('baruwa.pdf', pdf.getvalue(), "application/pdf") #msg.send() emails.append(msg) print "* Queue "+user.username+"'s report to: "+toaddr pdf.close() if emails: try: conn = SMTPConnection() conn.send_messages(emails) print "====== sending "+str(len(emails))+" messages =======" except Exception, exception: print "Sending failed ERROR: %s" % str(exception)
def handle_noargs(self, **options): from django.template.loader import render_to_string from django.contrib.auth.models import User from django.core.mail import EmailMultiAlternatives from django.conf import settings from django.db.models import Q from baruwa.messages.models import Message from baruwa.accounts.models import UserProfile import datetime tmp = UserProfile.objects.values('user').filter(send_report=1) ids = [profile['user'] for profile in tmp] users = User.objects.filter(id__in=ids) url = getattr(settings, 'QUARANTINE_REPORT_HOSTURL', '') a_day = datetime.timedelta(days=1) yesterday = datetime.date.today() - a_day from_email = getattr(settings, 'DEFAULT_FROM_EMAIL', 'postmaster@localhost') logo_path = getattr(settings, 'MEDIA_ROOT', '') + '/imgs/css/logo.jpg' logo = open(logo_path, 'rb').read() print _("=== Processing quarantine notifications ===") for user in users: if email_re.match(user.email) or email_re.match(user.username): spam_list = Message.quarantine_report.for_user(user).values( 'id', 'timestamp', 'from_address', 'to_address', 'subject' ).exclude(timestamp__lt=yesterday).exclude( spam=0).order_by('sascore')[:25] policy_list = Message.quarantine_report.for_user(user).values( 'id', 'timestamp', 'from_address', 'to_address', 'subject' ).exclude(timestamp__lt=yesterday).exclude(Q(spam=1) | Q(nameinfected=0) | Q(otherinfected=0) | Q(virusinfected=0) ).order_by('sascore')[:25] subject = _('Baruwa quarantine report for %(user)s') % { 'user': user.username} if email_re.match(user.username): to_addr = user.username if email_re.match(user.email): to_addr = user.email if spam_list or policy_list: for query_list in [spam_list, policy_list]: add_uuids(query_list) html_content = render_to_string( 'messages/quarantine_report.html', {'spam_items': spam_list, 'policy_items': policy_list, 'host_url': url}) text_content = render_to_string( 'messages/quarantine_report_text.html', {'spam_items': spam_list, 'policy_items': policy_list, 'host_url': url}) msg = EmailMultiAlternatives(subject, text_content, from_email, [to_addr]) embed_img(msg, 'baruwalogo', logo) msg.attach_alternative(html_content, "text/html") try: msg.send() for query_list in [spam_list, policy_list]: generate_release_records(query_list) print _("sent quarantine report to %(addr)s") % {'addr': to_addr} except SMTPException: print _("failed to send to: %(addr)s") % {'addr': to_addr} else: print _("skipping report to %(addr)s no messages") % {'addr': to_addr} print _("=== completed quarantine notifications ===")
def handle(self, *args, **options): if len(args) != 0: raise CommandError(_("Command doesn't accept any arguments")) by_domain = options.get('by_domain') domain_name = options.get('domain_name') copy_admin = options.get('copy_admin') period = options.get('period') include_daily = options.get('include_daily') enddate = None period_re = re.compile(r"(?P<num>(\d+))\s+(?P<period>(day|week|month))(?:s)?") if period: match = period_re.match(period) if not match: raise CommandError(_("The period you specified is invalid")) num = match.group('num') ptype = match.group('period') if not ptype.endswith('s'): ptype = ptype + 's' delta = datetime.timedelta(**{ptype: int(num)}) enddate = datetime.date.today() - delta from django.db.models import Count, Sum, Q from django.template.defaultfilters import filesizeformat from django.core.mail import EmailMessage, SMTPConnection from django.contrib.auth.models import User from django.conf import settings from django.template.loader import render_to_string from baruwa.accounts.models import UserProfile, UserAddresses from baruwa.messages.models import Message from baruwa.messages.templatetags.messages_extras import tds_trunc from baruwa.messages.models import MessageTotals from baruwa.utils.graphs import PieChart, PIE_CHART_COLORS, BarChart from reportlab.lib import colors from reportlab.lib.styles import getSampleStyleSheet from reportlab.lib.units import inch from reportlab.platypus import SimpleDocTemplate, Spacer, Table, \ TableStyle, Paragraph, Image, PageBreak try: from django.forms.fields import email_re except ImportError: from django.core.validators import email_re try: from cStringIO import StringIO except ImportError: from StringIO import StringIO table_style = TableStyle([ ('FONT', (0, 0), (-1, -1), 'Helvetica'), ('FONT', (0, 0), (-1, 0), 'Helvetica-Bold'), ('FONTSIZE', (0, 0), (-1, -1), 8), ('GRID', (0, 0), (-1, -1), 0.15, colors.black), ('ALIGN', (0, 0), (-1, 0), 'CENTER'), ('ALIGN', (4, 1), (-1, -1), 'CENTER'), ('ALIGN', (0, 0), (0, -1), 'CENTER'), ('VALIGN', (4, 1), (-1, -1), 'MIDDLE'), ('SPAN', (4, 1), (-1, -1)), ]) styles = getSampleStyleSheet() reports = [ [ 'from_address', {'from_address__exact': ""}, 'num_count', 'Top senders by quantity'], [ 'from_address', {'from_address__exact': ""}, 'total_size', 'Top senders by volume'], [ 'from_domain', {'from_domain__exact': ""}, 'num_count', 'Top sender domains by quantity'], [ 'from_domain', {'from_domain__exact': ""}, 'total_size', 'Top sender domains by volume'], [ 'to_address', {'to_address__exact': ""}, 'num_count', 'Top recipients by quantity'], [ 'to_address', {'to_address__exact': ""}, 'total_size', 'Top recipients by volume'], [ 'to_domain', {'to_domain__exact': "", 'to_domain__isnull': False}, 'num_count', 'Top recipient domains by quantity'], [ 'to_domain', {'to_domain__exact': "", 'to_domain__isnull': False}, 'total_size', 'Top recipient domains by volume'], ] emails = [] admin_addrs = [] if copy_admin: mails = User.objects.values('email').filter(is_superuser=True) admin_addrs = [mail['email'] for mail in mails] from_email = getattr(settings, 'DEFAULT_FROM_EMAIL', 'postmaster@localhost') url = getattr(settings, 'QUARANTINE_REPORT_HOSTURL', '') logo_dir = getattr(settings, 'MEDIA_ROOT', '') img = Image(logo_dir + '/imgs/css/logo.jpg') def build_chart(data, column, order, title): "build chart" headings = [('', _('Address'), _('Count'), _('Volume'), '')] rows = [[draw_square(PIE_CHART_COLORS[index]), tds_trunc(row[column], 45), row['num_count'], filesizeformat(row['total_size']), ''] for index, row in enumerate(data)] if len(rows) != 10: missing = 10 - len(rows) add_rows = [ ('', '', '', '', '') for ind in range(missing) ] rows.extend(add_rows) headings.extend(rows) dat = [row[order] for row in data] total = sum(dat) labels = [ ("%.1f%%" % ((1.0 * row[order] / total) * 100)) for row in data ] pie = PieChart() pie.chart.labels = labels pie.chart.data = dat headings[1][4] = pie table_with_style = Table(headings, [0.2 * inch, 2.8 * inch, 0.5 * inch, 0.7 * inch, 3.2 * inch]) table_with_style.setStyle(table_style) paragraph = Paragraph(title, styles['Heading1']) return [paragraph, table_with_style] def build_parts(account, enddate, isdom=None): "build parts" parts = [] sentry = 0 for report in reports: column = report[0] exclude_kwargs = report[1] order_by = "-%s" % report[2] order = report[2] title = report[3] if isdom: #dom data = Message.objects.values(column).\ filter(Q(from_domain=account.address) | \ Q(to_domain=account.address)).\ exclude(**exclude_kwargs).annotate( num_count=Count(column), total_size=Sum('size') ).order_by(order_by) if enddate: data.filter(date__gt=enddate) data = data[:10] else: #all users data = Message.report.all(user, enddate).values(column).\ exclude(**exclude_kwargs).annotate( num_count=Count(column), total_size=Sum('size') ).order_by(order_by) data = data[:10] if data: sentry += 1 pgraphs = build_chart(data, column, order, title) parts.extend(pgraphs) parts.append(Spacer(1, 70)) if (sentry % 2) == 0: parts.append(PageBreak()) parts.append(Paragraph(_('Message Totals'), styles['Heading1'])) if isdom: #doms msg_totals = MessageTotals.objects.doms(account.address, enddate) else: #norm filters = [] addrs = [ addr.address for addr in UserAddresses.objects.filter( user=account ).exclude(enabled__exact=0)] if enddate: efilter = { 'filter': 3, 'field': 'date', 'value': str(enddate) } filters.append(efilter) msg_totals = MessageTotals.objects.all( account, filters, addrs, profile.account_type) mail_total = [] spam_total = [] virus_total = [] dates = [] if include_daily: rows = [( Table([[draw_square(colors.white), Paragraph('Date', styles["Heading6"])]], [0.35 * inch, 1.50 * inch,]), Table([[draw_square(colors.green), Paragraph('Mail totals', styles["Heading6"])]], [0.35 * inch, 1.50 * inch,]), Table([[draw_square(colors.pink), Paragraph('Spam totals', styles["Heading6"])]], [0.35 * inch, 1.50 * inch,]), Table([[draw_square(colors.red), Paragraph('Virus totals', styles["Heading6"])]], [0.35 * inch, 1.50 * inch,]), )] for ind, msgt in enumerate(msg_totals): if ind % 10: dates.append('') else: dates.append(str(msgt.date)) mail_total.append(int(msgt.mail_total)) spam_total.append(int(msgt.spam_total)) virus_total.append(int(msgt.virus_total)) if include_daily: rows.append((str(msgt.date), msgt.mail_total, msgt.spam_total, msgt.virus_total)) graph = BarChart() graph.chart.data = [ tuple(mail_total), tuple(spam_total), tuple(virus_total) ] graph.chart.categoryAxis.categoryNames = dates graph_table = Table([[graph]], [7.4 * inch]) parts.append(graph_table) if include_daily: rows.append(('Totals', sum(mail_total), sum(spam_total), sum(virus_total))) parts.append(Spacer(1, 20)) graph_table = Table(rows, [1.85 * inch, 1.85 * inch, 1.85 * inch, 1.85 * inch,]) graph_table.setStyle(TableStyle([ ('FONTSIZE', (0, 0), (-1, -1), 8), ('FONT', (0, 0), (-1, -1), 'Helvetica'), ('FONT', (0, 0), (-1, 0), 'Helvetica-Bold'), ('GRID', (0, 0), (-1, -1), 0.15, colors.black), ('FONT', (0, -1), (-1, -1), 'Helvetica-Bold'), #('BACKGROUND', (0, -1), (-1, -1), colors.green), ])) parts.append(graph_table) return parts def build_pdf(charts): "Build a PDF" pdf = StringIO() doc = SimpleDocTemplate(pdf, topMargin=50, bottomMargin=18) logo = [(img, _('Baruwa mail report'))] logo_table = Table(logo, [2.0 * inch, 5.4 * inch]) logo_table.setStyle(TableStyle([ ('FONT', (0, 0), (-1, 0), 'Helvetica-Bold'), ('ALIGN', (0, 0), (-1, 0), 'LEFT'), ('ALIGN', (1, 0), (-1, 0), 'RIGHT'), ('FONTSIZE', (1, 0), (-1, 0), 10), ('LINEBELOW', (0, 0), (-1, -1), 0.15, colors.black), ])) parts = [logo_table] parts.append(Spacer(1, 20)) parts.extend(charts) try: doc.build(parts) except IndexError: pass return pdf def gen_email(pdf, user, owner): "generate and return email" text_content = render_to_string('reports/pdf_report.txt', {'user': user, 'url': url}) subject = _('Baruwa usage report for: %(user)s') % { 'user': owner} if email_re.match(user.username): toaddr = user.username if email_re.match(user.email): toaddr = user.email if admin_addrs: msg = EmailMessage(subject, text_content, from_email, [toaddr], admin_addrs) else: msg = EmailMessage(subject, text_content, from_email, [toaddr]) msg.attach('baruwa.pdf', pdf.getvalue(), "application/pdf") print _("* Queue %(user)s's report to: %(addr)s") % { 'user': owner, 'addr': toaddr} pdf.close() return msg print _("=================== Processing reports ======================") if by_domain: #do domain query #print "camacamlilone" domains = UserAddresses.objects.filter(Q(enabled=1), Q(address_type=1)) if domain_name != 'all': domains = domains.filter(address=domain_name) if not domains: print _("========== domain name %(dom)s does not exist ==========") % { 'dom': domain_name } for domain in domains: if email_re.match(domain.user.email) or email_re.match(domain.user.username): parts = build_parts(domain, enddate, True) if parts: pdf = build_pdf(parts) email = gen_email(pdf, domain.user, domain.address) emails.append(email) else: #do normal query profiles = UserProfile.objects.filter(send_report=1) for profile in profiles: try: user = profile.user if email_re.match(user.email) or email_re.match(user.username): parts = build_parts(user, enddate, False) if parts: pdf = build_pdf(parts) email = gen_email(pdf, user, user.username) emails.append(email) except User.DoesNotExist: pass if emails: try: conn = SMTPConnection() conn.send_messages(emails) print _("====== sending %(num)s messages =======") % { 'num': str(len(emails))} except Exception, exception: print _("Sending failed ERROR: %(error)s") % {'error': str(exception)}
def clean(self): "validate the form" cleaned_data = self.cleaned_data submited_field = cleaned_data.get('filtered_field') submited_by = int(cleaned_data.get('filtered_by')) submited_value = cleaned_data.get('filtered_value') if submited_by != 0: sbi = (submited_by - 1) else: sbi = submited_by if submited_field in BOOL_FIELDS: if not submited_by in BOOL_FILTER: filter_items = to_dict(list(FILTER_ITEMS)) error_msg = "%s does not support the %s filter" % ( filter_items[submited_field],FILTER_BY[sbi][1]) raise forms.ValidationError(error_msg) if submited_field in NUM_FIELDS: if not submited_by in NUM_FILTER: filter_items = to_dict(list(FILTER_ITEMS)) error_msg = "%s does not support the %s filter" % ( filter_items[submited_field],FILTER_BY[sbi][1]) raise forms.ValidationError(error_msg) if submited_value in EMPTY_VALUES: raise forms.ValidationError("Please supply a value to query") if not isnumeric(submited_value): raise forms.ValidationError("The value has to be numeric") if submited_field in TEXT_FIELDS: if not submited_by in TEXT_FILTER: filter_items = to_dict(list(FILTER_ITEMS)) error_msg = "%s does not support the %s filter" % ( filter_items[submited_field],FILTER_BY[sbi][1]) raise forms.ValidationError(error_msg) if submited_value in EMPTY_VALUES: raise forms.ValidationError("Please supply a value to query") if ( FILTER_BY[sbi][1] == 'is equal to' or FILTER_BY[sbi][1] == 'is not equal to' ): if (submited_field == 'from_address') or ( submited_field == 'to_address'): if not email_re.match(submited_value.strip()): raise forms.ValidationError( '%s is not a valid e-mail address.' % force_escape(submited_value)) if (submited_field == 'from_domain') or ( submited_field == 'to_domain'): if not DOM_RE.match(submited_value.strip()): raise forms.ValidationError( 'Please provide a valid domain name') if submited_field == 'clientip': if not ipv4_re.match(submited_value.strip()): raise forms.ValidationError( 'Please provide a valid ipv4 address') if submited_field in TIME_FIELDS: if not submited_by in TIME_FILTER: filter_items = to_dict(list(FILTER_ITEMS)) error_msg = "%s does not support the %s filter" % ( filter_items[submited_field],FILTER_BY[sbi][1]) raise forms.ValidationError(error_msg) if submited_value in EMPTY_VALUES: raise forms.ValidationError("Please supply a value to query") if submited_field == 'date': try: datetime.date( *time.strptime(submited_value, '%Y-%m-%d')[:3]) except ValueError: raise forms.ValidationError( 'Please provide a valid date in YYYY-MM-DD format') if submited_field == 'time': try: datetime.time(*time.strptime(submited_value, '%H:%M')[3:6]) except ValueError: raise forms.ValidationError( 'Please provide valid time in HH:MM format') return cleaned_data
def clean(self): "validate the form" cleaned_data = self.cleaned_data submited_field = cleaned_data.get('filtered_field') submited_by = int(cleaned_data.get('filtered_by')) submited_value = cleaned_data.get('filtered_value') if submited_by != 0: sbi = (submited_by - 1) else: sbi = submited_by if submited_field in BOOL_FIELDS: if not submited_by in BOOL_FILTER: filter_items = dict(FILTER_ITEMS) error_msg = _( "%(field)s does not support the %(filt)s filter") % { 'field': filter_items[submited_field], 'filt': FILTER_BY[sbi][1] } raise forms.ValidationError(error_msg) if submited_field in NUM_FIELDS: if not submited_by in NUM_FILTER: filter_items = dict(FILTER_ITEMS) error_msg = _( "%(field)s does not support the %(filt)s filter") % { 'field': filter_items[submited_field], 'filt': FILTER_BY[sbi][1] } raise forms.ValidationError(error_msg) if submited_value in EMPTY_VALUES: raise forms.ValidationError( _("Please supply a value to query")) if not isnumeric(submited_value): raise forms.ValidationError(_("The value has to be numeric")) if submited_field in TEXT_FIELDS: if not submited_by in TEXT_FILTER: filter_items = dict(FILTER_ITEMS) error_msg = _( "%(field)s does not support the %(filt)s filter") % { 'field': filter_items[submited_field], 'filt': FILTER_BY[sbi][1] } raise forms.ValidationError(error_msg) if submited_value in EMPTY_VALUES and submited_by not in [9, 10]: raise forms.ValidationError( _("Please supply a value to query")) if ((submited_field == 'from_address' or submited_field == 'to_address') and submited_by in [1, 2]): if not email_re.match(submited_value.strip()): raise forms.ValidationError( _('%(email)s is not a valid e-mail address.') % {'email': force_escape(submited_value)}) else: if submited_by in [7, 8]: try: re.compile(submited_value) except re.error: raise forms.ValidationError( _("Please provide a valid regex")) if ((submited_field == 'from_domain' or submited_field == 'to_domain') and submited_by in [1, 2]): if not DOM_RE.match(submited_value.strip()): raise forms.ValidationError( _('Please provide a valid domain name')) else: if submited_by in [7, 8]: try: re.compile(submited_value) except re.error: raise forms.ValidationError( _("Please provide a valid regex")) if submited_field == 'clientip': if not ipv4_re.match(submited_value.strip()): raise forms.ValidationError( _('Please provide a valid ipv4 address')) if submited_field == 'hostname': if ((not ipv4_re.match(submited_value.strip())) and (not DOM_RE.match(submited_value.strip()))): raise forms.ValidationError( _("Please provide a valid hostname or ipv4 address")) if submited_field in TIME_FIELDS: if not submited_by in TIME_FILTER: filter_items = dict(FILTER_ITEMS) error_msg = _( "%(field)s does not support the %(filt)s filter") % { 'field': filter_items[submited_field], 'filt': FILTER_BY[sbi][1] } raise forms.ValidationError(error_msg) if submited_value in EMPTY_VALUES: raise forms.ValidationError( _("Please supply a value to query")) if submited_field == 'date': try: datetime.date( *time.strptime(submited_value, '%Y-%m-%d')[:3]) except ValueError: raise forms.ValidationError( _('Please provide a valid date in YYYY-MM-DD format')) if submited_field == 'time': try: datetime.time(*time.strptime(submited_value, '%H:%M')[3:6]) except ValueError: raise forms.ValidationError( _('Please provide valid time in HH:MM format')) return cleaned_data
def handle_noargs(self, **options): from django.template.loader import render_to_string from django.contrib.auth.models import User from django.core.mail import EmailMultiAlternatives from django.conf import settings from django.db.models import Q from baruwa.messages.models import Message from baruwa.accounts.models import UserProfile import datetime tmp = UserProfile.objects.values("user").filter(send_report=1) ids = [profile["user"] for profile in tmp] users = User.objects.filter(id__in=ids) url = getattr(settings, "QUARANTINE_REPORT_HOSTURL", "") a_day = datetime.timedelta(days=1) yesterday = datetime.date.today() - a_day from_email = getattr(settings, "DEFAULT_FROM_EMAIL", "postmaster@localhost") logo_path = getattr(settings, "MEDIA_ROOT", "") + "/imgs/css/logo.jpg" logo = open(logo_path, "rb").read() print "=== Processing quarantine notifications ===" for user in users: if email_re.match(user.email) or email_re.match(user.username): spam_list = ( Message.quarantine_report.for_user(user) .values("id", "timestamp", "from_address", "to_address", "subject") .exclude(timestamp__lt=yesterday) .exclude(spam=0) .order_by("sascore")[:25] ) policy_list = ( Message.quarantine_report.for_user(user) .values("id", "timestamp", "from_address", "to_address", "subject") .exclude(timestamp__lt=yesterday) .exclude(Q(spam=1) | Q(nameinfected=0) | Q(otherinfected=0) | Q(virusinfected=0)) .order_by("sascore")[:25] ) subject = "Baruwa quarantine report for %s" % user.username if email_re.match(user.username): to_addr = user.username if email_re.match(user.email): to_addr = user.email if spam_list or policy_list: for query_list in [spam_list, policy_list]: add_uuids(query_list) html_content = render_to_string( "messages/quarantine_report.html", {"spam_items": spam_list, "policy_items": policy_list, "host_url": url}, ) text_content = render_to_string( "messages/quarantine_report_text.html", {"spam_items": spam_list, "policy_items": policy_list, "host_url": url}, ) msg = EmailMultiAlternatives(subject, text_content, from_email, [to_addr]) embed_img(msg, "baruwalogo", logo) msg.attach_alternative(html_content, "text/html") try: msg.send() for query_list in [spam_list, policy_list]: generate_release_records(query_list) print "sent quarantine report to " + to_addr except: print "failed to send to: " + to_addr else: print "skipping report to " + to_addr + " no messages" print "=== completed quarantine notifications ==="
def clean(self): "validate the form" cleaned_data = self.cleaned_data submited_field = cleaned_data.get('filtered_field') submited_by = int(cleaned_data.get('filtered_by')) submited_value = cleaned_data.get('filtered_value') if submited_by != 0: sbi = (submited_by - 1) else: sbi = submited_by if submited_field in BOOL_FIELDS: if not submited_by in BOOL_FILTER: filter_items = dict(FILTER_ITEMS) error_msg = _("%(field)s does not support the %(filt)s filter") % { 'field': filter_items[submited_field], 'filt': FILTER_BY[sbi][1]} raise forms.ValidationError(error_msg) if submited_field in NUM_FIELDS: if not submited_by in NUM_FILTER: filter_items = dict(FILTER_ITEMS) error_msg = _("%(field)s does not support the %(filt)s filter") % { 'field': filter_items[submited_field], 'filt': FILTER_BY[sbi][1]} raise forms.ValidationError(error_msg) if submited_value in EMPTY_VALUES: raise forms.ValidationError(_("Please supply a value to query")) if not isnumeric(submited_value): raise forms.ValidationError(_("The value has to be numeric")) if submited_field in TEXT_FIELDS: if not submited_by in TEXT_FILTER: filter_items = dict(FILTER_ITEMS) error_msg = _("%(field)s does not support the %(filt)s filter") % { 'field': filter_items[submited_field], 'filt': FILTER_BY[sbi][1]} raise forms.ValidationError(error_msg) if submited_value in EMPTY_VALUES and submited_by not in [9, 10]: raise forms.ValidationError(_("Please supply a value to query")) if ((submited_field == 'from_address' or submited_field == 'to_address') and submited_by in [1, 2]): if not email_re.match(submited_value.strip()): raise forms.ValidationError( _('%(email)s is not a valid e-mail address.') % {'email': force_escape(submited_value)}) else: if submited_by in [7, 8]: try: re.compile(submited_value) except re.error: raise forms.ValidationError( _("Please provide a valid regex") ) if ((submited_field == 'from_domain' or submited_field == 'to_domain') and submited_by in [1, 2]): if not DOM_RE.match(submited_value.strip()): raise forms.ValidationError( _('Please provide a valid domain name')) else: if submited_by in [7, 8]: try: re.compile(submited_value) except re.error: raise forms.ValidationError( _("Please provide a valid regex") ) if submited_field == 'clientip': if not ipv4_re.match(submited_value.strip()): raise forms.ValidationError( _('Please provide a valid ipv4 address')) if submited_field == 'hostname': if ((not ipv4_re.match(submited_value.strip())) and (not DOM_RE.match(submited_value.strip()))): raise forms.ValidationError( _("Please provide a valid hostname or ipv4 address") ) if submited_field in TIME_FIELDS: if not submited_by in TIME_FILTER: filter_items = dict(FILTER_ITEMS) error_msg = _("%(field)s does not support the %(filt)s filter") % { 'field': filter_items[submited_field], 'filt': FILTER_BY[sbi][1]} raise forms.ValidationError(error_msg) if submited_value in EMPTY_VALUES: raise forms.ValidationError(_("Please supply a value to query")) if submited_field == 'date': try: datetime.date( *time.strptime(submited_value, '%Y-%m-%d')[:3]) except ValueError: raise forms.ValidationError( _('Please provide a valid date in YYYY-MM-DD format')) if submited_field == 'time': try: datetime.time(*time.strptime(submited_value, '%H:%M')[3:6]) except ValueError: raise forms.ValidationError( _('Please provide valid time in HH:MM format')) return cleaned_data
def authenticate(self, username=None, password=None): try: from pyrad import packet from pyrad.client import Client, Timeout from pyrad.dictionary import Dictionary except ImportError: return None if not '@' in username: return None username = username.decode('utf-8') password = password.decode('utf-8') login_user, domain = username.split('@') dom = UserAddresses.objects.filter(address=domain, address_type=1) if not dom: return None hosts = MailAuthHost.objects.filter(useraddress=dom, protocol=3) if not hosts: return None for host in hosts: if not host.split_address: login_user = username try: client = Client( server=host.address, authport=host.port, secret=settings.RADIUS_SECRET[host.address].encode( 'utf-8'), dict=Dictionary(StringIO(DICTIONARY)), ) except AttributeError: return None request = client.CreateAuthPacket( code=packet.Accessrequestuest, User_Name=login_user, ) request["User-Password"] = request.PwCrypt(password) try: reply = client.SendPacket(request) except Timeout: return None except Exception: return None if reply.code == packet.AccessReject: return None if reply.code != packet.AccessAccept: return None try: user = User.objects.get(username=username) except User.DoesNotExist: user = User(username=username) user.set_unusable_password() user.is_staff = False user.is_superuser = False if email_re.match(username): user.email = username user.save() try: profile = user.get_profile() except UserProfile.DoesNotExist: profile = UserProfile(user=user, account_type=3) profile.save() return user return None
def handle_noargs(self, **options): from django.template.loader import render_to_string from django.contrib.auth.models import User from django.core.mail import EmailMultiAlternatives from django.conf import settings from django.db.models import Q from baruwa.messages.models import Message from baruwa.accounts.models import UserProfile import datetime tmp = UserProfile.objects.values('user').filter(send_report=1) ids = [profile['user'] for profile in tmp] users = User.objects.filter(id__in=ids) url = getattr(settings, 'QUARANTINE_REPORT_HOSTURL', '') a_day = datetime.timedelta(days=1) yesterday = datetime.date.today() - a_day from_email = getattr(settings, 'DEFAULT_FROM_EMAIL', 'postmaster@localhost') logo_path = getattr(settings, 'MEDIA_ROOT', '') + '/imgs/css/logo.jpg' logo = open(logo_path, 'rb').read() print _("=== Processing quarantine notifications ===") for user in users: if email_re.match(user.email) or email_re.match(user.username): spam_list = Message.quarantine_report.for_user(user).values( 'id', 'timestamp', 'from_address', 'to_address', 'subject').exclude(timestamp__lt=yesterday).exclude( spam=0).order_by('sascore')[:25] policy_list = Message.quarantine_report.for_user(user).values( 'id', 'timestamp', 'from_address', 'to_address', 'subject').exclude(timestamp__lt=yesterday).exclude( Q(spam=1) | Q(nameinfected=0) | Q(otherinfected=0) | Q(virusinfected=0)).order_by('sascore')[:25] subject = _('Baruwa quarantine report for %(user)s') % { 'user': user.username } if email_re.match(user.username): to_addr = user.username if email_re.match(user.email): to_addr = user.email if spam_list or policy_list: for query_list in [spam_list, policy_list]: add_uuids(query_list) html_content = render_to_string( 'messages/quarantine_report.html', { 'spam_items': spam_list, 'policy_items': policy_list, 'host_url': url }) text_content = render_to_string( 'messages/quarantine_report_text.html', { 'spam_items': spam_list, 'policy_items': policy_list, 'host_url': url }) msg = EmailMultiAlternatives(subject, text_content, from_email, [to_addr]) embed_img(msg, 'baruwalogo', logo) msg.attach_alternative(html_content, "text/html") try: msg.send() for query_list in [spam_list, policy_list]: generate_release_records(query_list) print _("sent quarantine report to %(addr)s") % { 'addr': to_addr } except SMTPException: print _("failed to send to: %(addr)s") % { 'addr': to_addr } else: print _("skipping report to %(addr)s no messages") % { 'addr': to_addr } print _("=== completed quarantine notifications ===")