1
1
# Flask-Login
2
2
3
- ![ Tests] ( https://github.com/maxcountryman/flask-login/workflows/Tests/badge.svg )
4
- [ ![ coverage] ( https://coveralls.io/repos/maxcountryman/flask-login/badge.svg?branch=main&service=github )] ( https://coveralls.io/github/maxcountryman/flask-login?branch=main )
5
- [ ![ Software License] ( https://img.shields.io/badge/license-MIT-brightgreen.svg )] ( LICENSE )
6
-
7
- Flask-Login provides user session management for Flask. It handles the common
3
+ Flask-Login provides user session management for [ Flask] [ ] . It handles the common
8
4
tasks of logging in, logging out, and remembering your users' sessions over
9
5
extended periods of time.
10
6
@@ -13,143 +9,86 @@ model. The only requirement is that your user objects implement a few methods,
13
9
and that you provide a callback to the extension capable of loading users from
14
10
their ID.
15
11
16
- ## Installation
12
+ Read the documentation at < https://flask-login.readthedocs.io > .
17
13
18
- Install the extension with pip:
14
+ [ Flask ] : https://flask.palletsprojects.com
19
15
20
- ``` sh
21
- $ pip install flask-login
22
- ```
23
16
24
- ## Usage
17
+ ## A Basic Example
25
18
26
- Once installed, the Flask-Login is easy to use. Let's walk through setting up
27
- a basic application. Also please note that this is a very basic guide: we will
28
- be taking shortcuts here that you should never take in a real application.
19
+ Let's walk through setting up a basic application. Note that this is a very basic guide:
20
+ we will be taking shortcuts here that you should never take in a real application.
29
21
30
- To begin we'll set up a Flask app:
22
+ To begin we'll set up a Flask app and a ` LoginManager ` from Flask-Login.
31
23
32
24
``` python
33
25
import flask
26
+ import flask_login
34
27
35
28
app = flask.Flask(__name__ )
36
- app.secret_key = ' super secret string' # Change this!
37
- ```
38
-
39
- Flask-Login works via a login manager. To kick things off, we'll set up the
40
- login manager by instantiating it and telling it about our Flask app:
41
-
42
- ``` python
43
- import flask_login
29
+ app.secret_key = " super secret string" # Change this!
44
30
45
31
login_manager = flask_login.LoginManager()
46
-
47
32
login_manager.init_app(app)
48
33
```
49
34
50
- To keep things simple we're going to use a dictionary to represent a database
51
- of users. In a real application, this would be an actual persistence layer.
52
- However it's important to point out this is a feature of Flask-Login: it
53
- doesn't care how your data is stored so long as you tell it how to retrieve it!
35
+ To keep things simple we're going to use a basic ` User ` class and a dictionary to
36
+ represent a database of users. In a real application, this would be an actual
37
+ persistence layer. However, it's important to point out this is a feature of
38
+ Flask-Login: it doesn't care how your data is stored so long as you tell it how to
39
+ retrieve it!
54
40
55
41
``` python
56
- # Our mock database.
57
- users
= {
' [email protected] ' : {
' password' :
' secret' }}
42
+ class User (flask_login .UserMixin ):
43
+ def __init__ (self , email , password ):
44
+ self .id = email
45
+ self .password = password
46
+
47
+ users = {" leafstorm" : User(" leafstorm" , " secret" )}
58
48
```
59
49
60
- We also need to tell Flask-Login how to load a user from a Flask request and
61
- from its session. To do this we need to define our user object, a
62
- ` user_loader ` callback, and a ` request_loader ` callback.
50
+ We also need to tell the login manager how to load a user from a request by defining its
51
+ ` user_loader ` callback. If no user is found it returns ` None ` .
63
52
64
53
``` python
65
- class User (flask_login .UserMixin ):
66
- pass
67
-
68
-
69
54
@login_manager.user_loader
70
- def user_loader (email ):
71
- if email not in users:
72
- return
55
+ def user_loader (id ):
56
+ return users.get( id )
57
+ ```
73
58
74
- user = User()
75
- user.id = email
76
- return user
59
+ Now we're ready to define our views. The login view will populate the session with
60
+ authentication info. The protected view will only be avialble to authenticated users;
61
+ visiting it otherwise will show an error. The logout view clearing the session.
77
62
63
+ ``` python
64
+ @app.get (" /login" )
65
+ def login ():
66
+ return """ <form method=post>
67
+ Email: <input name="email"><br>
68
+ Password: <input name="password" type=password><br>
69
+ <button>Log In</button>
70
+ </form>"""
78
71
79
- @login_manager.request_loader
80
- def request_loader (request ):
81
- email = request.form.get(' email' )
82
- if email not in users:
83
- return
72
+ @app.post (" /login" )
73
+ def login ():
74
+ user = users.get(flask.request.form[" email" ])
84
75
85
- user = User()
86
- user.id = email
87
- return user
88
- ```
76
+ if user is None or user.password != flask.request.form[" password" ]:
77
+ return flask.redirect(flask.url_for(" login" ))
89
78
90
- Now we're ready to define our views. We can start with a login view, which will
91
- populate the session with authentication bits. After that we can define a view
92
- that requires authentication.
79
+ flask_login.login_user(user)
80
+ return flask.redirect(flask.url_for(" protected" ))
93
81
94
- ``` python
95
- @app.route (' /login' , methods = [' GET' , ' POST' ])
96
- def login ():
97
- if flask.request.method == ' GET' :
98
- return '''
99
- <form action='login' method='POST'>
100
- <input type='text' name='email' id='email' placeholder='email'/>
101
- <input type='password' name='password' id='password' placeholder='password'/>
102
- <input type='submit' name='submit'/>
103
- </form>
104
- '''
105
-
106
- email = flask.request.form[' email' ]
107
- if email in users and flask.request.form[' password' ] == users[email][' password' ]:
108
- user = User()
109
- user.id = email
110
- flask_login.login_user(user)
111
- return flask.redirect(flask.url_for(' protected' ))
112
-
113
- return ' Bad login'
114
-
115
-
116
- @app.route (' /protected' )
82
+ @app.route (" /protected" )
117
83
@flask_login.login_required
118
84
def protected ():
119
- return ' Logged in as: ' + flask_login.current_user.id
120
- ```
85
+ return flask.render_template_string(
86
+ " Logged in as: {{ user.id }} " ,
87
+ user = flask_login.current_user
88
+ )
121
89
122
- Finally we can define a view to clear the session and log users out:
123
-
124
- ``` python
125
- @app.route (' /logout' )
90
+ @app.route (" /logout" )
126
91
def logout ():
127
92
flask_login.logout_user()
128
- return ' Logged out'
93
+ return " Logged out"
129
94
```
130
-
131
- We now have a basic working application that makes use of session-based
132
- authentication. To round things off, we should provide a callback for login
133
- failures:
134
-
135
- ``` python
136
- @login_manager.unauthorized_handler
137
- def unauthorized_handler ():
138
- return ' Unauthorized' , 401
139
- ```
140
-
141
- Documentation for Flask-Login is available on [ ReadTheDocs] ( https://flask-login.readthedocs.io/en/latest/ ) .
142
- For complete understanding of available configuration, please refer to the [ source code] ( https://github.com/maxcountryman/flask-login ) .
143
-
144
-
145
- ## Contributing
146
-
147
- We welcome contributions! If you would like to hack on Flask-Login, please
148
- follow these steps:
149
-
150
- 1 . Fork this repository
151
- 2 . Make your changes
152
- 3 . Install the dev requirements with ` pip install -r requirements/dev.txt `
153
- 4 . Submit a pull request after running ` tox ` (ensure it does not error!)
154
-
155
- Please give us adequate time to review your submission. Thanks!
0 commit comments