Giter VIP home page Giter VIP logo

flask-login's Introduction

Flask-Login

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.

Read the documentation at https://flask-login.readthedocs.io.

A Basic Example

Let's walk through setting up a basic application. 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 and a LoginManager from Flask-Login.

import flask
import flask_login

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

login_manager = flask_login.LoginManager()
login_manager.init_app(app)

To keep things simple we're going to use a basic User class and 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!

class User(flask_login.UserMixin):
    def __init__(self, email, password):
        self.id = email
        self.password = password

users = {"leafstorm": User("leafstorm", "secret")}

We also need to tell the login manager how to load a user from a request by defining its user_loader callback. If no user is found it returns None.

@login_manager.user_loader
def user_loader(id):
    return users.get(id)

Now we're ready to define our views. The login view will populate the session with authentication info. The protected view will only be avialble to authenticated users; visiting it otherwise will show an error. The logout view clearing the session.

@app.get("/login")
def login():
    return """<form method=post>
      Email: <input name="email"><br>
      Password: <input name="password" type=password><br>
      <button>Log In</button>
    </form>"""

@app.post("/login")
def login():
    user = users.get(flask.request.form["email"])

    if user is None or user.password != flask.request.form["password"]:
        return flask.redirect(flask.url_for("login"))

    flask_login.login_user(user)
    return flask.redirect(flask.url_for("protected"))

@app.route("/protected")
@flask_login.login_required
def protected():
    return flask.render_template_string(
        "Logged in as: {{ user.id }}",
        user=flask_login.current_user
    )

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

flask-login's People

Contributors

alanhamlett avatar bslatkin avatar davidism avatar dependabot-preview[bot] avatar dependabot[bot] avatar dtheodor avatar eeue56 avatar fuhrysteve avatar houstonfortney avatar jirikuncar avatar joelverhagen avatar kingdion avatar le717 avatar lpsinger avatar markhildreth avatar maxcountryman avatar miguelgrinberg avatar neilsh avatar netromdk avatar oskarihiltunen avatar pandermusubi avatar petermanser avatar porterjamesj avatar sbraz avatar singingwolfboy avatar therealmarv avatar tiesjan avatar timgates42 avatar typehorror avatar vhautsal avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

flask-login's Issues

user_logged_in signal should be emitted as well if user loggin from remember me cookie

In my case, I use another flask extension Flask-Principal with Flask-Login. I expect to load user identity as soon as the user login.

If I login without checking remember me option, it works fine. A user_logged_in signal is fired, so i can load user identity with other information.
However, If i checked remember me option while loggin, the next time, I login in automatically but the user_logged_in signal is not fired.

Loading user information in my case depends on user_logged_in signal. I think in both case(check or without check remember me option) should emit the signal.

Allow blank (but not None) static_url_path

I wanted to serve my static files form root “/” and not “/static”. Therefore my code look like that:
app = Flask(name, static_url_path='')
Unfortunately _load_user() sets the anonymous user for paths starting with static_url_path. In my case every url starts with static_url_path and I'm not able to access any of my restricted pages.

New PyPi Release

I recently started using Flask-Login on a project and ran into the bug #31. Downloading the latest sources fixed the issue. It looks like the package on PyPi was released last June and I was wondering if someone could release a newer package that included the fix for #31.

Unable use multilanguages login view if language stored in url

I don't find any ability to support login multilanguages and store language in url like /en/login and /ru/login or /login?lang=en and /login?lang=ru.

See login view example:

@app.route('/<lang>/login')
def login(lang):
    return render_template('login.html', lang=lang)

I can generate login url as url_for('login', lang='en') and I can set login view as app.login_manager.login_view = login, but there https://github.com/maxcountryman/flask-login/blob/master/flask_login.py#L99 url_for doesn't get any additional parameters.

login_user calls reload_user - as a consequence, 2 User objects are created in a row

I noticed that login_user() make a call to reload_user(), whose purpose is to create a new User object (from the userId).
However, when we call login_user, we have to provide a User object too.

At the end, two User objects are created when a login is performed.

Is there any reason for that ?
May I suggest to not call reload_user() from login_user() ?

Thanks,

"string indices must be integers" exception when trying to use MongoDB ObjectId

Hi, I would like to know if you plan to implement a feature. Please see my case below:

Steps to reproduce: trying to use MongoDB ObjectId (example:5123e65f1d41c839fefe0913) as id passed to the User(UserMixin) object.
Expected result: use the ObjectId in the code behind to create login cookie/session
Actual result: trow "string indices must be integers" exception
Attachment: the stack trace from the flask debugger uploaded here http://ubuntuone.com/0FfqxSZnR0T1CgWcbCL0bP

Can't install flask and flask-login in one go using pip

Installing flask and flask-login in one go yields unsatisfying results:

(env)svenstaro@cypher /tmp$ pip install flask flask-login
Downloading/unpacking flask
Downloading Flask-0.10.1.tar.gz (544kB): 544kB downloaded
Running setup.py egg_info for package flask

warning: no files found matching '*' under directory 'tests'
warning: no previously-included files matching '*.pyc' found under directory 'docs'
warning: no previously-included files matching '*.pyo' found under directory 'docs'
warning: no previously-included files matching '*.pyc' found under directory 'tests'
warning: no previously-included files matching '*.pyo' found under directory 'tests'
warning: no previously-included files matching '*.pyc' found under directory 'examples'
warning: no previously-included files matching '*.pyo' found under directory 'examples'
no previously-included directories found matching 'docs/_build'
no previously-included directories found matching 'docs/_themes/.git'
Downloading/unpacking flask-login
  Downloading Flask-Login-0.2.0.tar.gz
  Running setup.py egg_info for package flask-login
    Traceback (most recent call last):
      File "<string>", line 16, in <module>
  File "/tmp/env/build/flask-login/setup.py", line 25, in <module>
    from flask_login import __version__
  File "flask_login.py", line 20, in <module>
    from flask import (_request_ctx_stack, abort, current_app, flash, redirect,
ImportError: No module named flask
Complete output from command python setup.py egg_info:
Traceback (most recent call last):

File "<string>", line 16, in <module>

File "/tmp/env/build/flask-login/setup.py", line 25, in <module>

from flask_login import __version__

File "flask_login.py", line 20, in <module>

from flask import (_request_ctx_stack, abort, current_app, flash, redirect,

ImportError: No module named flask

----------------------------------------
Command python setup.py egg_info failed with error code 1 in /tmp/env/build/flask-login

Decorator order: explicit order should be described or somehow supported

Currently the order of decorators is not explicitly described, as the order of python decorators evaluate from the outside-inward (I believe),

@app.route("/logout")
@login_required`

Works as expected, though

@login_required
@app.route("/logout")

It would be good to either allow both decorator orders, or else explicitly describe this 'quirk' to ensure that developers are not confused, as views decorated in the incorrect order will be made public, and the current_user will be the Anonymous user.

It may be possible to inspect the function that the decorator wraps, and check if it is of the same name/params as app.route, or more generally, 'route'.

flask-login login_user from WebSocket

Hi,

I was trying to use flask-login inside a WebSocket call, everything in the session is working, but i think the login_user with remember=True is not, because if i watch the cookies on the browser side nothing happend, and the session of course is not "rembembered"

Excuse me for pasting the code, i do have the code un a private repository, but off course the code is AGPLv3

I pasted it in http://pastebin.com/9bwEHbwQ with 2 month expiration.

Thank you,

TypeError when User-Agent header is a unicode object

In _create_identifier (on line 133 of flask_login.py), the call to unicode:

    base = unicode("%s|%s" % (request.remote_addr,
                              request.headers.get("User-Agent")), 'utf8', errors='replace')

will fail if the User-Agent string already is a unicode object, raising:

TypeError: decoding Unicode is not supported

This happens at least when accessing a Flask 0.9 app using Flask-Login, running on Python 2.7.5, from either Firefox or Chrome. Excerpts from the Werkzeug traceback interpreter:

Chrome:

>>> request.headers.get("User-Agent")
u'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.110 Safari/537.36'  

Firefox:

>>> request.headers.get("User-Agent")
u'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:21.0) Gecko/20100101 Firefox/21.0'

A fix would be to call .encode('utf-8') on the user agent header value, or pass it to str (if the type varies).

Perform url quote twice on "next" argument.

When LoginManager.unauthorized create redirect on login_url and create "next" argument for it. It use request.url as base for next argument. But request.url is "raw" url and can contain quoted chars... and if it contain them, them will be quoted second time in function login_url (parts[4] = url_encode(md, sort=True))

As result we have incorrect value in "next" argument in case if original path contains quoted chars.

I suggest to user request.path instead of request.url as base for "next" argument.

My test case:

#!/usr/bin/env python2.7
# -*- coding:utf-8 -*-

from flask import *
from flask.ext import login as flask_login

__author__ = 'surabujin'

cfg = {
    'DEBUG': True,
    'SECRET_KEY': 'qweasdzxc'}


class User(object):
    idnr = 0

    def __init__(self, idnr):
        self.idnr = idnr

    def is_authenticated(self):
        """
        Returns True if the user is authenticated, i.e. they have provided valid credentials.
        (Only authenticated users will fulfill the criteria of login_required.)
        """
        return bool(self.idnr)

    def is_active(self):
        """
        Returns True if this is an active user - in addition to being authenticated, they also have activated
        their account, not been suspended, or any condition your application has for rejecting an account. Inactive
        accounts may not log in (without being forced of course).
        """
        return True

    def is_anonymous(self):
        """
        Returns True if this is an anonymous user.(Actual users should return False instead.)
        """
        return not self.idnr

    def get_id(self):
        """
        Returns a unicode that uniquely identifies this user, and can be used to load the user from the user_loader
        callback.Note that this must be a unicode - if the ID is natively an int or some other type, you will need
        to convert it to unicode.
        """
        return self.idnr


app = Flask(__name__)
app.config.update(cfg)

login = flask_login.LoginManager()
login.init_app(app)
login.login_view = 'login'
login.anonymous_user = lambda: User(0)
login.user_loader(lambda x: User(x))


@app.route('/')
@flask_login.login_required
def index():
    return 'Hello world'


@app.route('/#')
@flask_login.login_required
def diez():
    return 'Correct redirect'


@app.route('/%23')
def diez2():
    return 'Incorrect redirect'


@app.route('/login.x')
def login():
    flask_login.login_user(User(1))
    return redirect(request.args.get('next') or url_for('index'))


if __name__ == '__main__':
    app.run()

If you try to open page localhost:5000/%23 (i.e. /#) you will come into incorrect location...

rename setup_app -> init_app

As per flask-ext convention I think the method setup_app should be named init_app. This is obviously just a convention so nothing wrong with using setup_app here.

You could do this by adding a deprecation warning to the setup_app method, and providing an additional init_app method.

Integrate with flask-login but disable if desired

I'm interested in using flask-login, but I'm trying to make an app that will only optionally require logins and registered users. I checked the docs, but I didn't see any way to disable flask-login globally. I'd like to be able to add all the necessary integration (i.e. LoginManager and decorators), but turn the whole system off with a feature flag.

The use of a feature flag would allow me to have the default mode avoid user registration (to play around with the app), but turn on user handling when a group of users "gets serious."

Is this kind of feature available and I just missed it in my review of the documentation?

Function _create_identifier produces not printable identifier

So my session interface can't serrialize session and raises exception (I use signed cookies)

/usr/local/lib/python2.7/dist-packages/flask_login.py(136)_create_identifier()
135 hsh = md5()
--> 136 hsh.update(base.encode("utf8"))
137 return hsh.digest()

ipdb> base.encode("utf8")
'127.0.0.1|Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.97 Safari/537.22'
ipdb> n

/usr/local/lib/python2.7/dist-packages/flask_login.py(137)_create_identifier()
136 hsh.update(base.encode("utf8"))
--> 137 return hsh.digest()
138

ipdb> hsh.digest()
'6\x8b,]\xbd\xdd\x13\x08\xe5\x1a\x97F\xbc@?h'

Cant install flask-login

setup.py import flask_login.version
But in flask_login, it imports extra modules like Flask,..etc.

then if we didnt install Flask first, we cant install flask-login

AttributeError: 'RequestContext' object has no attribute 'user'

I'm getting this error, and I'd like any sort of input because it is a brick wall right now.

I have an application, that is using flask-security, which imports current_user through flask-login. Any integration issues are in the past and have been for some time.

I had a need to filter the request for some specific information, which I place on g. I had a blueprint which worked, and any integration issues are in the past.

Yesterday, I extracted this to a general extension: http://github.com/thrisp/flarf, which basically filters info to g, and becomes easier to configure, so it is more or less ready and tested to go. This was done replace something like this:
https://gist.github.com/anonymous/5628709, to make it less of a hassle to use between applications.

I put this back into my application, ONLY now I'm getting this, and as stated it is opaque: I don't know where or why user is not in RequestContext

Traceback (most recent call last):
  File "/home/zv/.virtualenvs/j/lib/python2.7/site-packages/flask/app.py", line 1701, in __call__
    return self.wsgi_app(environ, start_response)
  File "/home/zv/.virtualenvs/j/lib/python2.7/site-packages/flask/app.py", line 1689, in wsgi_app
    response = self.make_response(self.handle_exception(e))
  File "/home/zv/.virtualenvs/j/lib/python2.7/site-packages/flask/app.py", line 1687, in wsgi_app
    response = self.full_dispatch_request()
  File "/home/zv/.virtualenvs/j/lib/python2.7/site-packages/flask/app.py", line 1360, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/home/zv/.virtualenvs/j/lib/python2.7/site-packages/flask/app.py", line 1356, in full_dispatch_request
    rv = self.preprocess_request()
  File "/home/zv/.virtualenvs/j/lib/python2.7/site-packages/flask/app.py", line 1539, in preprocess_request
    rv = func()
  File "/home/zv/.virtualenvs/j/lib/python2.7/site-packages/Flask_Flarf-0.0.1-py2.7.egg/flask_flarf/flarf.py", line 48, in preprocess_request
    preprocess_func(r)
  File "/home/zv/.virtualenvs/j/lib/python2.7/site-packages/Project_Producer-0.0.1-py2.7.egg/project_producer/config/configs/request_filters_config.py", line 10, in preprocess_with_user
    g.preprocessed = current_app.extensions['flarf'].preprocess_cls(request)
  File "/home/zv/.virtualenvs/j/lib/python2.7/site-packages/Project_Producer-0.0.1-py2.7.egg/project_producer/config/configs/request_filters_config.py", line 17, in __init__
    self.aid = self.determine_account(request)
  File "/home/zv/.virtualenvs/j/lib/python2.7/site-packages/Project_Producer-0.0.1-py2.7.egg/project_producer/config/configs/request_filters_config.py", line 51, in determine_account
    current_user.account.identifier])
  File "/home/zv/.virtualenvs/j/lib/python2.7/site-packages/werkzeug/local.py", line 336, in __getattr__
    return getattr(self._get_current_object(), name)
  File "/home/zv/.virtualenvs/j/lib/python2.7/site-packages/werkzeug/local.py", line 295, in _get_current_object
    return self.__local()
  File "/home/zv/.virtualenvs/j/lib/python2.7/site-packages/flask_login.py", line 403, in <lambda>
    current_user = LocalProxy(lambda: _request_ctx_stack.top.user)
AttributeError: 'RequestContext' object has no attribute 'user'

theories:

  1. this function:
def preprocess_request(preprocess_func=self.preprocess_func):
            r = _request_ctx_stack.top.request
            request_endpoint = str(r.url_rule.endpoint).rsplit('.')[-1]
            if request_endpoint not in _flarf.preprocess_skip:
                preprocess_func(r)

gets run around, before, or something that using _request_ctx_stack is not yet in touch with user or removes user

  1. no clue

Any suggestions?

edit: also on stack overflow
http://stackoverflow.com/questions/16695418/attributeerror-requestcontext-object-has-no-attribute-user

load_user running excessively

Hey there,

I noticed today that my load_user function (which runs a SELECT statement against my user table) was running each time a request (valid or not valid) was made from my browser.

Here's a really simple script to demonstrate this:

import os
from flask import Flask
from flask.ext.login import LoginManager, login_user, logout_user, UserMixin

app = Flask(__name__)
app.config['SECRET_KEY'] = os.urandom(24)

login_manager = LoginManager()
login_manager.setup_app(app)


class User(UserMixin):
    def get_id(self):
        return 1

@login_manager.user_loader
def load_user(id):
    print 'Running load user function'
    user = User()
    return user


@app.route('/')
def index():
    return 'Hello world'


@app.route('/login')
def login():
    user = User()
    login_user(user)
    return 'Logged in'


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


if __name__ == "__main__":
    app.run(host='0.0.0.0', debug=True)

After requesting the /login URL, I then proceeded to a URL which doesn't exist (/abc):

e.g.

Running load user function
192.168.172.1 - - [13/Jan/2013 14:33:00] "GET /abc HTTP/1.1" 404 -
Running load user function
192.168.172.1 - - [13/Jan/2013 14:33:00] "GET /favicon.ico HTTP/1.1" 404 -

I understand that this is caused due to the binding against before_request which runs before all requests (valid or not) but I'm concerned that this behaviour could be a security risk for DOS attacks as the database is being queried unnecessarily. Any request against the web server will cause a SELECT query against the database, even for pages which don't exist. In addition, most browsers request favicon.ico which also results in at least 2 requests against the database per hit in a browser.

Is there any possible way around this?

Cannot Import (Flask 0.9)

Hi there,

I'm attempting to use flask-login with Flask 0.9 (fresh install from pip), but I'm having issues importing from the library through the Flask extension stuff.

For instance, if I try to import from flaskext.login import LoginManager, I get an error. If I check flaskext:

>>> import flaskext
>>> hasattr(flaskext, 'login')
False
>>> import flask_login

This forces me to import from flask_login directly, which I'm assuming isn't the desired behavior, since the docs point you to importing from flaskext.login.

I'd fix this myself, or at least try to find the root cause (it's highly likely I'm messing something up), but I'm new to Flask and pretty unfamiliar with the extension system despite my best efforts.

Comprehensive test suite based on unittest

Currently flask-login makes use of the outdated and abandoned? Atest testing library. Going forward tests should be ported to Michael Foord's superb unittest library. Additionally tests should strive for 100% functionality coverage to ease development and ensure flask-login is behaving as expected.

Broken compatibility with Werkzeug 0.9 and Flask 0.10

The current release version does not work well with Flask 0.10 and the current code in Flask-Login in master does not work with Werkzeug 0.9.

The two changes that break it:

  • sessions in flask can no longer contain binary data
  • headers are now unicode.

Check for None in _request_ctx_stack

When running Sphinx to generate documentation on an app that uses flask-login, I get the error

File "/Users/prschmid/.virtualenvs/myproject/lib/python2.7/site-packages/werkzeug/local.py", line 310, in __repr__
    obj = self._get_current_object()
File "/Users/prschmid/.virtualenvs/myproject/lib/python2.7/site-packages/werkzeug/local.py", line 295, in _get_current_object
    return self.__local()
File "/Users/prschmid/.virtualenvs/myproject/lib/python2.7/site-packages/flask_login.py", line 403, in <lambda>
    current_user = LocalProxy(lambda: _request_ctx_stack.top.user)
AttributeError: 'NoneType' object has no attribute 'user'

It would be nice if checked to make sure that _request_ctx_stack.top actually exists. Thoughts?

Problems setting cookie duration less than 6 hours

I'm using REMEMBER_COOKIE_DURATION to set how long a cookie lasts for 'remember me'.

There are no problems when I set the duration to be >= 6 hours, but when I set the duration to 5 hours or less (ie. timedelta(hours=5) ), the cookie doesn't get set.

I looked through 'flask_login.py' and it's doing:

duration = config.get("REMEMBER_COOKIE_DURATION", COOKIE_DURATION)
...
expires = datetime.utcnow() + duration
...
# actually set it
response.set_cookie(cookie_name, data, expires=expires, domain=domain)

which seems to me like it should work fine.
Could this have something to do with Flask or Werkzeug?

TypeError: 'NoneType' object is not callable

I have a user model class as follows:

class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    # more columns...

When I call login_user(user), it raises an exception:

Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1701, in __call__
    return self.wsgi_app(environ, start_response)
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1689, in wsgi_app
    response = self.make_response(self.handle_exception(e))
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1687, in wsgi_app
    response = self.full_dispatch_request()
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1360, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1358, in full_dispatch_request
    rv = self.dispatch_request()
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1344, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/vagrant/controllers/user.py", line 70, in user_login
    login_user(row)
  File "/usr/local/lib/python2.7/dist-packages/flask_login.py", line 438, in login_user
    current_app.login_manager.reload_user()
  File "/usr/local/lib/python2.7/dist-packages/flask_login.py", line 350, in reload_user
    user = self.user_callback(user_id)
TypeError: 'NoneType' object is not callable

I suspected it has something to do with user_id so I conducted a test to see if the following changes make any difference:

(Note that User is no longer inheriting UserMixin)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    # more columns...

    def get_id(self):
        return "test"

    def is_active(self):
        return True

After this change, it still raises the same exception.

current_user instance is of LocalProxy type

Hi, when using current_user instance I was having a weird bug with MongoEngine, then I decided to debug and when checking:

ipdb> type(current_user)
<class 'werkzeug.local.LocalProxy'>

That's not desired if I will use it directly. MongoEngine complains when using that instance during query/update, etc...
Is there any way to unwrap the proxy? Right now I have to query to the DB to get the real object.

Thanks

2 login_managers in 1 app possible?

I would like to use 1 login manager in a blueprint that represents domain.com.

The other login manager in *.domain.com (another blueprint). So cookies will be separate.
Basically login_manager.init_blueprint(), to make it active only inside a blueprint?

Thanks

Restore 0.1.3 versins on pypi.

Now I can't fetch pip install flask-login==0.1.3:

Could not find a version that satisfies the requirement flask-login==0.1.3 (from versions: 0.2.2, 0.2.1, 0.2.0, 0.1.2, 0.1.1)

Tests fail in 0.1.3, because test file is missing

$ /usr/bin/python -B setup.py test
[...]
tests.login.static_interactive
────────────────────────────────────────────────────────────────────────────────
Traceback (most recent call last):
  File "/var/tmp/paludis/build/dev-python-Flask-Login-0.1.3/work/Flask-Login-0.1.3/tests/login.py", line 307, in static_interactive
    assert rv.data == 'static content'
TestFailure

assert (rv.data == 'static content')
assert ('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">\n<title>404 Not Found</title>\n<h1>Not Found</h1>\n<p>The requested URL was not found on the server.</p><p>If you entered the URL manually please check your spelling and try again.</p>\n' == 'static content')

Failures: 1/21 (81 assertions)

The problem is that the tarball is missing tests/static/style.css. Tests should not fail using the released tarball.

Different behaviour with flashes and concurency with and without Flask-Login

When I use net example:

from flask import Flask, flash, redirect, get_flashed_messages, url_for


class Config(object):
    SECRET_KEY = 'test'

app = Flask(__name__)
app.config.from_object(Config)


# from flask.ext.login import UserMixin, LoginManager
# login_manager = LoginManager()
# login_manager.init_app(app)
#
# class User(UserMixin):
#     def __init__(self, id=None):
#         self.id = id
#
# login_manager.user_loader(lambda user_id: User('0001'))
# login_manager.user_loader(lambda user_id: None)


@app.route('/')
def home():
    flash(['test'])
    return redirect(url_for('result'))

@app.route('/result')
def result():
    js = '''
    <script>
        var ajax = function (url, callback) {
            var xhr = new XMLHttpRequest();
            xhr.open('POST', url, true);
            xhr.onreadystatechange = function(e) {
                if (this.status == 200) {
                    if (this.readyState == 4) {
                        callback(this.responseText);
                    }
                } else {
                    document.getElementById('content').innerHTML += '</br>' + 'error';
                }
            };

            xhr.send();
        };

        ajax('/post1', function (data) {
            document.getElementById('content').innerHTML += '</br>' + data;
        });
        ajax('/post2', function (data) {
            document.getElementById('content').innerHTML += '</br>' + data;
        });
    </script>
    '''
    return '<a href="/">back</a></br><div id="content">empty</div>' + js

@app.route('/post1', methods=['POST'])
def post1():
    result = '\npost1-data'
    messages = get_flashed_messages()
    for message in messages:
        result += '\n' + str(message)
    return result

@app.route('/post2', methods=['POST'])
def post2():
    return 'post2-data'

if __name__ == '__main__':
    app.run('0.0.0.0', 8080, True)
  1. then when I try go to / it set _flashes and redirect to result where I see:

    empty
    post1-data ['test']
    post2-data
    
  2. when I refresh this page several times I see:

    empty
    post1-data
    post2-data
    
  3. when go to / it repeat 1.

When I use next example:

from flask import Flask, flash, redirect, get_flashed_messages, url_for


class Config(object):
    SECRET_KEY = 'test'

app = Flask(__name__)
app.config.from_object(Config)


from flask.ext.login import UserMixin, LoginManager
login_manager = LoginManager()
login_manager.init_app(app)

class User(UserMixin):
    def __init__(self, id=None):
        self.id = id

login_manager.user_loader(lambda user_id: User('0001'))
# login_manager.user_loader(lambda user_id: None)


@app.route('/')
def home():
    flash(['test'])
    return redirect(url_for('result'))

@app.route('/result')
def result():
    js = '''
    <script>
        var ajax = function (url, callback) {
            var xhr = new XMLHttpRequest();
            xhr.open('POST', url, true);
            xhr.onreadystatechange = function(e) {
                if (this.status == 200) {
                    if (this.readyState == 4) {
                        callback(this.responseText);
                    }
                } else {
                    document.getElementById('content').innerHTML += '</br>' + 'error';
                }
            };

            xhr.send();
        };

        ajax('/post1', function (data) {
            document.getElementById('content').innerHTML += '</br>' + data;
        });
        ajax('/post2', function (data) {
            document.getElementById('content').innerHTML += '</br>' + data;
        });
    </script>
    '''
    return '<a href="/">back</a></br><div id="content">empty</div>' + js

@app.route('/post1', methods=['POST'])
def post1():
    result = '\npost1-data'
    messages = get_flashed_messages()
    for message in messages:
        result += '\n' + str(message)
    return result

@app.route('/post2', methods=['POST'])
def post2():
    return 'post2-data'

if __name__ == '__main__':
    app.run('0.0.0.0', 8080, True)
  1. then when I try go to / it set _flashes and redirect to result where I see:

    empty
    post1-data ['test']
    post2-data
    
  2. when I refresh this page several times I see:

    empty
    post1-data ['test']
    post2-data
    
  3. when go to / it set _flashes and redirect to result where I see:

    empty
    post1-data ['test'] ['test']
    post2-data
    
  4. when I refresh this page several times I see:

    empty
    post1-data ['test'] ['test']
    post2-data
    
  5. when go to / it set _flashes and redirect to result where I see:

    empty
    post1-data ['test'] ['test'] ['test']
    post2-data
    

...

Same issue when I use login_manager.user_loader(lambda user_id: None).

I use flask==0.9, werkzeug==0.8.3 and flask-login==0.2.3.

avoid trigger load_user() for static resource(url)

I observed the load_user() method is trigger even when loading a static resource like a css file. I confirmed it after looking into the source code. it all happens in my development environment.
It may be ok in production for we will use a web server to handle the static resources.

Authentication failure with uWSGI

Hi,

I've developped a simple Flask app which uses flack-login, it behaves perfectly when it is launched as a standalone app, but when it is called with uWSGI, the authentication never succeeds.
I assume that it may (must?) be an uWSGI issue or a configuration problem, but the (very basic) application works properly without flask-loginm thus that opened issue.
Are you aware of such behaviour or have any idea why flask-login would fail with uWSGI? I though about a buffers-size problem, but rose it to 65535 and it didn't have any effect.

I am using flask 0.10 and flask-login 0.2.4 installed with pip, and uwsgi + python-plugin 1.2.3 from Debian Wheezy.

Thanks

PEP8 cleanup

Currently flask-login does not respect PEP8 conventions. It would be great to have this cleaned up perhaps adding a small script to test for PEP8 compliance via the PEP8 module a la rauth's test suite.

_create_identifier returns a value that is not serializable to JSON

After becoming aware that Flask, by default, pickles its session object, and thus is vulnerable to remote execution if someone discovers your secret key ( see http://stacksmashing.net/2012/08/10/dear-flask-please-fix-your-secure-cookies/ ), I tried to switch to using itsdangerous for session management as detailed at http://flask.pocoo.org/snippets/51/ .

Unfortunately, this fails, because _create_identifier returns the raw MD5 digest in bytes, which can't be represented as a Unicode string, and thus serialized to JSON. I can work around this with a custom serializer, but it would be nice if there were at least an option to base64 encode this value or something.

_load_user assumes an application with static folder

304 def _load_user(self):
305 if request.path.startswith(current_app.static_url_path):
306 # load up an anonymous user for static pages
307 _request_ctx_stack.top.user = self.anonymous_user()
308 return

If the Flask app is instantiated like
Flask(name, static_folder=None)
or
Flask(name, static_url_path=None)

_load_user will throw an exception
TypeError: startswith first arg must be str, unicode, or tuple, not NoneType

Setting session val after login_user( ) causes freakout

I have a case where I create a new user, add a session value, then do a redirect. The problem is that after the request processing there is a call by Flask-Login to _set_cookie(), which itself calls current_user.get_auth_token(). Since current_user is not resolvable, you get the freakout. My particular version of the freakout is that my User get_auth_token() gets called with a "self" on None (nice trick). So yeah, I can't really get an auth token under those circumstances.

Frankly, I'm not sure why current_user isn't accessible immediately after login_user. Unless it is and there's something I've broken. For now my workaround is to not use the session and to instead write my own cookie to pass this value.

Unicode decode error

Hi,

When using Flask-Login with this snippet http://flask.pocoo.org/snippets/51/ - UnicodeDecodeError exception occurs. The object representation is like {'_id': "\xb6\xffgR\xa2A\xea?'m\x7f\xda\x08\xb7aO"}. Here is a full traceback for such situation:

File "/home/_/lib/python2.7/flask/app.py", line 1687, in wsgi_app
response = self.full_dispatch_request()
File "/home/
/lib/python2.7/flask/app.py", line 1362, in full_dispatch_request
response = self.process_response(response)
File "/home/**
/lib/python2.7/flask/app.py", line 1566, in process_response
self.save_session(ctx.session, response)
File "/home/_/lib/python2.7/flask/app.py", line 804, in save_session
return self.session_interface.save_session(self, session, response)
File "/home/
/**.py", line 51, in save_session
val = self.get_serializer(app).dumps(dict(session))
File "/home/_/lib/python2.7/itsdangerous.py", line 424, in dumps
return self.make_signer(salt).sign(self.dump_payload(obj))
File "/home/
/lib/python2.7/itsdangerous.py", line 519, in dump_payload
json = super(URLSafeSerializerMixin, self).dump_payload(obj)
File "/home/**
/lib/python2.7/itsdangerous.py", line 407, in dump_payload
return self.serializer.dumps(obj)
File "/home/**_/lib/python2.7/itsdangerous.py", line 539, in dumps
return simplejson.dumps(obj, separators=(',', ':'))
File "/usr/local/lib/python2.7/json/init.py", line 238, in dumps
**kw).encode(obj)
File "/usr/local/lib/python2.7/json/encoder.py", line 201, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/usr/local/lib/python2.7/json/encoder.py", line 264, in iterencode
return _iterencode(o, 0)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xb6 in position 1: invalid start byte

I couldn't be sure if it is related or not, but here is a passage from itsdangerous' documentation (http://packages.python.org/itsdangerous/#signing-interface):

"If unicode strings are provided, an implicit encoding to utf-8 happens. However after unsigning you won’t be able to tell if it was unicode or a bytestring."

Allow configurations to set HttpOnly and Secure flag on Remember Me cookie

Currently, the Remember Me cookie is being created with the HttpOnly and Secure flags always false. Add two new configuration options (REMEMBER_COOKIE_HTTPONLY and REMEMBER_COOKIE_SECURE). I would recommend defaulting the HTTPONLY flag to True, and the SECURE flag to False, since this is what the Flask defaults for the SESSION_COOKIE_* args are.

Note that this might be the reason for the some of the failures in Issue #25. If the user was working in an SSL environment, the remember me cookie would be sent in the response but not stored in the browser.

Remember Me is not working

I do set remember as True, and I can see that the session is returning values with 'set-cookie' in my Google Chrome's 'Inspect Element' Network Window. But the remember_token never saved.

I'm new to Flask and even Python. Please help. Thanks.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.