Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Flask-Login : login.py created by https://github.com/maxcountryman : Matthew Frazier
# -*- coding: utf-8 -*-
"""
Flask-Login example
===================
This is a small application that provides a trivial demonstration of
Flask-Login, including remember me functionality.
:copyright: (C) 2011 by Matthew Frazier.
:license: MIT/X11, see LICENSE for more details.
"""
from flask import Flask, request, render_template, redirect, url_for, flash
from flask.ext.login import (LoginManager, current_user, login_required,
login_user, logout_user, UserMixin, AnonymousUser,
confirm_login, fresh_login_required)
class User(UserMixin):
def __init__(self, name, id, active=True):
self.name = name
self.id = id
self.active = active
def is_active(self):
return self.active
class Anonymous(AnonymousUser):
name = u"Anonymous"
USERS = {
1: User(u"Notch", 1),
2: User(u"Steve", 2),
3: User(u"Creeper", 3, False),
}
USER_NAMES = dict((u.name, u) for u in USERS.itervalues())
app = Flask(__name__)
SECRET_KEY = "yeah, not actually a secret"
DEBUG = True
app.config.from_object(__name__)
login_manager = LoginManager()
login_manager.anonymous_user = Anonymous
login_manager.login_view = "login"
login_manager.login_message = u"Please log in to access this page."
login_manager.refresh_view = "reauth"
@login_manager.user_loader
def load_user(id):
return USERS.get(int(id))
login_manager.setup_app(app)
@app.route("/")
def index():
return render_template("index.html")
@app.route("/secret")
@fresh_login_required
def secret():
return render_template("secret.html")
@app.route("/login", methods=["GET", "POST"])
def login():
if request.method == "POST" and "username" in request.form:
username = request.form["username"]
if username in USER_NAMES:
remember = request.form.get("remember", "no") == "yes"
if login_user(USER_NAMES[username], remember=remember):
flash("Logged in!")
return redirect(request.args.get("next") or url_for("index"))
else:
flash("Sorry, but you could not log in.")
else:
flash(u"Invalid username.")
return render_template("login.html")
@app.route("/reauth", methods=["GET", "POST"])
@login_required
def reauth():
if request.method == "POST":
confirm_login()
flash(u"Reauthenticated.")
return redirect(request.args.get("next") or url_for("index"))
return render_template("reauth.html")
@app.route("/logout")
@login_required
def logout():
logout_user()
flash("Logged out.")
return redirect(url_for("index"))
if __name__ == "__main__":
app.run()
@ajaykgp

This comment has been minimized.

Copy link

@ajaykgp ajaykgp commented Dec 2, 2013

this example doesn't work. Throws ImportError: cannot import name LoginManager.

@konarkmodi

This comment has been minimized.

Copy link

@konarkmodi konarkmodi commented Dec 5, 2013

@ajaykgp :

from flaskext.login import should be from flask.ext.login import.....

Then it will work !!

@sjzabel

This comment has been minimized.

Copy link

@sjzabel sjzabel commented Jan 6, 2014

Thank you, This totally helped me out. I appreciate it.

@bkdinoop

This comment has been minimized.

Copy link
Owner Author

@bkdinoop bkdinoop commented Jan 10, 2014

@ajaykgp Sorry for the Typo Error

@lashex

This comment has been minimized.

Copy link

@lashex lashex commented Jan 17, 2014

I have been trying to figure out when and where to override is_authenticated() from the UserMixin. Anytime I try to override it and use an in-object property I always end up with a User that has an authenticated property value of False in subsequent uses, even when I set it to True. Is there something I need to do to ensure the session remembers the user object I am updating?

Here is the User object:

class User(UserMixin):
    def __init__(self, username='', email='',
                 uid=None, standing='good', active=False,
                 confirmed_at=dt.MAXYEAR, created=None):
        super(User, self).__init__()
        self.username = str(username)
        self.email = email
        self.active = active
        self._authenticated = False

    def is_active(self):
        return self.active

    def set_authenticated(self, value):
        if value:
            self._authenticated = True

    def is_authenticated(self):
        return self._authenticated

...and then in a pared down snippet of code, here's where I set the authenticated property to True

@app.route('/v1/user/login', methods=['POST', 'OPTIONS'])
def login():
    u = json.loads(request.data)
    user = datastore.get_user(u['username'])

    if user.check_password(u['password']):
        user.set_authenticated(True) # <<< here is where the value should become True
        if login_user(user, remember=remember):
            return make_response(jsonify(username=u['username'],
                                                 last_login=user.last_login,
                                                 message='Login successful'), 200)
@jamespo

This comment has been minimized.

Copy link

@jamespo jamespo commented Feb 5, 2014

Shouldn't AnonymousUser be AnonymousUserMixin ?

@victorfang

This comment has been minimized.

Copy link

@victorfang victorfang commented Mar 10, 2014

Sorry I'm new to flask... how do I install flask.ext.login ?
My OS is ubuntu... flask itself is working. but not this one. thanks.

sudo easy_install flask.ext.login

Searching for flask.ext.login
Reading http://pypi.python.org/simple/flask.ext.login/
Couldn't find index page for 'flask.ext.login' (maybe misspelled?)
Scanning index of all packages (this may take a while)

@raphonic

This comment has been minimized.

Copy link

@raphonic raphonic commented Apr 4, 2014

@victorfang If you haven't got it installed yet, try 'sudo easy_install Flask-Login'

@l-r

This comment has been minimized.

Copy link

@l-r l-r commented Jun 9, 2014

@jamespo
They changed the AnonymousUser name to AnonymousUserMixin, see mattupstate/flask-security#119

@RitheshShenthar

This comment has been minimized.

Copy link

@RitheshShenthar RitheshShenthar commented Dec 2, 2014

Hi! Thanks for this! Anyone know where I can find the corresponding .html files etc? Is this part of a full package somewhere else?

@chasedehan

This comment has been minimized.

Copy link

@chasedehan chasedehan commented Feb 9, 2018

Thanks for this! I was seriously struggling with the User class as almost every tutorial forces you to use sqlalchemy for the database. The way you did it made so much more sense.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment