def signup():
    """
    GET returns the template for the signup page, when the form is submitted the data is sent back
    to the endpoint using POST which creates a new user.
    """

    form = SignUpForm()
    if form.validate_on_submit():
        if not User.check_unique_username(form.username.data):
            flash("A user already exists with that username.")
        elif not User.check_unique_email(form.email.data):
            flash("A user already exists with that email address.")
        else:
            user = User()
            user.username = form.username.data
            user.email = form.email.data
            user.password = bcrypt.generate_password_hash(
                form.password.data).decode("utf-8")

            db.session.add(user)
            db.session.commit()

            login_user(user)

            return redirect(url_for("users.dashboard"))

    return render_template("signup.html", form=form)
Beispiel #2
0
def auth_register():
    """
    Creates a new user in the app

    Returns:
    Tuple containing the dict of the new user and status code
    """

    user_fields = user_schema.load(request.json)

    # Check uniqueness of username/email and return aborts instead of getting errors
    if User.query.filter_by(username=user_fields["username"]).first():
        return abort(400, description="Username is unavailable.")

    if User.query.filter_by(email=user_fields["email"]).first():
        return abort(400, description="Email already registered.")

    user = User()
    user.username = user_fields["username"]
    user.email = user_fields["email"]
    user.password = bcrypt.generate_password_hash(
        user_fields["password"]).decode("utf-8")

    db.session.add(user)
    db.session.commit()

    return (jsonify(user_schema.dump(user)), 201)
def auth_register():
    """
    Creates a new user in the app

    Returns:
    Tuple containing the dict of the new user and status code
    """

    user_fields = user_register_schema.load(request.json)

    # Check uniqueness of email and return abort instead of getting errors
    if User.query.filter_by(email=user_fields["email"]).first():
        return abort(400, description="Email already registered.")

    user = User()
    user.email = user_fields["email"]
    user.password = bcrypt.generate_password_hash(user_fields["password"]).decode("utf-8")

    db.session.add(user)
    db.session.commit()

    # Need to retrieve the user after adding to the database so that the href and uri fields
    # can be updated with the correct user id
    users = User.query.filter_by(email=user_fields["email"])

    # Need to remove password from user_fields otherwise it will replace the password hash with
    # the clear text password entered by the user to register
    del user_fields["password"]
    user_fields["href"] = f"https://api.spotify.com/user/{users[0].id}"
    user_fields["uri"] = f"spotify:user:{users[0].id}"

    users.update(user_fields)
    db.session.commit()

    return (jsonify(user_schema.dump(user)), 201)
Beispiel #4
0
def edit_user_account_details():
    """
    GET returns the template for the edit account page, when the form is submitted the data is
    sent back to the endpoint using POST which updates the users account data.
    """

    form = EditUserAccountForm()
    if form.validate_on_submit():
        if current_user.username != form.username.data and not User.check_unique_username(
                form.username.data):
            flash("A user already exists with that username.")
        elif current_user.email != form.email.data and not User.check_unique_email(
                form.email.data):
            flash("A user already exists with that email address.")
        elif form.new_password.data and not current_user.check_password(
                form.current_password.data):
            flash("Your current password is incorrect.")
        else:
            user = User.query.filter_by(id=current_user.id)

            data = {}
            if form.username.data:
                data["username"] = form.username.data
            if form.email.data:
                data["email"] = form.email.data
            if form.confirm_password.data:
                data["password"] = bcrypt.generate_password_hash(
                    form.confirm_password.data).decode("utf-8")

            fields = user_schema.load(data, partial=True)

            user.update(fields)
            db.session.commit()

            flash("Account details updated successfully.")
            return redirect(url_for("users.get_user_account_details"))

    # Prepopulate the form with existing data
    form.username.data = current_user.username
    form.email.data = current_user.email

    return render_template("account_edit.html", form=form)
def seed_db():
    """
    Custom flask db command to seed tables with fake data for testing
    """

    users = []
    for i in range(5):
        user = User()
        user.username = f"Test User {i + 1}"
        user.email = f"test{i + 1}@test.com"
        user.password = bcrypt.generate_password_hash("123456").decode("utf-8")
        db.session.add(user)
        users.append(user)

    db.session.commit()

    team_list = []
    for i in range(10):
        team = Team()
        team.name = f"Team {i + 1}"

        # Make sure there is always at least 1 public/private team
        if i == 8:
            team.is_private = False
        elif i == 9:
            team.is_private = True
        else:
            team.is_private = random.choice([True, False])
        owner = random.choice(users)
        team.owner_id = owner.id
        owner.teams.append(team)
        team_list.append(team)

    db.session.commit()

    pokemon_list = []
    for team in team_list:
        number_of_pokemon = random.randint(0, 6)
        for i in range(number_of_pokemon):
            pokemon = Pokemon()
            pokemon.pokemon_id = random.randint(1, 898)
            pokemon.pokeapi_id = pokemon.pokemon_id
            pokemon.pokemon_name = f"Random Name {i + 1}"
            if pokemon.pokeapi_id not in [
                    pokemon.pokeapi_id for pokemon in pokemon_list
            ]:
                db.session.add(pokemon)
            pokemon_list.append(pokemon)

            team_pokemon = Teams_Pokemon()
            team_pokemon.team_id = team.id
            team_pokemon.team_index = i + 1
            team_pokemon.pokeapi_id = pokemon.pokemon_id
            team.team_pokemon.append(team_pokemon)

    db.session.commit()

    move_list = []
    for team in team_list:
        number_of_moves = random.randint(0, 4)
        for team_pokemon in team.team_pokemon:
            for i in range(number_of_moves):
                move = Move()
                move.move_id = random.randint(1, 826)
                move.move_name = f"Random Move {i + 1}"
                if move.move_id not in [move.move_id for move in move_list]:
                    db.session.add(move)
                move_list.append(move)

                pokemon_move = Pokemon_Moves()
                pokemon_move.team_pokemon_id = team_pokemon.id
                pokemon_move.pokeapi_id = team_pokemon.pokemon.pokeapi_id
                pokemon_move.pokemon_move_index = i + 1
                pokemon_move.move_id = move.move_id
                db.session.add(pokemon_move)

    db.session.commit()

    print("TABLES SEEDED")
Beispiel #6
0
def seed_db():
    """
    Custom flask db command to seed tables with fake data for testing
    """

    faker = Faker()

    users = []
    for i in range(10):
        user = User()
        user.username = f"testuser{i + 1}"
        user.email = f"test{i + 1}@test.com"
        user.password = bcrypt.generate_password_hash("123456").decode("utf-8")
        db.session.add(user)
        users.append(user)

    db.session.commit()

    checklists = []
    for i in range(10):
        # Pick random user to create a checklist for
        user = random.choice(users)
        checklist = Checklist()
        checklist.title = faker.catch_phrase()
        checklist.is_group = random.choice([True, False])
        checklist.owner_id = user.id
        user.owned_checklists.append(checklist)
        user.checklists.append(checklist)

        # If group list, pick random users who aren't the owner to add to association table
        if checklist.is_group:
            num_members = random.randint(2, 5)
            for i in range(num_members):
                member = random.choice(users)
                if member != user:
                    member.checklists.append(checklist)

        checklists.append(checklist)

    db.session.commit()

    for i in range(30):
        # Pick a random checklist to create an item for
        checklist = random.choice(checklists)
        item = Item()
        item.name = faker.catch_phrase()

        # Randomly assign status, if True add current datetime for completion
        item.status = random.choice([True, False])
        if item.status:
            item.completion_date = datetime.now()
        item.checklist_id = checklist.id

        # If group list, get members and append None
        # Randomly pick a member to assign to the item, None indicates item is unassigned
        if checklist.is_group:
            users = checklist.users.copy()
            users.append(None)
            user = random.choice(users)
            if user:
                item.assigned_id = user.id
                user.items.append(item)
            else:
                item.assigned_id = None
        checklist.items.append(item)

    db.session.commit()
    print("TABLES SEEDED")
Beispiel #7
0
def seed_db():
    """
    Custom flask db command to seed tables with fake data for testing
    """

    faker = Faker()

    products = ["free", "premium", "student", "duo", "family"]
    genres = ["rock", "pop", "instrumental", "jazz", "metal", "hip-hop", "country"]
    album_types = ["album", "single", "compilation"]
    labels = ["Warner Music Group", "EMI", "Sony Music", "BMG", "Universal Music Group", "PolyGram"]
    copyright_types = ["C", "P"]

    users = []
    for i in range(10):
        user = User()
        user.display_name = f"Test User {i + 1}"
        user.email = f"test{i + 1}@test.com"
        user.href = f"https://api.spotify.com/users/{i + 1}"
        user.password = bcrypt.generate_password_hash("123456").decode("utf-8")
        user.product = random.choice(products)
        user.uri = f"spotify:user:{i + 1}"
        db.session.add(user)
        users.append(user)

    admin = User()
    admin.display_name = "Admin"
    admin.email = "*****@*****.**"
    admin.href = "https://api.spotify.com/users/11"
    admin.password = bcrypt.generate_password_hash("admin123").decode("utf-8")
    admin.uri = "spotify:user:11"
    admin.admin = True
    db.session.add(admin)

    db.session.commit()

    artists = []
    for i in range(5):
        artist = Artist()
        artist.name = f"Artist {i + 1}"
        artist.followers = random.randint(1, 10000)
        artist.genre = random.choice(genres)
        artist.href = f"https://api.spotify.com/artists/{i + 1}"
        artist.popularity = random.randint(1, 100)
        artist.uri = f"spotify:artist:{i + 1}"
        db.session.add(artist)
        artists.append(artist)

    db.session.commit()

    albums = []
    for i in range(10):
        album = Album()
        album.name = f"Album {i + 1}"
        album.album_type = random.choice(album_types)
        album.copyright = faker.catch_phrase()
        if len(album.copyright) > 100:
            album.copyright = album.copyright[:99]
        album.copyright_type = random.choice(copyright_types)
        album.href = f"https://api.spotify.com/albums/{i + 1}"
        album.label = random.choice(labels)
        album.release_date = random.randint(1990, 2020)
        album.uri = f"spotify:album:{i + 1}"
        artist = random.choice(artists)
        album.artist_id = artist.id
        album.genre = artist.genre
        artist.albums.append(album)
        albums.append(album)

    db.session.commit()

    tracks = []
    current_track_id = 1
    for album in albums:
        number_of_tracks = random.randint(1, 12)
        for i in range(number_of_tracks):
            track = Track()
            track.name = faker.catch_phrase()
            track.duration_ms = random.randint(180000, 300000)
            track.explicit = random.choice([True, False])
            track.href = f"https://api.spotify.com/tracks/{current_track_id}"
            track.popularity = random.randint(1, 100)
            track.preview_url = f"https://p.scdn.co/mp3-preview/{current_track_id}"
            track.track_number = i + 1
            track.uri = f"spotify:track:{current_track_id}"
            track.is_local = random.choice([True, False])
            track.album_id = album.id
            artist = album.artist
            track.artist_id = artist.id
            album.tracks.append(track)
            artist.tracks.append(track)
            tracks.append(track)
            current_track_id += 1

    db.session.commit()

    for track in tracks:
        for user in users:
            trackrating = Track_Rating()
            trackrating.track_id = track.id
            trackrating.user_id = user.id
            trackrating.rating = random.randint(0, 5)
            if trackrating.rating > 0:
                user.track_ratings.append(trackrating)

    db.session.commit()

    print("TABLES SEEDED")