Gurkenkönig
Gurkenkönig

Reputation: 828

How to write model in custom EVE route

I am experimenting a bit with EVE and am now faced with the question of how to manipulate data in custom created endpoints. Example: I need a POST "user" method where I can intercept the data, hash the password and then save the new user.

For this purpose I would like to overwrite or extend the existing POST method. My attempt:

@app.route('/users', methods=['POST'])
def create_user():
    user = app.data.driver.db['user']
    print(request.json)
    username = request.json.get('username')
    password = request.json.get('password')
    if username is None or password is None:
        abort(400)  # arguments are missing
    if user.find({ 'username': username}) is not None:
        abort(400)  # user is existing
    => hash password
    => save user with hashed password

Unfortunately, overwriting the POST method created by my users model like this does not work either.

Upvotes: 1

Views: 66

Answers (2)

Gurkenkönig
Gurkenkönig

Reputation: 828

Thanks to gcws hint, here is my resulting code for a POST user request in EVE with flask_bcrypt:

...
from flask import request    
from flask_bcrypt import Bcrypt

...

bcrypt = Bcrypt()


def pre_user_post_callback(request):
    print('A POST on "user" was just performed!')

    pw_hash = bcrypt.generate_password_hash(request.json["password"], 12)
    del request.json["password"]
    request.json["password_hash"] = pw_hash.decode()

    print(bcrypt.check_password_hash(request.json["password_hash"] , '12345')) #  True if requested pw is 12345



app.on_pre_POST_user += pre_user_post_callback

Upvotes: 0

gcw
gcw

Reputation: 1621

You need to use an event hook for that, more specifically, on_insert_users_hook where you can modify the item before insert into database. See the documentation and example here (https://docs.python-eve.org/en/stable/features.html#insert-events).

Upvotes: 1

Related Questions