Esempio n. 1
0
    def hash(self, request):
        """
        Creates an hash of `version_id` of all accessible assets by the user.
        Useful to detect changes between each request.

        :param request:
        :return: JSON
        """
        user = self.request.user
        if user.is_anonymous:
            raise exceptions.NotAuthenticated()
        else:
            accessible_assets = get_objects_for_user(
                user, "view_asset", Asset).filter(asset_type=ASSET_TYPE_SURVEY) \
                .order_by("uid")

            assets_version_ids = [
                asset.version_id for asset in accessible_assets
                if asset.version_id is not None
            ]
            # Sort alphabetically
            assets_version_ids.sort()

            if len(assets_version_ids) > 0:
                hash = md5(hashable_str(
                    "".join(assets_version_ids))).hexdigest()
            else:
                hash = ""

            return Response({"hash": hash})
Esempio n. 2
0
 def test_version_content_hash(self):
     _content = {
         'survey': [{
             'type': 'note',
             'label': 'Read me',
             'name': 'n1'
         }],
     }
     new_asset = Asset.objects.create(asset_type='survey', content=_content)
     expected_hash = hashlib.sha1(
         hashable_str(json.dumps(new_asset.content,
                                 sort_keys=True))).hexdigest()
     self.assertEqual(new_asset.latest_version.content_hash, expected_hash)
     return new_asset
    def test_assets_hash(self):
        another_user = User.objects.get(username="******")
        user_asset = Asset.objects.first()
        user_asset.save()
        user_asset.assign_perm(another_user, "view_asset")

        self.client.logout()
        self.client.login(username="******", password="******")
        creation_response = self.create_asset()

        another_user_asset = another_user.assets.last()
        another_user_asset.save()

        versions_ids = [user_asset.version_id, another_user_asset.version_id]
        versions_ids.sort()
        expected_hash = md5(hashable_str(''.join(versions_ids))).hexdigest()
        hash_url = reverse("asset-hash")
        hash_response = self.client.get(hash_url)
        self.assertEqual(hash_response.data.get("hash"), expected_hash)
Esempio n. 4
0
 def hash(self):
     return '%s' % md5(hashable_str(self.xml)).hexdigest()
Esempio n. 5
0
 def content_hash(self):
     # used to determine changes in the content from version to version
     # not saved, only compared with other asset_versions
     _json_string = json.dumps(self.version_content, sort_keys=True)
     return hashlib.sha1(hashable_str(_json_string)).hexdigest()
Esempio n. 6
0
def gravatar_url(email, https=True):
    return "%s://www.gravatar.com/avatar/%s?%s" % (
        'https' if https else 'http',
        hashlib.md5(hashable_str(email.lower())).hexdigest(),
        urlencode({'s': '40'}),
    )
Esempio n. 7
0
def sluggify(_str, _opts):
    """
    this method is ported over from coffeescript:
    jsapp/xlform/src/model.utils.coffee
    """
    _initial = _str
    if _str == '':
        return ''
    opts = dict(DEFAULT_OPTS, **_opts)

    if opts['lrstrip']:
        _str = _str.strip()
    elif opts['lstrip']:
        _str = _str.lstrip()
    elif opts['rstrip']:
        _str = _str.rstrip()

    if opts['lowerCase']:
        _str = _str.lower()

    if opts['underscores']:
        _str = re.sub(r'\s', '_', _str)
        # .replace(/[_]+/g, "_") <- replaces duplicates?

    if opts['replaceNonWordCharacters']:
        if opts['nonWordCharsExceptions']:
            regex = r'[^a-zA-Z0-9_{}]'.format(opts['nonWordCharsExceptions'])
        else:
            regex = r'[^a-zA-Z0-9_]+'  # Cannot use `\W`. Different behaviour with Python 2 & 3

        _str = re.sub(regex, '_', _str)
        if _str != '_' and re.search('_$', _str):
            _str = re.sub('_$', '', _str)

    if opts['characterLimit']:
        _limit = opts['characterLimit']
        if opts['characterLimit_shorten_method'] == 'ends':
            _str = _shorten_long_name(_str, _limit, join_with='_')
        else:
            _str = _str[0:opts['characterLimit']]

    if opts['validXmlTag']:
        if re.search(r'^\d', _str):
            _str = '_' + _str

    if opts['preventDuplicateUnderscores']:
        while re.search('__', _str):
            _str = re.sub('__', '_', _str)

    names = opts.get('other_names', opts['preventDuplicates'])
    if isinstance(names, list):
        names_lc = [name.lower() for name in names]
        attempt_base = _str
        if len(attempt_base) == 0:
            # empty string because arabic / cyrillic characters
            _str = 'h{}'.format(
                hashlib.md5(hashable_str(_initial[0:7])).hexdigest()[0:7])
        attempt = attempt_base
        incremented = 0
        while attempt.lower() in names_lc:
            incremented += 1
            attempt = "{0}_{1:03d}".format(attempt_base, incremented)
        _str = attempt

    return _str