예제 #1
0
def test_get_db(app):
    # Assert the connection is the same within the same request context
    with app.app_context():
        conn = get_db()
        assert conn is get_db()

    # Assert the connection is closed
    with pytest.raises(sqlite3.ProgrammingError) as e:
        conn.execute('SELECT 1')
    assert 'closed' in str(e.value)
예제 #2
0
def update(public_id, field1=None, field2=None):
    """
    Update the public resource identified by public_id, 
    at least 1 more parameter must be passed

    Parameters
    ----------
    public_id : int
    field1 : str, optional
    field2 : str, optional

    Returns
    -------
    str
        string indicating the operation result
    """
    if field1 is None and field2 is None:
        return 'Bad Request'

    db = get_db()
    db.execute('UPDATE `public` SET `field1`=?, `field2`=? WHERE `id`=?',
               (field1, field2, public_id))
    db.commit()

    return 'ok'
예제 #3
0
def read(public_id=None):
    """
    Read the public resource identified by public_id, or all of them if not specified

    Parameters
    ----------
    public_id : int, optional
        The id of the public resource

    Returns
    -------
    list(dict)
        A list with dictionary/ies with the data of the public resource/s
    """
    db = get_db()
    if public_id is None:
        rows = [
            dict(row)
            for row in db.execute('SELECT * FROM `public`').fetchall()
        ]
    else:
        rows = [
            dict(row)
            for row in db.execute('SELECT * FROM `public` WHERE `id`=?', (
                public_id, )).fetchall()
        ]

    return rows
예제 #4
0
def login(email, password):
    """Give the user a JWT to access the data

    Parameters
    ----------
    email : str
        The email of the user
    password : str
        The password of the user

    Returns
    -------
    str
        An error code if an error occurs, or the JWT otherwise
    """
    db = get_db()

    user = db.execute('SELECT `password` FROM `user` WHERE `email`=?',
                      (email, )).fetchone()

    if user is None or not check_password_hash(user['password'], password):
        return 'Wrong Credentials'

    # issued time of the token
    iat = datetime.utcnow().replace(microsecond=0)
    db.execute('UPDATE user SET iat=? WHERE email=?', (iat, email))
    db.commit()

    payload = {'iat': iat, 'email': email}
    token = jwt.encode(payload, env['auth']['key'], algorithm='HS256')

    return token
예제 #5
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)
예제 #6
0
def create(email, password, user_type=None):
    """
    Create a user

    Parameters
    ----------
    email : str
    password : str
    user_type : str, optional
        Can be either 'user' or 'admin'

    Returns
    -------
    str
        string indicating the operation result
    """
    if email is None or password is None:
        return 'Bad Request'

    db = get_db()
    db.execute(
        'INSERT INTO `user`(`email`, `password`, `type`) VALUES(?, ?, ?)',
        (email, generate_password_hash(password), user_type)
    )
    db.commit()

    return 'ok'
예제 #7
0
def delete(public_id):
    """
    Delete the public resource identified by public_id

    Parameters
    ----------
    public_id : int

    Returns
    -------
    str
        string indicating the operation result
    """
    db = get_db()
    db.execute('DELETE FROM `public` WHERE `id`=?', (public_id, ))
    db.commit()

    return 'ok'
예제 #8
0
def check_token(token):
    """Check if a given token is valid

    Parameters
    ----------
    token : str
        The token to verify

    Returns
    -------
    bool
        True if it is valid, False if it is not
    """
    decoded = jwt.decode(token, env['auth']['key'], algorithms=['HS256'])
    email, iat = decoded['email'], datetime.utcfromtimestamp(decoded['iat'])
    db = get_db()

    user = db.execute('SELECT `id` FROM `user` WHERE `email`=? AND `iat`=?',
                      (email, iat)).fetchone()

    return user is not None
예제 #9
0
def user_data(token):
    """
    Get the data of the user identified by a token

    Parameters
    ----------
    token : JWT
        The token with the user credentials

    Returns
    -------
    dict
        A dict with the user info
    """
    decoded = jwt.decode(token, env['auth']['key'], algorithms=['HS256'])
    email, iat = decoded['email'], decoded['iat']

    db = get_db()
    return dict(
        db.execute('SELECT * FROM `user` WHERE `email`=?', (email,)).fetchone()
    )
예제 #10
0
def create(field1=None, field2=None):
    """
    Create a public resource, at least 1 parameter must be passed

    Parameters
    ----------
    field1 : str, optional
    field2 : str, optional

    Returns
    -------
    str
        string indicating the operation result
    """
    if field1 is None and field2 is None:
        return 'Bad Request'

    db = get_db()
    db.execute('INSERT INTO `public`(`field1`, `field2`) VALUES(?, ?)',
               (field1, field2))
    db.commit()

    return 'ok'