Beispiel #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)
def addCreature():
    """Render and handle the form to add an creature"""
    db = get_db()
    types = db.execute('SELECT * FROM creature_type').fetchall()

    # If the form has been submitted, add the item to the table.
    if request.method == 'POST':
        db.execute('INSERT INTO creature (name_common,    \
                                          name_latin,     \
                                          photo_attr,     \
                                          photo_url,      \
                                          wiki_url,       \
                                          user_id,        \
                                          type_id)        \
                    VALUES (?,?,?,?,?,?,?)',
                   (request.form['name_common'],
                    request.form['name_latin'],
                    request.form['photo_attr'],
                    request.form['photo_url'],
                    request.form['wiki_url'],
                    g.user_id,
                    request.form['type_id']))
        db.commit()
        flash("Successfully added " + request.form['name_common'])
        return redirect(url_for('lists.listAll'))

    # Otherwise, render the form.
    return render_template('/lists/creature_add.html', types=types)
def listAll():
    """List all creatures in all categories"""
    db = get_db()
    types = db.execute('SELECT * FROM creature_type').fetchall()
    creatures = db.execute('SELECT * FROM creature').fetchall()
    return render_template('lists/list.html', types=types,
                           creatures=creatures, page_title='All')
Beispiel #4
0
def load_logged_in_user():
    """Check current session user when loading every page

    Use the unhashed gplus_id of the current user in session
    to find the user's id in the 'user' table so the lists
    templates and functions can determine authorization for
    performing CRUD operations.
    """
    user_id = session.get('user_id')
    if user_id is None:
        g.user_id = None
    else:
        users = get_db().execute('SELECT * FROM user').fetchall()
        user_found_flag = False
        for u in users:
            if check_password_hash(u['gplus_id'], user_id):
                g.user_id = u['id']
                user_found_flag = True
                redirect(url_for('lists.listAll'))

        # If something went wrong with the session, close the
        # session and redirect the user to the login page.
        if not user_found_flag:
            session.clear()
            g.user_id = None
def test_register(client, app):
    assert client.get('/auth/register').status_code == 200
    response = client.post('/auth/register',
                           data={
                               'name': 'a',
                               'password': '******'
                           })
    assert 'http://localhost/auth/login' == response.headers['Location']

    with app.app_context():
        assert get_db().execute(
            "select * from user where name = 'a'", ).fetchone() is not None
def showCreature(creature_id):
    """Show the requested creature information"""
    db = get_db()
    types = db.execute('SELECT * FROM creature_type').fetchall()
    creature = db.execute('SELECT * FROM creature WHERE id = ?',
                          (creature_id,)).fetchone()

    if creature:
        return render_template('/lists/creature_show.html', types=types,
                               creature=creature)
    else:
        flash("This entry does not exist.")
        return redirect(url_for('lists.listAll'))
Beispiel #7
0
    def wildlifeJSON():
        """Create JSON endpoint"""
        db = get_db()
        creatures = db.execute('SELECT * FROM creature').fetchall()
        json_creatures = [{
            'id': c['id'],
            'name_common': c['name_common'],
            'name_latin': c['name_latin'],
            'photo_url': c['photo_url'],
            'photo_attr': c['photo_attr'],
            'wiki_url': c['wiki_url'],
            'type': c['type_id']
        } for c in creatures]

        return jsonify(json_creatures)
Beispiel #8
0
 def wildlifeCreatureJSON(creature_id):
     """Create JSON endpoint"""
     db = get_db()
     c = db.execute('SELECT * FROM creature WHERE id = ?',
                    (creature_id, )).fetchone()
     if c:
         json_creature = {
             'id': c['id'],
             'name_common': c['name_common'],
             'name_latin': c['name_latin'],
             'photo_url': c['photo_url'],
             'photo_attr': c['photo_attr'],
             'wiki_url': c['wiki_url'],
             'type': c['type_id']
         }
         return jsonify(json_creature)
     else:
         return redirect(url_for('index'))
Beispiel #9
0
 def wildlifeTypeJSON(url_text):
     """Create JSON endpoint"""
     db = get_db()
     creatures = db.execute(
         'SELECT * FROM creature \
                             WHERE type_id = ?', (url_text, )).fetchall()
     if creatures:
         json_creatures = [{
             'id': c['id'],
             'name_common': c['name_common'],
             'name_latin': c['name_latin'],
             'photo_url': c['photo_url'],
             'photo_attr': c['photo_attr'],
             'wiki_url': c['wiki_url'],
             'type': c['type_id']
         } for c in creatures]
         return jsonify(json_creatures)
     else:
         return redirect(url_for('index'))
def deleteCreature(creature_id):
    """Render and handle the form to delete a creature"""
    db = get_db()
    types = db.execute('SELECT * FROM creature_type').fetchall()
    creature = db.execute('SELECT * FROM creature WHERE id = ?',
                          (creature_id,)).fetchone()

    # Only the owner of a creature may edit its entry.
    if g.user_id is not creature['user_id']:
        flash("You may only delete an entry you own.")
        return redirect(url_for('lists.listAll'))

    # If the form has been submitted, delete the entry from its table.
    if request.method == 'POST':
        db.execute('DELETE FROM creature where id = ?', (creature_id,))
        db.commit()
        flash("Successfully deleted " + creature['name_common'])
        return redirect(url_for('lists.listAll'))

    # Otherwise, render the form.
    return render_template('/lists/creature_delete.html', types=types,
                           creature=creature)
def listByType(url_text):
    """List only the creatures of the requested category"""
    db = get_db()
    types = db.execute('SELECT * FROM creature_type').fetchall()
    creatures = db.execute('SELECT * FROM creature').fetchall()
    creaturesDisplayable = []

    title = ''
    # Check to see if URL is looking for a valid creature type.
    for t in types:
        if url_text == t['url_text']:
            title = t['name']

    # If there's no title, the URL doesn't match possible creature types.
    if title == '':
        return redirect(url_for('index'))

    # Otherwise, only show the creatures of the desired type.
    for c in creatures:
        if c['type_id'] == url_text:
            creaturesDisplayable.append(c)

    return render_template('lists/list.html', types=types,
                           creatures=creaturesDisplayable, page_title=title)
def editCreature(creature_id):
    """Render and handle the form to edit a creature"""
    db = get_db()
    types = db.execute('SELECT * FROM creature_type').fetchall()
    creature = db.execute('SELECT * FROM creature WHERE id = ?',
                          (creature_id,)).fetchone()

    # Only the owner of a creature may edit its entry.
    if g.user_id is not creature['user_id']:
        flash("You may only edit an entry you own.")
        return redirect(url_for('lists.listAll'))

    # If the form has been submitted, edit the entry in its table.
    if request.method == 'POST':

        # Only use new values if they were submitted.
        # Otherwise, use the previous values.
        if request.form['name_common']:
            name_common = request.form['name_common']
        else:
            name_common = creature['name_common']

        if request.form['name_latin']:
            name_latin = request.form['name_latin']
        else:
            name_latin = creature['name_latin']

        if request.form['photo_attr']:
            photo_attr = request.form['photo_attr']
        else:
            photo_attr = creature['photo_attr']

        if request.form['photo_url']:
            photo_url = request.form['photo_url']
        else:
            photo_url = creature['photo_url']

        if request.form['wiki_url']:
            wiki_url = request.form['wiki_url']
        else:
            wiki_url = creature['wiki_url']

        if request.form['type_id']:
            type_id = request.form['type_id']
        else:
            type_id = creature['type_id']

        # Never allow for updating the owner of a creature.
        user_id = creature['user_id']

        db.execute('UPDATE creature SET name_common = ?,    \
                                        name_latin = ?,     \
                                        photo_attr = ?,     \
                                        photo_url = ?,      \
                                        wiki_url = ?,       \
                                        user_id = ?,        \
                                        type_id = ?         \
                  WHERE id = ?', (name_common,
                                  name_latin,
                                  photo_attr,
                                  photo_url,
                                  wiki_url,
                                  user_id,
                                  type_id,
                                  creature_id))
        db.commit()
        flash("Successfully edited " + creature['name_common'])
        return redirect(url_for('lists.listAll'))

    # Otherwise, render the form.
    return render_template('/lists/creature_edit.html', types=types,
                           creature=creature)
Beispiel #13
0
def login():
    """Handle the GET and POST methods of user login"""

    db = get_db()
    types = db.execute('SELECT * FROM creature_type').fetchall()

    # Create and store access token in the session.
    if request.method == 'GET':
        state = ''.join(random.choice(string.ascii_uppercase
                                      + string.digits) for x in range(32))
        session['state'] = state
        return render_template('auth/login.html', types=types,
                               glogin=True, STATE=state)

    # The user has logged in with google.
    elif request.method == 'POST':

        # Validate state token.
        if request.args.get('state') != session['state']:
            response = make_response(
                json.dumps('Invalid state parameter.'), 401)
            response.headers['Content-Type'] = 'application/json'
            return response

        # Obtain authorization code.
        code = request.data
        try:
            # Upgrade the authorization code into a credentials object.
            oauth_flow = flow_from_clientsecrets(
                app.root_path + '/client_secrets.json', scope=''
            )
            oauth_flow.redirect_uri = 'postmessage'
            credentials = oauth_flow.step2_exchange(code)
        except FlowExchangeError:
            response = make_response(
                json.dumps('Failed to upgrade the authorization code.'), 401)
            response.headers['Content-Type'] = 'application/json'
            return response

        # Check that the access token is valid.
        access_token = credentials.access_token
        url = ('https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=%s'
               % access_token)
        h = httplib2.Http()
        result = json.loads(h.request(url, 'GET')[1].decode('utf-8'))

        # If there was an error in the access token info, abort.
        if result.get('error') is not None:
            response = make_response(json.dumps(result.get('error')), 500)
            response.headers['Content-Type'] = 'application/json'
            return response

        # Verify that the access token is used for the intended user.
        gplus_id = credentials.id_token['sub']
        if result['user_id'] != gplus_id:
            response = make_response(
                json.dumps("Token's user ID doesn't match user ID."), 401)
            response.headers['Content-Type'] = 'application/json'
            return response

        # Verify that the access token is valid for this app.
        if result['issued_to'] != app.config['CLIENT_ID']:
            response = make_response(
                json.dumps("Token's client ID does not match app's."), 401)
            response.headers['Content-Type'] = 'application/json'
            return response

        stored_access_token = session.get('access_token')
        stored_gplus_id = session.get('gplus_id')
        if stored_access_token is not None and gplus_id == stored_gplus_id:
            response = make_response(
                json.dumps('Current user is already connected.'), 200
            )
            response.headers['Content-Type'] = 'application/json'
            return response

        # Store the access token in the session for later use.
        session['access_token'] = credentials.access_token
        session['user_id'] = gplus_id

        # If the user does not exist in the user table, add them.
        users = db.execute('SELECT * FROM user').fetchall()
        user_found_flag = False
        for u in users:
            if check_password_hash(u['gplus_id'], gplus_id):
                user_found_flag = True

        if not user_found_flag:
            hashed_gplus_id = generate_password_hash(gplus_id)
            db.execute(
                'INSERT INTO user (gplus_id) VALUES (?)',
                (hashed_gplus_id,)
            )
            db.commit()

        flash("You are now logged in!")
        return redirect(url_for('lists.listAll'))
Beispiel #14
0
 def index():
     """Handle the index route"""
     db = get_db()
     types = db.execute('SELECT * FROM creature_type').fetchall()
     return render_template('front_page.html', types=types)