Exemplo n.º 1
0
 def clean_draftlist(self):
     draftlist = self.cleaned_data.get("draftlist", None)
     if draftlist:
         draftlist = re.sub(" *[,;] *", " ", draftlist)
         draftlist = draftlist.strip().split()
         drafts = []
         for draft in draftlist:
             if draft.endswith(".txt"):
                 draft = draft[:-4]
             if re.search("-[0-9][0-9]$", draft):
                 filename = draft[:-3]
                 rev = draft[-2:]
             else:
                 filename = draft
                 rev = None
             try:
                 if settings.USE_DB_REDESIGN_PROXY_CLASSES:
                     from ietf.doc.models import DocAlias
                     id = DocAlias.objects.get(name=filename)
                     # proxy attribute for code below
                     id.revision = id.document.rev
                 else:
                     id = InternetDraft.objects.get(filename=filename)
             except Exception, e:
                 log("Exception: %s" % e)
                 raise forms.ValidationError("Unknown Internet-Draft: %s - please correct this." % filename)
             if rev and id.revision != rev:
                 raise forms.ValidationError("Unexpected revision '%s' for draft %s - the current revision is %s.  Please check this." % (rev, filename, id.revision))
             drafts.append("%s-%s" % (filename, id.revision))
         return " ".join(drafts)
Exemplo n.º 2
0
    def authenticate(self, remote_user):
        user = RemoteUserBackend.authenticate(self, remote_user)
        if not user:
            return user

        # Create profile if it doesn't exist
        try:
            profile = user.get_profile()
        except IetfUserProfile.DoesNotExist:
            profile = IetfUserProfile(user=user)
            profile.save()

        # Remove any automatic groups, the proper ones will be retrieved by 
        # find_groups
        groups = [group for group in user.groups.exclude(name__in=AUTOMATIC_GROUPS)]

        # Update group memberships
        group_names = IetfUserBackend.find_groups(user.username)
        for group_name in group_names:
            # Create groups as needed
            group,created = Group.objects.get_or_create(name=group_name)
            if created:
                log("IetfUserBackend created Group '%s'" % (group_name,))
            groups.append(group)
        user.groups = groups
        return user
Exemplo n.º 3
0
Arquivo: mail.py Projeto: mcr/ietfdb
def send_smtp(msg, bcc=None):
    '''
    Send a Message via SMTP, based on the django email server settings.
    The destination list will be taken from the To:/Cc: headers in the
    Message.  The From address will be used if present or will default
    to the django setting DEFAULT_FROM_EMAIL

    If someone has set test_mode=True, then just append the msg to
    the outbox.
    '''
    add_headers(msg)
    (fname, frm) = parseaddr(msg.get('From'))
    addrlist = msg.get_all('To') + msg.get_all('Cc', [])
    if bcc:
        addrlist += [bcc]
    to = [addr for name, addr in getaddresses(addrlist)]
    if not to:
        log("No addressees for email from '%s', subject '%s'.  Nothing sent." % (frm, msg.get('Subject', '[no subject]')))
    else:
        if test_mode:
            outbox.append(msg)
            return
        server = None
        try:
            server = smtplib.SMTP()
            log("SMTP server: %s" % repr(server))
            #if settings.DEBUG:
            #    server.set_debuglevel(1)
            conn_code, conn_msg = server.connect(settings.EMAIL_HOST, settings.EMAIL_PORT)
            log("SMTP connect: code: %s; msg: %s" % (conn_code, conn_msg))
            if settings.EMAIL_HOST_USER and settings.EMAIL_HOST_PASSWORD:
                server.ehlo()
                if 'starttls' not in server.esmtp_features:
                    raise ImproperlyConfigured('password configured but starttls not supported')
                (retval, retmsg) = server.starttls()
                if retval != 220:
                    raise ImproperlyConfigured('password configured but tls failed: %d %s' % ( retval, retmsg ))
                # Send a new EHLO, since without TLS the server might not
                # advertise the AUTH capability.
                server.ehlo()
                server.login(settings.EMAIL_HOST_USER, settings.EMAIL_HOST_PASSWORD)
            server.sendmail(frm, to, msg.as_string())
            # note: should pay attention to the return code, as it may
            # indicate that someone didn't get the email.
        except:
            if server:
                server.quit()
            # need to improve log message
            log("got exception '%s' (%s) trying to send email from '%s' to %s subject '%s'" % (sys.exc_info()[0], sys.exc_info()[1], frm, to, msg.get('Subject', '[no subject]')))
            if isinstance(sys.exc_info()[0], smtplib.SMTPException):
                raise
            else:
                raise smtplib.SMTPException({'really': sys.exc_info()[0], 'value': sys.exc_info()[1], 'tb': sys.exc_info()[2]})
        server.quit()
        log("sent email from '%s' to %s subject '%s'" % (frm, to, msg.get('Subject', '[no subject]')))
Exemplo n.º 4
0
 def process_exception(self, request, exception):
     if isinstance(exception, smtplib.SMTPException):
         type = sys.exc_info()[0]
         value = sys.exc_info()[1]
         # See if it's a non-smtplib exception that we faked
         if type == smtplib.SMTPException and len(
                 value.args) == 1 and isinstance(
                     value.args[0],
                     dict) and value.args[0].has_key('really'):
             orig = value.args[0]
             type = orig['really']
             tb = traceback.format_tb(orig['tb'])
             value = orig['value']
         else:
             tb = traceback.format_tb(sys.exc_info()[2])
         log("SMTP Exception: %s" % type)
         log("SMTP Exception: args: %s" % value)
         log("SMTP Exception: tb: %s" % tb)
         return render_to_response('email_failed.html', {
             'exception': type,
             'args': value,
             'traceback': "".join(tb)
         },
                                   context_instance=RequestContext(request))
     return None
Exemplo n.º 5
0
def update(request, ipr_id=None):
    """Update a specific IPR disclosure"""
    ipr = get_object_or_404(models.IprDetail, ipr_id=ipr_id)
    if not ipr.status in [1,3]:
	raise Http404        
    type = "specific"
    if ipr.generic:
	type = "generic"
    if ipr.third_party:
	type = "third-party"
    # We're either asking for initial permission or we're in
    # the general ipr form.  If the POST argument has the first
    # field of the ipr form, then we must be dealing with that,
    # so just pass through - otherwise, collect the updater's
    # info first.
    submitter = None
    if not(request.POST.has_key('legal_name')):
	class UpdateForm(BaseContactForm):
	    def __init__(self, *args, **kwargs):
                super(UpdateForm, self).__init__(*args, **kwargs)
                self.fields["update_auth"] = forms.BooleanField()
                
	if request.method == 'POST':
	    form = UpdateForm(request.POST)
        elif '_testpost' in request.REQUEST:
            form = UpdateForm(request.GET)
	else:
	    form = UpdateForm()

	if not(form.is_valid()):
            for error in form.errors:
                log("Form error for field: %s: %s"%(error, form.errors[error]))
	    return render("ipr/update.html", {"form": form, "ipr": ipr, "type": type}, context_instance=RequestContext(request))
	else:
	    submitter = form.cleaned_data

    return new(request, type, ipr, submitter)
Exemplo n.º 6
0
def post_approved_draft(url, name):
    """Post an approved draft to the RFC Editor so they can retrieve
    the data from the Datatracker and start processing it. Returns
    response and error (empty string if no error)."""

    request = urllib2.Request(url)
    request.add_header("Content-type", "application/x-www-form-urlencoded")
    request.add_header("Accept", "text/plain")
    # HTTP basic auth
    username = "******"
    password = settings.RFC_EDITOR_SYNC_PASSWORD
    request.add_header(
        "Authorization", "Basic %s" %
        base64.encodestring("%s:%s" % (username, password)).replace("\n", ""))

    if settings.SERVER_MODE != "production":
        return ("OK", "")

    log("Posting RFC-Editor notifcation of approved draft '%s' to '%s'" %
        (name, url))
    text = error = ""
    try:
        f = urllib2.urlopen(request,
                            data=urllib.urlencode({'draft': name}),
                            timeout=20)
        text = f.read()
        status_code = f.getcode()
        f.close()
        log("RFC-Editor notification result for draft '%s': %s:'%s'" %
            (name, status_code, text))

        if status_code != 200:
            raise Exception("Status code is not 200 OK (it's %s)." %
                            status_code)

        if text != "OK":
            raise Exception("Response is not \"OK\".")

    except Exception as e:
        # catch everything so we don't leak exceptions, convert them
        # into string instead
        log("Exception on RFC-Editor notification for draft '%s': '%s'" %
            (name, e))
        error = unicode(e)

    return text, error
Exemplo n.º 7
0
    def process_exception(self, request, exception):
	if isinstance(exception, smtplib.SMTPException):
	    type = sys.exc_info()[0]
	    value = sys.exc_info()[1]
	    # See if it's a non-smtplib exception that we faked
	    if type == smtplib.SMTPException and len(value.args) == 1 and isinstance(value.args[0], dict) and value.args[0].has_key('really'):
		orig = value.args[0]
		type = orig['really']
		tb = traceback.format_tb(orig['tb'])
		value = orig['value']
	    else:
		tb = traceback.format_tb(sys.exc_info()[2])
            log("SMTP Exception: %s" % type)
            log("SMTP Exception: args: %s" % value)
            log("SMTP Exception: tb: %s" % tb)
	    return render_to_response('email_failed.html', {'exception': type, 'args': value, 'traceback': "".join(tb)},
		context_instance=RequestContext(request))
	return None
Exemplo n.º 8
0
def post_approved_draft(url, name):
    """Post an approved draft to the RFC Editor so they can retrieve
    the data from the Datatracker and start processing it. Returns
    response and error (empty string if no error)."""

    request = urllib2.Request(url)
    request.add_header("Content-type", "application/x-www-form-urlencoded")
    request.add_header("Accept", "text/plain")
    # HTTP basic auth
    username = "******"
    password = settings.RFC_EDITOR_SYNC_PASSWORD
    request.add_header("Authorization", "Basic %s" % base64.encodestring("%s:%s" % (username, password)).replace("\n", ""))

    if settings.SERVER_MODE != "production":
        return ("OK", "")

    log("Posting RFC-Editor notifcation of approved draft '%s' to '%s'" % (name, url))
    text = error = ""
    try:
        f = urllib2.urlopen(request, data=urllib.urlencode({ 'draft': name }), timeout=20)
        text = f.read()
        status_code = f.getcode()
        f.close()
        log("RFC-Editor notification result for draft '%s': %s:'%s'" % (name, status_code, text))

        if status_code != 200:
            raise Exception("Status code is not 200 OK (it's %s)." % status_code)

        if text != "OK":
            raise Exception("Response is not \"OK\".")

    except Exception as e:
        # catch everything so we don't leak exceptions, convert them
        # into string instead
        log("Exception on RFC-Editor notification for draft '%s': '%s'" % (name, e))
        error = unicode(e)

    return text, error
Exemplo n.º 9
0
    def process_response(self, request, response):
	for q in connection.queries:
	    if re.match('(update|insert)', q['sql'], re.IGNORECASE):
		log(q['sql'])
        return response
Exemplo n.º 10
0
                        rev="")
                else:
                    rfc = Rfc.objects.get(rfc_number=int(rfcnum))
                    iprrfc = models.IprRfc(document=rfc, ipr=instance)
                    iprrfc.save()

            send_mail(request, settings.IPR_EMAIL_TO, ('IPR Submitter App', '*****@*****.**'), 'New IPR Submission Notification', "ipr/new_update_email.txt", {"ipr": instance, "update": update})
            return render("ipr/submitted.html", {"update": update}, context_instance=RequestContext(request))
        else:
            if 'ietf_contact_is_submitter' in data:
                form.ietf_contact_is_submitter_checked = True
            if 'hold_contact_is_submitter' in data:
                form.hold_contact_is_submitter_checked = True

            for error in form.errors:
                log("Form error for field: %s: %s"%(error, form.errors[error]))
            # Fall through, and let the partially bound form, with error
            # indications, be rendered again.
            pass
    else:
        if update:
            form = IprForm(initial=update.__dict__)
        else:
            form = IprForm()
        form.unbound_form = True

    # ietf.utils.log(dir(form.ietf_contact_is_submitter))
    return render("ipr/details_edit.html", {"ipr": form, "section_list":section_list, "debug": debug}, context_instance=RequestContext(request))

def update(request, ipr_id=None):
    """Update a specific IPR disclosure"""
Exemplo n.º 11
0
def form(request):
    wgs = IETFWG.objects.filter(group_type__group_type_id=1).exclude(group_acronym__acronym='2000').select_related().order_by('acronym.acronym')
    log("Search form")
    return render("ipr/search.html", {"wgs": wgs}, context_instance=RequestContext(request))
Exemplo n.º 12
0
 def process_response(self, request, response):
     for q in connection.queries:
         if re.match('(update|insert)', q['sql'], re.IGNORECASE):
             log(q['sql'])
     return response
Exemplo n.º 13
0
def send_smtp(msg, bcc=None):
    '''
    Send a Message via SMTP, based on the django email server settings.
    The destination list will be taken from the To:/Cc: headers in the
    Message.  The From address will be used if present or will default
    to the django setting DEFAULT_FROM_EMAIL

    If someone has set test_mode=True, then just append the msg to
    the outbox.
    '''
    add_headers(msg)
    (fname, frm) = parseaddr(msg.get('From'))
    addrlist = msg.get_all('To') + msg.get_all('Cc', [])
    if bcc:
        addrlist += [bcc]
    to = [addr for name, addr in getaddresses(addrlist)]
    if not to:
        log("No addressees for email from '%s', subject '%s'.  Nothing sent." %
            (frm, msg.get('Subject', '[no subject]')))
    else:
        if test_mode:
            outbox.append(msg)
            return
        server = None
        try:
            server = smtplib.SMTP()
            log("SMTP server: %s" % repr(server))
            #if settings.DEBUG:
            #    server.set_debuglevel(1)
            conn_code, conn_msg = server.connect(settings.EMAIL_HOST,
                                                 settings.EMAIL_PORT)
            log("SMTP connect: code: %s; msg: %s" % (conn_code, conn_msg))
            if settings.EMAIL_HOST_USER and settings.EMAIL_HOST_PASSWORD:
                server.ehlo()
                if 'starttls' not in server.esmtp_features:
                    raise ImproperlyConfigured(
                        'password configured but starttls not supported')
                (retval, retmsg) = server.starttls()
                if retval != 220:
                    raise ImproperlyConfigured(
                        'password configured but tls failed: %d %s' %
                        (retval, retmsg))
                # Send a new EHLO, since without TLS the server might not
                # advertise the AUTH capability.
                server.ehlo()
                server.login(settings.EMAIL_HOST_USER,
                             settings.EMAIL_HOST_PASSWORD)
            server.sendmail(frm, to, msg.as_string())
            # note: should pay attention to the return code, as it may
            # indicate that someone didn't get the email.
        except:
            if server:
                server.quit()
            # need to improve log message
            log("got exception '%s' (%s) trying to send email from '%s' to %s subject '%s'"
                % (sys.exc_info()[0], sys.exc_info()[1], frm, to,
                   msg.get('Subject', '[no subject]')))
            if isinstance(sys.exc_info()[0], smtplib.SMTPException):
                raise
            else:
                raise smtplib.SMTPException({
                    'really': sys.exc_info()[0],
                    'value': sys.exc_info()[1],
                    'tb': sys.exc_info()[2]
                })
        server.quit()
        log("sent email from '%s' to %s subject '%s'" %
            (frm, to, msg.get('Subject', '[no subject]')))