def decode_alpha(hashid): hashids = Hashids(alphabet='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',salt=salt,min_length=20) if hashids.decode(hashid): # if can be decoded result = str(hashids.decode(hashid)[0]) # returns decoded string else: # else if cannot be decoded result = 0 # returns int 0 return result
def hashid(*values, decode=False, min_length=7): hash_class = Hashids(min_length=min_length) if type(values[0]) == dict and decode: new_dict = {} for key, value in values[0].items(): if hasattr(value, "value"): value = value.value if value and hash_class.decode(value): value = hash_class.decode(value) if type(value) == tuple: value = value[0] new_dict.update({key: value}) return new_dict if not decode: if isinstance(values[0], dict): new_dic = {} for key, value in values[0].items(): if hasattr(value, "value"): value = value.value if str(value).isdigit(): new_dic.update({key: hash_class.encode(int(value))}) else: new_dic.update({key: value}) return new_dic return hash_class.encode(*values) return Hashids().decode(*values)
def test_alphabet_without_standard_separators(self): h = Hashids( alphabet='abdegjklmnopqrvwxyzABDEGJKLMNOPQRVWXYZ1234567890') assert h.decode('X50Yg6VPoAO4') == (7452, 2967, 21401) assert h.decode('GAbDdR') == (1, 2, 3) assert h.decode('5NMPD') == (60125, ) assert h.decode('yGya5') == (99, 25)
def reverse_hash(hash_str): """Reverse a hash parsed from the request URL. Accept a unique hash string representing hashed data and decode it to return the data. Args: hash_str: an hash string. Returns: array of decoded data None if there's no decoded data """ # split the hash_str with the delim: hashs = hash_str.split(Hasher.delim) # ensure the list has more than a part before decoding if len(hashs) < 2: return None # decode the timestamp_hash (i.e hashs[0] ) # with the app secret key: hashids = Hashids(salt=Hasher.secret_key, min_length=Hasher.timehash_min_length, alphabet=Hasher.alphabet) timestamp = hashids.decode(hashs[0])[0] # decode the data_hash with the timestamp: hashids = Hashids(salt=str(timestamp), min_length=Hasher.hash_min_length, alphabet=Hasher.alphabet) data_list = [hashids.decode(item)[0] for item in hashs[1:]] return data_list
def reverse_hash(hash_str): """ Accepts a unique hash string representing a user account and decodes it to return an actual intance of that account Returns None if decoded user does not exits """ # split the hash_str with the delim: hashs = hash_str.split(UserHasher.delim) # ensure the list has only 2 parts if len(hashs) != 2: return None # decode the timestamp_hash (i.e hashs[0] ) with the app secret key: hashids = Hashids( salt=secret_key, min_length=UserHasher.timehash_min_length, alphabet=UserHasher.alphabet) timestamp = hashids.decode(hashs[0])[0] # decode the pk_hash (i.e hashs[1] ) with the timestamp: hashids = Hashids( salt=str(timestamp), min_length=UserHasher.pkhash_min_length, alphabet=UserHasher.alphabet) account_pk = hashids.decode(hashs[1])[0] try: # return the account for that pk if it exists: registered_account = User.objects.get(pk=account_pk) return registered_account except ObjectDoesNotExist: # return None if it doesn't: return None
def test_single_number(self): h = Hashids() assert h.decode('j0gW') == (12345,) assert h.decode('jR') == (1,) assert h.decode('Lw') == (22,) assert h.decode('Z0E') == (333,) assert h.decode('w0rR') == (9999,)
def test_single_number(self): h = Hashids() assert h.decode('j0gW') == (12345, ) assert h.decode('jR') == (1, ) assert h.decode('Lw') == (22, ) assert h.decode('Z0E') == (333, ) assert h.decode('w0rR') == (9999, )
def decode(hashid): hashids = Hashids(salt=salt,min_length=11) if hashids.decode(hashid): # if can be decoded result = str(hashids.decode(hashid)[0]) # returns decoded string else: # else if cannot be decoded result = 0 # returns int 0 return result
def activate_user(self): self.status = STATUS_ACTIVE self.credits = app.config['REFERRAL_INITIAL_CREDITS'] hashids = Hashids() if self.referral_code is not None and len(hashids.decode(user.referral_code)) > 0: referral_user = User.query.filter_by(id=hashids.decode(user.referral_code)).first() if referral_user is not None: referral_user.credits = referral_user.credits + app.config['REFERRAL_ADD_CREDITS'] db.session.commit()
def test_alphabet(self): h = Hashids( alphabet= '!"#%&\',-/0123456789:;<=>ABCDEFGHIJKLMNOPQRSTUVWXYZ_`abcdefghijklmnopqrstuvwxyz~' ) assert h.decode('_nJUNTVU3') == (2839, 12, 32, 5) assert h.decode('7xfYh2') == (1, 2, 3) assert h.decode('Z6R>') == (23832, ) assert h.decode('AYyIB') == (99, 25)
def hashid_decode(value, salt=imp.encoded_urls["salt"], min_length=imp.encoded_urls["min_length"]): hashids = Hashids(alphabet=imp.encoded_urls["alphabet"], salt=salt, min_length=min_length) if len(hashids.decode(value)) == 0: return None else: return hashids.decode(value)[0]
def test_updates_when_changing_real_column_value(): from django.conf import settings from tests.test_app.models import TestModel instance = TestModel.objects.create() instance.id = 3 # works before saving hashids_instance = Hashids(salt=settings.DJANGO_HASHIDS_SALT) assert hashids_instance.decode(instance.hashid)[0] == 3 # works after saving instance.save() hashids_instance = Hashids(salt=settings.DJANGO_HASHIDS_SALT) assert hashids_instance.decode(instance.hashid)[0] == 3
def blockUnblockUsers(request): if request.user.is_authenticated(): if request.method == 'POST': hashids = Hashids(min_length=16) dataType = request.POST.get('data_type') setUserId = request.POST.get('user_id') uId = hashids.decode(setUserId) currentUser = uId[0] try: userData = BlockedUser.objects.filter(blocked_user_id = currentUser, user_id = request.user.id) except BlockedUser.DoesNotExist: userData = None if('0' == dataType): if not userData: blockUser = BlockedUser() blockUser.blocked_user_id = currentUser blockUser.user_id = request.user.id blockUser.is_blocked = 1 blockUser.save() else: blockUser = BlockedUser.objects.get(blocked_user_id=currentUser) blockUser.blocked_user_id = currentUser blockUser.user_id = request.user.id blockUser.is_blocked = 1 blockUser.save() response = HttpResponse(json.dumps({'type':dataType,'id':currentUser,'success': 'Added successfully'}),content_type='application/json') response.status_code = 200 return response else: if userData: userData.delete() print "there" response = HttpResponse(json.dumps({'id':currentUser,'type':dataType,'success': 'Deleted successfully'}),content_type='application/json') response.status_code = 200 return response
def post(self, request, *args, **kwargs): identifier = request.query_params.get("daemo_id", False) if not identifier: return Response("Missing identifier", status=status.HTTP_400_BAD_REQUEST) try: from django.conf import settings from hashids import Hashids hash = Hashids(salt=settings.SECRET_KEY) task_worker_id, task_id, template_item_id = hash.decode(identifier) with transaction.atomic(): task_worker = TaskWorker.objects.get(id=task_worker_id, task_id=task_id) task_worker_result, created = TaskWorkerResult.objects.get_or_create( task_worker_id=task_worker.id, template_item_id=template_item_id ) # only accept in progress, submitted, or returned tasks if task_worker.task_status in [1, 2, 5]: task_worker_result.status = 1 task_worker_result.result = request.data task_worker_result.save() return Response(request.data, status=status.HTTP_200_OK) else: return Response("Task cannot be modified now", status=status.HTTP_400_BAD_REQUEST) except ValueError: return Response("Invalid identifier", status=status.HTTP_400_BAD_REQUEST) except Exception: return Response("Fail", status=status.HTTP_400_BAD_REQUEST)
class NIdNoise: NSALT = "dakjsl#^%6bqhcjhb" HASH_LENGTH = 11 # Here will be the instance stored. __instance = None @staticmethod def get_instance(): """ Static access method. """ if NIdNoise.__instance == None: NIdNoise() return NIdNoise.__instance def __init__(self): """ Virtually private constructor. """ if NIdNoise.__instance != None: raise Exception("NIdNoise class is a singleton!") else: self.hashids = Hashids(salt=self.NSALT, min_length=self.HASH_LENGTH) NIdNoise.__instance = self def ennoise_id(self, id): if id >= 0: return self.hashids.encode(id) else: return '' def denoise_id(self, nid): if nid: return self.hashids.decode(nid)[0] else: return ''
class Hashes(): """ Obfuscate integers using hashids. params: salt: A random string to make the obfuscated output unique. min-length: the minimum length of the obfuscated string to be generated from an integer. """ def __init__(self, salt, min_length): self.length = min_length self.__hash = Hashids(salt=salt, min_length=self.length) @property def length(self): return self.__length @length.setter def length(self, value): if value < 1 or not isinstance(value, int): raise ValueError('Min length argument should be an integer \ greater than 1.') else: self.__length = value def encode(self, value): """ Build hash from a int value. """ return self.__hash.encode(value) def decode(self, value): """ Restores encoded hash values to tuple. """ return self.__hash.decode(value)
def hasher(): hashids = Hashids(salt='www.smokingpipes.com') hashid = hashids.encode(random.randint(1, 1000)) print(hashid) ints = hashids.decode('mVN') print(ints)
def decode_id(hashstr): hashids = Hashids( min_length=config().get('safe', 'hashids_length'), salt=config().get('safe', 'hashids_salt'), alphabet=config().get('safe', 'hashids_alphabet') ) return hashids.decode(hashstr)[0]
def hashid_to_int(hashid, min_length=11, salt=settings.RESPONSIVE_WRAPPER_HASHIDS_SALT): hashids = Hashids(salt, min_length=min_length) try: return hashids.decode(hashid)[0] except IndexError: pass
def get_object(self, queryset=None): unit = get_object_or_404( Unit, pk=self.kwargs['pk'], ) data_update = unit.unitdataupdate # Using hashids library to decrypt the url verify key. hashids = Hashids( salt=data_update.residents_update_key, min_length=50, ) verify_key = hashids.decode(self.kwargs['verify_key']) # If the decrypted verify key is different to the data update # id, the link is corrupt. if data_update.id != verify_key[0]: raise Http404 return get_object_or_404( UnitDataUpdate, enable_residents_update=True, pk=verify_key[0], )
def internal_id_from_model_and_external_id(model, external_id): """ Return the internal ID from the external ID and model combination. Because the HashId is a combination of the model's content type and the internal ID, we validate here that the external ID decodes as expected, and that the content type corresponds to the model we're expecting. """ hashids = Hashids(salt=settings.HASHIDS_SALT) if hashids is None: raise AssertionError( "To use hashids features you must set " "ENABLE_HASHID_FIELDS to true " "and provide a HASHIDS_SALT in your dynamic_rest settings.") try: content_type_id, instance_id = hashids.decode(external_id) except (TypeError, ValueError): raise model.DoesNotExist content_type = ContentType.objects.get_for_id(content_type_id) if content_type.model_class() != model: raise model.DoesNotExist return instance_id
def deleteSpecificUser(request): if request.user.is_authenticated(): hashids = Hashids(min_length=16) if request.method == 'POST': userId = request.POST.get('user_id') uId = hashids.decode(userId) currentUser = uId[0] try: userData = UserSpecificContacts.objects.filter( specific_user_id=currentUser, user_id=request.user.id) userCount = UserSpecificContacts.objects.filter( user_id=request.user.id).count() except UserSpecificContacts.DoesNotExist: userData = None userCount = 0 if userData: userData.delete() response = HttpResponse(json.dumps({ 'id': currentUser, 'type': 1, 'count': userCount, 'success': 'Added successfully' }), content_type='application/json') response.status_code = 200 return response
def post(self, request, *args, **kwargs): identifier = request.query_params.get('daemo_id', False) if not identifier: return Response("Missing identifier", status=status.HTTP_400_BAD_REQUEST) try: from django.conf import settings from hashids import Hashids hash = Hashids(salt=settings.SECRET_KEY) task_worker_id, task_id, template_item_id = hash.decode(identifier) with transaction.atomic(): task_worker = TaskWorker.objects.get(id=task_worker_id, task_id=task_id) task_worker_result, created = TaskWorkerResult.objects.get_or_create( task_worker_id=task_worker.id, template_item_id=template_item_id) # only accept in progress, submitted, or returned tasks if task_worker.task_status in [1, 2, 5]: task_worker_result.status = 1 task_worker_result.result = request.data task_worker_result.save() return Response(request.data, status=status.HTTP_200_OK) else: return Response("Task cannot be modified now", status=status.HTTP_400_BAD_REQUEST) except ValueError: return Response("Invalid identifier", status=status.HTTP_400_BAD_REQUEST) except Exception: return Response("Fail", status=status.HTTP_400_BAD_REQUEST)
def to_pk(hash_string): id_hash = Hashids(salt=settings.SECRET_KEY, min_length=12) pk = id_hash.decode(hash_string) if len(pk): return pk[0] else: return None
def hashid_to_int(hashid, min_length=11, salt=settings.DJANGOCMS_DISQUS_HASHIDS_SALT): hashids = Hashids(salt, min_length=min_length) try: return hashids.decode(hashid)[0] except IndexError: pass
def decode_key(key): h = Hashids(SEED) key = h.decode(key) if len(key) > 0: return key[0] return 0
def hasher(): hashids = Hashids(salt='www.smokingpipes.com') hashid = hashids.encode(random.randint(1, 1000)) print(hashid) ints = hashids.decode('mVN') print(ints)
def hashid_to_int(hashid, min_length=30, salt=settings.DJANGOCMS_FORMS_HASHIDS_SALT): hashids = Hashids(salt, min_length=min_length) try: return hashids.decode(hashid)[0] except IndexError: pass
def download_profile_deleted_tracks(link): endpoint = get_available_endpoint() print(f"API endpoint: {endpoint}") res = resolve_link(link, endpoint) j = json.loads(res) user_id = j['data']['id'] username = j['data']['handle'] full_username = j['data']['name'] # We want to be able to use the API to include deleted tracks, which means we can't use the User ID # provided by Audius, instead we have to get a little creative. # Get *actual* User ID # Uses https://hashids.org/python/ # See https://audius.co/static/js/utils/route/hashIds.ts hashids = Hashids(salt="azowernasdfoia", min_length=5) actual_user_id = hashids.decode(user_id)[0] r = requests.get( f"{endpoint}/tracks?filter_deleted=false&limit=100&offset=0&user_id={actual_user_id}" ) j = json.loads(r.text) deleted_tracks = [] for t in j['data']: if (t['is_delete']): deleted_tracks.append(t) print(f"Number of deleted tracks: {len(deleted_tracks)}") for index, i in enumerate(deleted_tracks): print(f"Track [ {index + 1} / {len(deleted_tracks)} ]") download_deleted_track(i, username, full_username)
def test_ignores_changes_to_value(): from django.conf import settings from tests.test_app.models import TestModel instance = TestModel.objects.create() instance.id = 3 instance.hashid = "FOO" hashids_instance = Hashids(salt=settings.DJANGO_HASHIDS_SALT) assert hashids_instance.decode(instance.hashid)[0] == 3 # works after saving instance.save() instance.hashid = "FOO" hashids_instance = Hashids(salt=settings.DJANGO_HASHIDS_SALT) assert hashids_instance.decode(instance.hashid)[0] == 3
def token_retrieve(request): token = None if 'X_TOKEN' in request.META: token = request.META['X_TOKEN'] elif 'HTTP_X_TOKEN' in request.META: token = request.META['HTTP_X_TOKEN'] if token is not None: if len(token) == 20: token = UUID(hexlify(b85decode(token.encode())).decode()) if len(token) == 25: hasher = Hasher(salt=settings.SECRET_KEY) token = UUID(hasher.decode(token)) try: token = Token.objects.get(id=token, is_active=True, is_anonymous=False) request.user = token.owner if token.due is not None and token.due < timezone.now(): token.is_active = False token.save() token = None except Exception: token = None return token
def test_can_use_per_field_config(): from tests.test_app.models import TestModelWithDifferentConfig instance = TestModelWithDifferentConfig.objects.create() hashid = instance.hashid hashids_instance = Hashids(salt="AAA", min_length=5, alphabet="OPQRST1234567890") assert hashids_instance.decode(hashid)[0] == instance.pk
def inlinequery(bot, update): """Handle the inline query.""" query = update.inline_query.query lang = update.inline_query.from_user.language_code user = update.inline_query.from_user.first_name try: user += " " + update.inline_query.from_user.last_name except (AttributeError, TypeError): pass try: user += " (" + update.inline_query.from_user.username + ")" except (AttributeError, TypeError): pass logger.info("{} - {} - {}".format(lang, user, query)) db = database.Database() results = [] if re.findall("^([a-zA-Z]+)$", query): short = re.findall("^([a-zA-Z]+)$", query) news = db.get_last_news(short[0]) for new in news: results.append(create_article(*new)) elif re.findall("^([a-zA-Z]+[0-9]+)$", query): article = db.get_news_by_id( *re.findall("^([a-zA-Z]+)([0-9]+)$", query)[0]) if article: results.append(create_article(*article)) elif re.findall("^[A-Z0-9a-z]{6,}$", query): hashids = Hashids(salt=config.SALT, min_length=6) news_id = hashids.decode(query)[0] results.append(create_article(*db.get_news(news_id))) try: update.inline_query.answer(results) except BadRequest as e: logger.exception(e)
def __retrieve__(self, request): token, user = None, None if 'HTTP_X_MODIFIED_BY' in request.META: user = request.META['HTTP_X_MODIFIED_BY'] if 'HTTP_X_TOKEN' in request.META: token = request.META['HTTP_X_TOKEN'] else: return token if len(token) == 25: hasher = Hasher(salt=settings.SECRET_KEY) token = UUID(hasher.decode(token)) token = Token.objects.filter(id=token, is_active=True, is_anonymous=False) if token: token = token[0] request.user = token.owner user = User.objects.filter(id=user) if token.has_perm('core.propagate_token') and user: request.user = user[0] if token.due and token.due < timezone.now(): token.is_active = False token.save() token = None else: token = None return token
def is_hashid(identifier): hashids = Hashids(salt=settings.ABACO_HASHIDS_SALT) dec = hashids.decode(identifier) if len(dec) > 0: return True else: return False
def decode_encodeid(self, hash_id): # if isinstance(encode_id, int) is False: # encode_id = int(encode_id) hash_ids = Hashids(salt='{}'.format(self.SALT), min_length=8, alphabet='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890') encode_id = hash_ids.decode(hash_id) return encode_id[0]
def post(self, request, *args, **kwargs): identifier = request.query_params.get('daemo_id', False) if not identifier: return Response("Missing identifier", status=status.HTTP_400_BAD_REQUEST) try: from django.conf import settings from hashids import Hashids identifier_hash = Hashids(salt=settings.SECRET_KEY, min_length=settings.ID_HASH_MIN_LENGTH) if len(identifier_hash.decode(identifier)) == 0: return Response("Invalid identifier", status=status.HTTP_400_BAD_REQUEST) task_worker_id, task_id, template_item_id = identifier_hash.decode(identifier) template_item = models.TemplateItem.objects.get(id=template_item_id) task = models.Task.objects.get(id=task_id) source_url = None if template_item.aux_attributes['src']: source_url = urlsplit(template_item.aux_attributes['src']) else: source_url = urlsplit(task.data[template_item.aux_attributes['data_source']]) if 'HTTP_REFERER' not in request.META.keys(): return Response(data={"message": "Missing referer"}, status=status.HTTP_403_FORBIDDEN) referer_url = urlsplit(request.META['HTTP_REFERER']) if referer_url.netloc != source_url.netloc or referer_url.scheme != source_url.scheme: return Response(data={"message": "Referer does not match source"}, status=status.HTTP_403_FORBIDDEN) redis_publisher = RedisPublisher(facility='external', broadcast=True) task_hash = Hashids(salt=settings.SECRET_KEY, min_length=settings.ID_HASH_MIN_LENGTH) message = RedisMessage(json.dumps({"task_id": task_hash.encode(task_id), "daemo_id": identifier, "template_item": template_item_id })) redis_publisher.publish_message(message) with transaction.atomic(): task_worker = TaskWorker.objects.get(id=task_worker_id, task_id=task_id) task_worker_result, created = TaskWorkerResult.objects.get_or_create(task_worker_id=task_worker.id, template_item_id=template_item_id) # only accept in progress, submitted, or returned tasks if task_worker.status in [1, 2, 5]: task_worker_result.result = request.data task_worker_result.save() update_worker_cache.delay([task_worker.worker_id], constants.TASK_SUBMITTED) return Response(request.data, status=status.HTTP_200_OK) else: return Response("Task cannot be modified now", status=status.HTTP_400_BAD_REQUEST) except ValueError: return Response("Invalid identifier", status=status.HTTP_400_BAD_REQUEST) except Exception: return Response("Fail", status=status.HTTP_400_BAD_REQUEST)
def cert_id_decode(key, hashid): hashids = Hashids(salt=key) try: cert_id = hashids.decode(hashid)[0] except IndexError: # Not encoded with the same key return None return cert_id
class HornerHashIds(): def __init__(self): self.hashids = Hashids(salt=HASH_IDS_SALT) def encode(self, *values): return self.hashids.encode(*values) def decode(self, hashid): return self.hashids.decode(hashid)
class MobileUrlHashUtil(object): def __init__(self): self.instance = Hashids(MOBILE_SALT, min_length=8) def encode(self, str): return self.instance.encode(str) def decode(self, str): return self.instance.decode(str)[0]
def get_redirect_url(self, *args, **kwargs): hash_id = Hashids() hashed = kwargs['hash_id'] decoded = hash_id.decode(hashed) bookmark = get_object_or_404(Bookmark, id=decoded[0]) if self.request.user in User.objects.all(): Click.objects.create(bookmark=bookmark, user=self.request.user) else: Click.objects.create(bookmark=bookmark) return bookmark.url
def author_posts(request, hashid): hashids = Hashids(salt=settings.SECRET_KEY) author_id = hashids.decode(str(hashid))[0] context = { 'posts': Post.objects.filter( author_id=author_id).order_by('-published'), 'author': Post.objects.filter(author_id=author_id)[0].author, 'author_id': author_id, } return render(request, 'author_posts.html', context)
def api_filter_link(filter_id): hashids = Hashids() # Check to make sure that the filter ID is valid # If it isn't, we don't set any cookie data filter_info = hashids.decode(filter_id) if filter_info and len(filter_info) == 4: session["filter_id"] = filter_id return redirect("/")
def get(self, request, **kwargs): hashids = Hashids(salt='saltstring') id = hashids.decode(kwargs['url'])[0] bookmark = Bookmark.objects.get(pk=id) new_url = bookmark.url if request.user.is_authenticated(): click = Click(user_id=request.user, bookmark=bookmark, time=timezone.now()) click.save() else: user = User.objects.filter(username='******')[0] click = Click(user_id=user, bookmark=bookmark, time=timezone.now()) click.save() return HttpResponseRedirect(new_url)
class HashidsField(serializers.Field): def __init__(self, *args, **kwargs): kwargs.setdefault('help_text', 'Hash id field') salt = kwargs.pop('salt', settings.HASHIDS_SALT) min_length = kwargs.pop('min_length', settings.HASHIDS_MIN_LENGTH) self.hashids = Hashids(salt=salt, min_length=min_length) super().__init__(*args, **kwargs) def to_representation(self, obj): return self.hashids.encode(obj) def to_internal_value(self, value): return self.hashids.decode(value)
def getjob(inputs): """ Get meta data about jobs for the given user. Either a list of all jobs for this user, or filtering can be done by providing a spesific jobid or job status. """ # Split the input path: /jobs/<user>(/<id|finshed|queued|processing>) fields = inputs.rstrip('/').split('/') user = fields[0] hashids = Hashids(salt=user) if len(fields) > 1: # User has specified a filter, need to determine if its status or id query = 'match' f = fields[1] if f.lower() in STATUS.values(): key = 'status' value = f.lower() else: key = 'id' h = hashids.decode(f) if len(h) == 0: return APIError(404, 'No such job exists') else: value = h[0] else: # User has not provided a filter, showing all jobs query = 'wildcard' key = 'status' value = '*' # Search in ES search = {"query": {query: {key: value}}} res = es.search(index=indexname, doc_type=user, body=search) records = res['hits']['hits'] if len(records) == 0: return APIError(404, 'No such job exists') # Create the json result which will be returned to the user if key == 'id': rec = records[0]['_source'] rec.pop('id') # Remove the actual ES id return rec else: jobs = Dict() for data in records: rec = data['_source'] jobid = hashids.encode(rec['id']) jobs[jobid].jobid = jobid jobs[jobid].created = rec['timestamp'] jobs[jobid].desc = rec['desc'] return jobs
class HashIdSerializer(BaseKeySerializer): def __init__(self, salt): self.hash_maker = Hashids(salt=salt) def dumps(self, v): assert isinstance(v, int) return self.hash_maker.encode(v) def loads(self, v): assert isinstance(v, str) result = self.hash_maker.decode(v) if not result: raise ValueError("invalid id") return result[0]
def scan_marker(scan_id): hashid = Hashids(min_length=6, salt=app.config['HASHID_KEY']) try: marker_id = hashid.decode(scan_id)[0] except IndexError: abort(404) try: asas = query_db("INSERT INTO scans (user_id, marker_id) values(%s, %s)", [str(session.get('user_id')), str(marker_id)]) except MySQLdb.Error, e: if e.args[0] == 1452: abort(404) elif e.args[0] == 1062: flash("You've already scanned this torch.") else: flash("Database Error. %s %s" % (e.args[0], e.args[1]))
def deljob(user, jobid): """ Delete a job with given id for given user. """ # Decode jobid hashid = Hashids(salt=user) hid = hashid.decode(jobid) if len(hid) == 0: return APIError(404, 'No such job exists') # Check if the job actually exists q = {'query': {'match': {'id': hid[0]}}} res = es.search(index=indexname, doc_type=user, body=q) records = res['hits']['hits'] if len(records) == 1: res = es.delete(index=indexname, doc_type=user, id=hid[0]) if res['found']: return None else: raise APIError(502, 'Deletion failed') else: raise APIError(404, 'No such job exists')
def create(self, request, *args, **kwargs): worker = get_or_create_worker(worker_id=request.data.get('workerId')) provider = MTurkProvider('https://' + request.get_host()) task_id = request.data.get('taskId', -1) task_hash = Hashids(salt=settings.SECRET_KEY, min_length=settings.ID_HASH_MIN_LENGTH) task_id = task_hash.decode(task_id) if len(task_id) == 0: task_id = -1 hit_id = request.data.get('hitId', -1) mturk_hit = get_object_or_404(MTurkHIT, task_id=task_id, hit_id=hit_id) assignment_id = request.data.get('assignmentId', -1) mturk_assignment_id = None task_worker = None if assignment_id != 'ASSIGNMENT_ID_NOT_AVAILABLE': assignment, is_valid = provider.get_assignment(assignment_id) if not assignment or (is_valid and assignment.HITId != hit_id): return Response(data={"message": "Invalid assignment"}, status=status.HTTP_400_BAD_REQUEST) task_worker, created = TaskWorker.objects.get_or_create(worker=worker, task_id=task_id[0]) if created: task_worker.task_status = TaskWorker.STATUS_IN_PROGRESS task_worker.save() assignment, created = MTurkAssignment.objects.get_or_create(hit=mturk_hit, assignment_id=assignment_id, task_worker=task_worker) mturk_assignment_id = assignment.id if created: assignment.status = TaskWorker.STATUS_IN_PROGRESS assignment.save() task_serializer = TaskSerializer(instance=mturk_hit.task, fields=('id', 'template', 'project_data', 'status'), context={'task_worker': task_worker}) response_data = { 'task': task_serializer.data, 'assignment': mturk_assignment_id } return Response(data=response_data, status=status.HTTP_200_OK)
def decode_url(self, url): hashids = Hashids(salt=settings.SECRET_KEY, min_length=10) decoded = hashids.decode(url) if not decoded: raise Exception("Could not decode hashid to pk") return decoded[0]
def test_only_one_valid(self): h = Hashids(min_length=6) assert h.decode(h.encode(1)[:-1] + '0') == ()
def test_alphabet_with_two_standard_separators(self): h = Hashids(alphabet='abdegjklmnopqrvwxyzABDEGJKLMNOPQRVWXYZ1234567890uC') assert h.decode('GJNNmKYzbPBw') == (7452, 2967, 21401) assert h.decode('DQCXa4') == (1, 2, 3) assert h.decode('38V1D') == (60125,) assert h.decode('373az') == (99, 25)
def test_alphabet_without_standard_separators(self): h = Hashids(alphabet='abdegjklmnopqrvwxyzABDEGJKLMNOPQRVWXYZ1234567890') assert h.decode('X50Yg6VPoAO4') == (7452, 2967, 21401) assert h.decode('GAbDdR') == (1, 2, 3) assert h.decode('5NMPD') == (60125,) assert h.decode('yGya5') == (99, 25)
def test_all_parameters(self): h = Hashids('arbitrary salt', 16, 'abcdefghijklmnopqrstuvwxyz') assert h.decode('wygqxeunkatjgkrw') == (7452, 2967, 21401) assert h.decode('pnovxlaxuriowydb') == (1, 2, 3) assert h.decode('jkbgxljrjxmlaonp') == (60125,) assert h.decode('erdjpwrgouoxlvbx') == (99, 25)
def test_min_length(self): h = Hashids(min_length=25) assert h.decode('pO3K69b86jzc6krI416enr2B5') == (7452, 2967, 21401) assert h.decode('gyOwl4B97bo2fXhVaDR0Znjrq') == (1, 2, 3) assert h.decode('Nz7x3VXyMYerRmWeOBQn6LlRG') == (6097,) assert h.decode('k91nqP3RBe3lKfDaLJrvy8XjV') == (99, 25)
def test_alphabet(self): h = Hashids(alphabet='!"#%&\',-/0123456789:;<=>ABCDEFGHIJKLMNOPQRSTUVWXYZ_`abcdefghijklmnopqrstuvwxyz~') assert h.decode('_nJUNTVU3') == (2839, 12, 32, 5) assert h.decode('7xfYh2') == (1, 2, 3) assert h.decode('Z6R>') == (23832,) assert h.decode('AYyIB') == (99, 25)
def test_salt(self): h = Hashids(salt='Arbitrary string') assert h.decode('QWyf8yboH7KT2') == (683, 94108, 123, 5) assert h.decode('neHrCa') == (1, 2, 3) assert h.decode('LRCgf2') == (2, 4, 6) assert h.decode('JOMh1') == (99, 25)
def test_multiple_numbers(self): h = Hashids() assert h.decode('vJvi7On9cXGtD') == (683, 94108, 123, 5) assert h.decode('o2fXhV') == (1, 2, 3) assert h.decode('xGhmsW') == (2, 4, 6) assert h.decode('3lKfD') == (99, 25)