def test_single_number(self): h = Hashids() assert h.encrypt(12345) == 'rGAx' assert h.encrypt(1) == 'yE' assert h.encrypt(22) == 'B8' assert h.encrypt(333) == '7G9' assert h.encrypt(9999) == 'zpz5'
def test_alphabet_without_standard_separators(self): h = Hashids( alphabet='abdegjklmnopqrvwxyzABDEGJKLMNOPQRVWXYZ1234567890') assert h.encrypt(7452, 2967, 21401) == 'X50Yg6VPoAO4' assert h.encrypt(1, 2, 3) == 'GAbDdR' assert h.encrypt(60125) == '5NMPD' assert h.encrypt(99, 25) == 'yGya5'
def test_alphabet_with_two_standard_separators(self): h = Hashids( alphabet='abdegjklmnopqrvwxyzABDEGJKLMNOPQRVWXYZ1234567890uC') assert h.encrypt(7452, 2967, 21401) == 'GJNNmKYzbPBw' assert h.encrypt(1, 2, 3) == 'DQCXa4' assert h.encrypt(60125) == '38V1D' assert h.encrypt(99, 25) == '373az'
def test_single_number(self): h = Hashids() assert h.encrypt(12345) == 'j0gW' assert h.encrypt(1) == 'jR' assert h.encrypt(22) == 'Lw' assert h.encrypt(333) == 'Z0E' assert h.encrypt(9999) == 'w0rR'
def auto_accept_friends(msg): ## Accept request new_friend = msg.card.accept() nextUserID = int( (floor(get_activities()['user_id'].dropna().max() / 1e6) + 1) * 1e6 + randint(1, 999999)) # Next user's ID print(nextUserID) ## Deal with too many users in a cohort users = get_users() cohortCount = int(len(users.loc[users.cohort == cohort]) / 9) if cohortCount > 120: new_friend.send( "Current round of recruitment is finished. We will message you as soon as the next round begins!" ) ## Please write this in Chinese? new_friend.set_remark_name("WL_" + str(nextUserID)) else: ## Get wxid (assuming that this is the unique ID we can use) userName = new_friend.user_name[1:] # Check whether existing user TODO # Create hashes for the new user, save in user db, create new activity nextUserID = int( (floor(get_activities()['user_id'].dropna().max() / 1e6) + 1) * 1e6 + randint(1, 999999)) # Next user's ID treatment = "T" + str(choices(treat_no, treat_prob)[0]) print("adding new user", nextUserID, "assigning treatment", treatment, "...") for day in range(9): user_id_hashids = Hashids(salt=str(10 * nextUserID + day) + "user_id", min_length=16) day_hashids = Hashids(salt=str(10 * nextUserID + day) + "day", min_length=10) hashed_user_id = user_id_hashids.encrypt(nextUserID) hashed_day = day_hashids.encrypt(day) requests.post("https://dailyeventinfo.com/userInsert/" + str(nextUserID) + "/" + str(day) + "/" + str(userName) + "/" + str(cohort) + "/" + str(treatment) + "/" + hashed_user_id + "/" + hashed_day) requests.post("https://dailyeventinfo.com/activityUpdate/" + str(nextUserID) + "/0/0/0/0/0") # Send intro message day = 0 user_id_hashids = Hashids(salt=str(10 * nextUserID + day) + "user_id", min_length=16) day_hashids = Hashids(salt=str(10 * nextUserID + day) + "day", min_length=10) hashed_user_id = user_id_hashids.encrypt(nextUserID) hashed_day = day_hashids.encrypt(day) sendURL = "https://dailyeventinfo.com/" + hashed_user_id.strip( ) + "/" + hashed_day.strip() + "/info" new_friend.send(intro) new_friend.send(sendURL) # Set remark_name to use for reminder messages new_friend.set_remark_name(str(nextUserID))
def test_alphabet(self): h = Hashids( alphabet= '!"#%&\',-/0123456789:;<=>ABCDEFGHIJKLMNOPQRSTUVWXYZ_`abcdefghijklmnopqrstuvwxyz~' ) assert h.encrypt(2839, 12, 32, 5) == '_nJUNTVU3' assert h.encrypt(1, 2, 3) == '7xfYh2' assert h.encrypt(23832) == 'Z6R>' assert h.encrypt(99, 25) == 'AYyIB'
def auto_accept_friends(): ## Accept request # new_friend = msg.card.accept() previousMax = get_activities()['user_id'].dropna().max() if previousMax == 33333337530699: previousMax = previousMax - 33333330000000 if previousMax > 3 * 1e6: previousMax = previousMax - 3 * 1e6 nextUserID = int((floor(previousMax / 1e6) + 1) * 1e6 + randint(1, 999999)) # Next user's ID ## Deal with too many users in a cohort users = get_users() cohortCount = int(len(users.loc[users.cohort == int(cohort)]) / 2) if cohortCount > 51: print(u"次轮招募已完成,我们将在下轮开始时尽快联系您!") print("WL_" + str(nextUserID)) else: ## Get wxid (assuming that this is the unique ID we can use) userName = '******' # Create hashes for the new user, save in user db, create new activity treatment = random_treatment() # Add cohort name to remark name to use for reminder messages nextUserID = int(cohort + str(nextUserID)) print("adding new user", nextUserID, "assigning treatment", treatment, "...") for day in range(1, 3): user_id_hashids = Hashids(salt=str(10 * nextUserID + day) + "user_id", min_length=16) day_hashids = Hashids(salt=str(10 * nextUserID + day) + "day", min_length=10) hashed_user_id = user_id_hashids.encrypt(nextUserID) hashed_day = day_hashids.encrypt(day) requests.post("https://dailyeventinfo.com/userInsert/" + str(nextUserID) + "/" + str(day) + "/" + str(userName) + "/" + str(cohort) + "/" + str(treatment) + "/" + hashed_user_id + "/" + hashed_day) requests.post("https://dailyeventinfo.com/activityUpdate/" + str(nextUserID) + "/1/0/0/0/0") day = 1 user_id_hashids = Hashids(salt=str(10 * nextUserID + day) + "user_id", min_length=16) day_hashids = Hashids(salt=str(10 * nextUserID + day) + "day", min_length=10) hashed_user_id = user_id_hashids.encrypt(nextUserID) hashed_day = day_hashids.encrypt(day) day1_url = "https://dailyeventinfo.com/xian/" + hashed_user_id.strip( ) + "/" + hashed_day.strip() + "/info" print(day1_wechat_prompt) print(day1_url) # Set remark_name to use for reminder messages print(str(nextUserID))
def forgotten_password(request): text_for_result = '' form = forgotten_password_form() if request.method == 'POST': form = forgotten_password_form(request.POST) if form.is_valid(): try: email = request.POST.get('email') member = Member.objects.filter(email=email)[0] memberUser = User.objects.filter(email=email)[0] hashids = Hashids() hashid = hashids.encrypt(member.password) memberUser.set_password(str(hashid)) member.password = str(hashid) if member: template = get_template("mail_forgotten_password.html") context = Context({ 'username': member.username, 'password': member.password }) content = template.render(context) mailgun_operator = mailgun() mailgun_operator.send_mail_with_html(member.email, content) text_for_result = 'We are send your password to your email. ' else: text_for_result = 'Wrong mail address.' return HttpResponseRedirect('/accounts/login') except Exception as e: print e return HttpResponseRedirect('/sorry') return render_to_response('forgotten_password.html', locals(), context_instance=RequestContext(request))
def gen_new_id(model): if model.find({}): hashids = Hashids(salt=SALT, min_length="6") id = model.find({}).count() + 1 return hashids.encrypt(id) else: raise "Model doesn\'n exist"
def get_new_id(model): hashids = Hashids(salt=SALT, min_length="6") try: id = model.find({}).count() + 1 except: id = 0 return hashids.encrypt(id)
def gen_new_id(model): if model.find({}): hashids = Hashids(salt=SALT, min_length="6") id = model.find({}).count() + 1 return hashids.encrypt(id) else: raise "Model doesn'n exist"
def forgotten_password(request): text_for_result = '' form = forgotten_password_form() if request.method == 'POST': form = forgotten_password_form(request.POST) if form.is_valid(): try: email = request.POST.get('email') member = Member.objects.filter(email=email)[0] memberUser = User.objects.filter(email=email)[0] hashids = Hashids() hashid = hashids.encrypt(member.password) memberUser.set_password(str(hashid)) member.password = str(hashid) if member: template = get_template("mail_forgotten_password.html") context = Context({'username': member.username, 'password': member.password}) content = template.render(context) mailgun_operator = mailgun() mailgun_operator.send_mail_with_html(member.email, content) text_for_result = 'We are send your password to your email. ' else: text_for_result = 'Wrong mail address.' return HttpResponseRedirect('/accounts/login') except Exception as e: print e return HttpResponseRedirect('/sorry') return render_to_response('forgotten_password.html', locals(), context_instance=RequestContext(request))
def get_new_id(model, length): hashids = Hashids(salt=SALT, min_length=length) try: id = model.find({}).count() + 1 except: id = 0 return hashids.encrypt(id)
def forgotten_password(request): text_for_result = '' form = forgotten_password_form() if request.method == 'POST': form = forgotten_password_form(request.POST) if form.is_valid(): try: email = request.POST.get('email') member = User.objects.filter(email=email)[0] hashids = Hashids() hashid = hashids.encrypt(member.username) member.set_password(str(hashid)) if member: context = Context({ 'username': member.username, 'password': str(hashid) }) mailgun_operator = mailgun() mailgun_operator.send_mail_with_html( email_to=member.email, template_name='mail_forgotten_password.html', context=context, subject='Forgotten Password') text_for_result = 'We are send your password to your email.' else: text_for_result = 'Wrong mail address.' except Exception as e: print e return HttpResponseRedirect('/sorry') return render_to_response('forgotten_password.html', locals(), context_instance=RequestContext(request))
class ID(object): def __init__(self): self.hashids = Hashids(salt='!@sasSD092f0Hu7&', min_length=6) def int2hash(self, id): return self.hashids.encrypt(long(id)) def hash2int(self, hash_id): return self.hashids.decrypt(hash_id)[0]
def save(self, **kwargs): ''' Sobreescribe el save(), asignando un codigo de reservacion unico ''' self.full_clean() super(Reservacion, self).save() hashids = Hashids(min_length=5, salt=uuid.uuid1().hex) self.codigo = hashids.encrypt(self.id).upper() super(Reservacion, self).save()
def generate_hash(redis_connection, redis_namespace=':short', hash_salt=''): """ Generates an URL hash. This will increase the hash counter for the current day no mater if the hash will be used or not. """ days_since_epoch = int(time.time() / 86400) day_index = redis_connection.incr(redis_namespace + 'HI:' + str(days_since_epoch)) hashids = Hashids(salt=hash_salt) return hashids.encrypt(days_since_epoch, day_index)
def form_valid(self, form): form.instance.user = self.request.user hashids = Hashids(min_length = 4, salt="browndogbella") previous = Bookmark.objects.latest('id') previousid = previous.id if previous.id is None: previousid = 0 form.instance.short = hashids.encrypt(previousid + 1) messages.add_message(self.request, messages.SUCCESS,"You created a bookmark!") return super(BookmarkCreate, self).form_valid(form)
def create(self, validated_data): hashids = Hashids(min_length = 4, salt="ArloBeaIdaKatie") previous = Bookmark.objects.latest('id') previousid = previous.id if previous.id is None: previousid = 0 bookmark = Bookmark.objects.create(**validated_data) bookmark.short = hashids.encrypt(previousid + 1) bookmark.save() return bookmark
class HashidsPrimaryKeyField(serializers.Field): def __init__(self, *args, **kwargs): salt = kwargs.pop('salt', settings.SECRET_KEY) min_length = kwargs.pop('min_length', settings.HASHIDS_MIN_LENGTH) self.hashids = Hashids(salt=salt, min_length=min_length) super(HashidsPrimaryKeyField, self).__init__(*args, **kwargs) def to_native(self, value): return self.hashids.encrypt(value)
def recuperar_contrasena(request): ''' Controlador correspondiente a la recuperacion de contrasena Parametros: request -> Solicitud HTTP ''' datos = {} if request.method == 'GET': formulario_recuperar_contrasena = RecuperarContrasenaForm() elif request.method == 'POST': formulario_recuperar_contrasena = RecuperarContrasenaForm(request.POST) if formulario_recuperar_contrasena.is_valid(): nombre_usuario = formulario_recuperar_contrasena.cleaned_data['nombre_usuario'] usuario = User.objects.filter(username=nombre_usuario, is_active=True).first() if usuario: ''' Enviar Email al usuario ''' tipo_usuario = obtener_tipo_usuario(usuario.cuenta) email_usuario = '' if tipo_usuario == 'medico': if usuario.cuenta.medico.email: email_usuario = usuario.cuenta.medico.email else: messages.add_message(request, messages.ERROR,MensajeTemporalError.RECUPERAR_CONTRASENA_SIN_EMAIL) return redirect('recuperar_contrasena') elif tipo_usuario == 'departamento': if usuario.cuenta.departamento.email: email_usuario = usuario.cuenta.departamento.email else: messages.add_message(request, messages.ERROR,MensajeTemporalError.RECUPERAR_CONTRASENA_SIN_EMAIL) return redirect('recuperar_contrasena') else: if usuario.email: email_usuario = usuario.email with transaction.atomic(): hashids = Hashids(min_length=5, salt=uuid.uuid1().hex) password = hashids.encrypt(usuario.cuenta.id).upper() usuario.cuenta.clave_inicial = password usuario.set_password(password) usuario.save() usuario.cuenta.save() enviar_email(asunto='Recuperación de Clave de Acceso.', contenido_texto='Su clave de acceso ha sido recuperada. Su nombre de usuario es: ' + usuario.username + ' y su clave de acceso es: ' + usuario.cuenta.clave_inicial + ' .', contenido_html='', recipiente='*****@*****.**') messages.add_message(request, messages.SUCCESS, MensajeTemporalExito.RECUPERAR_CONTRASENA_EXITOSO) return redirect('inicio') else: messages.add_message(request, messages.ERROR, MensajeTemporalError.RECUPERAR_CONTRASENA_FALLIDO) return redirect('recuperar_contrasena') datos["formulario_recuperar_contrasena"] = formulario_recuperar_contrasena return render_to_response('autenticacion/recuperar_contrasena.html', datos, context_instance=RequestContext(request))
def get_instance_form(self, applicant, offer, form): hashid = Hashids(salt='codetag Job Post') if OfferApplicant.objects.filter(applicant=applicant, offer=offer).exists(): offer_applicant = OfferApplicant.objects.get(applicant=applicant, offer=offer) offer_applicant.observation = form.cleaned_data['observation'] offer_applicant.resume = form.cleaned_data['resume'] offer_applicant.state = False offer_applicant.token = hashid.encrypt(offer.id, applicant.id) offer_applicant.save() else: offer_applicant = OfferApplicant() offer_applicant.applicant = applicant offer_applicant.offer = offer offer_applicant.observation = form.cleaned_data['observation'] offer_applicant.resume = form.cleaned_data['resume'] offer_applicant.state = False offer_applicant.token = hashid.encrypt(offer.id, applicant.id) offer_applicant.save() return offer_applicant
def test_serialization(self): id = 1001 content = 'foo' msg = Message(id, content) serializer = MessageSerializer(msg) hashids = Hashids(salt=settings.SECRET_KEY, min_length=settings.HASHIDS_MIN_LENGTH) self.assertNotEquals(serializer.data.get('id'), msg.id) self.assertEquals(serializer.data.get('id'), hashids.encrypt(msg.id))
def shortenURL(anonymous = True): from hashids import Hashids import random hashids = Hashids(salt="Kilimokwanza", min_length=4) if len(Bookmark.objects.all()) == 0: lastentry = Bookmark() lastentry.id = 0 else: lastentry = Bookmark.objects.latest('id') return hashids.encrypt(lastentry.id+1)
def createHash(identificator): '''Generator of public hash keys This method automatically generate unique public hashes to be used when referencing objects inside the system. This is done to introduce identificator obfuscation and to stop URL snooping attempts. Args: :identificator (int): identificator number to ofuscate (usually the model id) ''' hashids = Hashids(salt="esh2YTBZesh2YTBZ", min_length=5) return hashids.encrypt(identificator)
def form_valid(self, form): # #this is what happens when the formis valid form.instance.user = self.request.user hashids = Hashids(min_length = 4, salt="ArloBeaIdaKatie") previous = Bookmark.objects.latest('id') previousid = previous.id if previous.id is None: previousid = 0 form.instance.short = hashids.encrypt(previousid + 1) # # #super will save for you messages.add_message(self.request, messages.SUCCESS,"You created a bookmark!") return super(BookmarkCreate, self).form_valid(form)
class HashidsPrimaryKeyRelatedField(serializers.PrimaryKeyRelatedField): def __init__(self, *args, **kwargs): salt = kwargs.pop('salt', settings.SECRET_KEY) min_length = kwargs.pop('min_length', settings.HASHIDS_MIN_LENGTH) self.hashids = Hashids(salt=salt, min_length=min_length) super(HashidsPrimaryKeyRelatedField, self).__init__(*args, **kwargs) def to_native(self, pk): return self.hashids.encrypt(pk) def from_native(self, data): pk = self.hashids.decrypt(data)[0] return super(HashidsPrimaryKeyRelatedField, self).from_native(pk)
def short(): link_id = '' site = request.forms.get("txtSearch") ip = request.environ.get('REMOTE_ADDR') generated_id = Hashids(salt=site, min_length=8) link_id = generated_id.encrypt(len(site) + int(str.replace(ip, '.', ''))) addUrl = conn.execute("INSERT INTO shorted(ShortID, Url) VALUES('" + link_id + "', '" + site + "');") conn.commit() if addUrl: return dict(Data=link_id) else: return dict(Data="Eklenirken Hata Oluştu") conn.close()
def create_bookmarks(num_bookmarks): fake = Faker() hashids = Hashids(min_length = 4, salt="ArloBeaIdaKatie") for i in range(num_bookmarks): bookmark = Bookmark() users = User.objects.all() bookmark.user = random.choice(users) bookmark.long = fake.uri() bookmark.short = hashids.encrypt(i) bookmark.title = fake.bs() bookmark.description = fake.catch_phrase() unaware = fake.date_time_between(start_date="-4m", end_date="-2m") now_aware = unaware.replace(tzinfo=pytz.UTC) bookmark.created = now_aware bookmark.edited = now_aware bookmark.save()
def aceptar_solicitud_usuario(request): ''' Controlador correspondiente a la aprobacion de solicitudes de usuarios Parametros: request -> Solicitud HTTP ''' formulario_solicitud_usuario = GestionarSolicitudUsuarioForm(request.POST) if formulario_solicitud_usuario.is_valid(): id_cuenta = int(formulario_solicitud_usuario.cleaned_data['id_cuenta']) try: cuenta_usuario = Cuenta.objects.get(id=id_cuenta) except ObjectDoesNotExist: messages.add_message(request, messages.ERROR, MensajeTemporalError. APROBACION_USUARIO_FALLIDA) with transaction.atomic(): cuenta_usuario.estado = 'A' hashids = Hashids(min_length=5, salt=uuid.uuid1().hex) password = hashids.encrypt(cuenta_usuario.id).upper() cuenta_usuario.clave_inicial = password usuario = cuenta_usuario.usuario usuario.is_active = True usuario.set_password(password) usuario.save() cuenta_usuario.save() ''' Enviar Email al usuario ''' tipo_usuario = '' try: if cuenta_usuario.medico: tipo_usuario = 'medico' except ObjectDoesNotExist: tipo_usuario = 'departamento' if tipo_usuario == 'medico': if cuenta_usuario.medico.email: enviar_email(asunto='Su cuenta ha sido aprobada.', contenido_texto='La cuenta solicitada ha sido aprobada. Su usuario es: ' + cuenta_usuario.usuario.username + ' y su clave de acceso es: ' + cuenta_usuario.clave_inicial + ' .', contenido_html='', recipiente='*****@*****.**') elif tipo_usuario == 'departamento': if cuenta_usuario.departamento.email: enviar_email(asunto='Su cuenta ha sido aprobada.', contenido_texto='La cuenta solicitada ha sido aprobada. Su usuario es: ' + cuenta_usuario.usuario.username + ' y su clave de acceso es: ' + cuenta_usuario.clave_inicial + ' .', contenido_html='', recipiente='*****@*****.**') messages.add_message(request, messages.SUCCESS, construir_mensaje(MensajeTemporalExito.SOLICITUD_USUARIO_APROBADA, "La clave de acceso del usuario es: " + cuenta_usuario.clave_inicial)) else: messages.add_message(request, messages.ERROR, MensajeTemporalError. APROBACION_USUARIO_FALLIDA) return redirect('solicitudes_usuarios')
def forgotten_password(request): text_for_result = '' form = forgotten_password_form() if request.method == 'POST': form = forgotten_password_form(request.POST) if form.is_valid(): try: email = request.POST.get('email') member = User.objects.filter(email=email)[0] hashids = Hashids() hashid = hashids.encrypt(member.username) member.set_password(str(hashid)) if member: context = Context({'username': member.username, 'password': str(hashid)}) mailgun_operator = mailgun() mailgun_operator.send_mail_with_html(email_to=member.email, template_name='mail_forgotten_password.html', context=context, subject='Forgotten Password') text_for_result = 'We are send your password to your email.' else: text_for_result = 'Wrong mail address.' except Exception as e: print e return HttpResponseRedirect('/sorry') return render_to_response('forgotten_password.html', locals(), context_instance=RequestContext(request))
def gen_auth_token(userid): hashids = Hashids(salt=userid) dt = datetime.datetime.now() to_encrypt = int(dt.strftime("%d"))+int(dt.strftime("%m"))+int(dt.strftime("%Y")) return hashids.encrypt(to_encrypt,int(dt.strftime("%S"))+to_encrypt)
cohort_users = users.loc[users.cohort == int( cohort)].drop_duplicates(subset=['user_id']) if len(cohort_users) == 0: previousMax = 0 else: previousMax = int( (max(pd.to_numeric(cohort_users['user_id'])) % 1e6) / 1e3) nextUserID = int( int(cohort) * 1e7 + int(surveyorNumber) * 1e6 + (previousMax + 1) * 1e3 + randint(1, 999)) user_id_hashids = Hashids(salt=str(10 * nextUserID + day) + "user_id", min_length=16) day_hashids = Hashids(salt=str(10 * nextUserID + day) + "day", min_length=10) hashed_user_id = user_id_hashids.encrypt(nextUserID) hashed_day = day_hashids.encrypt(day) requests.post(URL + "userInsert/" + str(nextUserID) + "/" + str(day) + "/" + str("lll" + str(k) + str(day)) + "/" + cohort + "/" + str("T" + str(k)) + "/" + hashed_user_id + "/" + hashed_day) requests.post(URL + "activityUpdate/" + str(nextUserID) + "/" + str(day) + "/0/0/0/0") print(URL + "shanghai/" + hashed_user_id + "/" + hashed_day + "/info") if (part == 2): for r in range(1): for k in range(1, 5): print("Treatment " + str(k)) for day in range(1, 7):
def new_user_process(input_ID): users = get_users() cohort_users = users.loc[users.cohort == int(cohort)].drop_duplicates( subset=['user_id']) cohort_users['surveyor'] = ( (pd.to_numeric(cohort_users['user_id']) / 1e6) % 10).astype(int) curr_cohort_user_count = int( len( set(cohort_users.loc[cohort_users.surveyor == int(surveyorNumber)] ['user_id']))) if input_ID in list( set(users.loc[users.cohort != int(cohort)] ['wechat_id'])): # Already existing user from prev. cohorts return ["EXISTING USER", msg_ineligible] elif input_ID in list(set(cohort_users['wechat_id']) ): # Already existing user in current cohort if cohort_users.loc[cohort_users.wechat_id == input_ID].iloc[0]['surveyor'] != surveyorNumber: return [ "(DUPLICATE INPUT: OTHER SURVEYOR'S SUBJECT)", "[DON'T SEND ANY MESSAGE; NOTIFY ZIXIN ABOUT THIS DUPLICATE]" ] else: theUser = cohort_users.loc[(cohort_users.wechat_id == input_ID) & (cohort_users.day == 0)] msg_URL = URL + "s/" + theUser.user_id_hashid.iloc[ 0] + "/" + theUser.day_hashid.iloc[0] + "/info" return [ "(DUPLICATE INPUT) SAVE USER AS: " + str(theUser.user_id.iloc[0]), msg_initial + msg_URL ] elif curr_cohort_user_count >= maxnum_cohort: # Max cohort size reached requests.post(URL + "userInsert/WAITLIST/TBD" + "/" + str(input_ID) + "/" + str(int(cohort) + 1) + "/TBD/TBD/TBD") return ["MAX SIZE REACHED: SAVED IN WAITLIST", msg_maxnum_cohort] else: # Create nickname # if len(cohort_users) == 0: previousMax = 0 else: previousMax = int( (max(pd.to_numeric(cohort_users['user_id'])) % 1e6) / 1e3) nextUserID = int( int(cohort) * 1e7 + int(surveyorNumber) * 1e6 + (previousMax + 1) * 1e3 + randint(1, 999)) # Assign treatment group # treatment = "T" + str(seq[previousMax] + 1) # Save user profile in allUsers # for day in range(maxday + 1): user_id_hashids = Hashids(salt=str(10 * nextUserID + day) + "user_id", min_length=16) day_hashids = Hashids(salt=str(10 * nextUserID + day) + "day", min_length=10) hashed_user_id = user_id_hashids.encrypt(nextUserID) hashed_day = day_hashids.encrypt(day) requests.post(URL + "userInsert/" + str(nextUserID) + "/" + str(day) + "/" + str(input_ID) + "/" + str(cohort) + "/" + str(treatment) + "/" + hashed_user_id + "/" + hashed_day) if day == 0: msg_URL = URL + "shanghai/" + hashed_user_id + "/" + hashed_day + "/info" ## XXX Change URL accordingly # Set up initial allActivities # requests.post( URL + "activityUpdate/" + str(nextUserID) + "/0/0/0/0/0" ) ## XXX I put day 0 here for new user. Is this going to be a problem? (I need this so that we send correct reminder for people who didn't even finish consent form) # Return output for surveyors # return ["SAVE USER AS: " + str(nextUserID), msg_initial + msg_URL]
def test_alphabet(self): h = Hashids(alphabet='!"#%&\',-/0123456789:;<=>ABCDEFGHIJKLMNOPQRSTUVWXYZ_`abcdefghijklmnopqrstuvwxyz~') assert h.encrypt(2839, 12, 32, 5) == '_nJUNTVU3' assert h.encrypt(1, 2, 3) == '7xfYh2' assert h.encrypt(23832) == 'Z6R>' assert h.encrypt(99, 25) == 'AYyIB'
def hash_day(row): nextUserID = row['nextUserID'] day_hashids = Hashids(salt=str(10 * nextUserID + day) + "day", min_length=10) hashed_day = day_hashids.encrypt(day) return hashed_day
def save(self, *args, **kwargs): if not self.pk: hashids = Hashids(settings.SECRET_KEY) self.hash = hashids.encrypt(int(round(time.time() * 10000))) super(Paste, self).save(*args, **kwargs)
from hashids import Hashids hashids = Hashids(salt='deutsch', min_length=5, alphabet='abcdefghijkmnopqrstuvwxyz') for i in range(12000,12100): print (hashids.encrypt(i))
def test_only_one_valid(self): h = Hashids(min_length=6) assert h.decrypt(h.encrypt(1)[:-1] + '0') == ()
def test_multiple_numbers(self): h = Hashids() assert h.encrypt(683, 94108, 123, 5) == 'vJvi7On9cXGtD' assert h.encrypt(1, 2, 3) == 'o2fXhV' assert h.encrypt(2, 4, 6) == 'xGhmsW' assert h.encrypt(99, 25) == '3lKfD'
def test_alphabet_with_two_standard_separators(self): h = Hashids(alphabet='abdegjklmnopqrvwxyzABDEGJKLMNOPQRVWXYZ1234567890uC') assert h.encrypt(7452, 2967, 21401) == 'GJNNmKYzbPBw' assert h.encrypt(1, 2, 3) == 'DQCXa4' assert h.encrypt(60125) == '38V1D' assert h.encrypt(99, 25) == '373az'
def test_alphabet_without_standard_separators(self): h = Hashids(alphabet='abdegjklmnopqrvwxyzABDEGJKLMNOPQRVWXYZ1234567890') assert h.encrypt(7452, 2967, 21401) == 'X50Yg6VPoAO4' assert h.encrypt(1, 2, 3) == 'GAbDdR' assert h.encrypt(60125) == '5NMPD' assert h.encrypt(99, 25) == 'yGya5'
def test_all_parameters(self): h = Hashids('arbitrary salt', 16, 'abcdefghijklmnopqrstuvwxyz') assert h.encrypt(7452, 2967, 21401) == 'wygqxeunkatjgkrw' assert h.encrypt(1, 2, 3) == 'pnovxlaxuriowydb' assert h.encrypt(60125) == 'jkbgxljrjxmlaonp' assert h.encrypt(99, 25) == 'erdjpwrgouoxlvbx'
def test_min_length(self): h = Hashids(min_length=25) assert h.encrypt(7452, 2967, 21401) == 'pO3K69b86jzc6krI416enr2B5' assert h.encrypt(1, 2, 3) == 'gyOwl4B97bo2fXhVaDR0Znjrq' assert h.encrypt(6097) == 'Nz7x3VXyMYerRmWeOBQn6LlRG' assert h.encrypt(99, 25) == 'k91nqP3RBe3lKfDaLJrvy8XjV'
def gen_uid(num, name=''): hashids = Hashids(salt='some salt', min_length=5) return hashids.encrypt(num + 1)
class notify(): def __init__(self, ): conf = config().token() self.hash_id = Hashids(salt=conf['hash'], min_length=int(conf['tamanho_token'])) def generate(self, user_id, email_monitor): self.key = randint(1000, 9999) filename = '{0}'.format(str(user_id)) pathname = os.path.abspath(os.path.join('tokens', filename)) save = '{0}:{1}:{2}'.format(str(self.key), str(user_id), email_monitor) f = open(os.path.abspath(os.path.join('tokens', filename)), 'w').write(save) key_hash = self.hash_id.encrypt(self.key) result_send = sendemail(email_monitor, key_hash) return result_send def verify(self, user_id, msg, leaks): db = banco() response = textos['monitor_ativado_err'] if len(msg.split(' ')) == 3: cmd, email1, key_hash = msg.split(' ') filename = '{0}'.format(str(user_id)) pathname_token = os.path.abspath(os.path.join('tokens', filename)) if os.path.exists(pathname_token): if checkemail(email1) != None: for code in open(pathname_token): key, user, email = code.split(':') #QUERY BANCO result_key_hash = self.hash_id.decrypt(key_hash) if result_key_hash: if user_id == int(user) and result_key_hash[ 0] == int(key) and email1 == email.strip(): response = textos['monitor_ativado'] db.users.insert(user_service_id=user_id, email=email1) user = db(db.users.user_service_id == user_id).select().first() for leak in leaks.check(email1): db.leaks.insert(leaksource=leak, user_id=user) db.commit() os.remove(pathname_token) break else: response = textos['codigo_invalido'] else: response = textos['email_invalido'] else: response = textos['codigo_invalido'] return response def delete(self, user_id, msg): db = banco() cmd, email = msg.split(' ') query = db((db.users.user_service_id == user_id) & (db.users.email == email)) user = query.select() if user: query.delete() response = textos['delete_ok'] db.commit() else: response = textos['delete_err'] return response def monitor(self, user_id, msg): db = banco() monitor = msg.split(' ') if len(monitor) == 2: email_monitor = monitor[1] check_email = checkemail(email_monitor) if check_email != None: user = db((db.users.user_service_id == user_id) & (db.users.email == email_monitor)).select().first() if not user: email_result = self.generate(user_id, email_monitor) if email_result: response = textos['email_monitor_ativado'].format( email_monitor) else: response = textos['email_monitor_err'].format( email_monitor) else: response = textos['email_ja_cadastrado'] else: response = textos['email_invalido'] return response
def linkHash(self): hasher = Hashids(settings.EXCHANGE_HASH_SALT) return hasher.encrypt(self.id)
np.arange(1), 5), # change to 9 if repeat for day 0 (consent) - day 8 (inclusive) 'userName': '******', 'cohort': 5, 'treatment': 'T', 'link': 'link', } df = pd.DataFrame(dict) index = 0 # keep track of the row index for user_id in user_ids: # hashing user_id_hashids = Hashids(salt=str(10 * user_id + day) + "user_id", min_length=16) day_hashids = Hashids(salt=str(10 * user_id + day) + "day", min_length=10) hashed_user_id = user_id_hashids.encrypt(user_id) hashed_day = day_hashids.encrypt(day) # shanghai cohort cohort = 5 # TODO TODO TODO # cohort = 4 # iterate through each treatment treatment = treatments[user_id % 5] df.at[index, 'treatment'] = treatment # dummy username userName = '******' + str(user_id) # create link df.at[ index, 'link'] = "http://127.0.0.1:5000/shanghai/" + hashed_user_id + "/" + hashed_day + "/info" # update user table requests.post("http://127.0.0.1:5000/userInsert/" + str(user_id) + "/" +
def new_user_process(input_ID, surveyorNumber): db = get_db() users = get_users() cohort_users = users.loc[users.cohort == int(cohort)].drop_duplicates( subset=['user_id']) cohort_users['surveyor'] = ( (pd.to_numeric(cohort_users['user_id']) / 1e6) % 10).astype(int) curr_cohort_user_count = int(len(set(cohort_users['user_id']))) curr_cohort_user_count_mine = int( len( set(cohort_users.loc[cohort_users.surveyor == int( surveyorNumber)]['user_id']))) if (' ' in str(input_ID)): # Prevent inputting space in the input ID return ['<b><font color="red">无效微信号,请核对后再输入一次!</font></b>'] elif input_ID in list( set(users.loc[users.cohort != int(cohort)]['wechat_id']) ): # Already existing user from prev. cohorts return [u'<b><font color="red">该用户已存在</font></b>!', msg_ineligible] elif input_ID in list(set(cohort_users['wechat_id']) ): # Already existing user in current cohort if (int(cohort_users.loc[cohort_users.wechat_id == input_ID]. iloc[0]['surveyor']) != int(surveyorNumber)): return [ u'<font color="red">(其他研究员已输入过该微信号!请不要发送任何信息,并将此用户告知 Zixin 子鑫)<br></font>' ] else: theUser = cohort_users.loc[(cohort_users.wechat_id == input_ID) & (cohort_users.day == 0)] msg_URL = URL + "shanghai/" + theUser.user_id_hashid.iloc[ 0] + "/" + theUser.day_hashid.iloc[0] + "/info" return [ u'<b><font color="red">(您已输入过该微信号!)<br></font>请将其备注名改为</b>:\ <span style="background-color:PaleGreen;">' + str(theUser.user_id.iloc[0]), msg_initial + msg_URL + '<br><br><b>🔺copy above (do not forget URL)</b><span>' ] elif curr_cohort_user_count_mine >= maxnum_cohort_each: # Surveyor's quota is filled if curr_cohort_user_count >= maxnum_cohort: # Cohort mix size reached db.execute( 'INSERT INTO user (user_id, day, wechat_id, cohort, treatment, user_id_hashid, day_hashid)' ' VALUES (?, ?, ?, ?, ?, ?, ?)', ('WAITLIST', 'TBD', str(input_ID), str(int(cohort) + 1), 'TBD', 'TBD', 'TBD')) db.commit() return [ u'<font color="red">人数上限已满:已存入候补名单</font>', msg_maxnum_cohort ] else: return [ u'<font color="red">你的招募人数上限已经达到(棒),但是其他调查者还没有完成。请联系子鑫,请其他调查者招募此用户!</font>' ] else: # Create nickname # if len(cohort_users) == 0: previousMax = 0 else: previousMax = int( (max(pd.to_numeric(cohort_users['user_id']) % 1e6)) / 1e3) nextUserID = int( int(cohort) * 1e7 + int(surveyorNumber) * 1e6 + (previousMax + 1) * 1e3 + randint(1, 999)) # Assign treatment group # treatment = seq_str[seq[previousMax]] # Save user profile in allUsers # for day in range(maxday + 1): user_id_hashids = Hashids(salt=str(10 * nextUserID + day) + "user_id", min_length=16) day_hashids = Hashids(salt=str(10 * nextUserID + day) + "day", min_length=10) hashed_user_id = user_id_hashids.encrypt(nextUserID) hashed_day = day_hashids.encrypt(day) db.execute( 'INSERT INTO user (user_id, day, wechat_id, cohort, treatment, user_id_hashid, day_hashid)' ' VALUES (?, ?, ?, ?, ?, ?, ?)', (str(nextUserID), str(day), str(input_ID), str(cohort), str(treatment), hashed_user_id, hashed_day)) db.commit() if day == 0: msg_URL = URL + "shanghai/" + hashed_user_id + "/" + hashed_day + "/info" # Set up initial allActivities # now = datetime.now() db.execute( 'REPLACE INTO activity (user_id, day, day_complete, survey_page, day_started, curr_time)' ' VALUES (?, ?, ?, ?, ?, ?)', (str(nextUserID), 0, 0, 0, now, now)) db.commit() # Return output for surveyors # return [ u'<b>请将其备注名改为</b>:' + '<span style="background-color:PaleGreen;">' + str(nextUserID), msg_initial + msg_URL + '<br><br><b>🔺copy above (do not forget URL)</b><span>' ]
def __generate_id(self): hashids = Hashids(salt=ID_SALT, alphabet=ID_ALPHABET, min_length=6) return hashids.encrypt(int(time.time()))
def createHash(identificator): hashids = Hashids(salt="esh2YTBZesh2YTBZ", min_length=5) return hashids.encrypt(identificator)
def short_id(self): if self.slug: return self.slug else: hashids = Hashids(salt=settings.SECRET_KEY, min_length=4) return hashids.encrypt(self.id)
def test_salt(self): h = Hashids(salt='Arbitrary string') assert h.encrypt(683, 94108, 123, 5) == 'QWyf8yboH7KT2' assert h.encrypt(1, 2, 3) == 'neHrCa' assert h.encrypt(2, 4, 6) == 'LRCgf2' assert h.encrypt(99, 25) == 'JOMh1'