• Stars
    star
    3,569
  • Rank 12,428 (Top 0.3 %)
  • Language
    Python
  • License
    MIT License
  • Created over 12 years ago
  • Updated about 2 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Flask user session management.

Flask-Login

Tests coverage Software License

Flask-Login provides user session management for Flask. It handles the common tasks of logging in, logging out, and remembering your users' sessions over extended periods of time.

Flask-Login is not bound to any particular database system or permissions model. The only requirement is that your user objects implement a few methods, and that you provide a callback to the extension capable of loading users from their ID.

Installation

Install the extension with pip:

$ pip install flask-login

Usage

Once installed, the Flask-Login is easy to use. Let's walk through setting up a basic application. Also please note that this is a very basic guide: we will be taking shortcuts here that you should never take in a real application.

To begin we'll set up a Flask app:

import flask

app = flask.Flask(__name__)
app.secret_key = 'super secret string'  # Change this!

Flask-Login works via a login manager. To kick things off, we'll set up the login manager by instantiating it and telling it about our Flask app:

import flask_login

login_manager = flask_login.LoginManager()

login_manager.init_app(app)

To keep things simple we're going to use a dictionary to represent a database of users. In a real application, this would be an actual persistence layer. However it's important to point out this is a feature of Flask-Login: it doesn't care how your data is stored so long as you tell it how to retrieve it!

# Our mock database.
users = {'[email protected]': {'password': 'secret'}}

We also need to tell Flask-Login how to load a user from a Flask request and from its session. To do this we need to define our user object, a user_loader callback, and a request_loader callback.

class User(flask_login.UserMixin):
    pass


@login_manager.user_loader
def user_loader(email):
    if email not in users:
        return

    user = User()
    user.id = email
    return user


@login_manager.request_loader
def request_loader(request):
    email = request.form.get('email')
    if email not in users:
        return

    user = User()
    user.id = email
    return user

Now we're ready to define our views. We can start with a login view, which will populate the session with authentication bits. After that we can define a view that requires authentication.

@app.route('/login', methods=['GET', 'POST'])
def login():
    if flask.request.method == 'GET':
        return '''
               <form action='login' method='POST'>
                <input type='text' name='email' id='email' placeholder='email'/>
                <input type='password' name='password' id='password' placeholder='password'/>
                <input type='submit' name='submit'/>
               </form>
               '''

    email = flask.request.form['email']
    if email in users and flask.request.form['password'] == users[email]['password']:
        user = User()
        user.id = email
        flask_login.login_user(user)
        return flask.redirect(flask.url_for('protected'))

    return 'Bad login'


@app.route('/protected')
@flask_login.login_required
def protected():
    return 'Logged in as: ' + flask_login.current_user.id

Finally we can define a view to clear the session and log users out:

@app.route('/logout')
def logout():
    flask_login.logout_user()
    return 'Logged out'

We now have a basic working application that makes use of session-based authentication. To round things off, we should provide a callback for login failures:

@login_manager.unauthorized_handler
def unauthorized_handler():
    return 'Unauthorized', 401

Documentation for Flask-Login is available on ReadTheDocs. For complete understanding of available configuration, please refer to the source code.

Contributing

We welcome contributions! If you would like to hack on Flask-Login, please follow these steps:

  1. Fork this repository
  2. Make your changes
  3. Install the dev requirements with pip install -r requirements/dev.txt
  4. Submit a pull request after running tox (ensure it does not error!)

Please give us adequate time to review your submission. Thanks!

More Repositories

1

axum-login

🪪 User identification, authentication, and authorization for Axum.
Rust
550
star
2

flask-bcrypt

Flask-Bcrypt is a Flask extension that provides bcrypt hashing utilities for your application.
Python
324
star
3

tower-sessions

🥠 Sessions as a `tower` and `axum` middleware.
Rust
214
star
4

flask-uploads

File uploads for Flask.
Python
208
star
5

flask-seasurf

SeaSurf is a Flask extension for preventing cross-site request forgery (CSRF).
Python
190
star
6

logmon

Realtime log reader in Flask
Python
176
star
7

flake

Decentralized, k-ordered unique IDs in Clojure
Clojure
142
star
8

atomos

Atomic primitives for Python.
Python
119
star
9

warc-parquet

🗄️ A simple CLI for converting WARC to Parquet.
Rust
103
star
10

axum-sessions

🥠 Cookie-based sessions for Axum via async-session.
Rust
74
star
11

aquamarine

A demo of zero-downtime deploys with Docker Compose and Traefik
Shell
53
star
12

irctk

A simple framework for writing IRC applications
Python
44
star
13

quanta

Distributed CRDT of sparse integer vectors.
Clojure
33
star
14

forma

🐚 An opinionated SQL formatter.
Rust
27
star
15

axum-messages

🛎️ One-time notification messages for Axum.
Rust
26
star
16

tower-sessions-stores

🚃 Previously bundled session stores for `tower-sessions`.
Rust
23
star
17

hyperlight

A performance-focused HTTP reverse proxy
Clojure
19
star
18

flask-themes

Flask Themes
Python
19
star
19

cryptotrade

A simple Python API wrapper for Bitcoin trading platforms such as MtGox and TradeHill
Python
14
star
20

flog

A blog written with Flask
Python
9
star
21

flask-wepay

A Flask wrapper for WePay's Python API
Python
8
star
22

blizzard

HTTP unique ID generation service
Clojure
8
star
23

st

Fast and simple statistics on the command line.
Rust
6
star
24

markov-domains

Finds available domains using Markov chains.
Clojure
6
star
25

nautilus

User authentication and management service
Clojure
5
star
26

yelp-api

A wrapper for Yelp's public API
PHP
4
star
27

affinis

An IRC library for Clojure.
Clojure
4
star
28

wtforms

Python
4
star
29

rauth

A Python library for OAuth 1.0/a, 2.0, and Ofly
Python
4
star
30

simpleirc

An IRC connection layer written in Python.
Python
4
star
31

headers-accept

🤝 The missing `Accept` implementation for `headers::Header`.
Rust
4
star
32

pyxine-branch

Branch of the Python extension for xine
Python
3
star
33

fluyt

ClojureScript HTTP requests
Clojure
3
star
34

cozy

A modern Node API template for the weary traveller
JavaScript
3
star
35

dotfiles

Development environment configuration files.
Shell
3
star
36

ewt

EDN Web Tokens
Clojure
3
star
37

flask-simpleoauth

A dead simple OAuth 1.0a provider in Flask
Python
3
star
38

simpleoauth

Simple, correct OAuth 1.0 and 2.0 signing methods.
Python
2
star
39

kaa

Kaa is the resident IRC bot on VoxInfinitus, written with IrcTK
Python
2
star
40

voxinfinitus

Basic Django apps providing CMS and blog functionality for Voxi
Python
2
star
41

mage

A Clojure-like Lisp.
Python
2
star
42

tasker

simple task manager
Python
2
star
43

ChatOnMacWebAPI-Swift

Swift
2
star
44

chatter

Chatter is a quick and dirty realtime chat application written in Flask
Python
2
star
45

bitpit-https-bridge

A simple Flask app to bridge the unsecured service with a secured page
Python
1
star
46

conceptis.org

My personal site and blog
Python
1
star
47

primes

A simple Clojure program for generating a multiplication table of primes
Clojure
1
star
48

konvej

Httpbin in Clojure.
Clojure
1
star
49

atrium

HTTP Authentication Service
1
star
50

clasp

A dead simple routing DSL for Clojure's ring.
Clojure
1
star
51

celeb

Incomplete Flask gallery project, now abandoned
Python
1
star
52

accord

A simple OAuth 1.0/a, 2.0 consumer client for Clojure.
Clojure
1
star
53

locksmithing

Lock-free, concurrent data structure experiments.
Clojure
1
star