Exemplo n.º 1
0
    def form_valid(self, form):
        username = generate_username()[0]
        exists = User.objects.filter(username=username)
        if exists:
            username = '******'.format(generate_username()[0], randint(1, 999))

        User.objects.create(email=form.cleaned_data['email'],
                            username=username)
        messages.success(self.request, 'Welcome to PyATL!')
        return super().form_valid(form)
Exemplo n.º 2
0
def fast_signup():
    form = CadastroRapido()

    rand_name = generate_username(1)[0]
    rand_email = (rand_name + '@email.com').lower()
    rand_password = str(uuid.uuid4())[:8]

    if form.validate_on_submit():
        user = User(email=rand_email,
                    name=rand_name,
                    password=rand_password,
                    role=roles['user'],
                    last_audio=None,
                    seed=None)
        db.session.add(user)
        db.session.commit()

        flash('Cadastrado rápido criado com sucesso!', 'success')
        flash(f'Email: {rand_email}', 'info')
        flash(f'Senha: {rand_password}', 'info')

        # Log in automatically and force remember_me
        login_user(user, True)
        # POST/REDIRECT/GET Pattern - Prevent unwanted redirects
        next = request.args.get('next')
        if next is None or not next.startswith('/'):
            next = url_for('main.sound_test')
        return redirect(url_for('main.sound_test'))
    users = User.query.all()
    return render_template('auth/fast_signup.html', form=form, users=users)
Exemplo n.º 3
0
 def handle(self, *args, **options):
     Tag.objects.bulk_create([Tag(tag=t[0], slug=t[1]) for t in tags],
                             ignore_conflicts=True)
     names = generate_username(int(options["num_users"]))
     User = get_user_model()
     users = [
         User.objects.create_user(username=n, password=self.password)
         for n in names
     ]
     print(users)
     gen = DocumentGenerator()
     gen.init_word_cache(5000)
     gen.init_sentence_cache(5000)
     for user in users:
         user = User.objects.get(username=user.username)
         user.profile.bio = gen.sentence()
         user.profile.save()
         articles = Article.objects.bulk_create([
             Article(
                 slug=make_slug(gen.sentence()),
                 title=gen.sentence(),
                 description=gen.sentence(),
                 body=gen.paragraph(),
                 author=user.profile,
             )
             # Make sure every user has at least 1 article
             for _ in range(random.randrange(1, self.article_upper_bound))
         ])
         print(articles)
         # Make sure every article has 1 tag, could add more later
         for article in articles:
             article.tags.add(Tag.objects.get(slug=random.choice(tags)[1]))
     self.stdout.write(self.style.SUCCESS(f"Created {len(users)} users"))
Exemplo n.º 4
0
def getUsername():

    maxAttempts = 3
    attempts = 0

    while attempts < maxAttempts:

        # Print message prompting user to input their name
        inputPrompt = ""
        if attempts == 0:
            inputPrompt = "\nTo begin, please enter your username:\n"
        else:
            inputPrompt = "\nPlease try again:\n"
        usernameFromInput = input(inputPrompt)

        # Validate username
        if len(usernameFromInput) < 5 or not usernameFromInput.isidentifier():
            print(
                "Your username must be at least 5 characters long, alphanumeric only (a-z/A-Z/0-9), have no spaces, and cannot start with a number!"
            )
        else:
            return usernameFromInput

        attempts += 1

    print("\nExhausted all " + str(maxAttempts) +
          " attempts, assigning username instead...")
    return generate_username()[0]
Exemplo n.º 5
0
def violent_pianist(host, port):
    #poc not my code I just instrumented it diff to understand it or try not sure original author ;) sorry google if u care
    usernames = generate_username(10)  # randomize user name here
    username = random.choice(usernames)
    hostname = "lol"
    sink_object = MST_120_Custom_channel(
        host, port, username)  #new object with access to mst120 channel
    print("Detecting if exploit is present using username: "******"successful hit on plugin rdp is vuln")

    else:
        print("Rdp Is Not Vulnerable")

    global_connection_dict = {
        "RSA_Modulus": sink_object.server_rsa_modulus,
        "RSA_Magic": sink_object.rsa_magic,
        "RSA_Server_Exponent": sink_object.rsa_SERVER_EXPONENT,
        "RSA_Bitlen": sink_object.rsa_bitlen,
        "RSA_Server_Random": sink_object.SERVER_RANDOM,
        "Channel_Socket": channel_socket,
        "Rc4_Enc_Key": rc4enckey,
        "Hmackey": hmackey
    }

    return (result, global_connection_dict)
Exemplo n.º 6
0
def RegistrationForm():
    if current_user.is_authenticated:
        return redirect(url_for("explore"))
    if request.method == "POST":
        first_name_ = request.form.get("f_name")
        last_name_ = request.form.get("l_name")
        a = generate_username(1)
        username_ = a[0]
        email_ = request.form.get("r_email")
        password_ = request.form.get("r_pass")
        confirm_password_ = request.form.get("c_pass")
        conditions = request.form.getlist("tc")
        hashed_password = bcrypt.generate_password_hash(password_).decode(
            "utf-8")
        if password_ == confirm_password_:
            user = User(
                first_name=first_name_,
                last_name=last_name_,
                username=username_,
                email=email_,
                password=hashed_password,
            )
            db.session.add(user)
            db.session.commit()
            flash(
                "Your account has been created! You will now be able to log in!",
                "success",
            )
            return render_template("home.html", title="Home")
        else:
            flash("Account not created as password was not confirmed", "info")
            return render_template("home.html", title="Home")
    return redirect(url_for("home"))
Exemplo n.º 7
0
def main():
    random = int(input('Enter random text you want:'))
    file1 = open("usr.csv", "w")
    file2 = generate_username(random)
    str1 = '\n'.join(map(str, file2))
    file1.write(str1)
    print(str1)
    file1.close()
    with open('usr.csv', 'r') as usr:
        while (True):
            username = usr.readline()
            print("Line: {}".format(username.strip()))
            if username == "":
                print("::DONE::")
                break
            # When a newline is returned, the line is empty.
            if username == "\n":
                print("::EMPTY LINE::")
                continue
            driver.implicitly_wait(10)
            email = driver.find_element_by_xpath('//*[@id="inbox_field"]')
            slow_typing(email, username)
            # driver.save_screenshot('image.png')
            driver.implicitly_wait(10)
            go = driver.find_element_by_xpath('//*[@id="go_inbox"]')
            go.click()

            driver.find_element_by_xpath('//*[@id="inbox_field"]').clear()
            driver.implicitly_wait(10)
def get_username():
    global user_names
    if len(user_names)>0:
        temp = user_names[0]
        user_names.pop(0)
        return temp
    else:
        return generate_username()[0]
Exemplo n.º 9
0
def room(request, room_name):
    user = generate_username(1)[0]
    author = user
    return render(request, 'room.html', {
        'room_name': room_name,
        'username': user,
        'author': author
    })
Exemplo n.º 10
0
 def is_safe(self, username):
     """
     Checks if username is safe to use
     """
     if is_safe_username(username):
         self.username = username
     else:
         username = generate_username(1)[0]
         self.username = username
Exemplo n.º 11
0
async def home(request):
    session = await get_session(request)
    last_visit = session['username'] if 'username' in session else None
    if last_visit == None:
        session['username'] = generate_username(1)[0]

    async with aiofiles.open('./views/index.html', mode='r') as f:
        contents = await f.read()
        return web.Response(text=contents, content_type='text/html')
Exemplo n.º 12
0
def CreateAccount(request):
    if request.method == 'POST':
        name = request.POST['hosname']
        username = generate_username(1)
        email = request.POST['email']
        address = request.POST['address']
        district = request.POST['dist']
        city = request.POST['city']
        if name.isalnum() == False or address.isalnum(
        ) == False or city.isalnum() == False or district.isalnum() == False:
            if name.isspace() or address.isspace() or city.isspace(
            ) or district.isspace():
                messages.warning(request, 'please enter valid information')
            else:
                if request.POST['pass'] == request.POST['confpass']:
                    try:
                        useremail = User.objects.get(email=email)
                        messages.warning(request,
                                         'This email is already registered !')
                    except User.DoesNotExist:
                        password = request.POST['pass']
                        user = User.objects.create_user(username=username[0],
                                                        email=email,
                                                        password=password,
                                                        first_name=name,
                                                        last_name='hospital')
                        if user:
                            messages.success(request,
                                             f'Account Created for {name}')
                            db = firebase.database()
                            db.child('Vendors').child(user.id).set({
                                "Vendor_Name":
                                name,
                                "Address":
                                address,
                                "city":
                                city,
                                'district':
                                district
                            })

                            login(request, user)
                            return redirect('dashboard')
                        else:
                            messages.warning(request,
                                             'Account not created try again')
                else:
                    messages.warning(request,
                                     "passwords didn't match ! Try again")
                    return redirect('signup')
        else:
            messages.warning(
                request,
                'Please provide valid information ! Fields must be text')

    return render(request, 'hospitalauth/signup.html')
Exemplo n.º 13
0
def signup():
    auth_data = generate_username(2)
    username = auth_data[0][:20]
    password = auth_data[1][:64]
    response = requests.post(f"{host}/am/signup",
                             params={
                                 "username": username,
                                 "password": password
                             })
    return username, password, response.json()
Exemplo n.º 14
0
    def __init__(self, username: str = None, email: str = None):
        self.domains = self.get_domains()
        self._email, self._email_hash = None, None

        if email is not None:
            self.email = email
        elif username is not None:
            self.email = username + choice(self.domains)
        else:
            self.email = generate_username()[0].lower() + choice(self.domains)
Exemplo n.º 15
0
def app():
    # Define Columns

    # Create random username
    user = generate_username(1)

    # Get tweet info
    df_tweets = load_predictions()
    tweet_info = get_tweet(df_tweets)
    tweet_body = tweet_info['text'].values[0].replace("\n", "<br>")
    counter = df_tweets.loc[df_tweets['flag'] == 1
                            & df_tweets['reviewed_target'].isna()].shape[0] - 1

    st.write('Is the following Tweet related to a real diaster?')

    if tweet_info['target'].values[0] == 1:
        predict_val = 'Disaster'
    else:
        predict_val = 'Not Disaster'

    predict_pct = int(tweet_info['probability'].values[0] * 100)

    c1, c2 = st.beta_columns(2)
    c1.write(f'Prediction: {predict_val} ({predict_pct}%)')
    c2.write(f'Remaining to Review: {counter}')

    test_html = html_body(user=generate_username(1),
                          tweet_body=tweet_body,
                          tweet_prob=tweet_info['probability'],
                          counter=counter,
                          data_url=data_url)

    # Tweet Container + Styling
    st.markdown(test_html, unsafe_allow_html=True)  #Title rendering

    c1, c2 = st.beta_columns(2)

    if c1.button(label="No, not a disaster", key="btn-not-disaster"):
        update_predictions(df_tweets, tweet_info, label=0)

    if c2.button(label="Yes, its a disaster", key='btn-disaster'):
        update_predictions(df_tweets, tweet_info, label=1)
Exemplo n.º 16
0
 def get_account(self, password=None):
     """Create and return a new account."""
     username = (generate_username(1)[0]).lower()
     domain = random.choice(self._get_domains_list())
     address = "{}@{}".format(username, domain)
     if not password:
         password = self._generate_password(6)
     response = self._make_account_request("accounts", address, password)
     account = Account(response["id"], response["address"], password)
     self._save_account(account)
     return account
Exemplo n.º 17
0
def svc2_checker(team_id, ip, flag, redis_conf):
    logger.info('Starting svc2_checker')
    requests.packages.urllib3.disable_warnings(category=InsecureRequestWarning)

    redis_conn = StrictRedis(**redis_conf,
                             charset="utf-8",
                             decode_responses=True)

    # getting state from last run
    state_key = get_redis_statuses_unique_key(team_id=team_id,
                                              service_id=SERVICE_NAME)
    state = redis_conn.hgetall(state_key)

    last_flag = state.get("last_flag")
    flag_pushed = state.get("flag_pushed") == 'True'
    status = state.get("status")
    username = state.get("username")
    password = state.get("password")

    # PUSH if flag is new (new round) or we didn't pushed in last try
    if last_flag != flag or not flag_pushed:
        username = generate_username(1)[0]
        password = generate_str(16)
        status, trace = push_flag(ip, flag, username, password)
        flag_pushed = status == SERVICE_STATE_UP

    # try pull if flag is pushed
    if flag_pushed:
        status, trace = pull_flag(ip, flag, username, password)

    # if PUSH is OK
    if status == SERVICE_STATE_UP:
        status, trace = check_functionality(ip)

    # state for checker, write whatever need. No strict format
    service_status = {
        'date': datetime.now().isoformat(),
        'last_flag': flag,
        'flag_pushed': flag_pushed,
        'username': username,
        'password': password
    }

    # saving full state
    redis_conn.hmset(state_key, service_status)

    # state for scoreboard, strict properties
    redis_conn.hset(state_key, 'status', status)
    redis_conn.hset(state_key, 'trace', trace)

    logger.info('Finishing svc2_checker')

    # return status for SLA calculation
    return status
Exemplo n.º 18
0
def main():
    parser = argparse.ArgumentParser(
        description='Generate Compelling Usernames.')
    parser.add_argument('num_results',
                        type=int,
                        default=1,
                        nargs='?',
                        help='Number of results to return')
    args = parser.parse_args()

    for username in generate_username(num_results=args.num_results):
        print(username)
Exemplo n.º 19
0
def create_supplier_account(request):

    supname = request.POST['supname']
    supusername = generate_username(1)
    supemail = request.POST['supemail']
    supaddress = request.POST.get('supaddress')
    supdist = request.POST['supdist']
    suppass = request.POST['suppass']
    supcity = request.POST['supcity']
    if supname.isalnum() == False or supaddress.isalnum(
    ) == False or supcity.isalnum() == False or supdist.isalnum() == False:
        if supname.isspace() or supaddress.isspace() or supcity.isspace(
        ) or supdist.isspace():
            messages.warning(request, 'Please enter valid imformation')
        else:
            if request.POST['suppass'] == request.POST['supconfpass']:
                try:
                    useremail = User.objects.get(email=supemail)
                    messages.warning(request,
                                     'This email is already registered !')
                    return redirect('signup')
                except User.DoesNotExist:
                    supplier = User.objects.create_user(
                        username=supusername[0],
                        email=supemail,
                        password=suppass,
                        first_name=supname,
                        last_name='supplier')
                    if supplier:
                        db = firebase.database()
                        db.child('Anucool_Employees').child(supplier.id).set({
                            'Employee_Name':
                            supname,
                            "city":
                            supcity,
                            'Address':
                            supaddress,
                            'district':
                            supdist,
                        })
                        print('accout created for supplier')
                        login(request, supplier)
                        messages.success(request,
                                         f'Account created for {supname} !')
                    return redirect('supplier_dashboard')
            else:
                messages.warning(request,
                                 "Passwords didn't match ! Please try again")
                return redirect('signup')
    else:
        messages.warning(request, "Please provide valid information")
        return redirect('signup')
Exemplo n.º 20
0
def create_new_chat():
    try:
        id = str(uuid.uuid4())
        name = generate_username(1)[0]
        chats_coll.add({
            "nid": id,
            "users": [],
            "chat": "",
            "name": name,
        }, id)
        return (redirect("/chat/{}".format(id)))
    except:
        return ("There is an error. Please try again.")
Exemplo n.º 21
0
def create_new_user(hashed_email: str) -> User:
    random_username = generate_username(1)[0]
    random_username = random_username.lower()
    pwo = PasswordGenerator()
    pwo.minlen = 30 # (Optional)
    pwo.maxlen = 30 # (Optional)
    pwo.minuchars = 2 # (Optional)
    pwo.minlchars = 3 # (Optional)
    pwo.minnumbers = 1 # (Optional)
    pwo.minschars = 0 # (Optional)
    pwo.excludeschars = "!$%^*:="
    random_password = pwo.generate()
    random_email = f'{random_username}@example.com'
    return add_user(f'{random_username}', random_password, random_email, '', hashed_email, exitOnFailure=False)
Exemplo n.º 22
0
def generate_random_username(length=5, chars=ascii_lowercase + digits, split=4, delimiter=''):
    username = generate_username(1)[0] + ''.join(
        [choice(chars) for i in range(length)]
    )
    if split:
        username = delimiter.join(
            [username[start:start + split] for start in range(0, len(username), split)]
        )
    try:
        Profile.objects.get(username=username)
        return generate_random_username(
            length=length, chars=chars, split=split, delimiter=delimiter
        )
    except Profile.DoesNotExist:
        return username
Exemplo n.º 23
0
    def post(self, request, **kwargs):
        """
        Update the user's account information.
        """
        Stream = apps.get_model("music.Stream")
        Ticket = apps.get_model("music.Ticket")

        if not request.user.profile.activated_at:
            self.http_response_403("Not permitted")

        stream_name = request.POST.get("name", None)
        tags = request.POST.get("tags", None)
        if not stream_name or not tags:
            self.http_response_400("Missing data")

        now = datetime.now()
        holder_name = (
            request.user.profile.default_display_name or generate_username(1)[0]
        )

        stream = Stream.objects.create(
            title=stream_name,
            tags=tags,
            owner=request.user,
            owner_name=holder_name,
            status=Stream.STATUS_ACTIVATED,
        )
        stream.unique_custom_id = str(stream.uuid)
        stream.save()

        Ticket.objects.create(
            stream=stream,
            holder=request.user,
            email=request.user.email,
            name=holder_name,
            is_administrator=True,
            updated_at=now,
        )

        async_to_sync(channel_layer.group_send)(
            "homepage",
            {
                "type": "send_update",
                "text": {"created": {"stream": [Stream.objects.serialize(stream)],}},
            },
        )

        return self.http_response_200({})
Exemplo n.º 24
0
def user_uploader():
    start = time.time()
    user_list = []
    ct = datetime.datetime.utcnow()
    usernames_list = generate_username(10005)
    new_usernames_list = [username + str(random.randint(0, 100000000)) for username in usernames_list]
    passwords_list = generate_passwords(10005)
    count = 0
    with open('data/PP_users.csv', encoding='utf8') as csv_file:
        csv_reader = csv.reader(csv_file, delimiter=',')
        # skip first row
        next(csv_reader)
        for row in csv_reader:
            if count < 10000: # skip those under 5011
                count +=1
                continue
            # we dont want UserIds greater than 20000
            if int(row[0]) > 20000:
                continue
            new_user = user(row[0], new_usernames_list[count-10000], passwords_list[count-10000], ct, ct)
            user_list.append(new_user.getList())
            count += 1
            if count == 20001:  # this means end at recipe #15000
                break

    sql = """INSERT INTO "Users"("UserId", "Username", "Password", "DateJoined", "LastAccessDate") VALUES(%s, %s, %s, %s, %s)"""
    conn = None
    try:
        # connect to the PostgreSQL database
        conn = conn = psycopg2.connect(host="reddwarf.cs.rit.edu", database="p320_03f", user="******",
                                       password="******")
        # create a new cursor
        cur = conn.cursor()
        # execute the INSERT statement
        for userinfo in user_list:
            cur.execute(sql, (userinfo[0], userinfo[1], userinfo[2], userinfo[3], userinfo[4]))
        # commit the changes to the database
        conn.commit()
        # close communication with the database
        cur.close()
    except (Exception, psycopg2.DatabaseError) as error:
        print(error)
    finally:
        if conn is not None:
            conn.close()
    end = time.time()
    print(end - start)
Exemplo n.º 25
0
def create():
    try:
        response = None
        user = generate_username(1)[0]
        print("Getting new key...")
        captcha_key = hcaptcha.new()
        if not captcha_key:
            raise Exception("Failed to get captcha key")
        print("\033[33mSuccessfully received captcha key\033[0m")

        # For now we only want to invite, for not getting accounts ban uncomment the headers
        headers = {
            'Content-Type': 'application/json',
            #'Cookie': '__dcfduid=61f8ced90af24ebc9736ccf74c566850',
            #'X-Track': 'eyJvcyI6IkxpbnV4IiwiYnJvd3NlciI6IkNocm9tZSIsImRldmljZSI6IiIsInN5c3RlbV9sb2NhbGUiOiJlbi1VUyIsImJyb3dzZXJfdXNlcl9hZ2VudCI6Ik1vemlsbGEvNS4wIChYMTE7IExpbnV4IHg4Nl82NCkgQXBwbGVXZWJLaXQvNTM3LjM2IChLSFRNTCwgbGlrZSBHZWNrbykgQ2hyb21lLzkxLjAuNDQ3Mi43NyBTYWZhcmkvNTM3LjM2IiwiYnJvd3Nlcl92ZXJzaW9uIjoiOTEuMC40NDcyLjc3Iiwib3NfdmVyc2lvbiI6IiIsInJlZmVycmVyIjoiIiwicmVmZXJyaW5nX2RvbWFpbiI6IiIsInJlZmVycmVyX2N1cnJlbnQiOiIiLCJyZWZlcnJpbmdfZG9tYWluX2N1cnJlbnQiOiIiLCJyZWxlYXNlX2NoYW5uZWwiOiJzdGFibGUiLCJjbGllbnRfYnVpbGRfbnVtYmVyIjo5OTk5LCJjbGllbnRfZXZlbnRfc291cmNlIjpudWxsfQ=='
        }
        payload = json.dumps({
            "username": user,
            "email": f"{user}@gmail.com",
            "password": password_gen(),
            "date_of_birth": "1998-05-14",
            "consent": True,
            "invite": invite if invite else None,
            "gift_code_sku_id": None,
            "captcha_key": captcha_key
        })
        print("Sending register...")
        response = requests.request("POST",
                                    register_url,
                                    headers=headers,
                                    data=payload)
        #is_valid(json.loads(response.text)["token"])
        if json.loads(response.text)["token"]:
            newUser = DataBase(user, 0, 0)
            newUser.GoToDB()
            print(
                f"Creating {user}, \033[32mSuccess\033[0m - {DataBase.Count()}"
            )
        else:
            raise Exception("failed to get token")
    except Exception as e:
        try:
            print(response.text)
        except:
            print(e)
        print(f"Creating {user}, \033[31mFailed\033[0m - {DataBase.Count()}")
Exemplo n.º 26
0
def main():
    username = str(sys.argv[1])
    password = str(sys.argv[2])
    rank = str(sys.argv[3])
    query_url = "http://127.0.0.1:5000/api/site/"

    if username == "random":
        from random_username.generate import generate_username
        username = generate_username(1)[0]

    query_data = {"api": "INVALID_API",\
            "create_user": "******",\
            "username": username,\
            "password": password,\
            "rank": rank}
    r = requests.post(query_url, query_data)
    print(r.text)
Exemplo n.º 27
0
    def promote_to_host(self, email, stream):
        """
        Promote user to host. If the user doesn't exist, create a ticket to
        hold their seat via email. If the user is currently in the stream, ping
        them so their UI is updated with added host controls.
        """
        Profile = apps.get_model("users", "Profile")
        Ticket = self.model

        ticket, created = Ticket.objects.get_or_create(
            stream=stream,
            email=email,
            defaults={
                "name": generate_username(1)[0],
                "stream": stream,
                "updated_at": datetime.now(),
                "is_administrator": True,
            },
        )

        if not created:
            ticket.is_administrator = True
            ticket.save()

        try:
            user = User.objects.get(email__iexact=email)
            async_to_sync(channel_layer.group_send)(
                f"user-{user.id}",
                {
                    "type": "send_update",
                    "text": {
                        "updated": {
                            "users": [
                                Profile.objects.serialize_user(
                                    user, active_ticket=ticket)
                            ],
                        }
                    },
                },
            )
        except User.DoesNotExist:
            pass
Exemplo n.º 28
0
def make_account():
    generated_username = generate_username(1)
    email_ext = "@gmail.com"
    username = generated_username[0]  # 4 extra nums
    password = getrandbits(30)  # 6 numbers (min is 6)
    email = generated_username[0] + email_ext

    browser.find_element_by_xpath(username_input).send_keys(username)
    browser.find_element_by_xpath(password_input).send_keys(password)
    browser.find_element_by_xpath(email_input).send_keys(email)
    browser.find_element_by_xpath(form_submit).click()
    time.sleep(0.5)
    browser.find_element_by_xpath(accept_button).click()

    #write account details to file
    with open("accounts.csv", "a+", newline='') as csvfile:
        csvwriter = csv.writer(csvfile)
        fields = [username, password, email]
        csvwriter.writerow(fields)

    print("Account Created: UN: ", username, "PW:", password, "EMAIL:", email)
Exemplo n.º 29
0
def random_email(username_also=False):
    """ 
    Return a random email
    """
    random_numbers = str(random.randrange(0, 5000))
    random_years = str(random.randrange(
        1833, 2050))  # 1833 when computer was invented (ABACUS)
    name_full = names.get_full_name()
    name_first = names.get_first_name()
    name_last = names.get_last_name()

    if (username_also == True):
        prefix = random.choice(
            [name_full.replace(" ", ""), name_first, name_last])
        two = prefix.lower() + str(random.randrange(
            0, 500))  # Random Name + number
        three = generate_username(
            1)[0] + random_numbers  # Random Username + random_number
        four = generate_username(
            1)[0] + random_years  # Random Username + Random Years
        five = prefix.lower()  # Random name only
        six = prefix.lower() + str(random.randrange(
            0, 500))  # Random name + Random number 0 to 500
        seven = generate_username(
            1)[0] + random_numbers  # random Username + random number
        eight = generate_username(
            1)[0] + random_years  # Random Username + random year
        FINAL_EMAIL = random.choice(
            [two, three, four, five, six, seven, eight])
    else:
        service = [
            "@gmail.com", "@yahoo.com", "@protonmail.com", "@outlook.com",
            "@yandex.com"
        ]
        prefix = random.choice(
            [name_full.replace(" ", ""), name_first, name_last])
        email_service = random.choice(
            [service[0], service[1], service[2], service[3], service[4]])

        mail_one = prefix.lower() + email_service
        mail_two = prefix.lower() + str(random.randrange(0,
                                                         500)) + email_service
        mail_three = generate_username(1)[0] + random_numbers + email_service
        mail_four = generate_username(1)[0] + random_years + email_service
        FINAL_EMAIL = random.choice(
            [mail_one, mail_two, mail_three, mail_four])

    return FINAL_EMAIL, prefix.lower()
Exemplo n.º 30
0
    def populate_people(self, amount):
        for _ in range(amount):
            username = generate_username()[0]
            password = make_password(get_random_string(random.randint(8, 15)))
            user = User.objects.create(username=username, password=password)

            fake = Faker()
            birth_date = fake.date_of_birth(minimum_age=15, maximum_age=60)

            gender_choices = [
                element for tuple in Gender.GENDER_CHOICES for element in tuple
            ][::2]
            gender = random.choice(gender_choices)

            type_choices = [
                element for tuple in Type.TYPE_CHOICES for element in tuple
            ][::2]
            type = random.choice(type_choices)

            person = Person.objects.create(user=user,
                                           birth_date=birth_date,
                                           gender=gender,
                                           type=type)