Example #1
0
    def urlencode(self, safe=None):
        """
        Returns an encoded string of all query string arguments.

        :arg safe: Used to specify characters which do not require quoting, for
            example::

                >>> q = QueryDict('', mutable=True)
                >>> q['next'] = '/a&b/'
                >>> q.urlencode()
                'next=%2Fa%26b%2F'
                >>> q.urlencode(safe='/')
                'next=/a%26b/'

        """
        output = []
        if safe:
            safe = force_bytes(safe, self.encoding)
            encode = lambda k, v: '%s=%s' % ((quote(k, safe), quote(v, safe)))
        else:
            encode = lambda k, v: urlencode({k: v})
        for k, list_ in self.lists():
            k = force_bytes(k, self.encoding)
            output.extend(encode(k, force_bytes(v, self.encoding))
                          for v in list_)
        return '&'.join(output)
Example #2
0
def getCacheEntry(request, viewType, skipCentralRefresh = False, isData = False):
    isCache = cacheIsAvailable(request)
    if isCache:
        is_json = False

        # We do this check to always rebuild cache for the page when it called from the crawler
        if (('HTTP_X_FORWARDED_FOR' in request.META) and (request.META['HTTP_X_FORWARDED_FOR'] in notcachedRemoteAddress) and
                skipCentralRefresh == False):
            return None

        request._cache_update_cache = False
        if ((('HTTP_ACCEPT' in request.META) and (request.META.get('HTTP_ACCEPT') in ('application/json'))) or (
                'json' in request.GET)):
            is_json = True
        key_prefix = "%s_%s_%s_" % (is_json, djangosettings.CACHE_MIDDLEWARE_KEY_PREFIX, viewType)
        if isData==False:
            try:
                if request.method == "POST":
                    path = hashlib.md5(encoding.force_bytes(encoding.iri_to_uri(request.get_full_path() + '?' + request.body)))
                else:
                    path = hashlib.md5(encoding.force_bytes(encoding.iri_to_uri(request.get_full_path())))
            except: path = hashlib.md5(encoding.force_bytes(encoding.iri_to_uri(request.get_full_path())))
            cache_key = '%s.%s' % (key_prefix, path.hexdigest())
            return cache.get(cache_key, None)
        else:
            if 'harvester' in request.META['PATH_INFO']:
                is_json = False
            key_prefix = "%s_%s_%s_" % (is_json, djangosettings.CACHE_MIDDLEWARE_KEY_PREFIX, viewType)
            cache_key = '%s' % (key_prefix)
            return cache.get(cache_key, None)
    else:
        return None
 def get_auth_token(cls, user_id):
     # Generate an auth token for the user id of a connection.
     return hmac.new(
         force_bytes(settings.SECRET_KEY),
         force_bytes(user_id),
         hashlib.sha1
     ).hexdigest()
Example #4
0
 def generic(self, method, path, data='',
             content_type='application/octet-stream', secure=False,
             **extra):
     """Constructs an arbitrary HTTP request."""
     parsed = urlparse(force_str(path))
     data = force_bytes(data, settings.DEFAULT_CHARSET)
     r = {
         'PATH_INFO': self._get_path(parsed),
         'REQUEST_METHOD': str(method),
         'SERVER_PORT': str('443') if secure else str('80'),
         'wsgi.url_scheme': str('https') if secure else str('http'),
     }
     if data:
         r.update({
             'CONTENT_LENGTH': len(data),
             'CONTENT_TYPE': str(content_type),
             'wsgi.input': FakePayload(data),
         })
     r.update(extra)
     # If QUERY_STRING is absent or empty, we want to extract it from the URL.
     if not r.get('QUERY_STRING'):
         query_string = force_bytes(parsed[4])
         # WSGI requires latin-1 encoded strings. See get_path_info().
         if six.PY3:
             query_string = query_string.decode('iso-8859-1')
         r['QUERY_STRING'] = query_string
     return self.request(**r)
Example #5
0
 def _reset_password(error_message=''):
     ''' subfunction used to reset password '''
     if request.method == "POST" and request.POST['reset_pass']:
         if not request.POST['reset_email']:
             error_message = 'Email field are empty.'
         else:
             associated_users= User.objects.filter(Q(email=request.POST['reset_email'])|Q(username=request.POST['reset_email']))
             if associated_users.exists():
                 for user in associated_users:
                     email_temp_data = Context({
                             'email': user.email,
                             'domain': request.META['HTTP_HOST'],
                             'site_name': '127.0.0.2:8000',
                             'uid': urlsafe_base64_encode(force_bytes(user.pk)),
                             'time': urlsafe_base64_encode(force_bytes(datetime.now())),
                             'user': user,
                             'token': default_token_generator.make_token(user),
                             'protocol': 'http',
                             })
                     text_subject = get_template('chtor_admin/_res_/reset_subject.txt').render()
                     html_content = get_template('chtor_admin/_res_/reset_email.html').render(email_temp_data)
                     msg = EmailMultiAlternatives(text_subject, html_content, '*****@*****.**', [request.POST['reset_email']])
                     msg.content_subtype = "html"
                     msg.send()
                     messages.error(request, error_message)
                     return render(request, 'chtor_admin/reset_password_done.html', {
                             'email': user.email
                             })
             else:
                 messages.error(request, 'This username does not exist in the system.')
                 return render(request, 'chtor_admin/reset_password.html')
             # send_mail('Subject here', 'Here is the message.', '*****@*****.**', [request.POST['reset_email']], fail_silently=False)
     messages.error(request, error_message)
     return render(request, 'chtor_admin/reset_password.html')
def salted_hmac(key_salt, value, secret=None):
    """
    Returns the HMAC-HASH of 'value', using a key generated from key_salt and a
    secret (which defaults to settings.SECRET_KEY).

    A different key_salt should be passed in for every application of HMAC.

    :type key_salt: any
    :type value: any
    :type secret: any
    :rtype: HMAC
    """
    if secret is None:
        secret = settings.SECRET_KEY

    key_salt = force_bytes(key_salt)
    secret = force_bytes(secret)

    # We need to generate a derived key from our base key.  We can do this by
    # passing the key_salt and our base key through a pseudo-random function and
    # SHA1 works nicely.
    digest = hashes.Hash(settings.CRYPTOGRAPHY_DIGEST,
                         backend=settings.CRYPTOGRAPHY_BACKEND)
    digest.update(key_salt + secret)
    key = digest.finalize()

    # If len(key_salt + secret) > sha_constructor().block_size, the above
    # line is redundant and could be replaced by key = key_salt + secret, since
    # the hmac module does the same thing for keys longer than the block size.
    # However, we need to ensure that we *always* do this.
    h = HMAC(key, settings.CRYPTOGRAPHY_DIGEST,
             backend=settings.CRYPTOGRAPHY_BACKEND)
    h.update(force_bytes(value))
    return h
Example #7
0
    def build_absolute_uri(self, path=None, parameters=None):
        """
        Returns absolute uri to the specified `path` with optional
        query string `parameters`.

        If no `path` is provided, the current request full path
        (including query string) will be used and extended by
        optional `parameters`.
        """

        params = {}
        if path:
            uri = self.request.build_absolute_uri('/%s%s' % (self.api.path, path))
        else:
            params = dict(self.parameters)
            uri = self.request.build_absolute_uri(self.request.path)

        enc = self.request.GET.encoding # todo: change to internal restosaur settings

        params.update(parameters or {})
        params = dict(map(lambda x: (force_bytes(x[0], enc), force_bytes(x[1], enc)),
            params.items()))

        if params:
            return '%s?%s' % (uri, urllib.urlencode(params))
        else:
            return uri
            def add_attributes(field):
                if verbose_names and field.verbose_name:
                    label = force_bytes(field.verbose_name)
                    if label.islower():
                        label = label.capitalize()
                else:
                    label = force_bytes(field.name)

                t = type(field).__name__
                if isinstance(field, (OneToOneField, ForeignKey)):
                    t += " ({0})".format(field.rel.field_name)
                # TODO: ManyToManyField, GenericRelation

                model['fields'].append({
                    'name': field.name,
                    'label': label,
                    'type': t,
                    'blank': field.blank,
                    'abstract': field in abstract_fields,
                    'relation': isinstance(field, RelatedField),
                    'primary_key': field.primary_key,
                    'verbose_name': field.verbose_name if hasattr(field, 'verbose_name') else '',
                    'auto_now': field.auto_now if hasattr(field, 'auto_now') else False,
                    'auto_now_add': field.auto_now_add if hasattr(field, 'auto_now_add') else False,
                    'auto_created': field.auto_created if hasattr(field, 'auto_created') else False,
                    'choices': bool(getattr(field, 'choices')),
                })
Example #9
0
    def test_user_can_reset_password(self):
        url = reverse("password_new")
        beverly = UserFactory(username="******")
        beverly.set_password("jack")
        beverly.save()

        mismatch_password_data = {
            "uid": urlsafe_base64_encode(force_bytes(beverly.pk)).decode(),
            "token": default_token_generator.make_token(beverly),
            "password": encode_string("wesley"),
            "confirm_password": encode_string("WESLEY")
        }
        response = self.client.post(url, mismatch_password_data, format='json')
        self.assertEqual(response.status_code, 400)
        self.assertFalse(User.objects.get(username='******').check_password('wesley'))

        bad_uid_data = {
            "uid": urlsafe_base64_encode(force_bytes(UserFactory().pk)).decode(),
            "token": default_token_generator.make_token(beverly),
            "password": encode_string("wesley"),
            "confirm_password": encode_string("wesley")
        }
        response = self.client.post(url, bad_uid_data, format='json')
        self.assertEqual(response.status_code, 400)
        self.assertFalse(User.objects.get(username='******').check_password('wesley'))

        good_data = {
            "uid": urlsafe_base64_encode(force_bytes(beverly.pk)).decode(),
            "token": default_token_generator.make_token(beverly),
            "password": encode_string("wesley"),
            "confirm_password": encode_string("wesley")
        }
        self.assertSchemaPost(url, "$setPasswordRequest", "$userResponse", good_data, None, status_OK=True)
        self.assertTrue(User.objects.get(username='******').check_password('wesley'))
def walk_storage(path, topdown=True, onerror=None, followlinks=False,
                 storage=default_storage):
    """
    Generate the file names in a stored directory tree by walking the tree
    top-down.

    For each directory in the tree rooted at the directory top (including top
    itself), it yields a 3-tuple (dirpath, dirnames, filenames).

    This is intended for use with an implementation of the Django storage API.
    You can specify something other than the default storage instance with
    the storage keyword argument.
    """
    if not topdown:
        raise NotImplementedError
    if onerror:
        raise NotImplementedError
    roots = [path]
    while len(roots):
        new_roots = []
        for root in roots:
            dirs, files = storage.listdir(root)
            files = [force_bytes(f) for f in files]
            dirs = [force_bytes(d) for d in dirs]
            yield root, dirs, files
            for dn in dirs:
                new_roots.append('%s/%s' % (root, dn))
        roots[:] = new_roots
            def add_relation(field, extras=""):
                if verbose_names and field.verbose_name:
                    label = force_bytes(field.verbose_name)
                    if label.islower():
                        label = label.capitalize()
                else:
                    label = force_bytes(field.name)

                # show related field name
                if hasattr(field, 'related_query_name'):
                    related_query_name = field.related_query_name()
                    if verbose_names and related_query_name.islower():
                        related_query_name = related_query_name.replace('_', ' ').capitalize()
                    label += force_bytes(' ({})'.format(related_query_name))

                # handle self-relationships and lazy-relationships
                if isinstance(field.rel.to, six.string_types):
                    if field.rel.to == 'self':
                        target_model = field.model
                    else:
                        raise Exception("Lazy relationship for model (%s) must be explicit for field (%s)" % (field.model.__name__, field.name))
                else:
                    target_model = field.rel.to

                _rel = {
                    'target_app': target_model.__module__.replace('.', '_'),
                    'target': target_model.__name__,
                    'type': type(field).__name__,
                    'name': field.name,
                    'label': label,
                    'arrows': extras,
                    'needs_node': True
                }
                if _rel not in model['relations'] and consider(_rel['target']):
                    model['relations'].append(_rel)
Example #12
0
def get_outgoing_url(url):
    """
    Bounce a URL off an outgoing URL redirector, such as
    outgoing.prod.mozaws.net.
    """
    if not settings.REDIRECT_URL:
        return url

    # django.utils.http._urlparse is a copy of python's urlparse()
    # "but uses fixed urlsplit() function".
    parsed_url = django_urlparse(url)
    url_netloc = parsed_url.netloc

    # This prevents a link like javascript://addons.mozilla.org...
    # being returned unchanged since the netloc matches the
    # safe list see bug 1251023
    if parsed_url.scheme not in ['http', 'https']:
        return '/'

    # No double-escaping, and some domain names are excluded.
    if (url_netloc == django_urlparse(settings.REDIRECT_URL).netloc or
            url_netloc in settings.REDIRECT_URL_ALLOW_LIST):
        return url

    url = force_bytes(jinja2.utils.Markup(url).unescape())
    sig = hmac.new(force_bytes(settings.REDIRECT_SECRET_KEY),
                   msg=url, digestmod=hashlib.sha256).hexdigest()
    # Let '&=' through so query params aren't escaped.  We probably shouldn't
    # bother to quote the query part at all.
    return '/'.join([settings.REDIRECT_URL.rstrip('/'), sig,
                     quote(url, safe='/&=')])
Example #13
0
    def add_relation(self, field, model, extras=""):
        if self.verbose_names and field.verbose_name:
            label = force_bytes(field.verbose_name)
            if label.islower():
                label = label.capitalize()
        else:
            label = field.name

        # show related field name
        if hasattr(field, 'related_query_name'):
            related_query_name = field.related_query_name()
            if self.verbose_names and related_query_name.islower():
                related_query_name = related_query_name.replace('_', ' ').capitalize()
            label = '{} ({})'.format(label, force_bytes(related_query_name))

        # handle self-relationships and lazy-relationships
        if isinstance(field.rel.to, six.string_types):
            if field.rel.to == 'self':
                target_model = field.model
            else:
                if '.' in field.rel.to:
                    app_label, model_name = field.rel.to.split('.', 1)
                else:
                    app_label = field.model._meta.app_label
                    model_name = field.rel.to
                target_model = apps.get_model(app_label, model_name)
        else:
            target_model = field.rel.to

        _rel = self.get_relation_context(target_model, field, label, extras)

        if _rel not in model['relations'] and self.use_model(_rel['target']):
            return _rel
    def load_template(self, template_name, template_dirs=None):
        if connection.tenant:
            key = '-'.join([str(connection.tenant.pk), template_name])
        else:
            key = template_name
        if template_dirs:
            # If template directories were specified, use a hash to
            # differentiate
            if connection.tenant:
                key = '-'.join([str(connection.tenant.pk), template_name,
                                hashlib.sha1(force_bytes('|'.join(template_dirs))).hexdigest()])
            else:
                key = '-'.join([template_name, hashlib.sha1(force_bytes('|'.join(template_dirs))).hexdigest()])

        if key not in self.template_cache:
            template, origin = self.find_template(template_name, template_dirs)
            if not hasattr(template, 'render'):
                try:
                    template = get_template_from_string(template, origin, template_name)
                except TemplateDoesNotExist:
                    # If compiling the template we found raises TemplateDoesNotExist,
                    # back off to returning the source and display name for the template
                    # we were asked to load. This allows for correct identification (later)
                    # of the actual template that does not exist.
                    return template, origin
            self.template_cache[key] = template
        return self.template_cache[key], None
def constant_time_compare(val1, val2):
    """
    :type val1: any
    :type val2: any
    :rtype: bool
    """
    return constant_time.bytes_eq(force_bytes(val1), force_bytes(val2))
Example #16
0
def deserialize_instance(model, data):
    ret = model()
    for k, v in data.items():
        is_db_value = False
        if k.startswith(SERIALIZED_DB_FIELD_PREFIX):
            k = k[len(SERIALIZED_DB_FIELD_PREFIX) :]
            is_db_value = True
        if v is not None:
            try:
                f = model._meta.get_field(k)
                if isinstance(f, DateTimeField):
                    v = dateparse.parse_datetime(v)
                elif isinstance(f, TimeField):
                    v = dateparse.parse_time(v)
                elif isinstance(f, DateField):
                    v = dateparse.parse_date(v)
                elif isinstance(f, BinaryField):
                    v = force_bytes(base64.b64decode(force_bytes(v)))
                elif is_db_value:
                    try:
                        # This is quite an ugly hack, but will cover most
                        # use cases...
                        v = f.from_db_value(v, None, None, None)
                    except:
                        raise ImproperlyConfigured(
                            "Unable to auto serialize field '{}', custom" " serialization override required".format(k)
                        )
            except FieldDoesNotExist:
                pass
        setattr(ret, k, v)
    return ret
Example #17
0
 def get_template_key(fragment_name, vary_on=None, prefix='template.cache'):
     """Compose the cache key of a template."""
     if vary_on is None:
         vary_on = ()
     key = ':'.join([urlquote(force_bytes(var)) for var in vary_on])
     args = hashlib.md5(force_bytes(key))
     return (prefix + '.%s.%s') % (fragment_name, args.hexdigest())
 def assert_is_input_message(self, msg):
     """
     Ensure passed message is the same as the message we have fed to the
     command
     """
     self.assertEqual(force_bytes(self.input_message.as_string(), 'utf-8'),
                      force_bytes(msg.as_string(), 'utf-8'))
Example #19
0
def pbkdf2(password, salt, iterations, dklen=0, digest=None):
    """Return the hash of password using pbkdf2."""
    if digest is None:
        digest = hashlib.sha256
    dklen = dklen or None
    password = force_bytes(password)
    salt = force_bytes(salt)
    return hashlib.pbkdf2_hmac(digest().name, password, salt, iterations, dklen)
Example #20
0
    def __init__(self, geo_input, srid=None):
        """
        The base constructor for GEOS geometry objects. It may take the
        following inputs:

         * strings:
            - WKT
            - HEXEWKB (a PostGIS-specific canonical form)
            - GeoJSON (requires GDAL)
         * buffer:
            - WKB

        The `srid` keyword specifies the Source Reference Identifier (SRID)
        number for this Geometry. If not provided, it defaults to None.
        """
        input_srid = None
        if isinstance(geo_input, bytes):
            geo_input = force_text(geo_input)
        if isinstance(geo_input, str):
            wkt_m = wkt_regex.match(geo_input)
            if wkt_m:
                # Handle WKT input.
                if wkt_m.group('srid'):
                    input_srid = int(wkt_m.group('srid'))
                g = self._from_wkt(force_bytes(wkt_m.group('wkt')))
            elif hex_regex.match(geo_input):
                # Handle HEXEWKB input.
                g = wkb_r().read(force_bytes(geo_input))
            elif json_regex.match(geo_input):
                # Handle GeoJSON input.
                ogr = gdal.OGRGeometry.from_json(geo_input)
                g = ogr._geos_ptr()
                input_srid = ogr.srid
            else:
                raise ValueError('String input unrecognized as WKT EWKT, and HEXEWKB.')
        elif isinstance(geo_input, GEOM_PTR):
            # When the input is a pointer to a geometry (GEOM_PTR).
            g = geo_input
        elif isinstance(geo_input, memoryview):
            # When the input is a buffer (WKB).
            g = wkb_r().read(geo_input)
        elif isinstance(geo_input, GEOSGeometry):
            g = capi.geom_clone(geo_input.ptr)
        else:
            raise TypeError('Improper geometry input type: %s' % type(geo_input))

        if not g:
            raise GEOSException('Could not initialize GEOS Geometry with given input.')

        input_srid = input_srid or capi.geos_get_srid(g) or None
        if input_srid and srid and input_srid != srid:
            raise ValueError('Input geometry already has SRID: %d.' % input_srid)

        super().__init__(g, None)
        # Set the SRID, if given.
        srid = input_srid or srid
        if srid and isinstance(srid, int):
            self.srid = srid
Example #21
0
	def post(self, request, *args, **kwargs):
		form = self.form_class(request.POST)
		if form.is_valid():
			data= form.cleaned_data["email_or_username"]
		if self.validate_email_address(data) is True:
			associated_users= User.objects.filter(Q(email=data)|Q(username=data))
			if associated_users.exists():
				for user in associated_users:
					c = {
						'email': user.email,
						'domain': request.META['HTTP_HOST'],
						'site_name': 'SinComplique',
						'uid': urlsafe_base64_encode(force_bytes(user.pk)),
						'user': user,
						'token': default_token_generator.make_token(user),
						'protocol': 'http',
					}
					subject_template_name = 'users/password_reset_subject.txt'
					email_template_name = 'users/password_reset_subject.html'
					subject = 'Cambio de Contraseña'
					subject = ''.join(subject.splitlines())
					email_txt = loader.render_to_string(subject_template_name, c)
					email_html = loader.render_to_string(email_template_name, c)
					send_mail(subject, email_html, settings.DEFAULT_FROM_EMAIL, [user.email])
				result = self.form_valid(form)
				messages.success(request, 'An email has been sent to ' + data +". Please check its inbox to continue reseting password.")
				return result
			result = self.form_invalid(form)
			messages.warning(request, 'No user is associated with this email address')
			return result
		else:
			associated_users= User.objects.filter(username=data)
			if associated_users.exists():
				for user in associated_users:
					c = {
						'email': user.email,
						'domain': request.META['HTTP_HOST'],
						'site_name': 'SinComplique',
						'uid': urlsafe_base64_encode(force_bytes(user.pk)),
						'user': user,
						'token': default_token_generator.make_token(user),
						'protocol': 'http',
					}
					subject_template_name='users/password_reset_subject.txt'
					email_template_name='users/password_reset_subject.html'
					subject = loader.render_to_string(subject_template_name, c)
					subject = ''.join(subject.splitlines())
					email_txt = loader.render_to_string(subject_template_name, c)
					email_html = loader.render_to_string(email_template_name, c)
					send_mail(subject, email_html, settings.DEFAULT_FROM_EMAIL , [user.email])
				result = self.form_valid(form)
				messages.success(request, 'Email has been sent to ' + data +"'s email address. Please check its inbox to continue reseting password.")
				return result
			result = self.form_invalid(form)
			messages.error(request, 'This username does not exist in the system.')
			return result
		messages.error(request, 'Invalid Input')
		return self.form_invalid(form)
Example #22
0
def register(request):
    """
    Display the user registration form and store the :model:`auth.User` and
    his :model:`inviMarket.Profile` in the database.

    **Context**

    ``form``
      An instace of the user registration form.

    ``error``
      A string variable containing any general error message.

    **Template:**

    :template:`inviMarket/register.html`

    """
    error = None
    if request.user.is_authenticated():
        return redirect('index')
    if request.method == 'POST':
        form = RegisterForm(request.POST)
        if 'terms' not in request.POST:
            error= _("You must read and accept the terms and conditions.")
        elif form.is_valid():
            if form.cleaned_data['last_name'] != "":
                return redirect('confirm')
            new_user = form.save()
            # Create a random activation key and store it in the user profile
            salt = hashlib.sha1(str(random.random())).hexdigest()[:5]
            activation_key = hashlib.sha1(salt+new_user.email).hexdigest()
            key_expires = timezone.now() + datetime.timedelta(2)
            lang = request.LANGUAGE_CODE
            profile = Profile(user=new_user, activation_key=activation_key,
                key_expires=key_expires, lang=lang, last_visit=timezone.now())
            profile.save()
            # Send the activation key to the user
            text = render_to_string('email/activation.txt',
                {'name': new_user.first_name,
                 'uidb64': urlsafe_base64_encode(force_bytes(new_user.id)),
                 'key': activation_key,
                 'domain': settings.DOMAIN,
                 })
            html = render_to_string('email/activation.html',
                {'name': new_user.first_name,
                 'uidb64': urlsafe_base64_encode(force_bytes(new_user.id)),
                 'key': activation_key,
                 'domain': settings.DOMAIN,
                 })
            subject = "Account activation"
            send_mail(subject, text, "inviMarket <*****@*****.**>",
                [new_user.email], html_message=html,fail_silently=False)
            return redirect('confirm')
    else:
        form = RegisterForm()
    return render(request, 'register.html', {'form': form, 'error': error})
 def cache_key(template_name, template_dirs):
     if connection.tenant and template_dirs:
         return '-'.join([str(connection.tenant.pk), template_name,
                          hashlib.sha1(force_bytes('|'.join(template_dirs))).hexdigest()])
     if template_dirs:
         # If template directories were specified, use a hash to differentiate
         return '-'.join([template_name, hashlib.sha1(force_bytes('|'.join(template_dirs))).hexdigest()])
     else:
         return template_name
Example #24
0
def get_user_password(user, disable=False):
    """Return ready-to-use password from user instance."""
    scheme, password = user.password.split("}")
    return (
        force_bytes(scheme) +
        b"}" +
        b"#" if disable else b"" +
        force_bytes(password)
    )
Example #25
0
 def mv(cls, src, dst, msg):
     """Move a file from src to dst."""
     try:
         if storage.exists(src):
             log.info(msg % (src, dst))
             move_stored_file(src, dst)
     except UnicodeEncodeError:
         msg = 'Move Failure: %s %s' % (force_bytes(src), force_bytes(dst))
         log.error(msg)
Example #26
0
 def test_force_bytes_exception(self):
     """
     force_bytes knows how to convert to bytes an exception
     containing non-ASCII characters in its args.
     """
     error_msg = "This is an exception, voilà"
     exc = ValueError(error_msg)
     self.assertEqual(force_bytes(exc), error_msg.encode())
     self.assertEqual(force_bytes(exc, encoding='ascii', errors='ignore'), b'This is an exception, voil')
Example #27
0
def make_activation_code():
    """ Generate a unique activation code. """
    random_string = str(random.random())
    random_digest = sha1(force_bytes(random_string)).hexdigest()[:5]
    time_string = str(datetime.now().microsecond)

    combined_string = random_digest + time_string

    return sha1(force_bytes(combined_string)).hexdigest()
 def get_compiled_content_file(self, asset):
     if isinstance(asset, GenericAsset):
         return registry_instance.finder_service.open_asset(asset)
     else:
         ret = ContentFile('')
         asset_manifest = registry_instance.asset_manifest_repository.get_asset_manifest_with_asset(asset)
         for content_line in asset_manifest.get_content_lines():
             ret.write(force_bytes(content_line))
             ret.write(force_bytes("\n"))
         return ret
Example #29
0
def send_signup_confirm_email(request, user):
    uid = urlsafe_base64_encode(force_bytes(user.pk))
    token = token_generator.make_token(user)

    context = { 
            'user': user,
            'host': request.scheme + '://' + request.META['HTTP_HOST'],
            'uid': urlsafe_base64_encode(force_bytes(user.pk))
            'token': token_generator.make_token(user),
        }
def _generate_orderless_cache_key(request, method, headerlist, key_prefix):
    """Returns a cache key from the headers given in the header list."""
    ctx = hashlib.md5()
    for header in headerlist:
        value = request.META.get(header, None)
        if value is not None:
            ctx.update(force_bytes(value))
    url = hashlib.md5(force_bytes(_generate_orderless_cache_url(request)))
    cache_key = "views.decorators.cache.cache_page.%s.%s.%s.%s" % (key_prefix, method, url.hexdigest(), ctx.hexdigest())
    return _i18n_cache_key_suffix(request, cache_key)
Example #31
0
 def convert_binaryfield_value(self, value, expression, connection,
                               context):
     if isinstance(value, Database.LOB):
         value = force_bytes(value.read())
     return value
Example #32
0
 def test_remove_user_from_chat_chat_does_not_exist(self):
     response = self.client.get(reverse('remove_user_from_chat',
                                        kwargs={'pk': '10',
                                                'user_pk': self.user.pk}), follow=True)
     self.assertIn(force_bytes('User or chat does not exist'), response.content)
Example #33
0
 def test_chat_view(self):
     response = self.client.get(reverse('chat', kwargs={'pk': self.chat.pk}), follow=True)
     self.assertEqual(response.status_code, 200)
     self.assertTemplateUsed('chat.html')
     self.assertIn(force_bytes(self.chat.title), response.content)
Example #34
0
 def test_delete_chat_doesnt_exist(self):
     response = self.client.get(reverse('delete_chat', kwargs={'pk': '10'}), follow=True)
     self.assertIn(force_bytes('You can not delete a chat that does not exist'), response.content)
Example #35
0
 def test_add_users_to_chat_not_chat_owner(self):
     chat = Chat.objects.create(owner=self.user1, title='test_chat1')
     response = self.client.post(reverse('add_users_to_chat', kwargs={'pk': chat.pk}), follow=True)
     self.assertEqual(response.status_code, 200)
     self.assertIn(force_bytes('You can only edit your own chats'), response.content)
Example #36
0
def get_cookie_signer(salt="django.core.signing.get_cookie_signer"):
    Signer = import_string(settings.SIGNING_BACKEND)
    key = force_bytes(settings.SECRET_KEY)  # SECRET_KEY may be str or bytes.
    return Signer(b"django.http.cookies" + key, salt=salt)
Example #37
0
def register_view(request):
    if request.method == "POST":

        username = request.POST['username']
        email = request.POST['email']
        password1 = request.POST['password1']
        password2 = request.POST['password2']
        birthdate = request.POST['date']
        createdat = datetime.datetime.now()
        faculty = request.POST['Bölüm']
        gender = request.POST['gender']
        converted = datetime.datetime.strptime(birthdate, '%Y-%m-%d')
        if str(email).split('@')[1] != 'isik.edu.tr':
            messages.error(
                request,
                'Güvenliğiniz için sadece Işık mailiniz ile kayıt olabilirsiniz.'
            )
            return redirect('register')
        if password1 != password2:
            messages.error(request, 'Ä°ki ÅŸifre eÅŸleÅŸmiyor.')
            return redirect('register')
        if len(password1) < 8:
            messages.error(request, 'Şifre 8 karakterden küçük olamaz.')
            return redirect('register')
        if converted.year > createdat.year:
            messages.error(request,
                           'Geçersiz doğum tarihi.Geçerli bir tarih giriniz.')
            return redirect('register')
        if email and User.objects.filter(email=email).exclude(
                username=username).exists():
            messages.error(
                request,
                'Email sistemde kayıtlı.Lütfen başka bir email giriniz.')
            return redirect('register')
        if User.objects.filter(username=username).exists():
            messages.error(
                request,
                'Kullanıcı adı sistemde kayıtlı.Lütfen başka bir kullanıcı adı giriniz.'
            )
            return redirect('register')

        user = User.objects.create_user(username=username,
                                        email=email,
                                        password=password1)
        profile = UserProfile(gender=gender,
                              faculty=faculty,
                              user=user,
                              birthdate=birthdate,
                              createdat=createdat)
        # user_test = UserProfile.objects.get(pk=13)
        profile.save()
        subject = 'Aramıza hoşgeldin - The Insider Sight'
        current_site = get_current_site(request)
        message = render_to_string(
            'account_activation_email.html', {
                'user': user,
                'domain': current_site.domain,
                'uid': urlsafe_base64_encode(force_bytes(user.pk)),
                'token': account_activation_token.make_token(user),
            })
        user.email_user(subject, message)

        messages.success(request, 'Onay maili belirttiğiniz maile gönderildi.')
        return redirect('register')
    else:
        return render(request, 'register.html')
Example #38
0
 def basic_auth(self, user, password):
     return b"Basic " + b64encode(force_bytes(user + ":" + password))
Example #39
0
 def test_leave_chat_chat_does_not_exist(self):
     response = self.client.get(reverse('leave_chat', kwargs={'pk': '10'}), follow=True)
     self.assertIn(force_bytes('This chat does not exist yet or have been deleted'), response.content)
Example #40
0
# TOKEN  generator import
from django.contrib.auth.tokens import default_token_generator
from django.contrib.sites.shortcuts import get_current_site
from django.core.mail import EmailMessage
from django.template.loader import render_to_string
from django.utils.encoding import force_bytes
from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode

current_site = get_current_site(request)
mail_subject = 'Activate your account.'
message = render_to_string(
    'person/acc_active_email.html', {
        'user': user,
        'domain': current_site.domain,
        'uid': urlsafe_base64_encode(force_bytes(user.pk)),
        'token': default_token_generator.make_token(user),
    })
to_email = form.cleaned_data.get('email')
email = EmailMessage(mail_subject, message, to=[to_email])
Example #41
0
def admin_options(request):
    cat_choice = Categoriechoiceform()
    typ = Categorie.objects.all().order_by('cat')
    kat = Kategorie.objects.all().order_by('kategorie')
    calc = Calc_Choices.objects.all()
    kat_element = ElementTOKat.objects.all().order_by('katgroup__kategorie')
    load_table = Element.objects.filter(categories=13)
    elements = KategorieElement.objects.all().order_by('kat_element')
    userform = SignupForm()
    user = request.user
    users = Userlimitform()

    event_cat_choice = EventsCategoriechoiceform()

    if request.method == 'POST':
        signupform = SignupForm(request.POST)

        if signupform.is_valid():
            to_email = signupform.cleaned_data.get('email')
            try:
                match = User.objects.get(email=to_email)

            except ObjectDoesNotExist:
                user = signupform.save(commit=False)
                user.is_active = True
                user.save()

                from mail_templated import EmailMessage

                current_site = get_current_site(request)

                message = EmailMessage(
                    'email\login.tpl', {
                        'user': user,
                        'domain': current_site.domain,
                        'uid': urlsafe_base64_encode(force_bytes(
                            user.pk)).decode(),
                        'token': PasswordResetTokenGenerator().make_token(user)
                    },
                    from_email='*****@*****.**',
                    to=[user.email])

                message.send()

                messages.success(
                    request,
                    'Benutzer wurde erfolgreich erstellt und eine E-Mail Verrifizierung an '
                    + to_email + ' versendet.')

            else:
                messages.warning(
                    request, 'E-Mail ' + to_email + ' ist bereits vergeben.')

        else:
            messages.warning(
                request,
                'Achtung! Überprüfen Sie die Eingabe der E-Mail und des Benutzernamen! Der Benutzername darf keine Leerzeichen enthalten. Folgende Zeichen dürfen verwendet werden: @/-/+/-/_'
            )

    return render(
        request, 'options/admin_options.html', {
            'kat': kat,
            'elements': elements,
            'calc': calc,
            'cat_choice': cat_choice,
            'load_table': load_table,
            'typ': typ,
            'kat_element': kat_element,
            'userform': userform,
            'user': user,
            'users': users,
            'event_cat_choice': event_cat_choice,
        })
Example #42
0
    def sign_cert(self,
                  ca,
                  csr,
                  expires=None,
                  algorithm=None,
                  subject=None,
                  cn_in_san=True,
                  csr_format=Encoding.PEM,
                  subject_alternative_name=None,
                  key_usage=None,
                  extended_key_usage=None,
                  tls_feature=None,
                  ocsp_no_check=False,
                  issuer_url=None,
                  crl_url=None,
                  ocsp_url=None,
                  issuer_alternative_name=None,
                  extra_extensions=None,
                  password=None):
        """Create a signed certificate from a CSR.

        **PLEASE NOTE:** This function creates the raw certificate and is usually not invoked directly. It is
        called by :py:func:`Certificate.objects.init() <django_ca.managers.CertificateManager.init>`, which
        passes along all parameters unchanged and saves the raw certificate to the database.

        Parameters
        ----------

        ca : :py:class:`~django_ca.models.CertificateAuthority`
            The certificate authority to sign the certificate with.
        csr : str or :py:class:`~cg:cryptography.x509.CertificateSigningRequest`
            A valid CSR. If not already a :py:class:`~cg:cryptography.x509.CertificateSigningRequest`, the
            format is given by the ``csr_format`` parameter.
        expires : datetime, optional
            Datetime for when this certificate will expire, defaults to the ``CA_DEFAULT_EXPIRES`` setting.
        algorithm : str or :py:class:`~cg:cryptography.hazmat.primitives.hashes.HashAlgorithm`, optional
            Hash algorithm used when signing the certificate, passed to
            :py:func:`~django_ca.utils.parse_hash_algorithm`. The default is the value of the
            :ref:`CA_DIGEST_ALGORITHM <settings-ca-digest-algorithm>` setting.
        subject : dict or str or :py:class:`~django_ca.subject.Subject`
            Subject string, e.g. ``"/CN=example.com"`` or ``Subject("/CN=example.com")``.
            The value is actually passed to :py:class:`~django_ca.subject.Subject` if it is not already an
            instance of that class. If this value is not passed or if the value does not contain a CommonName,
            the first value of the ``subject_alternative_name`` parameter is used as CommonName.
        cn_in_san : bool, optional
            Wether the CommonName should also be included as subjectAlternativeName. The default is
            ``True``, but the parameter is ignored if no CommonName is given. This is typically set
            to ``False`` when creating a client certificate, where the subjects CommonName has no
            meaningful value as subjectAlternativeName.
        csr_format : :py:class:`~cg:cryptography.hazmat.primitives.serialization.Encoding`, optional
            The format of the CSR. The default is ``PEM``.
        subject_alternative_name : dict or :py:class:`~django_ca.extensions.SubjectAlternativeName`, optional
            A dict passed to :py:class:`~django_ca.extensions.SubjectAlternativeName` if not already an
            instance of that class.
        key_usage : dict or :py:class:`~django_ca.extensions.KeyUsage`, optional
            Value for the ``keyUsage`` X509 extension. A dict passed to
            :py:class:`~django_ca.extensions.KeyUsage` if not already an instance of that class.
        extended_key_usage : dict or :py:class:`~django_ca.extensions.ExtendedKeyUsage`, optional
            Value for the ``extendedKeyUsage`` X509 extension. A dict passed to
            :py:class:`~django_ca.extensions.ExtendedKeyUsage` if not already an instance of that class.
        tls_feature : dict or :py:class:`~django_ca.extensions.TLSFeature`, optional
            Value for the ``TLSFeature`` X509 extension. The dict passed to
            :py:class:`~django_ca.extensions.TLSFeature` if not already an instance of that class.
        ocsp_no_check : bool, optional
            Add the OCSPNoCheck flag, indicating that an OCSP client should trust this certificate for it's
            lifetime. This value only makes sense if you intend to use the certificate for an OCSP responder,
            the default is ``False``. See `RFC 6990, section 4.2.2.2.1
            <https://tools.ietf.org/html/rfc6960#section-4.2.2.2>`_ for more information.
        issuer_url : ``str`` or ``bool``, optional
            Pass a custom issuer URL overriding the value configured in the CA or pass ``False`` to disable
            getting any issuer_url from the CA (e.g. to pass a custom extension in ``extra_extensions``).
        crl_url : ``str`` or ``bool``, optional
            Pass a custom CRL URL overriding the value configured in the CA or pass ``False`` to disable
            getting any issuer_url from the CA (e.g. to pass a custom extension in ``extra_extensions``).
        ocsp_url : ``str`` or ``bool``, optional
            Pass a custom OCSP URL overriding the value configured in the CA or pass ``False`` to disable
            getting any issuer_url from the CA (e.g. to pass a custom extension in ``extra_extensions``).
        issuer_alternative_name : ``dict`` or :py:class:`~django_ca.extensions.IssuerAlternativeName`, \
                optional
            Pass a custom issuer alternative name URL overriding the value configured in the CA or pass an
            empty dict to disable getting any issuer_url from the CA.
        extra_extensions : list of :py:class:`cg:cryptography.x509.Extension` or \
                :py:class:`django_ca.extensions.Extension`, optional
            An optional list of additional extensions to add to the certificate.
        password : bytes, optional
            Password used to load the private key of the certificate authority. If not passed, the private key
            is assumed to be unencrypted.

        Returns
        -------

        cryptography.x509.Certificate
            The signed certificate.
        """
        # TODO: This function does not check the expiry of the parent CA yet (manage.py sign_cert does)
        ########################
        # Normalize parameters #
        ########################
        if subject is None:
            subject = Subject(
            )  # we need a subject instance so we can possibly add the CN
        elif not isinstance(subject, Subject):
            subject = Subject(subject)

        if 'CN' not in subject and not subject_alternative_name:
            raise ValueError(
                "Must name at least a CN or a subjectAlternativeName.")

        algorithm = parse_hash_algorithm(algorithm)

        # Normalize extensions to django_ca.extensions.Extension subclasses
        if key_usage and not isinstance(key_usage, KeyUsage):
            key_usage = KeyUsage(key_usage)
        if extended_key_usage and not isinstance(extended_key_usage,
                                                 ExtendedKeyUsage):
            extended_key_usage = ExtendedKeyUsage(extended_key_usage)
        if tls_feature and not isinstance(tls_feature, TLSFeature):
            tls_feature = TLSFeature(tls_feature)

        if not subject_alternative_name:
            subject_alternative_name = SubjectAlternativeName({})
        elif not isinstance(subject_alternative_name, SubjectAlternativeName):
            subject_alternative_name = SubjectAlternativeName(
                subject_alternative_name)

        # use first SAN as CN if CN is not set
        if 'CN' not in subject:
            subject['CN'] = subject_alternative_name.value[0].value
        elif cn_in_san and 'CN' in subject:  # add CN to SAN if cn_in_san is True (default)
            try:
                cn_name = parse_general_name(subject['CN'])
            except idna.IDNAError:
                raise ValueError(
                    '%s: Could not parse CommonName as subjectAlternativeName.'
                    % subject['CN'])
            else:
                if cn_name not in subject_alternative_name:
                    subject_alternative_name.insert(0, cn_name)

        if issuer_url is None:
            issuer_url = ca.issuer_url
        if crl_url is None:
            crl_url = ca.crl_url
        if ocsp_url is None:
            ocsp_url = ca.ocsp_url
        if issuer_alternative_name is None:
            issuer_alternative_name = IssuerAlternativeName({
                'value':
                shlex_split(ca.issuer_alt_name, ','),
            })

        ################
        # Read the CSR #
        ################
        if isinstance(csr, x509.CertificateSigningRequest):
            req = csr
        elif csr_format == Encoding.PEM:
            req = x509.load_pem_x509_csr(force_bytes(csr), default_backend())
        elif csr_format == Encoding.DER:
            req = x509.load_der_x509_csr(force_bytes(csr), default_backend())
        else:
            raise ValueError('Unknown CSR format passed: %s' % csr_format)

        #########################
        # Send pre-issue signal #
        #########################
        pre_issue_cert.send(sender=self.model,
                            ca=ca,
                            csr=csr,
                            expires=expires,
                            algorithm=algorithm,
                            subject=subject,
                            cn_in_san=cn_in_san,
                            csr_format=csr_format,
                            subject_alternative_name=subject_alternative_name,
                            key_usage=key_usage,
                            extended_key_usage=extended_key_usage,
                            tls_featur=tls_feature,
                            issuer_url=issuer_url,
                            crl_url=crl_url,
                            ocsp_url=ocsp_url,
                            issuer_alternative_name=issuer_alternative_name,
                            extra_extensions=extra_extensions,
                            password=password)

        #######################
        # Generate public key #
        #######################
        public_key = req.public_key()

        builder = get_cert_builder(expires)
        builder = builder.public_key(public_key)
        builder = builder.issuer_name(ca.x509.subject)
        builder = builder.subject_name(subject.name)

        # Add extensions
        builder = builder.add_extension(x509.BasicConstraints(
            ca=False, path_length=None),
                                        critical=True)
        builder = builder.add_extension(
            x509.SubjectKeyIdentifier.from_public_key(public_key),
            critical=False)

        # Get authorityKeyIdentifier from subjectKeyIdentifier from signing CA
        builder = builder.add_extension(ca.get_authority_key_identifier(),
                                        critical=False)

        for critical, ext in self.get_common_extensions(
                issuer_url, crl_url, ocsp_url):
            builder = builder.add_extension(ext, critical=critical)

        if subject_alternative_name:
            builder = builder.add_extension(
                **subject_alternative_name.for_builder())

        if key_usage:
            builder = builder.add_extension(**key_usage.for_builder())

        if extended_key_usage:
            builder = builder.add_extension(**extended_key_usage.for_builder())

        if tls_feature:
            builder = builder.add_extension(**tls_feature.for_builder())

        if issuer_alternative_name:
            if not isinstance(issuer_alternative_name, IssuerAlternativeName):
                issuer_alternative_name = IssuerAlternativeName(
                    issuer_alternative_name)
            builder = builder.add_extension(
                **issuer_alternative_name.for_builder())

        if ocsp_no_check:
            builder = builder.add_extension(**OCSPNoCheck().for_builder())

        if extra_extensions:
            builder = self._extra_extensions(builder, extra_extensions)

        ###################
        # Sign public key #
        ###################
        cert = builder.sign(private_key=ca.key(password),
                            algorithm=algorithm,
                            backend=default_backend())

        return cert, req
Example #43
0
 def test_messages_view(self):
     response = self.client.get(reverse('messages'), follow=True)
     self.assertEqual(response.status_code, 200)
     self.assertTemplateUsed('messages.html')
     self.assertIn(force_bytes(self.chat.title), response.content)
Example #44
0
 def test_remove_user_from_chat_user_not_in_chat(self):
     response = self.client.get(reverse('remove_user_from_chat',
                                        kwargs={'pk': self.chat.pk,
                                                'user_pk': self.user2.pk}), follow=True)
     self.assertIn(force_bytes('Action not allowed'), response.content)
def _process_files(parsed_diff,
                   basedir,
                   repository,
                   base_commit_id,
                   request,
                   get_file_exists=None,
                   check_existence=False,
                   limit_to=None):
    """Collect metadata about files in the parser.

    Args:
        parsed_diff (reviewboard.diffviewer.parser.ParsedDiff):
            The parsed diff to process.

        basedir (unicode):
            The base directory to prepend to all file paths in the diff.

        repository (reviewboard.scmtools.models.Repository):
            The repository that the diff was created against.

        base_commit_id (unicode):
            The ID of the commit that the diff is based upon. This is
            needed by some SCMs or hosting services to properly look up
            files, if the diffs represent blob IDs instead of commit IDs
            and the service doesn't support those lookups.

        request (django.http.HttpRequest):
            The current HTTP request.

        check_existence (bool, optional):
            Whether or not existence checks should be performed against
            the upstream repository.

        get_file_exists (callable, optional):
            A callable to use to determine if a given file exists in the
            repository.

            If ``check_existence`` is ``True`` this argument must be
            provided.

        limit_to (list of unicode, optional):
            A list of filenames to limit the results to.

    Yields:
       reviewboard.diffviewer.parser.ParsedDiffFile:
       Each file present in the diff.

    Raises:
        ValueError:
            ``check_existence`` was ``True`` but ``get_file_exists`` was not
            provided.
    """
    if check_existence and get_file_exists is None:
        raise ValueError('Must provide get_file_exists when check_existence '
                         'is True')

    tool = repository.get_scmtool()
    basedir = force_bytes(basedir)

    parsed_change = parsed_diff.changes[0]

    for f in parsed_change.files:
        # This will either be a Revision or bytes. Either way, convert it
        # bytes now.
        orig_revision = force_bytes(f.orig_file_details)

        source_filename, source_revision = tool.parse_diff_revision(
            f.orig_filename, orig_revision, moved=f.moved, copied=f.copied)

        assert isinstance(source_filename, bytes), (
            '%s.parse_diff_revision() must return a bytes filename, not %r' %
            (type(tool).__name__, type(source_filename)))
        assert isinstance(source_revision, (bytes, Revision)), (
            '%s.parse_diff_revision() must return a revision which is either '
            'bytes or reviewboard.scmtools.core.Revision, not %r' %
            (type(tool).__name__, type(source_revision)))

        dest_filename = _normalize_filename(f.modified_filename, basedir)

        if limit_to is not None and dest_filename not in limit_to:
            # This file isn't actually needed for the diff, so save
            # ourselves a remote file existence check and some storage.
            continue

        source_filename = _normalize_filename(source_filename, basedir)

        # FIXME: this would be a good place to find permissions errors
        if (source_revision != PRE_CREATION and source_revision != UNKNOWN
                and not f.binary and not f.deleted and not f.moved
                and not f.copied
                and (check_existence
                     and not get_file_exists(force_text(source_filename),
                                             force_text(source_revision),
                                             base_commit_id=base_commit_id,
                                             request=request))):
            raise FileNotFoundError(force_text(source_filename),
                                    force_text(source_revision),
                                    base_commit_id)

        f.orig_filename = source_filename
        f.orig_file_details = source_revision
        f.modified_filename = dest_filename

        yield f
Example #46
0
 def test_delete_chat_not_owner(self):
     chat = Chat.objects.create(owner=self.user1, title='test_chat1')
     response = self.client.get(reverse('delete_chat', kwargs={'pk': chat.pk}), follow=True)
     self.assertEqual(len(Chat.objects.filter(title='test_chat1')), 1)
     self.assertIn(force_bytes('You can only delete your own chats'), response.content)
Example #47
0
 def path(self, name):
     """Actual file system path to name without any safety checks."""
     return os.path.normpath(os.path.join(self.location, force_bytes(name)))
Example #48
0
 def write(self, content):
     if self.read_started:
         raise ValueError("Unable to write a payload after he's been read")
     content = force_bytes(content)
     self.__content.write(content)
     self.__len += len(content)
Example #49
0
 def test_chat_users_view_user_not_in_chat(self):
     chat = Chat.objects.create(owner=self.user1, title='test_chat1')
     response = self.client.get(reverse('chat_users', kwargs={'pk': chat.pk}), follow=True)
     self.assertEqual(response.status_code, 200)
     self.assertIn(force_bytes('You can only view users from your own chats'), response.content)
Example #50
0
 def to_bytes(s):
     return force_bytes(s, settings.DEFAULT_CHARSET)
Example #51
0
def _generate_cache_header_key(key_prefix, request):
    """Return a cache key for the header cache."""
    url = hashlib.md5(force_bytes(iri_to_uri(request.build_absolute_uri())))
    cache_key = 'views.decorators.cache.cache_header.%s.%s' % (key_prefix,
                                                               url.hexdigest())
    return _i18n_cache_key_suffix(request, cache_key)
Example #52
0
def user_registration(request):
    if not request.user.is_authenticated:
        if request.method == "GET":
            # registration_form = CustomUserCreationForm()
            # login_form = AuthenticationForm()
            # context = {
            #     'registration_form': registration_form,
            #     'login_form': login_form,
            # }

            # return render(request, 'home/templates/home/index.html', context)
            return render(request, 'templates/404.html')

        elif request.method == 'POST':
            # extracting form data for user registration
            registration_form = CustomUserCreationForm(request.POST)

            # checking the validity of the form
            if registration_form.is_valid():
                password1 = registration_form.cleaned_data['password1']
                password2 = registration_form.cleaned_data['password2']

                # password and confirm password mismatch error
                if password1 != password2:
                    return HttpResponse("Password Mismatch.")
                username = registration_form.cleaned_data['username']
                email = registration_form.cleaned_data['email']
                reg_user = User.objects.filter(email=email).first()

                # checking if email is already registered
                if reg_user:
                    return HttpResponse(
                        "Email already registered. Try logging in!!")
                else:
                    reg_user = User.objects.filter(username=username).first()

                    # checking if username is already registered
                    if reg_user:
                        return HttpResponse(
                            "Username already registered. Try another one!!")
                    else:
                        # saving new user details into database with active status as false
                        user = registration_form.save(commit=False)
                        user.is_active = False
                        user.user_type = 'U'
                        user.save()
                        details = UserDetails.objects.create(user=user,
                                                             wallet_money=0)
                        details.save()

                    # Sending email process starts
                    current_site = get_current_site(request)
                    mail_subject = 'Activate your StrangeFlix account.'
                    email_context = {
                        'user': user.username,
                        'domain': current_site.domain,
                        'uid': urlsafe_base64_encode(force_bytes(user.pk)),
                        'token': account_activation_token.make_token(user),
                    }
                    # message to be displayed to user is render from a html template
                    html_message = render_to_string(
                        "accounts/acc_activate_email_template.html",
                        context=email_context)
                    to_email_list = [email]
                    # calling the send email function to send verification email and checking if mail is sent successfully
                    if send_email(subject=mail_subject,
                                  html_message=html_message,
                                  to_email=to_email_list
                                  ):  # to_email must be a tuple of list

                        response = f'A Confirmation email has been sent to {email}.' \
                                   f' Please visit the confirmation link to complete the registration and activate your account.'
                    else:
                        user.delete()
                        response = 'Mail can\'t be send now. Possible Cause - Connection Issue. Try again later sometime.'
                    return HttpResponse(response)
            else:
                # print(registration_form.errors.as_data())
                # in case of invalid form submission returning the error to user
                for e in registration_form.errors:
                    for err in registration_form.errors[e].as_data():
                        return HttpResponse(err)
                return HttpResponse("Form InValid")
    else:
        return HttpResponse("A user is already Logged In.")
Example #53
0
def dispatch_webhook_event(request, webhook_targets, event, payload):
    """Dispatch the given event and payload to the given WebHook targets.

    Args:
        request (django.http.HttpRequest):
            The HTTP request from the client.

        webhook_targets (list of
                         reviewboard.notifications.models.WebHookTarget):
            The list of WebHook targets containing endpoint URLs to dispatch
            to.

        event (unicode):
            The name of the event being dispatched.

        payload (dict):
            The payload data to encode for the WebHook payload.

    Raises:
        ValueError:
            There was an error with the payload format. Details are in the
            log and the exception message.
    """
    encoder = BasicAPIEncoder()
    bodies = {}

    raw_norm_payload = None
    json_norm_payload = None

    for webhook_target in webhook_targets:
        use_custom_content = webhook_target.use_custom_content
        encoding = webhook_target.encoding

        # See how we need to handle normalizing this payload. If we need
        # something JSON-safe, then we need to go the more aggressive route
        # and normalize keys to strings.
        if raw_norm_payload is None or json_norm_payload is None:
            try:
                if (raw_norm_payload is None
                        and (use_custom_content
                             or encoding == webhook_target.ENCODING_XML)):
                    # This payload's going to be provided for XML and custom
                    # templates. We don't want to alter the keys at all.
                    raw_norm_payload = normalize_webhook_payload(
                        payload=payload, request=request)
                elif (json_norm_payload is None and not use_custom_content
                      and encoding in (webhook_target.ENCODING_JSON,
                                       webhook_target.ENCODING_FORM_DATA)):
                    # This payload's going to be provided for JSON or
                    # form-data. We want to normalize all keys to strings.
                    json_norm_payload = normalize_webhook_payload(
                        payload=payload, request=request, use_string_keys=True)
            except TypeError as e:
                logging.exception(
                    'WebHook payload passed to '
                    'dispatch_webhook_event containing invalid '
                    'data types: %s', e)

                raise ValueError(six.text_type(e))

        if use_custom_content:
            try:
                assert raw_norm_payload is not None
                body = render_custom_content(webhook_target.custom_content,
                                             raw_norm_payload)
                body = force_bytes(body)
            except Exception as e:
                logging.exception('Could not render WebHook payload: %s', e)
                continue
        else:
            if encoding not in bodies:
                try:
                    if encoding == webhook_target.ENCODING_JSON:
                        assert json_norm_payload is not None
                        adapter = JSONEncoderAdapter(encoder)
                        body = adapter.encode(json_norm_payload,
                                              request=request)
                    elif encoding == webhook_target.ENCODING_XML:
                        assert raw_norm_payload is not None
                        adapter = XMLEncoderAdapter(encoder)
                        body = adapter.encode(raw_norm_payload,
                                              request=request)
                    elif encoding == webhook_target.ENCODING_FORM_DATA:
                        assert json_norm_payload is not None
                        adapter = JSONEncoderAdapter(encoder)
                        body = urlencode({
                            'payload':
                            adapter.encode(json_norm_payload, request=request),
                        })
                    else:
                        logging.error(
                            'Unexpected WebHookTarget encoding "%s" '
                            'for ID %s', encoding, webhook_target.pk)
                        continue
                except Exception as e:
                    logging.exception('Could not encode WebHook payload: %s',
                                      e)
                    continue

                body = force_bytes(body)
                bodies[encoding] = body
            else:
                body = bodies[encoding]

        headers = {
            'X-ReviewBoard-Event': event,
            'Content-Type': webhook_target.encoding,
            'Content-Length': '%s' % len(body),
            'User-Agent': 'ReviewBoard-WebHook/%s' % get_package_version(),
        }

        if webhook_target.secret:
            signer = hmac.new(webhook_target.secret.encode('utf-8'), body,
                              hashlib.sha1)
            headers['X-Hub-Signature'] = 'sha1=%s' % signer.hexdigest()

        logging.info('Dispatching webhook for event %s to %s', event,
                     webhook_target.url)

        try:
            url = webhook_target.url
            url_parts = urlsplit(url)

            if url_parts.username or url_parts.password:
                credentials, netloc = url_parts.netloc.split('@', 1)
                url = urlunsplit((url_parts.scheme, netloc, url_parts.path,
                                  url_parts.query, url_parts.fragment))
                headers['Authorization'] = \
                    'Basic %s' % b64encode(credentials.encode('utf-8'))

            if six.PY2:
                headers = {
                    force_str(key): force_str(value)
                    for key, value in six.iteritems(headers)
                }

            urlopen(Request(url, body, headers))
        except Exception as e:
            logging.exception('Could not dispatch WebHook to %s: %s',
                              webhook_target.url, e)

            if isinstance(e, HTTPError):
                logging.info('Error response from %s: %s %s\n%s',
                             webhook_target.url, e.code, e.reason, e.read())
Example #54
0
 def test_messages_chat_creation(self):
     response = self.client.post(reverse('messages'), data={'title': 'test_chat1'}, follow=True)
     chat = Chat.objects.get(title='test_chat1')
     self.assertTrue(isinstance(chat, Chat))
     self.assertEqual(response.status_code, 200)
     self.assertIn(force_bytes(chat.title), response.content)
Example #55
0
    def post_process(self, paths, dry_run=False, **options):
        """
        Post process the given OrderedDict of files (called from collectstatic).

        Processing is actually two separate operations:

        1. renaming files to include a hash of their content for cache-busting,
           and copying those files to the target storage.
        2. adjusting files which contain references to other files so they
           refer to the cache-busting filenames.

        If either of these are performed on a file, then that file is considered
        post-processed.
        """
        # don't even dare to process the files if we're in dry run mode
        if dry_run:
            return

        # where to store the new paths
        hashed_files = OrderedDict()

        # build a list of adjustable files
        matches = lambda path: matches_patterns(path, self._patterns.keys())
        adjustable_paths = [path for path in paths if matches(path)]

        # then sort the files by the directory level
        path_level = lambda name: len(name.split(os.sep))
        for name in sorted(paths.keys(), key=path_level, reverse=True):

            # use the original, local file, not the copied-but-unprocessed
            # file, which might be somewhere far away, like S3
            storage, path = paths[name]
            with storage.open(path) as original_file:

                # generate the hash with the original content, even for
                # adjustable files.
                hashed_name = self.hashed_name(name, original_file)

                # then get the original's file content..
                if hasattr(original_file, 'seek'):
                    original_file.seek(0)

                hashed_file_exists = self.exists(hashed_name)
                processed = False

                # ..to apply each replacement pattern to the content
                if name in adjustable_paths:
                    content = original_file.read().decode(
                        settings.FILE_CHARSET)
                    for patterns in self._patterns.values():
                        for pattern, template in patterns:
                            converter = self.url_converter(name, template)
                            try:
                                content = pattern.sub(converter, content)
                            except ValueError as exc:
                                yield name, None, exc
                    if hashed_file_exists:
                        self.delete(hashed_name)
                    # then save the processed result
                    content_file = ContentFile(force_bytes(content))
                    saved_name = self._save(hashed_name, content_file)
                    hashed_name = force_text(self.clean_name(saved_name))
                    processed = True
                else:
                    # or handle the case in which neither processing nor
                    # a change to the original file happened
                    if not hashed_file_exists:
                        processed = True
                        saved_name = self._save(hashed_name, original_file)
                        hashed_name = force_text(self.clean_name(saved_name))

                # and then set the cache accordingly
                hashed_files[self.hash_key(name)] = hashed_name
                yield name, hashed_name, processed

        # Finally store the processed paths
        self.hashed_files.update(hashed_files)
Example #56
0
 def hash_key(self, name):
     key = hashlib.md5(force_bytes(self.clean_name(name))).hexdigest()
     return 'staticfiles:%s' % key
Example #57
0
import hashlib
import hmac
import struct
from colorsys import hsv_to_rgb

from django.utils.encoding import force_bytes
from django.conf import settings

STYLE_SECRET_SAUCE = force_bytes(
    getattr(settings, 'PAIKKALA_STYLE_SECRET_SAUCE', ''))


def decimal_rgb_to_hex(rgb):
    return '#%02x%02x%02x' % (
        int(rgb[0] * 255),
        int(rgb[1] * 255),
        int(rgb[2] * 255),
    )


def compute_program_style(program):
    noise = hmac.HMAC(key=STYLE_SECRET_SAUCE,
                      msg=force_bytes(program.name),
                      digestmod=hashlib.sha256).digest()
    random_values = [v / (2 << 31) for v in struct.unpack('<IIIIIIII', noise)]
    hue1 = random_values[0]
    hue2 = (hue1 + 0.8) % 1.0
    sat1 = 0.6 + random_values[1] * 0.4
    sat2 = 0.6 + random_values[2] * 0.4
    val1 = 0.6 + random_values[3] * 0.3
    val2 = 0.6 + random_values[4] * 0.3
Example #58
0
    def dispatch(self, request, project_id=None, *args, **kwargs):
        helper = self.helper_cls(
            agent=request.META.get('HTTP_USER_AGENT'),
            project_id=project_id,
            ip_address=request.META['REMOTE_ADDR'],
        )
        origin = None

        try:
            origin = helper.origin_from_request(request)

            response = self._dispatch(request,
                                      helper,
                                      project_id=project_id,
                                      origin=origin,
                                      *args,
                                      **kwargs)
        except APIError as e:
            context = {
                'error': force_bytes(e.msg, errors='replace'),
            }
            if e.name:
                context['error_name'] = e.name

            response = HttpResponse(json.dumps(context),
                                    content_type='application/json',
                                    status=e.http_status)
            # Set X-Sentry-Error as in many cases it is easier to inspect the headers
            response['X-Sentry-Error'] = context['error']

            if isinstance(e, APIRateLimited) and e.retry_after is not None:
                response['Retry-After'] = six.text_type(e.retry_after)

        except Exception as e:
            # TODO(dcramer): test failures are not outputting the log message
            # here
            if settings.DEBUG:
                content = traceback.format_exc()
            else:
                content = ''
            logger.exception(e)
            response = HttpResponse(content,
                                    content_type='text/plain',
                                    status=500)

        # TODO(dcramer): it'd be nice if we had an incr_multi method so
        # tsdb could optimize this
        metrics.incr('client-api.all-versions.requests')
        metrics.incr('client-api.all-versions.responses.%s' %
                     (response.status_code, ))
        metrics.incr('client-api.all-versions.responses.%sxx' %
                     (six.text_type(response.status_code)[0], ))

        if helper.context.version:
            metrics.incr('client-api.v%s.requests' %
                         (helper.context.version, ))
            metrics.incr('client-api.v%s.responses.%s' %
                         (helper.context.version, response.status_code))
            metrics.incr('client-api.v%s.responses.%sxx' %
                         (helper.context.version,
                          six.text_type(response.status_code)[0]))

        if response.status_code != 200 and origin:
            # We allow all origins on errors
            response['Access-Control-Allow-Origin'] = '*'

        if origin:
            response['Access-Control-Allow-Headers'] = \
                'X-Sentry-Auth, X-Requested-With, Origin, Accept, ' \
                'Content-Type, Authentication'
            response['Access-Control-Allow-Methods'] = \
                ', '.join(self._allowed_methods())
            response['Access-Control-Expose-Headers'] = \
                'X-Sentry-Error, Retry-After'

        return response
Example #59
0
 def test_chat_new_message(self):
     data = {'from_user': self.user, 'chat': self.chat, 'body': 'test'}
     response = self.client.post(reverse('chat', kwargs={'pk': self.chat.pk}), data=data)
     message = Message.objects.filter(from_user=self.user, chat=self.chat, body='test').first()
     self.assertTrue(isinstance(message, Message))
     self.assertIn(force_bytes(message.body), response.content)
Example #60
0
def get_cookie_signer(salt='django.core.signing.get_cookie_signer'):
    Signer = import_string(settings.SIGNING_BACKEND)
    key = force_bytes(settings.SECRET_KEY)
    return Signer(b'django.http.cookies' + key, salt=salt)