-
-
Save bkdinoop/6698956 to your computer and use it in GitHub Desktop.
# -*- 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() |
Shouldn't AnonymousUser be AnonymousUserMixin ?
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)
@victorfang If you haven't got it installed yet, try 'sudo easy_install Flask-Login'
@jamespo
They changed the AnonymousUser name to AnonymousUserMixin, see pallets-eco/flask-security#119
Hi! Thanks for this! Anyone know where I can find the corresponding .html files etc? Is this part of a full package somewhere else?
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.
Here's actual code (April 2024). You just need to add simple index.html, secret.html ,etc
# -*- 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_login import (LoginManager, current_user, login_required,
login_user, logout_user, UserMixin,
confirm_login, fresh_login_required)
class User(UserMixin):
def __init__(self, name, id1, active=True):
self.name = name
self.id = id1
self.active = active
def is_active(self):
return self.active
class AnonymousUser(UserMixin):
name = "Anonymous"
id = None
active = False
class Anonymous(AnonymousUser):
name = "Anonymous"
USERS = {
1: User("Notch", 1),
2: User("Steve", 2),
3: User("Creeper", 3, False),
}
USER_NAMES = {u.name: u for u in USERS.values()} # Uwaga: metoda .itervalues() jest przestarzała w Python 3.x
app = Flask(__name__)
SECRET_KEY = "yeah, not actually a secret"
DEBUG = True
app.config.from_object(__name__)
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.anonymous_user = Anonymous
login_manager.login_view = "login"
login_manager.login_message = "Please log in to access this page."
login_manager.refresh_view = "reauth"
@login_manager.user_loader
def load_user(user_id):
return USERS.get(int(user_id))
@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("Invalid username.")
return render_template("login.html")
@app.route("/reauth", methods=["GET", "POST"])
@login_required
def reauth():
if request.method == "POST":
confirm_login()
flash("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(debug=True)
I have been trying to figure out when and where to override
is_authenticated()
from theUserMixin
. Anytime I try to override it and use an in-object property I always end up with aUser
that has anauthenticated
property value ofFalse
in subsequent uses, even when I set it toTrue
. Is there something I need to do to ensure the session remembers theuser
object I am updating?Here is the User object:
...and then in a pared down snippet of code, here's where I set the
authenticated
property toTrue