Custom Authentication Method for Flask-Security

I use flash security to authenticate users. I made sure that authentication works correctly with the decorator http_auth_required- the user is checked against the user store ( SQLAlchemyUserDatastorein my case), and everything is fine.

Now I would like to use my own authentication method (I will use my own LDAP authentication system), but still use the things that Flask-Security provides me (for example, current_user). I wrote my own decorator that looks like this:

def authenticate_with_ldap(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        if not request.authorization:
            return unauthorized_user_handler()
        user = user_datastore.get_user(request.authorization.username)
        if not user or not authenticate_with_ldap(user.email, user.password):
            return unauthorized_user_handler()
        return func(*args, **kwargs)
    return wrapper

However, when I look at the decoder http_auth_required, I see that it uses a private function called _check_http_auththat does some things that I cannot do on my own without accessing the private members, for example, the top of the request context stack and send signals. The code is as follows:

def _check_http_auth():
    auth = request.authorization or BasicAuth(username=None, password=None)
    user = _security.datastore.find_user(email=auth.username)

    if user and utils.verify_and_update_password(auth.password, user):
        _security.datastore.commit()
        app = current_app._get_current_object()
        _request_ctx_stack.top.user = user
        identity_changed.send(app, identity=Identity(user.id))
        return True

    return False

So my question is: what is the right way to have your own authentication method while still using Flask-Security to the fullest?

+4
source share
1 answer

You can accomplish this with a quick monkey patch. Not perfect, but I'm not sure what else you can do until the Flask-Security team writes a more elegant way to handle this.

import flask_security

def verify_and_update_password_custom(password, user):
    return user.verify_password(password)    

flask_security.forms.verify_and_update_password = verify_and_update_password_custom

, - . . , , .

+1

Source: https://habr.com/ru/post/1654333/


All Articles