Example #1
0
def profile(request):
    """
    Form for modifying and adding profile values
    """
    if request.method == 'POST':
        form = ProfileForm(request.POST,
                           instance = request.user)
        
        email = request.POST.get('email', '')
        if not email == '' and not email == request.user.email:
            #confirm the email
            salt = sha_constructor(str(random())).hexdigest()[:5]
            confirmation_key = sha_constructor(salt + email).hexdigest()
            current_site = Site.objects.get_current()
       
            path = reverse('confirm_email',
                            args=[confirmation_key])
                
            activate_url = u"http://%s%s" % (unicode(current_site.domain),
                                             path)
            context = {
                "user": request.user,
                "activate_url": activate_url,
                "current_site": current_site,
                "confirmation_key": confirmation_key,
            }
            subject = render_to_string(
                "email_confirmation_subject.txt",
                context)
        
            # remove superfluous line breaks
            subject = "".join(subject.splitlines())
            message = render_to_string(
                "email_confirmation_message.txt",
                context)
            print email
            send_mail(subject,
                      message,
                      getattr(settings,
                              'DEFAULT_FROM_EMAIL',
                              'do-not-reply@%s' % current_site),
                      [email])
        
            Email.objects.create(
                owner = request.user,
                email = email,
                email_is_verified = False,
                sent = datetime.now(),
                confirmation_key = confirmation_key)
        
        form.save()
        return HttpResponseRedirect(request.POST.get('next', '/'))

    else:
        form = ProfileForm(instance = request.user)
        next = request.GET.get('next', '/')
        return render_to_response('profile.html',
                                  {'form': form,
                                   'next': next},
                                  context_instance = RequestContext(request))
 def send_confirmation(self, email_address):
     salt = sha_constructor(str(random())).hexdigest()[:5]
     confirmation_key = sha_constructor(salt +
                                        email_address.email).hexdigest()
     current_site = Site.objects.get_current()
     # check for the url with the dotted view path
     try:
         path = reverse("emailconfirmation.views.confirm_email",
                        args=[confirmation_key])
     except NoReverseMatch:
         # or get path with named urlconf instead
         path = reverse("emailconfirmation_confirm_email",
                        args=[confirmation_key])
     activate_url = u"http://%s%s" % (unicode(current_site.domain), path)
     context = {
         "user": email_address.user,
         "activate_url": activate_url,
         "current_site": current_site,
         "confirmation_key": confirmation_key,
     }
     subject = render_to_string(
         "emailconfirmation/email_confirmation_subject.txt", context)
     # remove superfluous line breaks
     subject = "".join(subject.splitlines())
     message = render_to_string(
         "emailconfirmation/email_confirmation_message.txt", context)
     send_mail(subject,
               message,
               settings.DEFAULT_FROM_EMAIL, [email_address.email],
               priority="high")
     return self.create(email_address=email_address,
                        sent=datetime.now(),
                        confirmation_key=confirmation_key)
Example #3
0
def get_invitation_key(user):
    salt = sha_constructor(str(random.random()).encode()).hexdigest()[:5]
    nowish = datetime.datetime.now()
    user_str = user.get_username()
    key_str = "%s%s%s" % (nowish, salt, user_str)
    key = sha_constructor(key_str.encode()).hexdigest()
    return key
 def send_confirmation(self, email_address):
     salt = sha_constructor(str(random())).hexdigest()[:5]
     confirmation_key = sha_constructor(salt + email_address.email).hexdigest()
     current_site = Site.objects.get_current()
     # check for the url with the dotted view path
     try:
         path = reverse("emailconfirmation.views.confirm_email",
                        args=[confirmation_key])
     except NoReverseMatch:
         # or get path with named urlconf instead
         path = reverse(
             "emailconfirmation_confirm_email", args=[confirmation_key])
     activate_url = u"http://%s%s" % (unicode(current_site.domain), path)
     context = {
         "user": email_address.user,
         "activate_url": activate_url,
         "current_site": current_site,
         "confirmation_key": confirmation_key,
     }
     subject = render_to_string(
         "emailconfirmation/email_confirmation_subject.txt", context)
     # remove superfluous line breaks
     subject = "".join(subject.splitlines())
     message = render_to_string(
         "emailconfirmation/email_confirmation_message.txt", context)
     send_mail(subject, message, settings.DEFAULT_FROM_EMAIL,
               [email_address.email], priority="high")
     return self.create(
         email_address=email_address,
         sent=datetime.now(),
         confirmation_key=confirmation_key)
Example #5
0
def _generar_link_activacion(request, email):
    semilla = sha_constructor(str(random())).hexdigest()[:5]
    confirmacion_key = sha_constructor(semilla + email).hexdigest()
    dominio = request.META.get('HTTP_HOST', 'www.cualbondi.com.ar')
    path = 'usuarios/confirmar-email'
    url_activacion = u'http://{0}/{1}/{2}/'.format(dominio, path,
                                                   confirmacion_key)
    return confirmacion_key, url_activacion
Example #6
0
def generate_activation_key(user):
    """
    Generate an activation key using salt and sha.

    The activation key for the ``RegistrationProfile`` will be a
    SHA1 hash, generated from a combination of the ``User``'s
    username and a random salt.
    """
    salt = sha_constructor(str(random.random())).hexdigest()[:5]
    return sha_constructor(salt+user.username).hexdigest()
Example #7
0
 def create_pending_login(self, contact):
     if contact.user:
         return None
     salt = sha_constructor(str(random.random())).hexdigest()[:5]
     activation_key = sha_constructor(salt + contact.email).hexdigest()
     pending_login = self.create(
         contact=contact,
         date=datetime.datetime.now(),
         activation_key=activation_key,
     )
     return pending_login
Example #8
0
def profile(request):
    """
    Form for modifying and adding profile values
    """
    if request.method == 'POST':
        form = ProfileForm(request.POST, instance=request.user)

        email = request.POST.get('email', '')
        if not email == '' and not email == request.user.email:
            #confirm the email
            salt = sha_constructor(str(random())).hexdigest()[:5]
            confirmation_key = sha_constructor(salt + email).hexdigest()
            current_site = Site.objects.get_current()

            path = reverse('confirm_email', args=[confirmation_key])

            activate_url = u"http://%s%s" % (unicode(
                current_site.domain), path)
            context = {
                "user": request.user,
                "activate_url": activate_url,
                "current_site": current_site,
                "confirmation_key": confirmation_key,
            }
            subject = render_to_string("email_confirmation_subject.txt",
                                       context)

            # remove superfluous line breaks
            subject = "".join(subject.splitlines())
            message = render_to_string("email_confirmation_message.txt",
                                       context)
            print email
            send_mail(
                subject, message,
                getattr(settings, 'DEFAULT_FROM_EMAIL',
                        'do-not-reply@%s' % current_site), [email])

            Email.objects.create(owner=request.user,
                                 email=email,
                                 email_is_verified=False,
                                 sent=datetime.now(),
                                 confirmation_key=confirmation_key)

        form.save()
        return HttpResponseRedirect(request.POST.get('next', '/'))

    else:
        form = ProfileForm(instance=request.user)
        next = request.GET.get('next', '/')
        return render_to_response('profile.html', {
            'form': form,
            'next': next
        },
                                  context_instance=RequestContext(request))
Example #9
0
 def create_invitation(self, user, recipient=('*****@*****.**', 'Sirname', 'Lastname' ), save=True):
     """
     Create an ``InvitationKey`` and returns it.
     
     The key for the ``InvitationKey`` will be a SHA1 hash, generated 
     from a combination of the ``User``'s username and a random salt.
     """
     salt = sha_constructor(str(random.random())).hexdigest()[:5]
     key = sha_constructor("%s%s%s" % (datetime.datetime.now(), salt, user.username)).hexdigest()
     if not save:
         return InvitationKey(from_user=user, key='previewkey00000000', recipient=recipient, date_invited=datetime.datetime.now())
     return self.create(from_user=user, key=key, recipient=recipient)
Example #10
0
    def create_profile(self, user):
        """
        Create a ``RegistrationProfile`` for a given
        ``User``, and return the ``RegistrationProfile``.

        The activation key for the ``RegistrationProfile`` will be a
        SHA1 hash, generated from a combination of the ``User``'s
        username and a random salt.

        """
        salt = sha_constructor(str(random.random())).hexdigest()[:5]
        activation_key = sha_constructor(salt + user.username).hexdigest()
        return self.create(user=user, activation_key=activation_key)
Example #11
0
    def save(self, commit=True):
        user = super(UserRegistrationForm, self).save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        if commit:
            user.save()
            
            # Temporary commented out before we discuss accounts confirmation
            
            salt = sha_constructor(str(random())).hexdigest()[:5]
            confirmation_key = sha_constructor(salt + user.email).hexdigest()

            
        return user
Example #12
0
    def create_profile(self, user):
        """
        Create a ``RegistrationProfile`` for a given
        ``User``, and return the ``RegistrationProfile``.

        The activation key for the ``RegistrationProfile`` will be a
        SHA1 hash, generated from a combination of the ``User``'s
        username and a random salt.

        """
        salt = sha_constructor(str(random.random())).hexdigest()[:5]
        activation_key = sha_constructor(salt+user.username).hexdigest()
        return self.create(user=user,
                           activation_key=activation_key)
Example #13
0
def get_cache_key(bucket, name, args, kwargs):
    """
    Gets a unique SHA1 cache key for any call to a native tag.
    Use args and kwargs in hash so that the same arguments use the same key
    """
    u = ''.join(map(str, (bucket, name, args, kwargs)))
    return 'native_tags.%s' % sha_constructor(u).hexdigest()
Example #14
0
    def save(self, *args, **kwargs):
        user = User.objects.get(username=self.cleaned_data['username'])
        profile = user.get_profile()
        while True:
            hash_ = sha_constructor(str(random.random())).hexdigest()[8:16]
            try:
                if user.is_patient():
                    PatientProfile.objects.get(forgot_key=hash_)
                else:
                    ProfessionalProfile.objects.get(forgot_key=hash_)

            except profile.DoesNotExist:
                profile.forgot_key = hash_
                profile.forgot_key_updated = utcnow()
                profile.save()
                break

        ctx_dict = {
            'reset_link': 'http://%s/dashboard/public/#/accounts/reset/%s/' % (
                settings.SITE_URL, profile.forgot_key)}

        subject = render_to_string(
            'accounts/lost_password/email_subject.txt', ctx_dict)
        message = render_to_string(
            'accounts/lost_password/email_message.txt', ctx_dict)
        user.email_user(subject, message, settings.DEFAULT_FROM_EMAIL)

        return user
Example #15
0
    def invite(self, user, email):
        """
        Get or create an invitation for ``email`` from ``user``.

        This method doesn't an send email. You need to call ``send_email()``
        method on returned ``Invitation`` instance.
        """
        invitation = None
        try:
            # It is possible that there is more than one invitation fitting
            # the criteria. Normally this means some older invitations are
            # expired or an email is invited consequtively.
            invitation = self.filter(user=user, email=email)[0]
            if not invitation.is_valid():
                invitation = None
        except (Invitation.DoesNotExist, IndexError):
            pass
        if invitation is None:
            user.invitation_stats.use()
            key = '%s%0.16f%s%s' % (settings.SECRET_KEY,
                                    random.random(),
                                    user.email,
                                    email)
            key = sha_constructor(key).hexdigest()
            invitation = self.create(user=user, email=email, key=key)
        return invitation
Example #16
0
def sql_select(request):
    """
    Returns the output of the SQL SELECT statement.

    Expected GET variables:
        sql: urlencoded sql with positional arguments
        params: JSON encoded parameter values
        duration: time for SQL to execute passed in from toolbar just for redisplay
        hash: the hash of (secret + sql + params) for tamper checking
    """
    from debug_toolbar.panels.sql import reformat_sql
    sql = request.GET.get('sql', '')
    params = request.GET.get('params', '')
    hash = sha_constructor(settings.SECRET_KEY + sql + params).hexdigest()
    if hash != request.GET.get('hash', ''):
        return HttpResponseBadRequest('Tamper alert') # SQL Tampering alert
    if sql.lower().strip().startswith('select'):
        params = simplejson.loads(params)
        cursor = connection.cursor()
        cursor.execute(sql, params)
        headers = [d[0] for d in cursor.description]
        result = cursor.fetchall()
        cursor.close()
        context = {
            'result': result,
            'sql': reformat_sql(cursor.db.ops.last_executed_query(cursor, sql, params)),
            'duration': request.GET.get('duration', 0.0),
            'headers': headers,
        }
        return render_to_response('debug_toolbar/panels/sql_select.html', context)
    raise InvalidSQLError("Only 'select' queries are allowed.")
 def construct_username(self):
     """ Generate a random username"""
     while True:
         username = sha_constructor(str(
             random.random()).encode('utf-8')).hexdigest()[:5]
         if not User.objects.filter(username__iexact=username).exists():
             return username
def sql_select(request):
    """
    Returns the output of the SQL SELECT statement.

    Expected GET variables:
        sql: urlencoded sql with positional arguments
        params: JSON encoded parameter values
        duration: time for SQL to execute passed in from toolbar just for redisplay
        hash: the hash of (secret + sql + params) for tamper checking
    """
    from debug_toolbar.panels.sql import reformat_sql
    sql = request.GET.get('sql', '')
    params = request.GET.get('params', '')
    alias = request.GET.get('alias', 'default')
    hash = sha_constructor(settings.SECRET_KEY + sql + params).hexdigest()
    if hash != request.GET.get('hash', ''):
        return HttpResponseBadRequest('Tamper alert')  # SQL Tampering alert
    if sql.lower().strip().startswith('select'):
        params = simplejson.loads(params)
        cursor = connections[alias].cursor()
        cursor.execute(sql, params)
        headers = [d[0] for d in cursor.description]
        result = cursor.fetchall()
        cursor.close()
        context = {
            'result': result,
            'sql': reformat_sql(cursor.db.ops.last_executed_query(cursor, sql, params)),
            'duration': request.GET.get('duration', 0.0),
            'headers': headers,
            'alias': alias,
        }
        return render_to_response('debug_toolbar/panels/sql_select.html', context)
    raise InvalidSQLError("Only 'select' queries are allowed.")
Example #19
0
def get_cache_key(bucket, name, args, kwargs):
    """
    Gets a unique SHA1 cache key for any call to a native tag.
    Use args and kwargs in hash so that the same arguments use the same key
    """
    u = "".join(map(str, (bucket, name, args, kwargs)))
    return "native_tags.%s" % sha_constructor(u).hexdigest()
Example #20
0
def create_user(user, password, active=False):

    headers = {'Content-Type': 'application/json'}
    params = {}

    payload = {
        'schemas': ['urn:ietf:params:scim:schemas:core:2.0:User'],
        'userName':
        sha_constructor(str(random.random())).hexdigest()[:12],
        'name': {
            'givenName': user.first_name,
            'familyName': user.last_name
        },
        'displayName':
        u'{}{}'.format(user.first_name, user.last_name),
        'password':
        password,
        'emails': [{
            'value': user.email,
            'primary': True,
            'type': 'Work'
        }],
        'phoneNumbers': [{
            'value': user.mobile_number,
            'primary': True,
            'type': 'Work'
        }],
        'timezone':
        user.timezone,
        'title':
        user.job_title
    }

    if active:
        payload['active'] = True

    url = SCIM_CREATE_USER_ENDPOINT

    if settings.SCIM_TEST_MODE:
        params['access_token'] = settings.SCIM_TEST_MODE_ACCESS_TOKEN

    else:
        rpt = obtain_authorized_rpt_token(resource_uri=url)
        headers['Authorization'] = 'Bearer {}'.format(rpt)

    response = requests.post(url,
                             data=json.dumps(payload),
                             verify=settings.VERIFY_SSL,
                             headers=headers,
                             params=params)

    if response.status_code != 201:
        message = 'Error writing to idp: {} {}'.format(response.status_code,
                                                       response.text)
        logger.error(message)
        raise Exception(message)

    else:
        response = response.json()
        return response['id']
Example #21
0
def generate_sha1(string, salt=None):
    """
    Generates a sha1 hash for supplied string. Doesn't need to be very secure
    because it's not used for password checking. We got Django for that.
    :param string:
    The string that needs to be encrypted.
    :param salt:
    Optionally define your own salt. If none is supplied, will use a random
    string of 5 characters.
    :return: Tuple containing the salt and hash.
    """
    if not isinstance(string, str):
        string = str(string)
        if not salt:
            salt = sha_constructor(b"str(random.uniform(1,10))").hexdigest()[:5]
            hash = sha_constructor(salt.encode() + string.encode()).hexdigest()
    return (salt, hash)
Example #22
0
def gen_username():
    """Generates a random username."""
    while True:
        username = '******' % sha_constructor(str(random.random())).\
                   hexdigest()[:9]
        if not User.objects.filter(username__iexact=username).exists():
            break
    return username
Example #23
0
  def save(self, *args, **kwargs):
    # if no key is present, generate one
    if not self.key:
      salt = sha_constructor(str(random.random()).encode('utf-8')).hexdigest()[:5]
      self.key = sha_constructor((salt+self.name).encode('utf-8')).hexdigest()

      salt = sha_constructor(str(random.random()).encode('utf-8')).hexdigest()[:5]
      self.secret_key = sha_constructor((salt+self.name).encode('utf-8')).hexdigest()[:20]

    # create mongo record (upsert)

    # always use the new daily mongodb hosted at db.unityesg
    db.locations.update({'key':self.key}, {'$set': {
        'name':self.name,
        'secret_key':self.secret_key
      }}, True)

    super(Location, self).save(*args, **kwargs)
Example #24
0
def generate_sha1(string, salt=None):
    """
    Generates a sha1 hash for supplied string.

    :param string:
        The string that needs to be encrypted.

    :param salt:
        Optionally define your own salt. If none is supplied, will use a random
        string of 5 characters.

    :return: Tuple containing the salt and hash.
    """
    if not salt:
        salt = sha_constructor(str(random.random())).hexdigest()[:5]
    hash = sha_constructor(salt+str(string)).hexdigest()

    return (salt, hash)
 def make_token(self, contact):
     """Method for generating the token"""
     try:
         from hashlib import sha1 as sha_constructor
     except ImportError:
         from django.utils.hashcompat import sha_constructor
     token_input = unicode("%s%s%s" % (settings.SECRET_KEY, contact.id, contact.email)).encode('utf-8')
     token = sha_constructor(token_input).hexdigest()[::2]
     return token
Example #26
0
def get_hexdigest(algorithm, salt, raw_password):
    """
    Returns a string of the hexdigest of the given plaintext password and salt
    using the given algorithm ('md5', 'sha1' or 'crypt').
    """
    raw_password, salt = smart_str(raw_password), smart_str(salt)
    if algorithm == 'sha1':
        return sha_constructor(salt + raw_password).hexdigest()
    raise ValueError("Got unknown password algorithm type in password.")
 def test_activation_nonexistent_key(self):
     """
     Attempting to activate with a non-existent key (i.e., one not
     associated with any account) fails.
     """
     # Due to the way activation keys are constructed during
     # registration, this will never be a valid key.
     invalid_key = sha_constructor('foo').hexdigest()
     self.failIf(RegistrationProfile.objects.activate_user(invalid_key))
Example #28
0
    def test_activation_nonexistent_key(self):
        """
        Attempting to activate with a non-existent key (i.e., one not
        associated with any account) fails.

        """
        # Due to the way activation keys are constructed during
        # registration, this will never be a valid key.
        invalid_key = sha_constructor("foo").hexdigest()
        self.failIf(RegistrationProfile.objects.activate_user(invalid_key))
Example #29
0
    def save(self):
        """ Generate a random username before falling back to parent signup form """
        while True:
            username = sha_constructor(str(random.random())).hexdigest()[:5]
            try:
                User.objects.get(username__iexact=username)
            except User.DoesNotExist: break

        self.cleaned_data['username'] = username
        return super(SignupFormOnlyEmail, self).save()
Example #30
0
    def save(self):
        """ Generate a random username before falling back to parent signup form """
        while True:
            username = sha_constructor(str(random.random())).hexdigest()[:5]
            try:
                get_user_model().objects.get(username__iexact=username)
            except get_user_model().DoesNotExist: break

        self.cleaned_data['username'] = username
        return super(SignupFormOnlyEmail, self).save()
Example #31
0
    def save(self):
        """ Generate a random username before falling back to parent signup form """
        session = orm.sessionmaker()
        while True:
            username = unicode(sha_constructor(str(random.random())).hexdigest()[:5])
            user = session.query(User).filter(User.username==username).first()
            if not user:
                break

        self.cleaned_data['username'] = username
        return super(SignupFormOnlyEmail, self).save()
Example #32
0
def generate_sha1(string, salt=None):
    """
    Generates a sha1 hash for supplied string. Doesn't need to be very secure
    because it's not used for password checking. We got Django for that.

    :param string:
        The string that needs to be encrypted.

    :param salt:
        Optionally define your own salt. If none is supplied, will use a random
        string of 5 characters.

    :return: Tuple containing the salt and hash.

    """
    if not salt:
        salt = sha_constructor(str(random.random())).hexdigest()[:5]
    hash = sha_constructor(salt + str(string)).hexdigest()

    return (salt, hash)
Example #33
0
def generate_sha1(string, salt=None):
    """
    Generates a sha1 hash for supplied string. Doesn't need to be very secure
    because it's not used for password checking. We got Django for that.
    :param string:
        The string that needs to be encrypted.
    :param salt:
        Optionally define your own salt. If none is supplied, will use a random
        string of 5 characters.
    :return: Tuple containing the salt and hash.
    """
    if not isinstance(string, (str, text_type)):
        string = str(string)

    if not salt:
        salt = sha_constructor(str(random.random()).encode('utf-8')).hexdigest()[:5]

    salted_bytes = (smart_bytes(salt) + smart_bytes(string))
    hash_ = sha_constructor(salted_bytes).hexdigest()

    return salt, hash_
Example #34
0
 def create_invitation(self,
                       user,
                       recipient=('*****@*****.**', 'Sirname',
                                  'Lastname'),
                       save=True):
     """
     Create an ``InvitationKey`` and returns it.
     
     The key for the ``InvitationKey`` will be a SHA1 hash, generated 
     from a combination of the ``User``'s username and a random salt.
     """
     salt = sha_constructor(str(random.random())).hexdigest()[:5]
     key = sha_constructor(
         "%s%s%s" %
         (datetime.datetime.now(), salt, user.username)).hexdigest()
     if not save:
         return InvitationKey(from_user=user,
                              key='previewkey00000000',
                              recipient=recipient,
                              date_invited=datetime.datetime.now())
     return self.create(from_user=user, key=key, recipient=recipient)
Example #35
0
 def send_invitation(self, from_user, to_email, message):
     contact, created = Contact.objects.get_or_create(email=to_email, user=from_user)
     salt = sha_constructor(str(random())).hexdigest()[:5]
     confirmation_key = sha_constructor(salt + to_email).hexdigest()
     
     accept_url = u"http://%s%s" % (
         unicode(Site.objects.get_current()),
         reverse("friends_accept_join", args=(confirmation_key,)),
     )
     
     ctx = {
         "SITE_NAME": settings.SITE_NAME,
         "CONTACT_EMAIL": settings.CONTACT_EMAIL,
         "user": from_user,
         "message": message,
         "accept_url": accept_url,
     }
     
     subject = render_to_string("friends/join_invite_subject.txt", ctx)
     email_message = render_to_string("friends/join_invite_message.txt", ctx)
     
     send_mail(subject, email_message, settings.DEFAULT_FROM_EMAIL, [to_email])        
     return self.create(from_user=from_user, contact=contact, message=message, status="2", confirmation_key=confirmation_key)
Example #36
0
def generate_key(user, email):
    """Generates and returns unique keys.

    **Arguments**

    ``user``
        auth.User instance
    ``email``
        The new email address

    """
    obj_to_hash = default_token_generator.make_token(user) + email + str(
        random.random())
    return sha_constructor(obj_to_hash.encode("utf-8")).hexdigest()
Example #37
0
    def send_confirmation(self, email_address):
        salt = sha_constructor(str(random()).encode()).hexdigest()[:5]
        confirmation_key = sha_constructor('{}{}'.format(
            salt, email_address.email).encode()).hexdigest()
        current_site = Site.objects.get_current()
        # check for the url with the dotted view path
        try:
            path = reverse("emailconfirmation.views.confirm_email",
                           args=[confirmation_key])
        except NoReverseMatch:
            # or get path with named urlconf instead
            path = reverse("account_confirm_email", args=[confirmation_key])
        protocol = getattr(settings, "DEFAULT_HTTP_PROTOCOL", "http")
        activate_url = u"%s://%s%s" % (protocol, current_site.domain, path)

        context = {
            "user": email_address.user,
            "activate_url": activate_url,
            "current_site": current_site,
            "confirmation_key": confirmation_key,
        }
        subject = render_to_string(
            "emailconfirmation/email_confirmation_subject.txt", context)
        # remove superfluous line breaks
        subject = "".join(subject.splitlines())
        message = render_to_string(
            "emailconfirmation/email_confirmation_message.txt", context)
        send_mail(subject, message, settings.DEFAULT_FROM_EMAIL,
                  [email_address.email])
        confirmation = self.create(email_address=email_address,
                                   sent=now(),
                                   confirmation_key=confirmation_key)
        email_confirmation_sent.send(
            sender=self.model,
            confirmation=confirmation,
        )
        return confirmation
Example #38
0
def generate_sha1(string, salt=None):
    """
    Generates a sha1 hash for supplied string.

    :param string:
        The string that needs to be encrypted.

    :param salt:
        Optionally define your own salt. If none is supplied, will use a random
        string of 5 characters.

    :return: Tuple containing the salt and hash.

    """
    string = str(string)
    if not salt:
        salt = str(sha_constructor(str(random.random())).hexdigest()[:5])
    import hashlib
    # >> > sha = hashlib.sha256()
    # >> > sha.update('somestring'.encode())
    # >> > sha.hexdigest()
    hash = sha_constructor((salt + string).encode()).hexdigest()

    return hash
Example #39
0
def mock_license():

    return {
        'license_id':
        '0334bbcb-4121-4e23-a279-{}'.format(
            sha_constructor(str(random.random())).hexdigest()[:12]),
        'license_password':
        '******',
        'public_password':
        '******',
        'public_key':
        'ZwBd+OmGkTNQXlbx64jm+jDFODShWF+Ya+jHGzrI/nZBF/Hogn1t3ihbZQu65Fcvh21+mWtvPmWkGh4MeOTsnq+CINjCXiomERcUgPMR1UaxHV488vfrn0LOoc/8sZ7tbe5C99iOQJR7tQAQxaK8lwKEhJfwJBbPemgSZpm7mZWkWX1/NZTNnEJonHu++h1J1wD8t6APasYMIxBxOo8srC3MgStdMIHZfcwfo6Q+uKCAW7W7imAGUHBvVl6lkZrq61Qef4T81IhD3UmsfVsy3qUIBCIHj26UNKExqs6W0Uuk8MKPG8UFpAurYmIIMcbpw2bPk3iF2fg7oLlMRDSSQPdZGBwITM9fhlQ1y0Bg8SaVFClMUu1FoPETrRiuVgPJQ55vkl/FbrAGrgApEh7tUQ==',
        'expiration_date':
        timezone.now(),
        'creation_date':
        timezone.now() + datetime.timedelta(days=365)
    }
Example #40
0
def get_hexdigest(algorithm, salt, raw_password):
    """
    Returns a string of the hexdigest of the given plaintext password and salt
    using the given algorithm ('md5', 'sha1' or 'crypt').
    """
    raw_password, salt = smart_str(raw_password), smart_str(salt)
    if algorithm == 'crypt':
        try:
            import crypt
        except ImportError:
            raise ValueError('"crypt" password algorithm not supported in this environment')
        return crypt.crypt(raw_password, salt)

    if algorithm == 'md5':
        return md5_constructor(salt + raw_password).hexdigest()
    elif algorithm == 'sha1':
        return sha_constructor(salt + raw_password).hexdigest()
    raise ValueError("Got unknown password algorithm type in password.")
Example #41
0
 def __init__(self):
     key = tg.config.get('tgcaptcha.key', 'secret')
     if key == 'secret':
         log.warning('You need to set the "tgcaptcha.key" value in your '
                     'config file')
     key = sha_constructor(key).hexdigest()[:32]
     random.seed()
     self.aes = AES.new(key, AES.MODE_ECB)
     self.jpeg_generator = None
     # find the jpeg generator
     jpeg_gen = tg.config.get('tgcaptcha.jpeg_generator', 'vanasco_dowty')
     for ep in iter_entry_points('tgcaptcha2.jpeg_generators', jpeg_gen):
         self.jpeg_generator = ep.load()
     # find the text generator
     self.text_generator = None
     txt_gen = tg.config.get('tgcaptcha.text_generator', 'random_ascii')
     for ep in iter_entry_points('tgcaptcha2.text_generators', txt_gen):
         self.text_generator = ep.load()
def sql_explain(request):
    """
    Returns the output of the SQL EXPLAIN on the given query.

    Expected GET variables:
        sql: urlencoded sql with positional arguments
        params: JSON encoded parameter values
        duration: time for SQL to execute passed in from toolbar just for redisplay
        hash: the hash of (secret + sql + params) for tamper checking
    """
    from debug_toolbar.panels.sql import reformat_sql
    sql = request.GET.get('sql', '')
    params = request.GET.get('params', '')
    alias = request.GET.get('alias', 'default')
    hash = sha_constructor(settings.SECRET_KEY + sql + params).hexdigest()
    if hash != request.GET.get('hash', ''):
        return HttpResponseBadRequest('Tamper alert')  # SQL Tampering alert
    if sql.lower().strip().startswith('select'):
        params = simplejson.loads(params)
        cursor = connections[alias].cursor()

        conn = connections[alias].connection
        engine = conn.__class__.__module__.split('.', 1)[0]

        if engine == "sqlite3":
            # SQLite's EXPLAIN dumps the low-level opcodes generated for a query;
            # EXPLAIN QUERY PLAN dumps a more human-readable summary
            # See http://www.sqlite.org/lang_explain.html for details
            cursor.execute("EXPLAIN QUERY PLAN %s" % (sql,), params)
        else:
            cursor.execute("EXPLAIN %s" % (sql,), params)

        headers = [d[0] for d in cursor.description]
        result = cursor.fetchall()
        cursor.close()
        context = {
            'result': result,
            'sql': reformat_sql(cursor.db.ops.last_executed_query(cursor, sql, params)),
            'duration': request.GET.get('duration', 0.0),
            'headers': headers,
            'alias': alias,
        }
        return render_to_response('debug_toolbar/panels/sql_explain.html', context)
    raise InvalidSQLError("Only 'select' queries are allowed.")
def sql_profile(request):
    """
    Returns the output of running the SQL and getting the profiling statistics.

    Expected GET variables:
        sql: urlencoded sql with positional arguments
        params: JSON encoded parameter values
        duration: time for SQL to execute passed in from toolbar just for redisplay
        hash: the hash of (secret + sql + params) for tamper checking
    """
    from debug_toolbar.panels.sql import reformat_sql
    sql = request.GET.get('sql', '')
    params = request.GET.get('params', '')
    alias = request.GET.get('alias', 'default')
    hash = sha_constructor(settings.SECRET_KEY + sql + params).hexdigest()
    if hash != request.GET.get('hash', ''):
        return HttpResponseBadRequest('Tamper alert')  # SQL Tampering alert
    if sql.lower().strip().startswith('select'):
        params = simplejson.loads(params)
        cursor = connections[alias].cursor()
        result = None
        headers = None
        result_error = None
        try:
            cursor.execute("SET PROFILING=1")  # Enable profiling
            cursor.execute(sql, params)  # Execute SELECT
            cursor.execute("SET PROFILING=0")  # Disable profiling
            # The Query ID should always be 1 here but I'll subselect to get the last one just in case...
            cursor.execute("SELECT * FROM information_schema.profiling WHERE query_id=(SELECT query_id FROM information_schema.profiling ORDER BY query_id DESC LIMIT 1)")
            headers = [d[0] for d in cursor.description]
            result = cursor.fetchall()
        except:
            result_error = "Profiling is either not available or not supported by your database."
        cursor.close()
        context = {
            'result': result,
            'result_error': result_error,
            'sql': reformat_sql(cursor.db.ops.last_executed_query(cursor, sql, params)),
            'duration': request.GET.get('duration', 0.0),
            'headers': headers,
            'alias': alias,
        }
        return render_to_response('debug_toolbar/panels/sql_profile.html', context)
    raise InvalidSQLError("Only 'select' queries are allowed.")
Example #44
0
    def restore_object(self, attrs, instance=None):
        ''' Generate a random username before falling back to parent signup form '''
        while True:
            username = sha_constructor(str(random.random())).hexdigest()[:5]
            try:
                User.objects.get(username__iexact=username)
            except User.DoesNotExist:
                break

        new_user = UserenaSignup.objects.create_user(
            username=username,
            email=attrs['email'],
            password=attrs['password1'],
            active=not userena_settings.USERENA_ACTIVATION_REQUIRED,
            # this will be done manually in the next step to allow more flexibiliy
            send_email=False
        )

        return new_user
Example #45
0
def sql_profile(request):
    """
    Returns the output of running the SQL and getting the profiling statistics.

    Expected GET variables:
        sql: urlencoded sql with positional arguments
        params: JSON encoded parameter values
        duration: time for SQL to execute passed in from toolbar just for redisplay
        hash: the hash of (secret + sql + params) for tamper checking
    """
    from debug_toolbar.panels.sql import reformat_sql
    sql = request.GET.get('sql', '')
    params = request.GET.get('params', '')
    hash = sha_constructor(settings.SECRET_KEY + sql + params).hexdigest()
    if hash != request.GET.get('hash', ''):
        return HttpResponseBadRequest('Tamper alert') # SQL Tampering alert
    if sql.lower().strip().startswith('select'):
        params = simplejson.loads(params)
        cursor = connection.cursor()
        result = None
        headers = None
        result_error = None
        try:
            cursor.execute("SET PROFILING=1") # Enable profiling
            cursor.execute(sql, params) # Execute SELECT
            cursor.execute("SET PROFILING=0") # Disable profiling
            # The Query ID should always be 1 here but I'll subselect to get the last one just in case...
            cursor.execute("SELECT * FROM information_schema.profiling WHERE query_id=(SELECT query_id FROM information_schema.profiling ORDER BY query_id DESC LIMIT 1)")
            headers = [d[0] for d in cursor.description]
            result = cursor.fetchall()
        except:
            result_error = "Profiling is either not available or not supported by your database."
        cursor.close()
        context = {
            'result': result,
            'result_error': result_error,
            'sql': reformat_sql(cursor.db.ops.last_executed_query(cursor, sql, params)),
            'duration': request.GET.get('duration', 0.0),
            'headers': headers,
        }
        return render_to_response('debug_toolbar/panels/sql_profile.html', context)
    raise InvalidSQLError("Only 'select' queries are allowed.")
Example #46
0
	def checkSync(self, sum):
		"""
		Calculate a checksum of this Blip and compare it against the given
		checksum. Fires {@link pygowave.model.Blip.onOutOfSync onOutOfSync} if
		the checksum is wrong. Returns true if the checksum is ok.
		
		Note: Currently this only calculates the SHA-1 of the Blip's text. This
		is tentative and subject to change
		
		@function {public Boolean} checkSync
		@param {String} sum Input checksum to compare against
		"""
		if self._outofsync:
			return False
		mysum = sha_constructor(self._content.encode("utf-8")).hexdigest()
		if mysum != sum:
			self.fireEvent("outOfSync")
			self._outofsync = True
			return False
		else:
			return True
Example #47
0
def create_user(user):

    headers = {'Content-Type': 'application/json'}
    params = {}

    payload = {
        'schemas': ['urn:ietf:params:scim:schemas:core:2.0:User'],
        'userName': sha_constructor(str(random.random())).hexdigest()[:12],
        'name': {
            'givenName': user.first_name,
            'familyName': user.last_name
        },
        'displayName': u'{}{}'.format(user.first_name, user.last_name),
        'emails': [{
            'value': user.email,
            'primary': True,
            'type': 'Work'
        }]
    }
    file = 'Path to your file'
    with open(file, 'w') as outfile:
        json.dump(payload, outfile)
    with open(file, 'r+') as f:
        content = f.read()
        f.seek(0, 0)
        f.write("json_string =" + content)

    process = [
        'java', '-jar', 'Path to your jar file', 'create',
        '{0}'.format(user.email), '{0}'.format(user.id)
    ]
    process = subprocess.Popen(process, stdout=subprocess.PIPE)
    response = process.communicate()[0]
    response = json.loads(response)
    if response.get('totalResults') >= 1:
        resource = response.get('Resources')[0]
        return {"user_exist": True, "uuid": resource.get('id')}
    else:
        return response.get('id')
Example #48
0
def sql_explain(request):
    """
    Returns the output of the SQL EXPLAIN on the given query.

    Expected GET variables:
        sql: urlencoded sql with positional arguments
        params: JSON encoded parameter values
        duration: time for SQL to execute passed in from toolbar just for redisplay
        hash: the hash of (secret + sql + params) for tamper checking
    """
    from debug_toolbar.panels.sql import reformat_sql
    sql = request.GET.get('sql', '')
    params = request.GET.get('params', '')
    hash = sha_constructor(settings.SECRET_KEY + sql + params).hexdigest()
    if hash != request.GET.get('hash', ''):
        return HttpResponseBadRequest('Tamper alert') # SQL Tampering alert
    if sql.lower().strip().startswith('select'):
        params = simplejson.loads(params)
        cursor = connection.cursor()

        if settings.DATABASES['default']['ENGINE'] == "sqlite3":
            # SQLite's EXPLAIN dumps the low-level opcodes generated for a query;
            # EXPLAIN QUERY PLAN dumps a more human-readable summary
            # See http://www.sqlite.org/lang_explain.html for details
            cursor.execute("EXPLAIN QUERY PLAN %s" % (sql,), params)
        else:
            cursor.execute("EXPLAIN %s" % (sql,), params)

        headers = [d[0] for d in cursor.description]
        result = cursor.fetchall()
        cursor.close()
        context = {
            'result': result,
            'sql': reformat_sql(cursor.db.ops.last_executed_query(cursor, sql, params)),
            'duration': request.GET.get('duration', 0.0),
            'headers': headers,
        }
        return render_to_response('debug_toolbar/panels/sql_explain.html', context)
    raise InvalidSQLError("Only 'select' queries are allowed.")
Example #49
0
 def _generate_pwd_reset_token(self):
     salt = sha_constructor(str(random.random())).hexdigest()[:8]
     token = sha_constructor(salt+self.user.username).hexdigest()
     cache.set('pwd_reset_token:%s' % self.user.id, token, 60*60*3)
     return token
    def execute(self, sql, params=()):
        __traceback_hide__ = True
        start = datetime.now()
        try:
            return self.cursor.execute(sql, params)
        finally:
            stop = datetime.now()
            duration = ms_from_timedelta(stop - start)
            enable_stacktraces = getattr(settings,
                                        'DEBUG_TOOLBAR_CONFIG', {}) \
                                    .get('ENABLE_STACKTRACES', True)
            if enable_stacktraces:
                stacktrace = tidy_stacktrace(reversed(get_stack()))
            else:
                stacktrace = []
            _params = ''
            try:
                _params = simplejson.dumps(
                        [force_unicode(x, strings_only=True) for x in params]
                            )
            except TypeError:
                pass  # object not JSON serializable

            template_info = None
            cur_frame = sys._getframe().f_back
            try:
                while cur_frame is not None:
                    if cur_frame.f_code.co_name == 'render':
                        node = cur_frame.f_locals['self']
                        if isinstance(node, Node):
                            template_info = get_template_info(node.source)
                            break
                    cur_frame = cur_frame.f_back
            except:
                pass
            del cur_frame

            alias = getattr(self.db, 'alias', 'default')
            conn = connections[alias].connection
            # HACK: avoid imports
            if conn:
                engine = conn.__class__.__module__.split('.', 1)[0]
            else:
                engine = 'unknown'

            params = {
                'engine': engine,
                'alias': alias,
                'sql': self.db.ops.last_executed_query(self.cursor, sql,
                                                self._quote_params(params)),
                'duration': duration,
                'raw_sql': sql,
                'params': _params,
                'hash': sha_constructor(settings.SECRET_KEY \
                                        + smart_str(sql) \
                                        + _params).hexdigest(),
                'stacktrace': stacktrace,
                'start_time': start,
                'stop_time': stop,
                'is_slow': (duration > SQL_WARNING_THRESHOLD),
                'is_select': sql.lower().strip().startswith('select'),
                'template_info': template_info,
            }

            if engine == 'psycopg2':
                params.update({
                    'trans_id': self.logger.get_transaction_id(alias),
                    'trans_status': conn.get_transaction_status(),
                    'iso_level': conn.isolation_level,
                    'encoding': conn.encoding,
                })

            # We keep `sql` to maintain backwards compatibility
            self.logger.record(**params)
Example #51
0
from django.conf import settings

try:
    from hashlib import sha1 as sha_constructor
except ImportError:
    from django.utils.hashcompat import sha_constructor

if not hasattr(settings, 'PHASED_SECRET_DELIMITER'):
    settings.PHASED_SECRET_DELIMITER = sha_constructor(getattr(settings, 'SECRET_KEY', '')).hexdigest()

# quoting the sekrit delimiter to make sure Debug Toolbar doesn't render it
settings.PHASED_SECRET_DELIMITER = '"%s"' % settings.PHASED_SECRET_DELIMITER
Example #52
0
    def send_request(self, method, req_params=None, auth_params=None,
                     file_params=None, retries=None, timeout=None):
        '''Make an HTTP request to a server method.

        The given method is called with any parameters set in ``req_params``.
        If auth is True, then the request is made with an authenticated session
        cookie.  Note that path parameters should be set by adding onto the
        method, not via ``req_params``.

        :arg method: Method to call on the server.  It's a url fragment that
            comes after the base_url set in __init__().  Note that any
            parameters set as extra path information should be listed here,
            not in ``req_params``.
        :kwarg req_params: dict containing extra parameters to send to the
            server
        :kwarg auth_params: dict containing one or more means of authenticating
            to the server.  Valid entries in this dict are:

            :cookie: **Deprecated** Use ``session_id`` instead.  If both
                ``cookie`` and ``session_id`` are set, only ``session_id`` will
                be used.  A ``Cookie.SimpleCookie`` to send as a session cookie
                to the server
            :session_id: Session id to put in a cookie to construct an identity
                for the server
            :username: Username to send to the server
            :password: Password to use with username to send to the server
            :httpauth: If set to ``basic`` then use HTTP Basic Authentication
                to send the username and password to the server.  This may be
                extended in the future to support other httpauth types than
                ``basic``.

            Note that cookie can be sent alone but if one of username or
            password is set the other must as well.  Code can set all of these
            if it wants and all of them will be sent to the server.  Be careful
            of sending cookies that do not match with the username in this
            case as the server can decide what to do in this case.
        :kwarg file_params: dict of files where the key is the name of the
            file field used in the remote method and the value is the local
            path of the file to be uploaded.  If you want to pass multiple
            files to a single file field, pass the paths as a list of paths.
        :kwarg retries: if we get an unknown or possibly transient error from
            the server, retry this many times.  Setting this to a negative
            number makes it try forever.  Default to use the :attr:`retries`
            value set on the instance or in :meth:`__init__`.
        :kwarg timeout: A float describing the timeout of the connection. The
            timeout only affects the connection process itself, not the
            downloading of the response body. Defaults to the :attr:`timeout`
            value set on the instance or in :meth:`__init__`.
        :returns: If ProxyClient is created with session_as_cookie=True (the
            default), a tuple of session cookie and data from the server.
            If ProxyClient was created with session_as_cookie=False, a tuple
            of session_id and data instead.
        :rtype: tuple of session information and data from server

        .. versionchanged:: 0.3.17
            No longer send tg_format=json parameter.  We rely solely on the
            Accept: application/json header now.
        .. versionchanged:: 0.3.21
            * Return data as a Bunch instead of a DictContainer
            * Add file_params to allow uploading files
        .. versionchanged:: 0.3.33
            Added the timeout kwarg
        '''
        self.log.debug('proxyclient.send_request: entered')

        # parameter mangling
        file_params = file_params or {}

        # Check whether we need to authenticate for this request
        session_id = None
        username = None
        password = None
        if auth_params:
            if 'session_id' in auth_params:
                session_id = auth_params['session_id']
            elif 'cookie' in auth_params:
                warnings.warn(
                    'Giving a cookie to send_request() to'
                    ' authenticate is deprecated and will be removed in 0.4.'
                    ' Please port your code to use session_id instead.',
                    DeprecationWarning, stacklevel=2)
                session_id = auth_params['cookie'].output(attrs=[],
                                                          header='').strip()
            if 'username' in auth_params and 'password' in auth_params:
                username = auth_params['username']
                password = auth_params['password']
            elif 'username' in auth_params or 'password' in auth_params:
                raise AuthError('username and password must both be set in'
                                ' auth_params')
            if not (session_id or username):
                raise AuthError(
                    'No known authentication methods'
                    ' specified: set "cookie" in auth_params or set both'
                    ' username and password in auth_params')

        # urljoin is slightly different than os.path.join().  Make sure method
        # will work with it.
        method = method.lstrip('/')
        # And join to make our url.
        url = urljoin(self.base_url, quote(method))

        data = None     # decoded JSON via json.load()

        # Set standard headers
        headers = {
            'User-agent': self.useragent,
            'Accept': 'application/json',
        }

        # Files to upload
        for field_name, local_file_name in file_params:
            file_params[field_name] = open(local_file_name, 'rb')

        cookies = requests.cookies.RequestsCookieJar()
        # If we have a session_id, send it
        if session_id:
            # Anytime the session_id exists, send it so that visit tracking
            # works.  Will also authenticate us if there's a need.  Note that
            # there's no need to set other cookie attributes because this is a
            # cookie generated client-side.
            cookies.set(self.session_name, session_id)

        complete_params = req_params or {}
        if session_id:
            # Add the csrf protection token
            token = sha_constructor(to_bytes(session_id))
            complete_params.update({'_csrf_token': token.hexdigest()})

        auth = None
        if username and password:
            if auth_params.get('httpauth', '').lower() == 'basic':
                # HTTP Basic auth login
                auth = (username, password)
            else:
                # TG login
                # Adding this to the request data prevents it from being
                # logged by apache.
                complete_params.update({
                    'user_name': to_bytes(username),
                    'password': to_bytes(password),
                    'login': '******',
                })

        # If debug, give people our debug info
        self.log.debug('Creating request %(url)s' %
                       {'url': to_bytes(url)})
        self.log.debug('Headers: %(header)s' %
                       {'header': to_bytes(headers, nonstring='simplerepr')})
        if self.debug and complete_params:
            debug_data = copy.deepcopy(complete_params)

            if 'password' in debug_data:
                debug_data['password'] = '******'

            self.log.debug('Data: %r' % debug_data)

        if retries is None:
            retries = self.retries

        if timeout is None:
            timeout = self.timeout

        num_tries = 0
        while True:
            try:
                response = requests.post(
                    url,
                    data=complete_params,
                    cookies=cookies,
                    headers=headers,
                    auth=auth,
                    verify=not self.insecure,
                    timeout=timeout,
                )
            except (requests.Timeout, requests.exceptions.SSLError) as e:
                if isinstance(e, requests.exceptions.SSLError):
                    # And now we know how not to code a library exception
                    # hierarchy...  We're expecting that requests is raising
                    # the following stupidity:
                    # requests.exceptions.SSLError(
                    #   urllib3.exceptions.SSLError(
                    #     ssl.SSLError('The read operation timed out')))
                    # If we weren't interested in reraising the exception with
                    # full tracdeback we could use a try: except instead of
                    # this gross conditional.  But we need to code defensively
                    # because we don't want to raise an unrelated exception
                    # here and if requests/urllib3 can do this sort of
                    # nonsense, they may change the nonsense in the future
                    #
                    # And a note on the __class__.__name__/__module__ parsing:
                    # On top of all the other things it does wrong, requests
                    # is bundling a copy of urllib3.  Distros can unbundle it.
                    # But because of the bundling, python will think
                    # exceptions raised by the version downloaded by pypi
                    # (requests.packages.urllib3.exceptions.SSLError) are
                    # different than the exceptions raised by the unbundled
                    # distro version (urllib3.exceptions.SSLError).  We could
                    # do a try: except trying to import both of these
                    # SSLErrors and then code to detect either one of them but
                    # the whole thing is just stupid.  So we'll use a stupid
                    # hack of our own that (1) means we don't have to depend
                    # on urllib3 just for this exception and (2) is (slightly)
                    # less likely to break on the whims of the requests
                    # author.
                    if not (e.args
                            and e.args[0].__class__.__name__ == 'SSLError'
                            and e.args[0].__class__.__module__.endswith(
                                'urllib3.exceptions')
                            and e.args[0].args
                            and isinstance(e.args[0].args[0], ssl.SSLError)
                            and e.args[0].args[0].args
                            and 'timed out' in e.args[0].args[0].args[0]):
                        # We're only interested in timeouts here
                        raise
                self.log.debug('Request timed out')
                if retries < 0 or num_tries < retries:
                    num_tries += 1
                    self.log.debug(
                        'Attempt #%(try)s failed' % {'try': num_tries})
                    time.sleep(0.5)
                    continue
                # Fail and raise an error
                # Raising our own exception protects the user from the
                # implementation detail of requests vs pycurl vs urllib
                raise ServerError(
                    url, -1, 'Request timed out after %s seconds' % timeout)

            # When the python-requests module gets a response, it attempts to
            # guess the encoding using chardet (or a fork)
            # That process can take an extraordinarily long time for long
            # response.text strings.. upwards of 30 minutes for FAS queries to
            # /accounts/user/list JSON api!  Therefore, we cut that codepath
            # off at the pass by assuming that the response is 'utf-8'.  We can
            # make that assumption because we're only interfacing with servers
            # that we run (and we know that they all return responses
            # encoded 'utf-8').
            response.encoding = 'utf-8'

            # Check for auth failures
            # Note: old TG apps returned 403 Forbidden on authentication
            # failures.
            # Updated apps return 401 Unauthorized
            # We need to accept both until all apps are updated to return 401.
            http_status = response.status_code
            if http_status in (401, 403):
                # Wrong username or password
                self.log.debug('Authentication failed logging in')
                raise AuthError(
                    'Unable to log into server.  Invalid'
                    ' authentication tokens.  Send new username and password')
            elif http_status >= 400:
                if retries < 0 or num_tries < retries:
                    # Retry the request
                    num_tries += 1
                    self.log.debug(
                        'Attempt #%(try)s failed' % {'try': num_tries})
                    time.sleep(0.5)
                    continue
                # Fail and raise an error
                try:
                    msg = httplib.responses[http_status]
                except (KeyError, AttributeError):
                    msg = 'Unknown HTTP Server Response'
                raise ServerError(url, http_status, msg)
            # Successfully returned data
            break

        # In case the server returned a new session cookie to us
        new_session = response.cookies.get(self.session_name, '')

        try:
            data = response.json()
        except ValueError as e:
            # The response wasn't JSON data
            raise ServerError(
                url, http_status, 'Error returned from'
                ' json module while processing %(url)s: %(err)s' %
                {'url': to_bytes(url), 'err': to_bytes(e)})

        if 'exc' in data:
            name = data.pop('exc')
            message = data.pop('tg_flash')
            raise AppError(name=name, message=message, extras=data)

        # If we need to return a cookie for deprecated code, convert it here
        if self.session_as_cookie:
            cookie = Cookie.SimpleCookie()
            cookie[self.session_name] = new_session
            new_session = cookie

        self.log.debug('proxyclient.send_request: exited')
        data = munchify(data)
        return new_session, data
Example #53
0
 def generate_activation_key(email):
     salt = sha_constructor(str(random.random())).hexdigest()[:8]
     activation_key = sha_constructor(salt + email).hexdigest()
     return activation_key
Example #54
0
 def _generate_pwd_reset_token(self):
     salt = sha_constructor(str(random.random())).hexdigest()[:8]
     token = sha_constructor(salt + self.user.username).hexdigest()
     cache.set('pwd_reset_token:%s' % self.user.id, token, 60 * 60 * 3)
     return token
Example #55
0
 def generate_activation_key(email):
     salt = sha_constructor(str(random.random())).hexdigest()[:8]
     activation_key = sha_constructor(salt+email).hexdigest()
     return activation_key
Example #56
0
def get_unique_random(length=10):
    randtime = str(time.time()).split('.')[0]
    rand = ''.join([random.choice(randtime+string.letters+string.digits) for i in range(length)])
    return sha_constructor(rand).hexdigest()[:length]