Example #1
0
def avatar_file_path(instance=None, filename=None, size=None, ext=None):
    tmppath = [AVATAR_STORAGE_DIR]
    if AVATAR_HASH_USERDIRNAMES:
        tmp = md5_constructor(instance.user.username).hexdigest()
        tmppath.extend([tmp[0], tmp[1], instance.user.username])
    else:
        tmppath.append(instance.user.username)
    if not filename:
        # Filename already stored in database
        filename = instance.avatar.name
        if ext and AVATAR_HASH_FILENAMES:
            # An extension was provided, probably because the thumbnail
            # is in a different format than the file. Use it. Because it's
            # only enabled if AVATAR_HASH_FILENAMES is true, we can trust
            # it won't conflict with another filename
            (root, oldext) = os.path.splitext(filename)
            filename = root + "." + ext
    else:
        # File doesn't exist yet
        if AVATAR_HASH_FILENAMES:
            (root, ext) = os.path.splitext(filename)
            filename = md5_constructor(smart_str(filename)).hexdigest()
            filename = filename + ext
    if size:
        tmppath.extend(['resized', str(size)])
    tmppath.append(os.path.basename(filename))
    return os.path.join(*tmppath)
Example #2
0
 def __init__(self, metadata, instances, path, site=None, language=None):
     self.__metadata = metadata
     if metadata._meta.use_cache:
         if metadata._meta.use_sites and site:
             hexpath = md5_constructor(iri_to_uri(site.domain+path)).hexdigest()
         else:
             hexpath = md5_constructor(iri_to_uri(path)).hexdigest()
         if metadata._meta.use_i18n:
             self.__cache_prefix = 'rollyourown.seo.%s.%s.%s' % (self.__metadata.__class__.__name__, hexpath, language)
         else:
             self.__cache_prefix = 'rollyourown.seo.%s.%s' % (self.__metadata.__class__.__name__, hexpath)
     else:
         self.__cache_prefix = None
     self.__instances_original = instances
     self.__instances_cache = []
Example #3
0
 def render(self, context):
     # Try to resolve the variables.  If they are not resolve-able, then use
     # the provided name itself.
     try:
         email = self.email.resolve(context)
     except template.VariableDoesNotExist:
         email = self.email.var
     try:
         rating = self.rating.resolve(context)
     except template.VariableDoesNotExist:
         rating = self.rating.var
     try:
         size = self.size.resolve(context)
     except template.VariableDoesNotExist:
         size = self.size.var
     except AttributeError:
         size = self.size
     try:
         default = self.default.resolve(context)
     except template.VariableDoesNotExist:
         default = self.default.var
     
     gravatargs = {
         'hash': md5_constructor(email).hexdigest(),
         'rating': rating,
         'size': size,
         'default': urllib.quote_plus(default),
     }
     url = GRAVATAR_URL % gravatargs
     if 'as' in self.other_kwargs:
         context[self.other_kwargs['as']] = mark_safe(url)
         return ''
     return url
    def check_request(self, request):
        """Check that the given request is valid for this session.

        It's valid if its fingerprint hash matches the current hash, or
        if the duplicate nonce window is enabled and it matches a sufficiently
        recent hash.
        """
        if request.is_secure():
            if self.secure_key is None:
                seed = (randrange(0, MAX_NONCE_SEED), settings.SECRET_KEY)
                self.secure_key = md5_constructor("%s%s" % seed).hexdigest()
                request.session.modified = True
            else:
                cookie_name = settings.PSESSION_SECURE_COOKIE_NAME
                key = request.COOKIES.get(cookie_name, "")
                if key != self.secure_key:
                    return False
        hash = self.request_hash(request)
        if hash != self.hash:
            return False
        if settings.PSESSION_NONCE_TIMEOUT is not None:
            nonce = request.COOKIES.get(settings.PSESSION_COOKIE_NAME, "")
            if nonce not in self.get_valid_nonces():
                return False
        self.last_request_time = time.time()
        return True
Example #5
0
    def render(self, context):
        # Try to resolve the variables.  If they are not resolve-able, then use
        # the provided name itself.
        try:
            email = self.email.resolve(context)
        except template.VariableDoesNotExist:
            email = self.email.var
        try:
            rating = self.rating.resolve(context)
        except template.VariableDoesNotExist:
            rating = self.rating.var
        try:
            size = self.size.resolve(context)
        except template.VariableDoesNotExist:
            size = self.size.var
        except AttributeError:
            size = self.size
        try:
            default = self.default.resolve(context)
        except template.VariableDoesNotExist:
            default = self.default.var

        gravatargs = {
            'hash': md5_constructor(email).hexdigest(),
            'rating': rating,
            'size': size,
            'default': urllib.parse.quote_plus(default),
        }
        url = GRAVATAR_URL % gravatargs
        if 'as' in self.other_kwargs:
            context[self.other_kwargs['as']] = mark_safe(url)
            return ''
        return url
Example #6
0
def registration(request):

    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            user = User(
                username=form.cleaned_data['username'],
                email=form.cleaned_data['email'],
                first_name=form.cleaned_data['first_name'],
                last_name=form.cleaned_data['last_name'],
                is_active=False,
            )
            user.set_password(form.cleaned_data['password'])
            user.save()
            hash = md5_constructor(str(user.id) + form.cleaned_data['username']).hexdigest()
            confirm = RegConfirm(hash=hash, user_id=user.id)
            confirm.save()
            current_site = Site.objects.get(id=1)
            message = u'Поздравляем! Вы зарегистрировались на %s . Пожалуйста, пройдите по адресу %s для активации учетной записи.' % \
                      (current_site.domain, "http://" + current_site.domain + "/accounts/confirm/" + hash, )


            send_mail(u'Активация аккаунта ' + current_site.domain, message, 'system@'+current_site.domain,
                [form.cleaned_data['email']])

            return render(request, 'accounts/frontend/registration_done.html')
    else:
        form = RegistrationForm()
    return render(request, 'accounts/frontend/registration.html', {
        'form':form
    })
Example #7
0
    def backwards(self, orm):
        
        # Removing index on 'Thumbnail', fields ['storage_hash']
        db.delete_index('easy_thumbnails_thumbnail', ['storage_hash'])

        # Removing index on 'Source', fields ['storage_hash']
        db.delete_index('easy_thumbnails_source', ['storage_hash'])

        # Adding model 'Storage'
        db.create_table('easy_thumbnails_storage', (
            ('pickle', self.gf('django.db.models.fields.TextField')()),
            ('hash', self.gf('django.db.models.fields.CharField')(max_length=40, db_index=True)),
            ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
        ))
        db.send_create_signal('easy_thumbnails', ['Storage'])

        # Create a storage object. This may obviously not be the storage
        # object which the source / thumbnail objects actually belong to but
        # at least it lets us reverse migrate.
        storage = orm.Storage()
        storage.pickle = pickle.dumps(default_storage)
        storage.hash = md5_constructor(storage.pickle).hexdigest()
        storage.save()

        # Adding field 'Source.storage'
        db.add_column('easy_thumbnails_source', 'storage', self.gf('django.db.models.fields.related.ForeignKey')(default=storage.pk, to=orm['easy_thumbnails.Storage']), keep_default=False)

        # Adding field 'Thumbnail.storage'
        db.add_column('easy_thumbnails_thumbnail', 'storage', self.gf('django.db.models.fields.related.ForeignKey')(default=storage.pk, to=orm['easy_thumbnails.Storage']), keep_default=False)
Example #8
0
 def __getitem__(self, item):
     if item in ('PositiveIntegerField', 'PositiveSmallIntegerField'):
         # The check name must be unique for the database. Add a random
         # component so the regresion tests don't complain about duplicate names
         fldtype = {'PositiveIntegerField': 'int', 'PositiveSmallIntegerField': 'smallint'}[item]
         rnd_hash = md5_constructor(str(random.random())).hexdigest()
         unique = base64.b64encode(rnd_hash, '__')[:6]
         return '%(fldtype)s CONSTRAINT [CK_%(fldtype)s_pos_%(unique)s_%%(column)s] CHECK ([%%(column)s] >= 0)' % locals()
     return super(DataTypesWrapper, self).__getitem__(item)
    def request_hash(self, request):
        """Create a hash of the given request's fingerprint data.

        This hash will contain data that should be the same for every request
        in this session.
        """
        hash = md5_constructor()
        if settings.PSESSION_CHECK_HEADERS:
            for header in settings.PSESSION_CHECK_HEADERS:
                hash.update(request.META.get(header, ""))
        return hash.digest()
Example #10
0
def gravatar(email):
    """
    Takes an e-mail address and returns a gravatar image URL, using properties
    from the django settings file.
    """
    hashed_email = md5_constructor(email).hexdigest()
    return mark_safe(GRAVATAR_URL % {
        'hash': hashed_email,
        'rating': GRAVATAR_MAX_RATING, 
        'size': GRAVATAR_SIZE,
        'default': urllib.quote_plus(GRAVATAR_DEFAULT_IMG),
    })
Example #11
0
def gravatar(email):
    """
    Takes an e-mail address and returns a gravatar image URL, using properties
    from the django settings file.
    """
    hashed_email = md5_constructor(email).hexdigest()
    return mark_safe(
        GRAVATAR_URL % {
            'hash': hashed_email,
            'rating': GRAVATAR_MAX_RATING,
            'size': GRAVATAR_SIZE,
            'default': urllib.parse.quote_plus(GRAVATAR_DEFAULT_IMG),
        })
Example #12
0
def test_cache():
    html = '<ul><li><a href="/page/">page</a></li></ul>'
    template = '{% activeurl %}<ul><li><a href="/page/">page</a></li></ul>{% endactiveurl %}'

    context = {'request': requests.get('/page/')}
    set_cache = render(template, context)

    cache_key = 'django_activeurl.' \
    + md5_constructor(
        html + 'active' + 'li' + '/page/'
    ).hexdigest()

    assert cache.get(cache_key)
Example #13
0
 def __getitem__(self, item):
     if item in ('PositiveIntegerField', 'PositiveSmallIntegerField'):
         # The check name must be unique for the database. Add a random
         # component so the regresion tests don't complain about duplicate names
         fldtype = {
             'PositiveIntegerField': 'int',
             'PositiveSmallIntegerField': 'smallint'
         }[item]
         rnd_hash = md5_constructor(str(random.random())).hexdigest()
         unique = base64.b64encode(rnd_hash, '__')[:6]
         return '%(fldtype)s CONSTRAINT [CK_%(fldtype)s_pos_%(unique)s_%%(column)s] CHECK ([%%(column)s] >= 0)' % locals(
         )
     return super(DataTypesWrapper, self).__getitem__(item)
Example #14
0
    def test_use_cache(self):
        """ Checks that cache is being used when use_cache is set.
            Will only work if cache backend is not dummy.
        """
        if 'dummy' not in settings.CACHE_BACKEND:
            path = '/'
            hexpath = md5_constructor(iri_to_uri(path)).hexdigest()

            #unicode(seo_get_metadata(path, name="Coverage"))
            unicode(seo_get_metadata(path, name="WithCache"))

            self.assertEqual(cache.get('rollyourown.seo.Coverage.%s.title' % hexpath), None)
            self.assertEqual(cache.get('rollyourown.seo.WithCache.%s.title' % hexpath), "1234")
            self.assertEqual(cache.get('rollyourown.seo.WithCache.%s.subtitle' % hexpath), "")
Example #15
0
def get_storage_hash(storage):
    """
    Return a hex string hash for a storage object (or string containing
    'full.path.ClassName' referring to a storage object).
    """
    # If storage is wrapped in a lazy object we need to get the real thing.
    if isinstance(storage, LazyObject):
        if storage._wrapped is None:
            storage._setup()
        storage = storage._wrapped
    if not isinstance(storage, basestring):
        storage_cls = storage.__class__
        storage = '%s.%s' % (storage_cls.__module__, storage_cls.__name__)
    return md5_constructor(storage).hexdigest()
Example #16
0
    def test_use_cache_i18n(self):
        """ Checks that the cache plays nicely with i18n.
        """
        if 'dummy' not in settings.CACHE_BACKEND:
            path = '/'
            hexpath = md5_constructor(iri_to_uri(path)).hexdigest()

            #unicode(seo_get_metadata(path, name="Coverage"))
            unicode(seo_get_metadata(path, name="WithCacheI18n", language='de'))

            self.assertEqual(cache.get('rollyourown.seo.Coverage.%s.de.title' % hexpath), None)
            self.assertEqual(cache.get('rollyourown.seo.WithCacheI18n.%s.en.title' % hexpath), None)
            self.assertEqual(cache.get('rollyourown.seo.WithCacheI18n.%s.de.title' % hexpath), "1234")
            self.assertEqual(cache.get('rollyourown.seo.WithCacheI18n.%s.de.subtitle' % hexpath), "")
Example #17
0
    def test_use_cache_site(self):
        """ Checks that the cache plays nicely with sites.
        """
        if 'dummy' not in settings.CACHE_BACKEND:
            path = '/'
            site = Site.objects.get_current()
            hexpath = md5_constructor(iri_to_uri(site.domain+path)).hexdigest()

            #unicode(seo_get_metadata(path, name="Coverage"))
            unicode(seo_get_metadata(path, name="WithCacheSites", site=site))

            self.assertEqual(cache.get('rollyourown.seo.Coverage.%s.title' % hexpath), None)
            self.assertEqual(cache.get('rollyourown.seo.WithCacheSites.%s.title' % hexpath), "1234")
            self.assertEqual(cache.get('rollyourown.seo.WithCacheSites.%s.subtitle' % hexpath), "")
Example #18
0
def get_storage_hash(storage):
    """
    Return a hex string hash for a storage object (or string containing
    'full.path.ClassName' referring to a storage object).
    """
    # If storage is wrapped in a lazy object we need to get the real thing.
    if isinstance(storage, LazyObject):
        if storage._wrapped is None:
            storage._setup()
        storage = storage._wrapped
    if not isinstance(storage, six.string_types):
        storage_cls = storage.__class__
        storage = '%s.%s' % (storage_cls.__module__, storage_cls.__name__)
    return md5_constructor(storage.encode('utf8')).hexdigest()
Example #19
0
def get_gravatar(email, size=80, default='identicon'):
    """ Get Gravatar from an email address.

    :param size:
        The size in pixels of one side of the Gravatar's square image.
        Optional, if not supplied will default to ``80``.

    :param default:
        Defines what should be displayed if no image is found for this user.
        Optional argument which defaults to ``identicon``. The argument can be
        a URI to an image or one of the following options:

            ``404``
                Do not load any image if none is associated with the email
                hash, instead return an HTTP 404 (File Not Found) response.

            ``mm``
                Mystery-man, a simple, cartoon-style silhouetted outline of a
                person (does not vary by email hash).

            ``identicon``
                A geometric pattern based on an email hash.

            ``monsterid``
                A generated 'monster' with different colors, faces, etc.

            ``wavatar``
                Generated faces with differing features and backgrounds

            ``retro``
                Awesome generated, 8-bit arcade-style pixelated faces

            ``blank``
                A transparent PNG image (border added to HTML below for demonstration purposes)

    :return: The URI pointing to the Gravatar.

    """
    if account_settings.ACCOUNT_PHOTO_SECURE:
        base_url = 'https://secure.gravatar.com/avatar/'
    else:
        base_url = 'http://www.gravatar.com/avatar/'

    gravatar_url = '%(base_url)s%(gravatar_id)s?' % {'base_url': base_url,
        'gravatar_id': md5_constructor(email.lower()).hexdigest()}

    gravatar_url += urllib.urlencode({'s': str(size),'d': default})
    return gravatar_url
    def run(self, params={}):
        if self.cache_timeout_seconds is None:
            return self.query.run(return_one=self.return_one, return_list=self.return_list,
                                  params=params)

        cache_name = getattr(settings, 'APIHANGAR_CACHE', "default")
        cache = caches[cache_name]
        args = md5_constructor(json_dumps(params)).hexdigest()
        cache_key = "apihangar.endpoint_query.%s.%s" % (self.id, args)
        result = cache.get(cache_key)
        if result is not None:
            return result

        result = self.query.run(return_one=self.return_one, return_list=self.return_list,
                                params=params)
        cache.set(cache_key, result, self.cache_timeout_seconds)
        return result
Example #21
0
            def wrapper(*args, **kwargs):
                md5 = md5_constructor()
                md5.update('{}.{}'.format(func.__module__, func.__name__))
                if extra:
                    md5.update(str(extra))
                if args:
                    md5.update(repr(args))
                if kwargs:
                    md5.update(repr(sorted(kwargs.items())))

                cache_key = 'c:{}'.format(md5.hexdigest())

                try:
                    result = self.get(cache_key)
                except (ValueError, TypeError):
                    result = func(*args, **kwargs)
                    self.set(cache_key, result, timeout)
                return result
Example #22
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 #23
0
 def get_storage_hash(self, storage):
     """
     Return a hex string hash for a storage object (or string containing a
     pickle of a storage object).
     
     """
     try:
         # Make sure that pickle is getting a string, since it can choke
         # with unicode.
         storage_obj = pickle.loads(str(self.pickle))
     except:
         # We need to return some storage, and if there's an exception then
         # it is most likely the default_storage (since that fails with a
         # recursion error due to LazyObject "awesomeness").
         storage_obj = default_storage
     storage_cls = storage_obj.__class__
     name = '%s.%s' % (storage_cls.__module__, storage_cls.__name__)
     return md5_constructor(name).hexdigest()
            def wrapper(*args, **kwargs):
                md5 = md5_constructor()
                md5.update('{0}.{1}'.format(func.__module__, func.__name__))
                if extra:
                    md5.update(str(extra))
                if args:
                    md5.update(repr(args))
                if kwargs:
                    md5.update(repr(sorted(kwargs.items())))

                cache_key = 'c:{0}'.format(md5.hexdigest())

                try:
                    result = self.get(cache_key)
                except (ValueError, TypeError):
                    result = func(*args, **kwargs)
                    self.set(cache_key, result, timeout)
                return result
 def get_storage_hash(self, storage):
     """
     Return a hex string hash for a storage object (or string containing a
     pickle of a storage object).
     
     """
     try:
         # Make sure that pickle is getting a string, since it can choke
         # with unicode.
         storage_obj = pickle.loads(str(self.pickle))
     except:
         # We need to return some storage, and if there's an exception then
         # it is most likely the default_storage (since that fails with a
         # recursion error due to LazyObject "awesomeness").
         storage_obj = default_storage
     storage_cls = storage_obj.__class__
     name = '%s.%s' % (storage_cls.__module__, storage_cls.__name__)
     return md5_constructor(name).hexdigest()
Example #26
0
def get_gravatar(email, size=80, default="identicon"):
    """ Get's a Gravatar for a email address.

    :param size:
        The size in pixels of one side of the Gravatar's square image.
        Optional, if not supplied will default to ``80``.

    :param default:
        Defines what should be displayed if no image is found for this user.
        Optional argument which defaults to ``identicon``. The argument can be
        a URI to an image or one of the following options:

            ``404``
                Do not load any image if none is associated with the email
                hash, instead return an HTTP 404 (File Not Found) response.

            ``mm``
                Mystery-man, a simple, cartoon-style silhouetted outline of a
                person (does not vary by email hash).

            ``identicon``
                A geometric pattern based on an email hash.

            ``monsterid``
                A generated 'monster' with different colors, faces, etc.

            ``wavatar``
                Generated faces with differing features and backgrounds

    :return: The URI pointing to the Gravatar.

    """
    if userena_settings.USERENA_MUGSHOT_GRAVATAR_SECURE:
        base_url = "https://secure.gravatar.com/avatar/"
    else:
        base_url = "//www.gravatar.com/avatar/"

    gravatar_url = "%(base_url)s%(gravatar_id)s?" % {
        "base_url": base_url,
        "gravatar_id": md5_constructor(email.lower()).hexdigest(),
    }

    gravatar_url += urllib.urlencode({"s": str(size), "d": default})
    return gravatar_url
Example #27
0
def get_gravatar(email, size=80, default='identicon'):
    """ Get's a Gravatar for a email address.

    :param size:
        The size in pixels of one side of the Gravatar's square image.
        Optional, if not supplied will default to ``80``.

    :param default:
        Defines what should be displayed if no image is found for this user.
        Optional argument which defaults to ``identicon``. The argument can be
        a URI to an image or one of the following options:

            ``404``
                Do not load any image if none is associated with the email
                hash, instead return an HTTP 404 (File Not Found) response.

            ``mm``
                Mystery-man, a simple, cartoon-style silhouetted outline of a
                person (does not vary by email hash).

            ``identicon``
                A geometric pattern based on an email hash.

            ``monsterid``
                A generated 'monster' with different colors, faces, etc.

            ``wavatar``
                Generated faces with differing features and backgrounds

    :return: The URI pointing to the Gravatar.

    """
    if userena_settings.USERENA_MUGSHOT_GRAVATAR_SECURE:
        base_url = 'https://secure.gravatar.com/avatar/'
    else:
        base_url = '//www.gravatar.com/avatar/'

    gravatar_url = '%(base_url)s%(gravatar_id)s?' % \
            {'base_url': base_url,
             'gravatar_id': md5_constructor(email.lower()).hexdigest()}

    gravatar_url += urllib.urlencode({'s': str(size), 'd': default})
    return gravatar_url
Example #28
0
def invalidate_template_cache(fragment_name, *variables):
    """
    From http://djangosnippets.org/snippets/1593/
    
    This function invalidates a template-fragment cache bit.

    say you have:

    {% load cache %}
    {% cache 600 user_cache user.id %} something expensive here {% endcache %}

    To invalidate:

    invalidate_template_cache("user_cache", user.id)
    """
    args = md5_constructor(u':'.join([urlquote(unicode(v)) for v in variables]))
    cache_key = 'template.cache.%s.%s' % (fragment_name, args.hexdigest())
    cache.delete(cache_key)
    return cache_key
Example #29
0
def invalidate_template_cache(fragment_name, *variables):
    args = md5_constructor(u':'.join([urlquote(var) for var in variables]))
    cache_key = 'template.cache.%s.%s' % (fragment_name, args.hexdigest())
    cache.delete(cache_key)
    return
Example #30
0
def template_cache_name(fragment_name, *variables):
    args = md5_constructor(u':'.join([urlquote(var) for var in variables]))
    return 'template.cache.%s.%s' % (fragment_name, args.hexdigest())
 def _path(self, name):
     return os.path.join(self.cache_dir, md5_constructor(smart_str(name)).hexdigest())
Example #32
0
 def _get_query_key(self, request):
     """
     Returns an MD5 has of the request's query parameters.
     """
     querystring = request.GET.urlencode()
     return md5_constructor(querystring).hexdigest()
Example #33
0
 def _get_query_key(self, request):
     """
     Returns an MD5 has of the request's query parameters.
     """
     querystring = request.GET.urlencode()
     return md5_constructor(querystring.encode('UTF-8')).hexdigest()
Example #34
0
File: captcha.py Project: affix/fas
 def generate_captcha_text(self):
     """Automagically generates a string of text based on a key (length is from file default or override)"""
     return ''.join(
         md5_constructor("%s|%s|%s" %
                         (captcha__site_secret, self.captcha_key,
                          self.captcha_time_start)).hexdigest()[0:6])
Example #35
0
 def get_cache_key(self, netloc):
     """Returns a cache key based on ``netloc``."""
     netloc = md5_constructor(netloc)
     return 'multisite.alias.%s.%s' % (self.key_prefix,
                                       netloc.hexdigest())
Example #36
0
 def get_cache_key(self, netloc):
     """Returns a cache key based on ``netloc``."""
     netloc = md5_constructor(netloc.encode('utf-8'))
     return 'multisite.alias.%s.%s' % (self.key_prefix, netloc.hexdigest())
Example #37
0
File: captcha.py Project: Affix/fas
 def generate_captcha_text(self):
     """Automagically generates a string of text based on a key (length is from file default or override)"""
     return ''.join(md5_constructor("%s|%s|%s" %(captcha__site_secret,self.captcha_key,self.captcha_time_start)).hexdigest()[0:6])
 def __init__(self):
     seed = (randrange(0, MAX_NONCE_SEED), settings.SECRET_KEY)
     self.state = md5_constructor("%s%s" % seed).hexdigest()
 def nonces(self):
     """Generator producing sequence of nonce values."""
     state = self.state
     while True:
         yield state
         state = md5_constructor(state + settings.SECRET_KEY).hexdigest()
Example #40
0
    def save(self, *args, **kwargs):
        """Save the CertificateAuthority object"""

        # Set user to None if it's missing
        c_user = getattr(self, "user", None)
        # Variables to track changes
        c_action = self.action
        c_list = []

        if self.pk:
            if self.action in ("update", "revoke", "renew"):
                action = Openssl(self)
                prev = CertificateAuthority.objects.get(pk=self.pk)

                if self.action in ("revoke", "renew"):
                    if self.action == "revoke":
                        if not self.parent:
                            raise Exception("You cannot revoke a self-signed certificate! No parent => No revoke")

                        action.revoke_certificate(self.parent_passphrase)
                        action.generate_crl(self.parent.name, self.parent_passphrase)

                        prev.active = False
                        prev.der_encoded = False
                        prev.revoked = datetime.datetime.now()

                        c_list.append('Revoked certificate "%s"' % self.common_name)
                    elif self.action == "renew":
                        c_list.append('Renewed certificate "%s"' % self.common_name)

                        if self.parent and not action.get_revoke_status_from_cert():
                            action.revoke_certificate(self.parent_passphrase)
                            action.generate_crl(self.parent.name, self.parent_passphrase)

                        self.rebuild_ca_metadata(modify=True, task="replace")

                        if not self.parent:
                            action.generate_self_signed_cert()
                            action.generate_crl(self.name, self.passphrase)
                        else:
                            action.generate_csr()
                            action.sign_csr()
                            action.generate_crl(self.parent.name, self.parent_passphrase)

                        action.update_ca_chain_file()

                        prev.created = datetime.datetime.now()
                        delta = datetime.timedelta(self.valid_days)
                        prev.expiry_date = datetime.datetime.now() + delta

                        if prev.valid_days != self.valid_days:
                            c_list.append("Changed valid days from %d to %d" % (prev.valid_days, self.valid_days))

                        prev.valid_days = self.valid_days
                        prev.active = True
                        prev.revoked = None

                        if prev.country != self.country:
                            c_list.append('Updated country to "%s"' % self.country)
                        if prev.locality != self.locality:
                            c_list.append('Updated locality to "%s"' % self.locality)
                        if prev.organization != self.organization:
                            c_list.append('Updated organization to "%s"' % self.organization)
                        if prev.email != self.email:
                            c_list.append('Updated email to "%s"' % self.email)
                        if prev.OU != self.OU:
                            c_list.append('Updated OU to "%s"' % self.OU)

                        prev.country = self.country
                        prev.locality = self.locality
                        prev.organization = self.organization
                        prev.email = self.email
                        prev.OU = self.OU

                        prev.serial = action.get_serial_from_cert()
                        c_list.append("Serial number changed to %s" % prev.serial)

                    garbage = []
                    id_dict = {
                        "cert": [],
                        "ca": [],
                    }

                    from .views import chain_recursion as r_chain_recursion

                    r_chain_recursion(self.id, garbage, id_dict)

                    for i in id_dict["cert"]:
                        x = Certificate.objects.get(pk=i)
                        x.active = False
                        x.der_encoded = False
                        x.pkcs12_encoded = False
                        x.revoked = datetime.datetime.now()

                        super(Certificate, x).save(*args, **kwargs)
                        self.Update_Changelog(
                            obj=x,
                            user=c_user,
                            action="broken",
                            changes=(['Broken by %s of CA "%s"' % (c_action, self.common_name),]),
                        )

                    for i in id_dict["ca"]:
                        x = CertificateAuthority.objects.get(pk=i)
                        x.active = False
                        x.der_encoded = False
                        x.revoked = datetime.datetime.now()
                        super(CertificateAuthority, x).save(*args, **kwargs)
                        if x.pk != self.pk:
                            self.Update_Changelog(
                                obj=x,
                                user=c_user,
                                action="broken",
                                changes=(['Broken by %s of CA "%s"' % (c_action, self.common_name),]),
                            )

                if prev.description != self.description:
                    c_list.append('Updated description to "%s"' % self.description)
                    prev.description = self.description

                if prev.public != self.public:
                    c_list.append('Updated public to "%s"' % self.public)
                    prev.public = self.public

                if prev.der_encoded is not self.der_encoded:
                    c_list.append("DER encoding set to %s" % self.der_encoded)

                if self.der_encoded and self.action != "revoke":
                    action.generate_der_encoded()
                else:
                    action.remove_der_encoded()

                self = prev
                self.action = "update"
            else:
                raise Exception("Invalid action %s supplied" % self.action)
        else:
            self.created = datetime.datetime.now()
            delta = datetime.timedelta(self.valid_days)
            self.expiry_date = datetime.datetime.now() + delta

            self.active = True

            self.action = "update"

            print("Start REBuild")
            self.rebuild_ca_metadata(modify=True, task="append")

            action = Openssl(self)
            action.generate_key()

            if not self.parent:
                action.generate_self_signed_cert()
            else:
                action.generate_csr()
                action.sign_csr()

            if self.der_encoded:
                action.generate_der_encoded()

            action.generate_crl(self.name, self.passphrase)

            self.serial = action.get_serial_from_cert()

            chain = []
            chain_str = ""

            p = self.parent

            if not self.parent:
                chain.append("self-signed")
            else:
                chain.append(self.common_name)
                while p:
                    chain.append(p.common_name)
                    p = p.parent

            chain.reverse()

            for i in chain:
                if chain_str == "":
                    chain_str += "%s" % i
                else:
                    chain_str += "&nbsp;&rarr;&nbsp;%s" % i

            self.ca_chain = chain_str
            action.update_ca_chain_file()

            self.passphrase = md5_constructor(self.passphrase.encode("utf-8")).hexdigest()

            c_list.append('Created certificate "%s"' % self.common_name)

        self.parent_passphrase = None

        super(CertificateAuthority, self).save(*args, **kwargs)

        self.update_changelog(obj=self, user=c_user, action=c_action, changes=c_list)
Example #41
0
def invalidate_template_cache(fragment_name, *variables):
    args = md5_constructor(u':'.join([urlquote(var) for var in variables]))
    cache_key = 'template.cache.%s.%s' % (fragment_name, args.hexdigest())
    cache.delete(cache_key)
    return
Example #42
0
def md5sum(text):
    """Return the md5sum of a text string."""
    return md5_constructor(text).hexdigest()
Example #43
0
def template_cache_name(fragment_name, *variables):
    args = md5_constructor(u':'.join([urlquote(var) for var in variables]))
    return 'template.cache.%s.%s' % (fragment_name, args.hexdigest())
 def increment(self):
     """Increment the nonce stream, discarding initial nonce."""
     state = self.state
     state = self.state
     self.state = md5_constructor(state + settings.SECRET_KEY).hexdigest()
     return self.state
Example #45
0
def _get_new_submit_key():
    return md5_constructor(
        "%s%s" %
        (randrange(0, _MAX_CSRF_KEY), settings.SECRET_KEY)).hexdigest()
Example #46
0
File: captcha.py Project: Affix/fas
 def _generate_key( self , captcha_time_start=None , captcha_seed=None ):
     """Returns a hash based on text , seed , and site_secrect"""
     return md5_constructor("%s|%s|%s" %(captcha__site_secret,captcha_time_start,captcha_seed)).hexdigest()
Example #47
0
 def auto_guid(self):
     """Automatically generate a new guid from the metadata available."""
     return md5_constructor("|".join((
                 self.title, self.link, self.author))).hexdigest()
Example #48
0
File: captcha.py Project: affix/fas
 def _generate_key(self, captcha_time_start=None, captcha_seed=None):
     """Returns a hash based on text , seed , and site_secrect"""
     return md5_constructor("%s|%s|%s" %
                            (captcha__site_secret, captcha_time_start,
                             captcha_seed)).hexdigest()
Example #49
0
    def save(self, *args, **kwargs):
        """Save the Certificate object"""

        c_user = getattr(self, "user", None)
        c_action = self.action
        c_list = []

        if self.pk:
            if self.action in ("update", "revoke", "renew"):
                action = Openssl(self)
                prev = Certificate.objects.get(pk=self.pk)
                if self.action == "revoke":
                    if not self.parent:
                        raise Exception("You cannot revoke a self-signed certificate! No parent => No revoke")

                    # Revoke and generate CRL
                    action.revoke_certificate(self.parent_passphrase)
                    action.generate_crl(self.parent.name, self.parent_passphrase)

                    # Modify fields
                    prev.active = False
                    prev.der_encoded = False
                    prev.pkcs12_encoded = False
                    prev.revoked = datetime.datetime.now()
                    c_list.append('Revoked certificate "%s"' % self.common_name)
                elif self.action == "renew":
                    c_list.append('Renewed certificate "%s"' % self.common_name)

                    # Revoke if certificate is active
                    if self.parent and not action.get_revoke_status_from_cert():
                        action.revoke_certificate(self.parent_passphrase)
                        action.generate_crl(self.parent.name, self.parent_passphrase)

                    # Renew certificate and update CRL
                    if not self.parent:
                        action.generate_self_signed_cert()
                    else:
                        action.generate_csr()
                        action.sign_csr()
                        action.generate_crl(self.parent.name, self.parent_passphrase)

                    # Modify fields
                    prev.created = datetime.datetime.now()
                    delta = datetime.timedelta(self.valid_days)
                    prev.expiry_date = datetime.datetime.now() + delta

                    if prev.valid_days != self.valid_days:
                        c_list.append("Changed valid days from %d to %d" % (prev.valid_days, self.valid_days))

                    prev.valid_days = self.valid_days
                    prev.active = True
                    prev.revoked = None

                    # Make sure possibly updated fields are saved to DB
                    if prev.country != self.country:
                        c_list.append('Updated country to "%s"' % self.country)
                    if prev.locality != self.locality:
                        c_list.append('Updated locality to "%s"' % self.locality)
                    if prev.organization != self.organization:
                        c_list.append('Updated organization to "%s"' % self.organization)
                    if prev.email != self.email:
                        c_list.append('Updated email to "%s"' % self.email)
                    if prev.OU != self.OU:
                        c_list.append('Updated OU to "%s"' % self.OU)

                    prev.country = self.country
                    prev.locality = self.locality
                    prev.organization = self.organization
                    prev.email = self.email
                    prev.OU = self.OU

                    # Get the new serial
                    prev.serial = action.get_serial_from_cert()
                    c_list.append("Serial number changed to %s" % prev.serial)

                if self.action != "revoke":
                    if prev.pkcs12_encoded != self.pkcs12_encoded:
                        c_list.append("PKCS12 encoding set to %s" % self.der_encoded)

                    if self.pkcs12_encoded:
                        if prev.pkcs12_encoded and prev.pkcs12_passphrase == self.pkcs12_passphrase:
                            logger.debug("PKCS12 passphrase is unchanged. Nothing to do")
                        else:
                            action.generate_pkcs12_encoded()
                    else:
                        action.remove_pkcs12_encoded()
                        self.pkcs12_passphrase = prev.pkcs12_passphrase = None

                    if self.pkcs12_passphrase:
                        prev.pkcs12_passphrase = md5_constructor(self.pkcs12_passphrase).hexdigest()
                    else:
                        prev.pkcs12_passphrase = None

                    if prev.der_encoded is not self.der_encoded:
                        c_list.append("DER encoding set to %s" % self.der_encoded)

                    if self.der_encoded:
                        action.generate_der_encoded()
                    else:
                        action.remove_der_encoded()

                # Update description. This is always allowed
                if prev.description != self.description:
                    c_list.append('Updated description to "%s"' % self.description)
                    prev.description = self.description

                # Save the data
                self = prev
                self.action = "update"
            else:
                raise Exception("Invalid action %s supplied" % self.action)
        else:
            self.created = datetime.datetime.now()
            delta = datetime.timedelta(self.valid_days)
            self.expiry_date = datetime.datetime.now() + delta

            self.active = True

            logger.info("***** { New certificate generation: %s } *****" % self.name)

            action = Openssl(self)
            action.generate_key()

            if self.parent:
                action.generate_csr()
                action.sign_csr()
                self.ca_chain = self.parent.ca_chain
                if self.ca_chain == "self-signed":
                    self.ca_chain = self.parent.name
            else:
                action.generate_self_signed_cert()
                self.ca_chain = "self-signed"

            self.serial = action.get_serial_from_cert()

            if self.der_encoded:
                action.generate_der_encoded()

            if self.pkcs12_encoded:
                action.generate_pkcs12_encoded()

            if self.passphrase:
                self.passphrase = md5_constructor(self.passphrase).hexdigest()

            c_list.append('Created certificate "%s"' % action.subj)

        self.parent_passphrase = None
        super(Certificate, self).save(*args, **kwargs)

        self.update_changelog(obj=self, user=c_user, action=c_action, changes=c_list)
Example #50
0
def get_hexdigest(plaintext, length=None):
    digest = md5_constructor(smart_str(plaintext)).hexdigest()
    if length:
        return digest[:length]
    return digest