Exemplo n.º 1
0
def test_get_close_db(app):
    with app.app_context():
        db = get_db()
        assert db is get_db()

    with pytest.raises(sqlite3.ProgrammingError) as e:
        db.execute('SELECT 1')

    assert 'closed' in str(e)
Exemplo n.º 2
0
def app():
    db_fd, db_path = tempfile.mkstemp()

    app = create_app({
        'TESTING': True,
        'DATABASE': db_path,
    })

    with app.app_context():
        init_db()
        get_db().executescript(_data_sql)

    yield app

    os.close(db_fd)
    os.unlink(db_path)
Exemplo n.º 3
0
def all_users():

    db = get_db()

    users = db.execute('SELECT username, userid FROM user', ).fetchall()

    return render_template('user/user_list.html', users=users)
Exemplo n.º 4
0
def register():
    userid = str(uuid.uuid4())[:8]

    if request.method == 'POST':

        username = request.form['username']
        password = request.form['password']
        bio = request.form['bio']
        twitter = request.form['twitter']
        facebook = request.form['facebook']
        instagram = request.form['instagram']

        db = get_db()

        error = None

        if not username:
            error = 'Username is required'
        elif not password:
            error = 'Password is required'
        elif db.execute('SELECT id FROM user WHERE username = ?',
                        (username, )).fetchone() is not None:
            error = f'User {username} is already registered.'

        if error is None:

            dbquery = 'INSERT INTO user (username, password, userid '
            dbparams = [username, generate_password_hash(password), userid]
            values = 'VALUES (?, ?, ?'
            if bio:
                dbquery += ", bio"
                values += ", ?"
                dbparams.append(bio)
            if twitter:
                dbquery += ", twitter"
                values += ", ?"
                dbparams.append(twitter)
            if facebook:
                dbquery += ", facebook"
                values += ", ?"
                dbparams.append(facebook)
            if instagram:
                dbquery += ", instagram"
                values += ", ?"
                dbparams.append(instagram)

            dbquery += ")"

            values += ")"

            dbquery += values

            db.execute(dbquery, dbparams)
            db.commit()
            return redirect(url_for('auth.login'))

        flash(error)

    return render_template('auth/register.html')
Exemplo n.º 5
0
def load_logged_in_user():
    userid = session.get('userid')

    if userid is None:
        g.user = None
    else:
        g.user = get_db().execute('SELECT * FROM user WHERE userid = ?',
                                  (userid, )).fetchone()
Exemplo n.º 6
0
def delete_account():
    userid = g.user['userid']
    db = get_db()
    db.execute('DELETE FROM user WHERE userid=?', (userid, ))
    db.commit()
    session.clear()
    flash('Account Deleted')
    return redirect(url_for('index'))
Exemplo n.º 7
0
def add_exercises():
    """ /exercise/add is for using AJAX to add new exercises, instead of contantly redirecting to different pages. Will refactor to make it more secure. And only available to the current user. """

    # Get database so you can query it!
    if request.method == 'GET':
        return render_template('api/add_exercise.html')
    else:
        db = get_db()

        userid = g.user['userid']
        details = request.form['details']
        duration = request.form['duration']
        date = request.form['date']

        errors = []
        exercise = {}

        # First check if ID is empty
        if userid == '':
            # add relevant error
            errors.append("Id cannot be empty")
        # Now check to make sure the provided ID is present in the table
        elif db.execute('SELECT id FROM user WHERE userid = ?',
                        (userid, )).fetchone() is None:
            errors.append("You did not enter a valid ID")
        else:
            exercise['userid'] = userid

        if details == '':
            errors.append("no details provided")
        else:
            exercise['details'] = details
        if duration == '':
            errors.append("no duration provided")
        elif None:
            pass
        else:
            exercise['duration'] = int(duration)
        if date == '':
            errors.append("no date provided")
        else:
            exercise['date'] = date

        # If there IS NOT errors AND there IS an exercise
        if not errors and exercise:
            db.cursor().execute(
                'INSERT INTO exercise (userid, details, duration, date_of) VALUES (?, ?, ?, date(?))',
                (userid, details, duration, date))
            db.commit()
            # return the json data of your new exercise
            return redirect(
                url_for('user.user_exercises', userid=g.user['userid']))

        else:
            for error in errors:
                flash(error)
            return redirect(url_for('index'))
Exemplo n.º 8
0
def delete_exercise(exerciseid):
    """ Simple ajax route for deleting a exercise from the database for a user """

    db = get_db()
    userid = g.user['userid']
    db.execute('DELETE FROM exercise WHERE id=? AND userid=?',
               (exerciseid, userid))
    db.commit()
    flash('Exercise Deleted')
    return Response(status=200)
Exemplo n.º 9
0
def test_register(client,app):
    assert client.get('/auth/register').status_code == 200
    response = client.post(
        '/auth/register', data={'username': '******', 'password': '******'}
    )
    assert 'http://localhost/auth/login' == response.headers['Location']

    with app.app_context():
        assert get_db().execute(
            "SELECT * FROM user WHERE username = '******'"
        ).fetchone() is not None
Exemplo n.º 10
0
def edit_exercise(exerciseid):
    """ Simple route for editing a given exercise record. """

    db = get_db()
    userid = g.user['userid']

    exercise_to_edit = db.execute(
        'SELECT * FROM exercise WHERE id=? AND userid=?',
        (exerciseid, userid)).fetchone()

    return "Edit exercise."
Exemplo n.º 11
0
def get_users():
    """ Builds a list for all registered users on the site, so you can view their profiles and exercise logs. Currently under review. """

    db = get_db()

    users = db.execute("SELECT * FROM user").fetchall()

    all_users = []

    for user in users:
        all_users.append({
            "username": user['username'],
            "userid": user['userid']
        })

    return jsonify(all_users)
Exemplo n.º 12
0
def user_exercises(userid):

    # get the database
    db = get_db()

    exercises = db.execute(
        'SELECT * FROM user u JOIN exercise e ON u.userid = e.userid WHERE u.userid = ? LIMIT 10',
        (userid, )).fetchall()

    if len(exercises) == 0:
        exercises = db.execute('SELECT username FROM user WHERE userid = ?',
                               (userid, )).fetchone()
        print(exercises)
        if exercises is None:
            return render_template("errors/404.html"), 404

    return render_template('user/exercise_list.html',
                           exercises=exercises,
                           data={"userid": userid})
Exemplo n.º 13
0
def user_profile(userid):

    # get the database
    db = get_db()

    # user = db.execute(
    #     'SELECT * FROM profile p JOIN user u ON  p.userid = u.userid WHERE p.userid=?',
    #     (userid,)
    # ).fetchone()
    user = db.execute('SELECT * FROM user WHERE userid=?',
                      (userid, )).fetchone()

    if user is None:
        return render_template('errors/404.html'), 404
    if user is not None or not g.user or g.user['userid'] != userid:
        return render_template('user/profile.html', user=user)
    else:
        return redirect(url_for('api.add_profile'))

    # redirect to the index, I probably want to address this.
    return redirect(url_for('index'))
Exemplo n.º 14
0
def edit_profile(userid):
    db = get_db()
    if request.method == 'GET':
        if userid == g.user['userid']:

            user = db.execute('SELECT * FROM user WHERE userid=?',
                              (userid, )).fetchone()
            return render_template('user/edit_profile.html', user=user)
        else:
            abort(401)
    else:
        bio = request.form['bio']
        twitter = request.form['twitter']
        facebook = request.form['facebook']
        instagram = request.form['instagram']

        dbquery = 'UPDATE user SET '
        dbparams = []

        if bio:
            dbquery += "bio = ?,"
            dbparams.append(bio)
        if twitter:
            dbquery += "twitter = ?,"
            dbparams.append(twitter)
        if facebook:
            dbquery += "facebook = ?,"
            dbparams.append(facebook)
        if instagram:
            dbquery += "instagram = ?"
            dbparams.append(instagram)

        dbquery += ' WHERE userid = ?'
        dbparams.append(g.user['userid'])
        print(dbquery)
        print(dbparams)
        db.execute(dbquery, dbparams)
        db.commit()
        return redirect(url_for('user.user_profile', userid=g.user['userid']))
Exemplo n.º 15
0
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        db = get_db()
        error = None

        user = db.execute('SELECT * FROM user WHERE username = ?',
                          (username, )).fetchone()

        if user is None:
            error = 'Incorrect username.'
        elif not check_password_hash(user['password'], password):
            error = 'Incorrect password.'

        if error is None:
            session.clear()
            session['userid'] = user['userid']
            return redirect(url_for('index'))

        flash(error)

    return render_template('auth/login.html')