Skip to content

Commit 7556ec7

Browse files
committed
update readme
1 parent f83910a commit 7556ec7

File tree

1 file changed

+50
-111
lines changed

1 file changed

+50
-111
lines changed

Diff for: README.md

+50-111
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,6 @@
11
# Flask-Login
22

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
84
tasks of logging in, logging out, and remembering your users' sessions over
95
extended periods of time.
106

@@ -13,143 +9,86 @@ model. The only requirement is that your user objects implement a few methods,
139
and that you provide a callback to the extension capable of loading users from
1410
their ID.
1511

16-
## Installation
12+
Read the documentation at <https://flask-login.readthedocs.io>.
1713

18-
Install the extension with pip:
14+
[Flask]: https://flask.palletsprojects.com
1915

20-
```sh
21-
$ pip install flask-login
22-
```
2316

24-
## Usage
17+
## A Basic Example
2518

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.
2921

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.
3123

3224
```python
3325
import flask
26+
import flask_login
3427

3528
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!
4430

4531
login_manager = flask_login.LoginManager()
46-
4732
login_manager.init_app(app)
4833
```
4934

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!
5440

5541
```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")}
5848
```
5949

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`.
6352

6453
```python
65-
class User(flask_login.UserMixin):
66-
pass
67-
68-
6954
@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+
```
7358

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.
7762

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>"""
7871

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"])
8475

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"))
8978

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"))
9381

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")
11783
@flask_login.login_required
11884
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+
)
12189

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")
12691
def logout():
12792
flask_login.logout_user()
128-
return 'Logged out'
93+
return "Logged out"
12994
```
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

Comments
 (0)