Giter VIP home page Giter VIP logo

flask-user's Introduction

Flask-User v1.0

image

image

image

image

image

Attention:
Flask-User v1.0 is a Production/Stable version.
The previous version is Flask-User v0.6.

User Authentication and Management

So, you're writing a Flask web application and would like to authenticate your users.
You start with a simple Login page, but soon enough you'll need to handle:
  • Registrations and Email Confirmations
  • Change Usernames, Change Passwords, and Forgotten Passwords

And wouldn't it be nice to also offer:

  • Added Security
  • Increased Reliability
  • Role-based Authorization
  • Internationalization (Chinese, Dutch, English, Farsi, Finnish, French, German, Italian, Polish, Russian, Slovak, Spanish, Swedish, Turkish and Ukrainian)

Customizable, yet Ready to use

  • Largely Configurable -- By overriding configuration settings.
  • Fully Customizable -- By overriding methods and properties.
  • Ready to use -- Through sensible defaults.
  • Supports SQL and MongoDB databases.

Well documented

Additional features

  • MIT License
  • Tested on Python 2.7, 3.4, 3.5, 3.6, 3.7 and 3.8. Coverage: Over 90%.
  • Event hooking -- Through efficient signals.
  • Support for multiple emails per user

Minimal Requirements

  • bcrypt 2.0+
  • cryptography 1.6+
  • Flask 0.9+
  • Flask-Login 0.2+
  • Flask-WTF 0.9+
  • passlib 1.7+

Alternatives

Authors

Lead developer and Maintainer
Ling Thio -- https://github.com/lingthio

Collaborators and Maintainers
Andrey Semakin -- https://github.com/and-semakin

Contributors
Many contributors

Contact us

image

image

image

flask-user's People

Contributors

and-semakin avatar aripddev avatar bbc2 avatar cariaso avatar chromy avatar dafvid avatar donfruendo avatar jacek-sloma avatar johansigfrids avatar justinmoon avatar khoerling avatar lelit avatar lilac avatar lingthio avatar lotosikra avatar mamins1376 avatar mimmon avatar neurosnap avatar oudingfan avatar pbugni avatar philipto avatar pjz avatar silpol avatar sotlampr avatar swergas avatar szastupov avatar tedivm avatar vvch avatar wolfgang42 avatar yassineaddi 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

flask-user's Issues

Feature request: Different redirects for @roles_required and @login_required.

Currently, if a user has insufficient privileges for a given route protected by a @roles_required decorator, they are redirected to the /user/sign-in page with the flashed message 'Please Sign in to access this page.' This outcome and feedback to the user doesn't accurately reflect their current status and is potentially confusing as the user is still in fact signed in.

I would welcome an expansion to this immediately useful and essential decorator. A couple options and ideas come immediately to mind:

  • Create a configurable default redirect page and flashed message for unauthorized access attempts.
  • Expand @roles_required to accept a contextual / specific redirect page, flashed message or perhaps some amazing handler. For the first case, maybe something like:
@app.route('/admin')
@roles_required('admin', redirect='/user/unauthorized', message='admins only', category='error')
def admin_page():
    pass

Thanks for having added the @roles_required functionality! I'll look forward to contributing to its development.

Blueprint compatibility?

Hello lingthio,

Thanks for the great work~!
I'm trying to apply your powerful Flask-User to a Boilerplate template called cookie cutter-flask found here:
https://github.com/sloria/cookiecutter-flask

One question I'm having is whether or not Flask-User supports Blueprint. For me the only reason for Blueprint is the route: I want the route "/" to render different pages depending on users are logged in or not.

Thanks a lot~!

Send mail fails because current_app does not have a mail attribute

Hi, Sending mails fails because current_app does not have a mail attribute.

File "/Users/osilokee/.virtualenvs/nextleft/lib/python2.7/site-packages/flask_user/emails.py", line 44, in send_email
current_app.mail.send(message)

I know you can access the configured Flask-Mail extension using
current_app.extensions["mail"]

Is there a specific version of Flask-Mail that sets this attribute?

Thanks

Python 3.4 Signals

Flask v0.10.1
Flask-User v0.6.1

The following signal does not trigger in python 3.4, but works in python 2.7:

from flask.ext.user.signals import user_logged_in

@user_logged_in.connect_via(app)
def track_login(sender, user, **extra):
    sender.logger.info('user logged in')

If I change the way the signal is imported, it works fine in python 3.4 AND python 2.7:

from flask.ext.user import signals

@signals.user_logged_in.connect_via(app)
def track_login(sender, user, **extra):
    sender.logger.info('user logged in')

I'm starting to wonder if this is an issue with Flask and how it imports extensions into flask.ext, very strange behavior nonetheless ... I'll continue to investigate.

Links in emails with apache mod proxy

I'm using apache mod_proxy (on domain.com) and gunicorn (localhost:8080).

the url(_external=True) generate url like http://localhost:8080/user/ because the server is running on http://localhost:8080. Then apache rewrites the url of the page.

Though in the mails, apache cannot rewrite the url so the link are like http://localhost:8080/user/... which doesn't work as the the server is not on this localhost.

If I change SERVER_NAME, the server cannot get the requests anymore.

My solution was to replace

confirm_email_link = url_for('user.confirm_email', token=token, _external=True)

by

confirm_email_link = current_app.config['DOMAIN'] + url_for('user.confirm_email', token=token)

in views.py
and adding a constant in the config.

do you guys ever had this problem or I am doing it the wrong way?

Do you guys have a better solution.

Edit: My solution is really laim because I need to change the venv files, so if you have a better idea you are welcome!

User DB updated, even if email failed

Hello,

A small problem when there are errors in sending an email:
Seems like the user is created in the database before an email is sent.
If the flask app has a problem sending the email (e.g. transient network error when connecting to the SMTP server), the Database is still updated with this new user.
Then, the username and email are "Already used", but there's no way to a user to actual user them.

Support for a primary key field name other than 'id'

Using Flask-User for the first time. For the most part, I'm pretty impressed. Great project, well executed. Apologies in advance for the lengthy issue posting, but I hope all the extra detail is helpful.

The problem

I've just spent quite a while tracking down a number of unexpected behaviors due to a schema assumption that I have not found explicitly stated in the project documentation. I'm using the SQLAlchemyAdapter in my project.

For quite some time, it was impossible to figure out what was going on because there were no errors thrown by Flask-User. Instead, when it found itself unable to do something, it just dropped me back to the login page without alerting me to what the actual failure was (in dev/debug mode).

Pretty much every single bit of functionality that works with a User object expects to do so via an explicit id column/attribute existing on the User model itself.

I'm pretty sure I'm not alone in the Python world in not using id as my primary key column in my db models--because id() is part of Python's __builtin__ module. Kind of like how I never use type as an attribute, for the same reason. Instead, I've long made it a habit of using pk as the primary key attribute in db models.

How does this matter to Flask-User?

Well, in some places, I was initially able to get around this by adding an id property to my model (trying to not have to create a model with a primary key attribute different from all the other application models):

@property
def id(self):
    return self.pk

This worked for a bit, in certain spots, until I started tackling password resets. I was able to get a reset email sent off successfully, but each time I clicked on the link, I was told the token was invalid. I verified the token myself, and it was indeed valid. I also verified it had not expired (it'd only been a few seconds, but anything could happen, right?). I checked directly with the database to ensure it was indeed saved to the User object. It was.

So, I started debugging the logic from the built in reset_password() view function. That's when I landed on the problem being in UserManager.find_user_by_id(). It was returning no User object. Here's a quick refresher on the logic I copied over:

#  from reset_password() view
mgr = current_app.user_manager
is_valid, has_expired, user_id = mgr.verify_token(token, mgr.reset_password_expiration)
# returns: is_valid=True, has_expired=False, user_id=123

# next up, find the user who owns the token
user = mgr.find_user_by_id(user_id)  # here, user is None

Interestingly enough, UserManager.verify_token() was returning the user_id for the token provided to the view. So, that's when I figured it was the id attribute itself--something must be happening in the query that was actually passing an id=user_id instead of relying on a more abstract query that doesn't assume the name of the primary key column. I also guessed that my id property def was screwing up raising a helpful error (it was).

So, I checked out the find_user_by_id() source, and found:

# inside flask_user/__init__.py
def find_user_by_id(self, user_id):
        return self.db_adapter.find_object(self.db_adapter.UserClass, id=user_id)

That call to SQLAlchemyAdapter.find_object in turn calls:

# inside db_adapters.py
query = query.filter(field==field_value)  # case sensitive!!

Eureka!

That filter() method from SQLAlchemy is an attribute-specific query method. So, it wasn't failing because my id property was an attribute, but it was failing to have the desired effect (finding the user by its primary key value).

I know, I know, this wouldn't be happening if I'd just used the id column like the docs show.

The problem is, I didn't actually notice the User model schema until I was hours into working with Flask-User. I know, still my fault. But I wanted to create this issue anyway, both to offer some feedback, and provide some help in case others experience the same thing.

Suggestions for schema-agnostic primary key queries

The major motivator for submitting this issue is to suggest this is, while still arguably a developer's fault for not thinking the schema matters so dearly, an opportunity to improve Flask-User's handling of primary key queries and any needs to refer to and/or work with User objects by their primary key values.

I'm not sure about the other db adapter classes, but I know SQLAlchemy offers a handy helper method when it comes to looking up objects by their primary keys -- it's the Query.get() method! All you have to do is provide it the object's primary key as a single argument (no field names, keywords, or anything else required). An example implementation could be as simple as:

# in db_adapters.py
# for SQLAlchemy, not sure about others

def get_object(self, ObjectClass, pk):
        """ Find single object of class 'ObjectClass' by specified primary key"""
        return ObjectClass.query.get(pk)

Query.get() is guaranteed to always return one and only one object based on its underlying identity field as defined in its model. So, it's the easiest query that can be made via SQLAlchemy. It would also help make Flask-User less coupled to an assumed schema for User models.

Suggestion for schema-agnostic primary key usage

Because Flask-User depends on Flask-Login (and even offers its own UserMixin developers can use that extend's Flask-Login's own UserMixin class), I felt like this was a pretty good situation to highlight how relying on certain schema columns/attributes was a bit too much coupling for an extension.

Flask-Login already expects a get_id() method, and its UserMixin includes this method, as well as instructing developers to implement their own method if they need to specify how to get the id value for their custom User models. Moreover, it also instructs developers to specify their own user_loader() method to ensure that whatever the id value is, the LoginManager can query it from the db. I haven't gone through all the Flask-User code, but it seems to me the best de-coupled approach would be for Flask-User to rely, like Flask-Login does, on the result of the get_id() method whenever it needs a User object's primary key value. When it needs to query by that value, it should use the query.get() method from SQLAlchemy, instead of filtering on a schema-dependent primary key attribute value.

From what I can see, Flask-User implements the Flask-Login requirement for a user_loader method via its _user_loader() method. That method calls the schema-dependent find_user_by_id() method that I've already detailed above. Based on my suggestions, and barring any other areas I haven't yet found in the code, if find_user_by_id() was changed to use a get() instead of a filter() query call, this would instantly decouple Flask-User from its schema dependence for primary keys (for SQLAlchemy, at least).

It doesn't solve other schema-dependence issues, but those attributes are, for the most part, pretty sensible as far as field names are concerned (and they don't clash with __builtin__ methods/keywords). However, I still think it'd be helpful to point out that the fields are required--and required to be named exactly as they appear--in the docs. Even better would be to offer users a way to specify those fields that Flask-User requires for its functionality to work properly. That could be as easy as a dict or tuple passed in so people could specify field mappings.

Thanks for an overall fantastic extension.

Question: jinja templates role model

Hello! Congrats for the great addon Flask-User!
I'm trying to show/hide a link under jinja template depending on current user role but as I'm a flask noob I don't know if there's possiblity to add or maybe exists.

What I'm trying to do as example (not working):
{% if (user.roles == 'admin') %}
<a href....

Auto login after registration

Is there a setting to have the user automatically logged in once they register as opposed to redirecting them to the login page? Or, do I need to override the registration call to implement this myself?

I looked through the documentation and didn't seem to find any configuration setting for such an action.

Thanks!

Question: AssertionError: No sender address has been set

Hello,

I am trying to setup flask-user, and something probably very simple but that i don't have the ability to figure out out is holding me back. Can you help me figure out this traceback ? I did set MAIL_DEFAULT_SENDER in your Basic_app.py file and here's the traceback i'm getting. Any idea ?

Traceback (most recent call last):
File "/home/nick/www/flask/lib/python2.7/site-packages/flask/app.py", line 1701, in call
return self.wsgi_app(environ, start_response)
File "/home/nick/www/flask/lib/python2.7/site-packages/flask/app.py", line 1689, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/home/nick/www/flask/lib/python2.7/site-packages/flask/app.py", line 1687, in wsgi_app
response = self.full_dispatch_request()
File "/home/nick/www/flask/lib/python2.7/site-packages/flask/app.py", line 1360, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/nick/www/flask/lib/python2.7/site-packages/flask/app.py", line 1358, in full_dispatch_request
rv = self.dispatch_request()
File "/home/nick/www/flask/lib/python2.7/site-packages/flask/app.py", line 1344, in dispatch_request
return self.view_functionsrule.endpoint
File "/home/nick/www/flask/lib/python2.7/site-packages/flask_user/views.py", line 281, in register
raise e
AssertionError: No sender address has been set

How can I validate a user through an application API?

I have built an application that apart from user frontend, it provides also an API alternative for the same functionality. Is there a way to forward a given username and password to the flask-user manager for validation? I was looking at the login() function inside views.py and whole login logic seems hard-coded in the view with no obvious way to reuse it.

Deployment options require {{ confirm_email_link }} configuration

Apologies for asking here first should not be considered the proper place.

I've got a webapp deployed coupled with nginx, the later for handling https and serving static content. Nothing fancy the nginx conf boils down to:

server {
    listen 443 ssl ;
    server_name myapp.local; 

    location /static {
      root /home/www/myapp/static ;
    }

    location / {
      proxy_pass http://myapp.local:5000/ ;
    }
}

The problem is that every single account confirmation email redirects to:

  1. http:// and not the secure version
  2. the local service host
  3. the port number...
    I've tried fiddling with the SERVER_NAME Flask config var or even hardcoded parameters in Flask.run() method but someone Flask-User always manages to find the hostname and port where the app is running....

So the question is: what is the easiest way of modifying the confirm_mail_link variable in the confirm_email_link so that it points where I want to?

Thanks in advance.

Flask-babel's i18n messages is overridden by flask_user's in jinja2 templates

According to flask-user's documentation, I copy the 'flask_user.po' file to my application's translation directory, and in the same level as flask-babel's 'message.po' file.

If I initialize flask-babel before flask-user, flask-user will install its own translation to the jinja2 environment when executing 'init_app', which overrides default flask-babel's translation. On the other hand, if flask-user is initialized before flask-babel, its own translation would be overridden in jinja2 templates.

Flash error message not styled

The 'unauthenticated' view function emits an 'error' flash message, which is transformed to a div with Bootstrap's 'alert-error' class. However, Bootstrap 3 renamed 'alert-error' class to 'alert-danger'.

Feature request: User.has_roles() in addition to the @roles_required decorator

I believe it would be useful to have the ability to test a user's authorization independent of the @roles_required decorator. I would like the opportunity to present alternative choices and paths given their authorization profile.

Would it be possible to expose the relevant method(s) located in decorator.py and/or elsewhere for general usage?

Thanks!

Make it possible to define a "next" target after registration.

Currently the registration form redirects to the login page after a POST.
It would be great if there were some way to easily add a "next" value to the redirection target (similar to the next value in email confirmation links added in #15 )

My usecase would be this: I would attach a flag to the login url which triggers a message clarifying to the user that the email has been sent and the activation link needs to be clicked before they can log in.

Feature request: Option to redirect after Confirm Email Link

As I understand the current registration/email/confirmation process flow, after a user clicks on the email link to confirm their new registration, they are brought to the login page to sign in. After successful login, they are then redirected to the home page. This destination appears hardwired. Is there any way to configure or otherwise include a '?next=/page' value with the confirmation link so that after login, the user is redirected to another page?

For my application, I'm imagining a very slim registration process, perhaps only email and a password. After they confirm and sign-in, I'd like to then redirect them to a profile page where they then have the opportunity to fill in optional parts of the profile. I'd only want to use the 'sign-in' --> 'profile' flow when initiated from the confirmation email.

Cheers,
Mark

User Invitation Functionality

I'm looking to send an invite via email to a user, sort of like an admin tool to add users without them "registering" through the normal process.

I see in the USER_REQUIRE_INVITATION config variable with the comment "not yet implemented." I'm wondering if you are in the process of fleshing out this functionality or is it more of a wish list?

As it stands right now I'm attempting to manually go in and generate this process. My plan is to utilize the password reset (user_manager.generate_token(), reset_password_link, User.reset_password_token, etc.) functionality that has already been created but send it to a custom view, email template, etc.

Would you suggest this as the best course of action? The reason why I'm asking is if there is a plan to incorporate "user invitation" functionality, I would be more than willing to fork Flask-User and attempt to contribute.

Awesome package btw, the customizability and readability of the package has been really great.

Flask-User Documentation v0.5.1

I need Flask0-User v0.5.1 documentation that I am not founding anywhere, v0.5.1 link redirecting toward v0.6, will you please email me its v0.5.1.

Question: Using current_user.has_roles() with Flask-Admin

I'm trying to use Flask_Admin in my code like this :
if current_user.has_roles('secret'):
admin = Admin(app, index_view=MyAdminIndexView())
admin.add_view(ModelView(Role, db.session))
admin.add_view(ModelView(User, db.session))
I run this code ,have some problem like this:
AttributeError: 'NoneType' object has no attribute 'has_roles'

Support Login with remember_me

I'm using minimal app version.
Is it possible to add the remember_me option with Flask-User?
Also, why there is no recipe or example that shows how to use Flask-User with 'session'.

Feature request: Ability to have the Login form and Register form on one page.

It would help to have ability to assign separate prefixes to the login form fields and registration form fields. This will help to avoid field name conflicts when these forms are the same page.

As example (using flask-user views.py)

def login():
    """ Prompt for username/email and password and sign the user in."""
    user_manager =  current_app.user_manager

    # Initialize form
    form = user_manager.login_form(request.form, prefix="login")

The field names in the login form will then render as login-email and login-password

BuildError: ('user.confirm_email', {}, None) with USER_ENABLE_EMAIL=True and USER_CONFIRM_EMAIL=False

With the goal of speeding the sign-up process, I attempted to configure Flask-User to not require a confirming email sent to the email address used in the registration by setting: USER_ENABLE_CONFIRM_EMAIL = False.

After doing so, I received a fatal error: werkzeug.routing.BuildError: ('user.confirm_email', {}, None). I was able to reproduce the error using Flask-User/example_apps/roles_required_app.py from the latest v.0.4.3 build. By setting the related USER_ENABLE_EMAIL also to False, the registration process completed successfully.

My interest was to still collect the email address, but dispense with the confirmation process. But perhaps by changing the purpose of email away from registration, it moves it into the user profile realm, which will be covered in the future. If so, then it would seem that only one email-related configuration setting for email would be required that would both enable the email field and require confirmation. Once I set USER_ENABLE_EMAIL also to False, the program performed without error.

Please let me know if I can provide additional diagnostic information. And thanks again for Flask-User!

~Markosys

Configuration settings:
# Configure Flask-User
USER_ENABLE_USERNAME = True # Register and Login with username
USER_ENABLE_EMAIL = True # Register with email
USER_ENABLE_CONFIRM_EMAIL = False # Require email confirmation

Traceback:
Traceback (most recent call last):
File ".../.virtualenvs/flskusr/lib/python2.7/site-packages/flask/app.py", line 1836, in call
return self.wsgi_app(environ, start_response)
File ".../.virtualenvs/flskusr/lib/python2.7/site-packages/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File ".../.virtualenvs/flskusr/lib/python2.7/site-packages/flask/app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File ".../.virtualenvs/flskusr/lib/python2.7/site-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File ".../.virtualenvs/flskusr/lib/python2.7/site-packages/flask/app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File ".../.virtualenvs/flskusr/lib/python2.7/site-packages/flask/app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File ".../.virtualenvs/flskusr/lib/python2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File ".../.virtualenvs/flskusr/lib/python2.7/site-packages/flask/app.py", line 1461, in dispatch_request
return self.view_functionsrule.endpoint
File ".../.virtualenvs/flskusr/lib/python2.7/site-packages/flask_user/views.py", line 283, in register
send_registered_email(email_address, user, token)
File ".../.virtualenvs/flskusr/lib/python2.7/site-packages/flask_user/emails.py", line 53, in send_registered_email
confirm_email_link = url_for('user.confirm_email', token=token, _external=True)
File ".../.virtualenvs/flskusr/lib/python2.7/site-packages/flask/helpers.py", line 312, in url_for
return appctx.app.handle_url_build_error(error, endpoint, values)
File ".../.virtualenvs/flskusr/lib/python2.7/site-packages/flask/app.py", line 1641, in handle_url_build_error
reraise(exc_type, exc_value, tb)
File ".../.virtualenvs/flskusr/lib/python2.7/site-packages/flask/helpers.py", line 305, in url_for
force_external=external)
File ".../.virtualenvs/flskusr/lib/python2.7/site-packages/werkzeug/routing.py", line 1620, in build
raise BuildError(endpoint, values, method)
BuildError: ('user.confirm_email', {}, None)

Feature request: API based approach?

Are you interested in taking this a bit further, and creating a backend API service which would handle most of the account tasks, instead of the current "monolithic" approach?

Thanks for sharing your work!

AttributeError: 'UserManager' object has no attribute 'password_hash'

Got the following error when run a test.

Traceback (most recent call last):
File "//anaconda/envs/vshare/lib/python3.4/site-packages/_pytest/config.py", line 513, in getconftestmodules
      return self._path2confmods[path]
KeyError: local('/Users/wandonye/flask/projects/dimension5/tests')

During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "//anaconda/envs/vshare/lib/python3.4/site-packages/_pytest/config.py", line 537, in importconftest
    return self._conftestpath2mod[conftestpath]
KeyError: local('/Users/wandonye/flask/projects/dimension5/tests/conftest.py')

During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "//anaconda/envs/vshare/lib/python3.4/site-packages/_pytest/config.py", line 543, in importconftest
    mod = conftestpath.pyimport()
  File "//anaconda/envs/vshare/lib/python3.4/site-packages/py/_path/local.py", line 641, in pyimport
    __import__(modname)
  File "/Users/wandonye/flask/projects/dimension5/tests/conftest.py", line 12, in <module>
    from .factories import UserFactory
  File "/Users/wandonye/flask/projects/dimension5/tests/factories.py", line 16, in <module>
    class UserFactory(BaseFactory):
  File "/Users/wandonye/flask/projects/dimension5/tests/factories.py", line 19, in UserFactory
    password = user_manager.hash_password('example')
  File "//anaconda/envs/vshare/lib/python3.4/site-packages/flask_user/__init__.py", line 215, in hash_password
    return passwords.hash_password(self, password)
  File "//anaconda/envs/vshare/lib/python3.4/site-packages/flask_user/passwords.py", line 19, in hash_password
    if user_manager.password_hash == 'plaintext':
AttributeError: 'UserManager' object has no attribute 'password_hash'
ERROR: could not load /Users/wandonye/flask/projects/dimension5/tests/conftest.py

The code in conftest.py is like this:

class BaseFactory(SQLAlchemyModelFactory):
    class Meta:
        abstract = True
        sqlalchemy_session = db.session

class UserFactory(BaseFactory):
    username = Sequence(lambda n: "user{0}".format(n))
    email = Sequence(lambda n: "user{0}@example.com".format(n))
    password = user_manager.hash_password('example')
    is_enabled = True

    class Meta:
        model = User

Originally it was

password = PostGenerationMethodCall('set_password', 'example')

But I have to change it because User does not have 'set_password'. If I define one in the User class, then I have to import user_manager in the models file of User, which will create a loop of import.

Error with Confirm Email (v0.6.1)

After upgrading to v 0.6.1, the Confirm Registration process is not working as before.
A) The "confirm_email_message.html" is no longer being sent; "registered_message.html" is, instead.
B) If I put the "confirm email" link in the "registered_message.html", the flash response to link is that email is confirmed, but when login attempted, the error is that login is not enabled.

Can you tell me if I should change any of my settings below?

# # Flask-User: Base Configure
    USER_ENABLE_REGISTRATION    = True    # Allow new users to register
    USER_ENABLE_USERNAME        = False   # Register and Login with username
    USER_ENABLE_EMAIL           = True    # Register with email
    USER_ENABLE_CONFIRM_EMAIL   = True    # Require email confirmation
    USER_ENABLE_CHANGE_USERNAME = False
    USER_ENABLE_RETYPE_PASSWORD = True
    USER_ENABLE_CHANGE_PASSWORD = True
    USER_ENABLE_FORGOT_PASSWORD = True
    USER_ENABLE_LOGIN_WITHOUT_CONFIRM = False 

    # auto login
    USER_APP_NAME                    = 'MyApp'   # Used by email templates
    USER_AUTO_LOGIN                  = False
    USER_AUTO_LOGIN_AFTER_CONFIRM    = USER_AUTO_LOGIN
    USER_AUTO_LOGIN_AFTER_REGISTER   = USER_AUTO_LOGIN

    # Additional
    USER_CONFIRM_EMAIL_EXPIRATION = 2*24*3600    # Confirmation expiration in seconds; (2*24*3600 represents 2 days)
    USER_PASSWORD_HASH            = 'bcrypt'     # Any passlib crypt algorithm
    USER_PASSWORD_HASH_MODE       = 'passlib'    
    USER_RESET_PASSWORD_EXPIRATION  = 2*24*3600  # Reset password expiration in seconds; (2*24*3600 represents 2 days)
    USER_SEND_PASSWORD_CHANGED_EMAIL = True      # Send registered email; Requires USER_ENABLE_EMAIL=True
    USER_SEND_REGISTERED_EMAIL       = True      # Send registered email; Requires USER_ENABLE_EMAIL=True
    USER_SEND_USERNAME_CHANGED_EMAIL = True      # Send registered email; Requires USER_ENABLE_EMAIL=True

About adding role to a user, is there a better way?

When adding a role(role already exists) to a new user, here is my code, which is not cool.
Is there a better way?

            username = request.form.get('username')
            email = request.form.get('email')
            rolename = request.form.get('rolename')
            password = request.form.get('password', username)
            if not User.query.filter(User.username==username).first():
                user1 = User(username=username, email=email, is_enabled=True,
                        password=user_manager.hash_password(password))
                db.session.add(user1)
                db.session.commit()
                user = User.query.filter(User.username==username).first()
                role = Role.query.filter(Role.name==rolename).first()
                user_roles = UserRoles(user_id=user.id, role_id=role.id)
                db.session.add(user_roles)
                db.session.commit()

I failed with "user1.roles.append(Role(name='mm'))", because of the following error.

 IntegrityError: (IntegrityError) (1062, "Duplicate entry 'mm' for key 'name'") 'INSERT INTO role (name) VALUES (%s)' ('mm',)

Thank you all!

Using signals

Using Flask signals is new to me.

I am trying to use the 'user_logged_in' signal without success.
In the example below, _track_logins() is never called.

Can you point me in the right direction?

Example: userhelper.py (inside a registered blueprint)

from flask import current_app
from flask.ext.user.signals import user_logged_in
from . import myblueprint

app = current_app

@user_logged_in.connect_via(app)
def _track_logins(sender, user, **extra):
    print 'LOGIN DETECTED' 

Py.Test Failing

I'm getting some tests that are failing on a clean copy of the current Flask-User repo, any idea on what's causing the issue? I'll continue to investigate as I'm attempting to add more tests for the User Invitation functionality.

test_multiple_emails 

app = <Flask 'flask_user.tests.tst_app'>, 

db = <SQLAlchemy engine='sqlite:///:memory:'>, 

client = <flask_user.tests.tst_utils.TstClient object at 0xb5d3334c>

    def test_multiple_emails(app, db, client):
        """
        Test 'multiple emails per user' feature
        """

        # Set Flask-User settings
        um = current_app.user_manager
        um.enable_register = True
        um.enable_username = False
        um.enable_email = True
        um.enable_confirm_email = True
        um.enable_change_username = False
        um.enable_change_password = False
        um.enable_forgot_password = False
        um.enable_multiple_emails = True
        um.enable_retype_password = False

        # Adjust DbAdapter settings
        um.db_adapter.UserEmailClass = app.UserEmailClass

        # Adjust URL routes
        app.add_url_rule(um.email_action_url,  'user.email_action',  
um.email_action_view_function)
        app.add_url_rule(um.manage_emails_url, 'user.manage_emails',
um.manage_emails_view_function, methods=['GET', 'POST'])

        # constants
        EMAIL1 = '[email protected]'
        EMAIL2 = '[email protected]'
        PASSWORD = 'Password1'

        # Register user
        response = client.post_valid_form(url_for('user.register'), 
email=EMAIL1, password=PASSWORD)
        user_email1 = um.db_adapter.UserEmailClass.query.filter(
um.db_adapter.UserEmailClass.email==EMAIL1).first()
        assert user_email1 != None

        # Confirm email
        confirmation_token = um.generate_token(user_email1.id)
        client.get_valid_page(url_for('user.confirm_email', token=confirmation_token))

        # Log in using email1
        client.login(email=EMAIL1, password=PASSWORD)

        # Visit manage emails page
        response = client.get_valid_page(url_for('user.manage_emails'))
>       assert response.data.find(EMAIL1) >= 0
E       TypeError: Type str doesn't support the buffer API

flask_user/tests/test_multiple_emails.py:72: TypeError



self = <flask_user.tests.tst_utils.TstClient object at 0xb5d3334c>
url = 'http://localhost/user/confirm-email/VwMML4T0MxTBPG4dVwH9kg.B2e1PA.3SHyIq56C-krALmX8oAn_6yPQCo'

    def get_valid_page(self, url):
        """
            GET url and assert that the response contains no errors.
            """
        response = self.client.get(url, follow_redirects=True)
        assert response.status_code == 200, "GET %s returned %d" % (url, response.status_code)
       assert response_has_no_errors(response), "GET %s returned an error" % url
       AssertionError: GET 
http://localhost/user/confirm-email/VwMML4T0MxTBPG4dVwH9kg.B2e1PA.3SHyIq56C-krALmX8oAn_6yPQCo returned an error

flask_user/tests/tst_utils.py:45: AssertionError

Question: Customizing Templates help

I am trying to customize the flask user pages. I cannot find the default login_or_register.html template in order to add a couple of fields to it.

Also, when I try to override the other default templates by placing them in my app templates directory, I am getting nowhere- the defaults are still loaded!

For example, I created a public_base.html file, and placed it in my templates directory. That file consists of the following:

{% extends 'base.html' %}
    {% block body %}
    <div class="container">
        <div class="row">
            <div class="col-sm-8 col-md-7 col-lg-6 col-centered">
                <h1>
                {% block flash_messages %}
                    {%- with messages = get_flashed_messages(with_categories=true) -%}
                        {% if messages %}
                            {% for category, message in messages %}
                                {% if category=='error' %}
                                    {% set category='danger' %}
                                {% endif %}
                                <div class="alert alert-{{category}}">{{ message }}</div>
                            {% endfor %}
                        {% endif %}
                    {%- endwith %}
                {% endblock %}

                {% block content %}
                {% endblock %}

            </div>
        </div>
    </div>
    {% endblock %}

That didn't work. So I tried to override the forgot_password.html template, and changed the first line to: {% extends 'public_base.html' %}

But it still doesn't work.

database issue

I was using the Separated User/UserAuth DataModel.
If table user_auth has A, B and C, and table user has A and B only. When I log in as A and change my username from A to C, there will be sqlachemy error. The inconsistency of tables occurred after a mailing fail: when I register the new account C, confirmation mail was not sent successfully.
So I guess two things can be improved:

  1. make sure the adding operations of new user to the two tables are done next to each other, don't separate them by any other code.
  2. check both user_auth and user and make sure the new data won't incur any prime key conflicts.

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.