def create_token(): username = request.authorization.username token = str(base64.b64encode(str(random.getrandbits(128)).encode()), "utf-8") get_db().execute("UPDATE user SET token = '{}' WHERE username = '******'".format(token, username)) get_db().commit() return jsonify({'status': 'SUCCESS', 'token': token}), 200
def test_db_get(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.value)
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)
def add_person(): is_successful = True try: incoming_json = request.get_json(force=True) print(incoming_json) f_name = incoming_json['firstname'] l_name = incoming_json['lastname'] addr = incoming_json['address'] phone_num = incoming_json['phone'] if not f_name or not l_name or not addr or not phone_num: is_successful = False print('Invalid input parameters!!') else: db_connection = get_db() db_connection.execute( 'INSERT INTO person (firstname, lastname, address, phone) VALUES (?, ?, ?, ?)', (f_name, l_name, addr, phone_num)) db_connection.commit() except Exception as e: is_successful = False print(str(e)) if is_successful: return jsonify('{"success": true}') else: return jsonify('{"success": false}')
def get_person(): p_id = request.args.get('person_id') db_connection = get_db() persons = db_connection.execute( 'SELECT id, firstname, lastname, address, phone FROM person WHERE id = ?', (p_id, )).fetchone() return jsonify(persons)
def create_user(user): try: validated_user = validate_new_user_data(user) except Exception as e: return jsonify({'status': 'FAILURE', 'message': str(e)}), 400 print(validated_user) db = get_db() if db.execute( 'SELECT id FROM user WHERE username = ?', (validated_user['username'],) ).fetchone() is not None: return jsonify({'status': 'FAILURE', 'message': 'User exists'}), 400 db.execute( """INSERT INTO user (username, password, firstname, lastname, phone) VALUES (?, ?, ?, ?, ?)""", ( validated_user['username'], generate_password_hash(validated_user['password']), validated_user['firstname'], validated_user['lastname'], validated_user['phone'] ) ) db.commit() return jsonify({'status': 'SUCCESS', 'message': 'Created'}), 201
def get_all_users(): query = get_db().execute("""SELECT username FROM user""").fetchall() users = [] for item in query: users.append(item['username']) return jsonify({'status': 'SUCCESS', 'payload': users}), 200
def test_fetch_users(client, app): rsp = client.get("/api/users") assert rsp.status_code == 200 with app.app_context(): fetched_db = get_db() count_check = fetched_db.execute( "SELECT COUNT(id) FROM USER").fetchone()[0] assert count_check == 2
def load_logged_in_user(): """If a user id is stored in the session, load the user object from the database into ``g.user``.""" user_id = session.get('user_id') if user_id is None: g.user = None else: g.user = get_db().execute('SELECT * FROM user WHERE id = ?', (user_id, )).fetchone()
def wrapped_call(*args, **kwargs): headers = request.headers if not headers.get('token'): return jsonify({'status': 'FAILURE', 'message': 'Token authentication required'}), 401 tokens = [x[0] for x in get_db().execute("SELECT token FROM user").fetchall()] if headers.get('token') in tokens: return call(*args, **kwargs) else: return jsonify({'status': 'FAILURE', 'message': 'Invalid Token'}), 401
def wrapped_call(*args, **kwargs): error = None user = None auth = request.authorization print('auth request: {}'.format(auth)) if auth: user = get_db().execute('SELECT * FROM user WHERE username = ?', (auth.username, )).fetchone() if user is None: error = 'Invalid User' elif not check_password_hash(user['password'], auth.password): error = 'Invalid Authentication' if error: return jsonify({'status': 'FAILURE', 'message': error}), 401 return call(*args, **kwargs)
def put_specific_user(username, request): allowed_fields = ('firstname', 'lastname', 'phone') if not request.is_json: return jsonify({'status': 'FAILURE', 'message': 'Bad Request'}), 400 data = request.get_json() print(data) db = get_db() for key, value in data.items(): if key not in allowed_fields: return jsonify({'status': 'FAILURE', 'message': 'Field update not allowed'}), 403 db.execute("UPDATE user SET '{}' = '{}' WHERE username = '******'".format(key, value, username)) db.commit() return jsonify({'status': 'SUCCESS', 'message': 'Updated'}), 201
def get_specific_user(username): try: query = get_db().execute( """SELECT firstname, lastname, phone FROM user WHERE username = '******'""".format(username) ).fetchall() except: return jsonify({'status': 'FAILURE', 'message': 'user not found'}), 404 payload = {'firstname': query[0][0], 'lastname': query[0][1], 'phone': query[0][2]} return jsonify({'status': 'SUCCESS', 'message': 'retrieval succesful', 'payload': payload}), 200
def register(): """Register a new user. Validates that the username is not already taken. Hashes the password for security. """ if request.method == 'POST': username = request.form['username'] password = request.form['password'] firstname = request.form['firstname'] lastname = request.form['lastname'] phone = request.form['phone'] 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 = 'User {0} is already registered.'.format(username) if error is None: # the name is available, store it in the database and go to # the login page db.execute( """INSERT INTO user (username, password, firstname, lastname, phone) VALUES (?, ?, ?, ?, ?)""", (username, generate_password_hash(password), firstname, lastname, phone)) db.commit() return redirect(url_for('auth.login')) flash(error) return render_template('auth/register.html')
def login(): """Log in a registered user by adding the user id to the session.""" 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: # store the user id in a new session and return to the index session.clear() session['user_id'] = user['id'] return redirect(url_for('demo.user_page')) session.clear() return redirect(url_for('auth.error_page')) return render_template('auth/login.html')
def all_persons(): db_connection = get_db() persons = db_connection.execute( 'SELECT id, firstname, lastname, address, phone FROM person' ).fetchall() return jsonify(persons)