mattupstate / flask-security Goto Github PK
View Code? Open in Web Editor NEWQuick and simple security for Flask applications
License: MIT License
Quick and simple security for Flask applications
License: MIT License
i10n and i18n could be necessary for things such as Flash messages.
python manage.py addrole -u [email protected] -r admin
File "flask_security/datastore.py", line 60, in _prepare_role_modify_args
return self.find_user(email=user.email), self.find_role(role)
AttributeError: 'str' object has no attribute 'email'
changing this line to email=user - makes it work but I don't know if this function is used somewhere else and it would cause more issues.
Btw, it would be great if script commands would allow arbitrary arguments for createuser (resulting in populating these fields as well). And addrole/removerole would actually allow to identify user by arguments provided (use all of them for find_user kwargs). This way, custom auth that looks for username or email would be as easy as:
modify model, subclass datastore and change find_user
And all of commands would adapt to user input. If better help is required for addrole/removerole - it can inspect user model and check for keys that are unique or primary. So it can output meaningful help on how to use these methods (based on current user model). But this part is unnecessary in my opinion.
Hi,
what about spliting database engine dependent stuff into separate modules:
ext.sqlalchemy
ext.mongoengine
then it will be easier to add stuff and models could be defined on those modules.
I added email verification to my project and found out that you can verify email more than once, shouldn't it say "This account has already been verified"? This might be a security issue as this is touching database by changing time of verification every time.
It appears the main branch of Flask-Principal (https://bitbucket.org/aafshar/flask-principal-main) has not been updated in some time (2010). There are some changes I think need to be done to it, including:
Some other changes to investigate:
Add some way of adding additional fields to the User model. Perhaps providing a mixin when creating an instance of the datastore.
Stumbled over a problem this evening as I'm playing with flask-security. The docs say:
SECURITY_CONFIRMABLE
Specifies if users are required to confirm their email
address when registering a new account. If this value
is True Flask-Security creates an endpoint to handle
confirmations and requests to resend confirmation
instructions. The URL for this endpoint is specified by
the SECURITY_CONFIRM_URL configuration option.
Defaults to False.
Ok, no problem.
I realized that the password confirmation field wasn't showing up on the register page, so I removed {% if register_user_form.password_confirm %} from around the password_confirm field rendering, and got this error:
UndefinedError: 'flask_security.forms.ConfirmRegisterForm
object' has no attribute 'password_confirm'
I tracked the problem down to line 103 in flask_security/views.py:
if _security.confirmable or request.json:
form_class = ConfirmRegisterForm
else:
form_class = RegisterForm
The only difference between ConfirmRegisterForm and RegisterForm is that RegisterForm calls the PasswordConfirmFormMixin. Neither form has anything, as far as I can tell, with sending confirmation emails. :) So, unless I'm completely missing something, I think the above bit from views.py should be changed to:
if request.json:
form_class = ConfirmRegisterForm
else:
form_class = RegisterForm
That's what I've done on my installation, at any rate (along with modifying the template as mentioned above), and it now correctly displays the password confirmation field. I haven't run into any issues yet, but I'm working on a local machine, not a live server, so I haven't tried sending associated emails yet. :)
I was wondering if it is a feature or a bug that if you submit a duplicate registration an exception is thrown?
I get this error while trying to register an user:
AttributeError: 'NoneType' object has no attribute 'send'
File "/Users/g/myapp/lib/python2.7/site-packages/flask/app.py", line 1701, in __call__
return self.wsgi_app(environ, start_response)
File "/Users/g/myapp/lib/python2.7/site-packages/flask/app.py", line 1689, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/Users/g/myapp/lib/python2.7/site-packages/flask/app.py", line 1687, in wsgi_app
response = self.full_dispatch_request()
File "/Users/g/myapp/lib/python2.7/site-packages/flask/app.py", line 1360, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Users/g/myapp/lib/python2.7/site-packages/flask/app.py", line 1358, in full_dispatch_request
rv = self.dispatch_request()
File "/Users/g/myapp/lib/python2.7/site-packages/flask/app.py", line 1344, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/Users/g/myapp/lib/python2.7/site-packages/flask_security/views.py", line 113, in register
user = register_user(**form.to_dict())
File "/Users/g/myapp/lib/python2.7/site-packages/flask_security/registerable.py", line 39, in register_user
user=user, confirmation_link=confirmation_link)
File "/Users/g/myapp/lib/python2.7/site-packages/flask_security/utils.py", line 235, in send_mail
mail.send(msg)
I am using Python 2.7.3
, Flask 0.9
, Flask-Security 1.5.0
and Flask-Mail 0.7.3
Is there a buildin API-Method to update a crypted User-Password ?
Currently flask-security always sends mail through flask-mail. I need to use an external service (e.g. Cheetahmail, Responsys, etc.) instead. I would like the ability to disable sending mail through flask mail so that I can handle it only through signals.
In http://packages.python.org/Flask-Security/ in Getting Started,
from flask.ext.security.datastore.sqlalchemy import SQLAlchemyUserDataStore
Should be:
from flask.ext.security.datastore.sqlalchemy import SQLAlchemyUserDatastore
's' lowercase
I used this to display my login/registration form:
from flask.ext.security import Security, LoginForm, RegisterForm
@app.route("/login")
def login():
return render_template('login.html', form=LoginForm())
@app.route("/register")
def register():
return render_template('register.html', form=RegisterForm())
but flash messages for invalid forms are only displayed for login and not for registration.
Register page will just redirect back to register without any notification.
Am I doing something wrong or is this an issue?
When protecting a resource with either @roles_required() or @roles_accepted(), after a successful login, the next arg is not passed (url is http://localhost:5000/login )
When protecting a resource with @login_required(), "next" is correctly passed in the url: http://localhost:5000/login?next=%2Fmypage
That means tha when the login is successful, the user is always redirected to the '/' resource.
nosetests tests/configured_tests.py:BadConfiguredSecurityTests
Is it just me?
You can see this behavior at:
http://flask-social-example.herokuapp.com/login
Just enter a bogus username and submit.
I know it's related to how a login function is implemented but I figured if examples show it that way that is the "recommended/standard" way. If you have any thoughts or suggestions I'm willing to try and write a patch. :)
Both times when the ForgotPasswordForm validates or not, the forgot() view will raise a TemplateNotFound error. Other views do a redirect while this forgot view renders the 'passwords/new.html' template. Is there a reason for this?
There is a bit lack of documentation (that I know of), what is the suggested way to use these form views? The example in the source tree shows how to set up everything very nice, but lacks in other parts. It would be nice to see a full working example of login/registration/password recovery/etc. Just as a sidenote.
Its perhaps not clear that the flask-mail extension needs to be set up outside the context of flask-security.
It would be nice to have support for flask-peewee, beside flask-sqlalchemy and flask-mongoengine.
Thanks.
See slide 83 of Armin's presentation here: https://speakerdeck.com/u/mitsuhiko/p/advanced-flask-patterns
I need a register form with username
field, but the current design makes me hard to reuse views.register
and forms.RegisterForm
How about re-factory the views.register
into a class and expose some setter so I can customize the instance myself?
Or did I do something wrong?
Trying to run the example with MongoDB as the datastore.
from flask import Flask
from flask.ext.mongoengine import MongoEngine
from flask.ext.security import Security
from flask.ext.security.datastore.mongoengine import MongoEngineUserDatastore
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret'
app.config['MONGODB_DB'] = 'auth_test'
app.config['MONGODB_HOST'] = 'ds035997.mongolab.com'
app.config['MONGODB_PORT'] = 35997
db = MongoEngine(app)
Security(app, MongoEngineUserDatastore(db))
@app.before_first_request
def before_first_request():
user_datastore.create_role(name='admin')
user_datastore.create_user(username='asselinpaul', email='[email protected]',
password='paa1946', roles=['admin'])
@app.route("/login")
def login():
return render_template('login.html', form=LoginForm())
@app.route('/profile')
@login_required
def profile():
return render_template('profile.html')
I've install Flask and Flask-Security through virtualenv and can't see what's wrong, any help?
Thanks in advance.
Paul
At the moment a view method/endpoint can only be protected by one authentication mechanism (login_require
, auth_token_required
, or http_auth_required
) at a time. It would be nice to have a decorator that allows all or some of these mechanisms to be used on one view method/endpoint.
https://github.com/mattupstate/flask-security/blob/develop/example/app.py#L101
Are the column names and foreign keys swapped or am I missing something?
roles_users = db.Table('roles_users',
db.Column('user_id', db.Integer(), db.ForeignKey('role.id')),
db.Column('role_id', db.Integer(), db.ForeignKey('user.id')))
Using SQLAlchemy, when updating the password in this function it should be calling _datastore.commit() instead of _datastore.put(user) since the user already exists.
I think it would be nice to be 'cutting edge' and allow the configuration of Flask-Security to use password-less login as explained in this article:
http://notes.xoxco.com/post/27999787765/is-it-time-for-password-less-login
with MongoEngine and with confirmable = true.
my User class is using the default mongoengine id field, which is the same as the test class in https://github.com/mattupstate/flask-security/blob/develop/tests/test_app/mongoengine.py.
I'm not sure if this is a bug or a misconfiguration on my part. I'm running in virtualenv,
Flask-0.9
Flask_SQLAlchemy-0.16
Flask-Security-1.5.4
Heres the traceback.
File "/env/local/lib/python2.7/site-packages/flask_security/views.py", line 12, in
from flask import current_app, redirect, request, render_template, jsonify,
ImportError: cannot import name after_this_request
This is when using the simple quickstart (first example) code from the documentation at - http://packages.python.org/Flask-Security/quickstart.html
Any ideas?
Many Thanks,
Rob
Currently Flask-Security requires Flask-Mail, which requires Lamson, which doesn't play well on Windows (see: http://packages.python.org/Flask-Mail/ for workaround on not installing Lamson dependency).
I haven't familiarized myself with Flask-Mail to see what it's using Lamson for (Lamson appears to be a smtp server, and not client, so maybe just for testing/development). If it is just for testing/development, maybe Flask-Mail could use something like Inbox.py (https://github.com/kennethreitz/inbox.py)
Anyways, the main goal should be to improve Windows compatibility ('pip install Flask-Security' fails), but it may result in looking improving Flask-Mail, or removing it's dependency.
It would be nice if other mail systems could be use (for example, Google App Engine - https://developers.google.com/appengine/docs/python/mail/sendingmail)
Disclosure... This is not directly related to develop branch of flask-security. Perhaps, however, someone using mongodb version is interested in pymongo support in the future.
So far, wired flask-security to work with pymongo and I have all tests passing.
I have encountered a major road block at the moment. When I try to authenticate via json in Production mode (no app.test_client), it returns Invalid Passord.
I have traced it all the way down to one function call in the core python Lib hmac.py
file.
In testing: functional_tests.DefaultSecurityTests.test_ok_json_auth()
I watch and verify that the hmac.py.inner
value both when creating a password and later verifying are the SAME.
However, when I am in production mode, I watch and notice that the hmac.py.inner
value when creating a password and later verifying are DIFFERENT.
On line 73 of python/Lib/hmac.py
, something is happening here that I cannot step into with a debugger and yet something inside this black box seems to be influenced by my being in test vs production mode.
self.inner.update(key.translate(trans_36))
I do not want to abandon this effort on the enhancement of this extension.
This is where you can find/follow/watch my efforts. [email protected]:LarryEitel/exi.git
Thanks in advance for any input.
At http://packages.python.org/Flask-Security/ in section "Getting Started", the code states:
user_datastore.create_user(username='matt', email='[email protected]',
password='password', roles['admin'])
But it should be:
user_datastore.create_user(username='matt', email='[email protected]',
password='password', roles=['admin'])
(a '=' is missing for the last argument)
Right now each email, which send by Flask-Security
, has static subject, but in most cases we need to customize email subject due to different applicaiton.
Yeah, it also possible to do in current implementation as:
from flask import Flask
from flask.ext.mail import Mail
from flask.ext.security import Security
app = Flask('appname')
mail = Mail(app)
...
def send_mail(message):
if message.subject == 'Welcome':
message.subject = 'Confirm your account'
mail.send(message)
...
security = Security(app, datastore)
app.extensions['security']._send_mail_task = send_mail
But I think it's ugly ability and more natural way is to adding default subjects similar to default messages and customize they as SUBJECT_WELCOME
in project settings.
What do you think?
I was trying to use with mongoengine but i'm having a hard time because can' t find good examples
Use a token instead of user ID with Flask-Login as it is more secure
See http://packages.python.org/Flask-Login/#alternative-tokens
The documentation gives a great example on how to install and otherwise use this but it lacks the actual command to create the tables, although it already describes how to put roles and users in.
In the example one can find this:
@app.before_first_request
def before_first_request():
db.drop_all()
db.create_all()
Maybe include something like that in documentation. Or make Security() init create tables
There's a bad in datastore.py
in the find_user
;
Traceback (most recent call last):
File "manage.py", line 7, in <module>
from flaskapp.core import app
File "/Users/eskil/src/flaskapp/flaskapp/core.py", line 14, in <module>
from flask_security import Security, SQLAlchemyUserDatastore
File "/Users/eskil/src/flaskapp/env/lib/python2.7/site-packages/flask_security/__init__.py", line 16, in <module>
from .datastore import SQLAlchemyUserDatastore, MongoEngineUserDatastore
File "/Users/eskil/src/flaskapp/env/lib/python2.7/site-packages/flask_security/datastore.py", line 60
user = self.find_user(email=user.email)
SyntaxError: keyword can't be an expression
I'm starting to wonder if having functions such as registration, confirmations, password reset would be better off in a companion extension, similar to flask-social. Perhaps name it flask-users?
If anyone happens to see this issue I'd love to hear any feedback.
I submitted a pull request to Flask-Script to allow for nested managers and would like your feedback on it. If accepted, it would be nice to have a preconfigured manager instance (the pull request actually shows an example of how flask-security could work).
https://github.com/rduplain/flask-script/pull/39
Thanks.
It would be awesome to be able to override Flask-Login
messages (such as login_message
and needs_refresh_message
) in the Flask-Security
message config.
You can change the message like this:
login_manager.login_message = "Message goes here"
Alternatively, surfacing login_manager
would work, too.
(Thanks for this package, btw -- saved me a ton of time and works like a charm.)
I am fishing around your docs. Noticed datastore referenced mongoengine. Haven't reviewed your code yet to determine this myself... (on iPad at the moment) Is it convenient to override User class to access User class of my own connected directly to pymongo?
Allow any sort of message to be configurable
I believe it would be helpful to add a convenience view that allows an authenticated user to change their existing password.
This feature can currently be written "DIY" style using Flask-Security - it would be a handy time saver if this view was available in the extension.
ERROR: test_confirm_bad_token (tests.signals_tests.ConfirmableSignalsTests)
....
File "C:\Users\Larry__prjs_fx\py\flask-security\flask_security\utils.py", line 199, in get_max_age
return int(expires.strftime('%s')) - int(now.strftime('%s'))
ValueError: Invalid format string
Hi, I'm currently using the stable version and am finding it really hard to be able to authenticate users manually. The main reason for requiring this is to get authentication working via an ajax call. I've noticed in the dev branch there is a utility function that looks like it might do this. Is this my only option?
Cheers.
I think it would be very useful and almost required to use signals to notify when accounts have been at least created and confirmed.
I dont see an elegant way to handle these cases.
I think using signals will give end users the hooks into the flask security system without having to modify the flask_security core code.
Thoughts?
Thanks.
Hi. I use Flask-Security and want to implement api authentication, but I can't login throw bultin views. For example I try(example in #30):
curl -X POST -H "Content-Type: application/json" -d '{"email":"[email protected]", "password":"1234Qwer"}' localhost:5000/login
but got:
{
"meta": {
"code": 400
},
"response": {
"errors": {
"csrf_token": [
"CSRF token missing"
]
}
}
}
I undestand, that I need csrf_token, but for api use it's not needed. Is there way to manually authenticate user or other way to do this?
Thanks for the great app:)
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.