PrettyPrinted / flask_auth_scotch

123 stars 143 forks source link

Where does "Please log in to access this page." message come from? #9

Open jbhanks opened 2 years ago

jbhanks commented 2 years ago

Hi, I am using this as a learning example, but there is one thing that I don't understand: When I access a url like /profile without being logged in, it redirects to the login page and displays " "Please log in to access this page.". I can find all the other flashed messages in the code, but not this one. Where is that message coming from? Is it part of flask_login?

image

timhanke commented 2 years ago

Hi, yes it is part of the flask_login LoginManager.

The route /profile is decorated with @login_required wich checks for authorization. Looking in the documentation for the flask_login decorator @login_required

https://flask-login.readthedocs.io/en/latest/#flask_login.login_required

reveals that the callback LoginManager.unauthorized is called in case of violation.

https://flask-login.readthedocs.io/en/latest/#flask_login.LoginManager.unauthorized

And there we see that if you do not register a special callback function login message the LoginManager.login_message will be flashed to the user while redirecting him to the login view.

In this project the login message still is on its default value from creating the login manager and the easiest way to change this message would be overwrite the default message by adding a line like login_manager.login_message = 'your custom flash message after initialisation of the login manager at line 21 to __init__.py.

grafik And you will get the result: grafik

flask is very well documented and your clue to find this by yourself was the @require_login decorator which causes you not to reach /profile. Then follow the docs until you find that the flashing string is stored in the LoginManager instance and then just try to modify it (at a smart place after initialisation before its been called).