Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to override login of flask-security?

I want to do some customization when a user logs in. The problem is that the project is using flask-security which implicitly handles user login. I want to check some records of users in the database when users log in.

How can I override "login" function in flask-security?

I saw a similar post, and tried it but it's not working. Plus, it is not exactly what I want to do. I maybe need to stop the default behavior in case of some users.

So, is anyone having this kind of issue? How can I do it?

like image 590
arslan Avatar asked Jul 04 '17 09:07

arslan


2 Answers

You can override the login form when you are setting up Flask-Security:

user_datastore = SQLAlchemyUserDatastore(db, User, Role)
security = Security(app, user_datastore, login_form=CustomLoginForm)

Then create your custom login form class that extends the default LoginForm. And override the validate function to do stuff before or after the login attempt.

from flask_security.forms import LoginForm

class CustomLoginForm(LoginForm):
    def validate(self):
        # Put code here if you want to do stuff before login attempt

        response = super(CustomLoginForm, self).validate()

        # Put code here if you want to do stuff after login attempt

        return response

"reponse" will be True or False based on if the login was successful or not. If you want to check possible errors that occurred during the login attempt see "self.errors"

Greetings, Kevin ;)

like image 77
Kevin Avatar answered Nov 09 '22 18:11

Kevin


after registering the flask security extension, you can create an endpoint with the exact same name/route and it should override the one registered by Flask-security.

If you are using blueprints, make sure you register your blueprint before registering Flask-security.

like image 40
level09 Avatar answered Nov 09 '22 19:11

level09