mirror of
https://github.com/wassname/flask-security.git
synced 2026-08-11 11:18:40 +08:00
Merge branch 'feature/token-authentication' into feature/decorators
This commit is contained in:
@@ -55,7 +55,9 @@ _default_config = {
|
||||
'CONFIRM_EMAIL_WITHIN': '5 days',
|
||||
'RESET_PASSWORD_WITHIN': '2 days',
|
||||
'LOGIN_WITHOUT_CONFIRMATION': False,
|
||||
'EMAIL_SENDER': 'no-reply@localhost'
|
||||
'EMAIL_SENDER': 'no-reply@localhost',
|
||||
'TOKEN_AUTHENTICATION_KEY': 'auth_token',
|
||||
'TOKEN_AUTHENTICATION_HEADER': 'X-Auth-Token'
|
||||
}
|
||||
|
||||
|
||||
@@ -247,6 +249,8 @@ class Security(object):
|
||||
self.login_without_confirmation = utils.config_value(app, 'LOGIN_WITHOUT_CONFIRMATION')
|
||||
self.confirm_email = utils.config_value(app, 'CONFIRM_EMAIL')
|
||||
self.email_sender = utils.config_value(app, 'EMAIL_SENDER')
|
||||
self.token_authentication_key = utils.config_value(app, 'TOKEN_AUTHENTICATION_KEY')
|
||||
self.token_authentication_header = utils.config_value(app, 'TOKEN_AUTHENTICATION_HEADER')
|
||||
|
||||
self.confirm_email_within_text = utils.config_value(app, 'CONFIRM_EMAIL_WITHIN')
|
||||
values = self.confirm_email_within_text.split()
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from flask import current_app
|
||||
from flask.ext.security.exceptions import BadCredentialsError, \
|
||||
UserNotFoundError, AuthenticationError
|
||||
from flask.ext.security.utils import generate_token
|
||||
from werkzeug.local import LocalProxy
|
||||
|
||||
security = LocalProxy(lambda: current_app.security)
|
||||
|
||||
|
||||
def find_user_by_authentication_token(token):
|
||||
if not token:
|
||||
raise BadCredentialsError('Authentication token required')
|
||||
return security.datastore.find_user(authentication_token=token)
|
||||
|
||||
|
||||
def generate_authentication_token(user):
|
||||
while True:
|
||||
token = generate_token()
|
||||
try:
|
||||
find_user_by_authentication_token(token)
|
||||
except UserNotFoundError:
|
||||
break
|
||||
|
||||
now = datetime.utcnow()
|
||||
|
||||
try:
|
||||
user['authentication_token'] = token
|
||||
user['authentication_token_generated_at'] = now
|
||||
except TypeError:
|
||||
user.authentication_token = token
|
||||
user.authentication_token_generated_at = now
|
||||
|
||||
return user
|
||||
|
||||
|
||||
def authenticate_by_token(token):
|
||||
try:
|
||||
return find_user_by_authentication_token(token)
|
||||
except UserNotFoundError:
|
||||
raise BadCredentialsError('Invalid authentication token')
|
||||
except Exception, e:
|
||||
raise AuthenticationError(str(e))
|
||||
|
||||
|
||||
def reset_authentication_token(user):
|
||||
user = generate_authentication_token(user)
|
||||
security.datastore._save_model(user)
|
||||
Reference in New Issue
Block a user