2014-05-09 21:39:43 +00:00
|
|
|
import ldap
|
|
|
|
import logging
|
2015-03-26 19:10:58 +00:00
|
|
|
import json
|
|
|
|
import itertools
|
|
|
|
import uuid
|
2015-03-26 20:13:35 +00:00
|
|
|
import struct
|
2015-05-11 17:01:49 +00:00
|
|
|
import os
|
2015-06-02 22:19:22 +00:00
|
|
|
import urllib
|
|
|
|
import jwt
|
2014-05-09 21:39:43 +00:00
|
|
|
|
2015-03-26 19:10:58 +00:00
|
|
|
from util.aes import AESCipher
|
2014-05-13 16:17:26 +00:00
|
|
|
from util.validation import generate_valid_usernames
|
|
|
|
from data import model
|
2015-06-01 17:51:00 +00:00
|
|
|
from collections import namedtuple
|
2015-06-02 22:19:22 +00:00
|
|
|
from datetime import datetime, timedelta
|
2014-05-09 21:39:43 +00:00
|
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
2015-05-12 01:23:18 +00:00
|
|
|
if os.environ.get('LDAP_DEBUG') == '1':
|
|
|
|
logger.setLevel(logging.DEBUG)
|
2014-05-09 21:39:43 +00:00
|
|
|
|
2015-05-12 01:23:18 +00:00
|
|
|
ch = logging.StreamHandler()
|
|
|
|
ch.setLevel(logging.DEBUG)
|
|
|
|
|
|
|
|
logger.addHandler(ch)
|
2014-05-09 21:39:43 +00:00
|
|
|
|
2015-06-02 22:19:22 +00:00
|
|
|
|
|
|
|
def _get_federated_user(username, email, federated_service, create_new_user):
|
|
|
|
db_user = model.verify_federated_login(federated_service, username)
|
|
|
|
if not db_user:
|
|
|
|
if not create_new_user:
|
|
|
|
return (None, 'Invalid user')
|
|
|
|
|
|
|
|
# We must create the user in our db
|
|
|
|
valid_username = None
|
|
|
|
for valid_username in generate_valid_usernames(username):
|
|
|
|
if model.is_username_unique(valid_username):
|
|
|
|
break
|
|
|
|
|
|
|
|
if not valid_username:
|
|
|
|
logger.error('Unable to pick a username for user: %s', username)
|
|
|
|
return (None, 'Unable to pick a username. Please report this to your administrator.')
|
|
|
|
|
|
|
|
db_user = model.create_federated_user(valid_username, email, federated_service, username,
|
|
|
|
set_password_notification=False)
|
|
|
|
else:
|
|
|
|
# Update the db attributes from ldap
|
|
|
|
db_user.email = email
|
|
|
|
db_user.save()
|
|
|
|
|
|
|
|
return (db_user, None)
|
|
|
|
|
|
|
|
|
|
|
|
class JWTAuthUsers(object):
|
|
|
|
""" Delegates authentication to a REST endpoint that returns JWTs. """
|
|
|
|
PUBLIC_KEY_FILENAME = 'jwt-authn.cert'
|
|
|
|
|
2015-06-22 22:17:37 +00:00
|
|
|
def __init__(self, verify_url, issuer, override_config_dir, http_client, public_key_path=None):
|
2015-06-02 22:19:22 +00:00
|
|
|
self.verify_url = verify_url
|
|
|
|
self.issuer = issuer
|
2015-06-12 21:58:19 +00:00
|
|
|
self.client = http_client
|
2015-06-02 22:19:22 +00:00
|
|
|
|
2015-06-12 21:58:19 +00:00
|
|
|
default_key_path = os.path.join(override_config_dir, JWTAuthUsers.PUBLIC_KEY_FILENAME)
|
2015-06-02 22:19:22 +00:00
|
|
|
public_key_path = public_key_path or default_key_path
|
|
|
|
if not os.path.exists(public_key_path):
|
|
|
|
error_message = ('JWT Authentication public key file "%s" not found in directory %s' %
|
2015-06-12 21:58:19 +00:00
|
|
|
(JWTAuthUsers.PUBLIC_KEY_FILENAME, override_config_dir))
|
2015-06-02 22:19:22 +00:00
|
|
|
|
|
|
|
raise Exception(error_message)
|
|
|
|
|
|
|
|
with open(public_key_path) as public_key_file:
|
|
|
|
self.public_key = public_key_file.read()
|
|
|
|
|
|
|
|
def verify_user(self, username_or_email, password, create_new_user=True):
|
2015-06-12 21:58:19 +00:00
|
|
|
result = self.client.get(self.verify_url, timeout=2, auth=(username_or_email, password))
|
2015-06-02 22:19:22 +00:00
|
|
|
|
|
|
|
if result.status_code != 200:
|
|
|
|
return (None, result.text or 'Invalid username or password')
|
|
|
|
|
|
|
|
try:
|
|
|
|
result_data = json.loads(result.text)
|
|
|
|
except ValueError:
|
|
|
|
raise Exception('Returned JWT Authentication body does not contain JSON')
|
|
|
|
|
|
|
|
# Load the JWT returned.
|
|
|
|
encoded = result_data.get('token', '')
|
|
|
|
try:
|
|
|
|
payload = jwt.decode(encoded, self.public_key, algorithms=['RS256'],
|
|
|
|
audience='quay.io/jwtauthn', issuer=self.issuer)
|
|
|
|
except jwt.InvalidTokenError:
|
|
|
|
logger.exception('Exception when decoding returned JWT')
|
|
|
|
return (None, 'Invalid username or password')
|
|
|
|
|
|
|
|
if not 'sub' in payload:
|
|
|
|
raise Exception('Missing username field in JWT')
|
|
|
|
|
|
|
|
if not 'email' in payload:
|
|
|
|
raise Exception('Missing email field in JWT')
|
|
|
|
|
|
|
|
if not 'exp' in payload:
|
|
|
|
raise Exception('Missing exp field in JWT')
|
|
|
|
|
|
|
|
# Verify that the expiration is no more than 300 seconds in the future.
|
2015-06-28 08:37:09 +00:00
|
|
|
expiration = datetime.utcfromtimestamp(payload['exp'])
|
|
|
|
if expiration > datetime.utcnow() + timedelta(seconds=300):
|
2015-06-02 22:19:22 +00:00
|
|
|
logger.debug('Payload expiration is outside of the 300 second window: %s', payload['exp'])
|
|
|
|
return (None, 'Invalid username or password')
|
|
|
|
|
|
|
|
# Parse out the username and email.
|
|
|
|
return _get_federated_user(payload['sub'], payload['email'], 'jwtauthn', create_new_user)
|
|
|
|
|
|
|
|
def confirm_existing_user(self, username, password):
|
|
|
|
db_user = model.get_user(username)
|
|
|
|
if not db_user:
|
|
|
|
return (None, 'Invalid user')
|
|
|
|
|
|
|
|
federated_login = model.lookup_federated_login(db_user, 'jwtauthn')
|
|
|
|
if not federated_login:
|
|
|
|
return (None, 'Invalid user')
|
|
|
|
|
|
|
|
return self.verify_user(federated_login.service_ident, password, create_new_user=False)
|
|
|
|
|
|
|
|
|
2014-05-09 21:39:43 +00:00
|
|
|
class DatabaseUsers(object):
|
|
|
|
def verify_user(self, username_or_email, password):
|
|
|
|
""" Simply delegate to the model implementation. """
|
2015-05-12 01:23:18 +00:00
|
|
|
result = model.verify_user(username_or_email, password)
|
|
|
|
if not result:
|
|
|
|
return (None, 'Invalid Username or Password')
|
|
|
|
|
|
|
|
return (result, None)
|
|
|
|
|
2015-05-20 20:37:09 +00:00
|
|
|
def confirm_existing_user(self, username, password):
|
|
|
|
return self.verify_user(username, password)
|
2014-05-09 21:39:43 +00:00
|
|
|
|
|
|
|
|
|
|
|
class LDAPConnection(object):
|
|
|
|
def __init__(self, ldap_uri, user_dn, user_pw):
|
|
|
|
self._ldap_uri = ldap_uri
|
|
|
|
self._user_dn = user_dn
|
|
|
|
self._user_pw = user_pw
|
|
|
|
self._conn = None
|
|
|
|
|
|
|
|
def __enter__(self):
|
2015-05-12 01:23:18 +00:00
|
|
|
trace_level = 2 if os.environ.get('LDAP_DEBUG') == '1' else 0
|
2015-05-11 17:01:49 +00:00
|
|
|
self._conn = ldap.initialize(self._ldap_uri, trace_level=trace_level)
|
2015-05-20 18:53:31 +00:00
|
|
|
self._conn.set_option(ldap.OPT_REFERRALS, 1)
|
2015-06-12 19:39:55 +00:00
|
|
|
|
|
|
|
try:
|
|
|
|
self._conn.simple_bind_s(self._user_dn, self._user_pw)
|
|
|
|
except ldap.INVALID_CREDENTIALS:
|
|
|
|
logger.exception('LDAP admin dn or password are invalid')
|
|
|
|
return None
|
2015-05-12 01:23:18 +00:00
|
|
|
|
2014-05-09 21:39:43 +00:00
|
|
|
return self._conn
|
|
|
|
|
|
|
|
def __exit__(self, exc_type, value, tb):
|
|
|
|
self._conn.unbind_s()
|
|
|
|
|
|
|
|
|
|
|
|
class LDAPUsers(object):
|
2015-06-01 17:51:00 +00:00
|
|
|
_LDAPResult = namedtuple('LDAPResult', ['dn', 'attrs'])
|
|
|
|
|
2014-05-13 19:52:20 +00:00
|
|
|
def __init__(self, ldap_uri, base_dn, admin_dn, admin_passwd, user_rdn, uid_attr, email_attr):
|
2014-05-09 21:39:43 +00:00
|
|
|
self._ldap_conn = LDAPConnection(ldap_uri, admin_dn, admin_passwd)
|
2014-05-13 16:17:26 +00:00
|
|
|
self._ldap_uri = ldap_uri
|
2014-05-09 21:39:43 +00:00
|
|
|
self._base_dn = base_dn
|
|
|
|
self._user_rdn = user_rdn
|
|
|
|
self._uid_attr = uid_attr
|
|
|
|
self._email_attr = email_attr
|
|
|
|
|
2015-05-26 19:46:35 +00:00
|
|
|
def _get_ldap_referral_dn(self, referral_exception):
|
|
|
|
logger.debug('Got referral: %s', referral_exception.args[0])
|
|
|
|
if not referral_exception.args[0] or not referral_exception.args[0].get('info'):
|
|
|
|
logger.debug('LDAP referral missing info block')
|
|
|
|
return None
|
|
|
|
|
|
|
|
referral_info = referral_exception.args[0]['info']
|
|
|
|
if not referral_info.startswith('Referral:\n'):
|
|
|
|
logger.debug('LDAP referral missing Referral header')
|
|
|
|
return None
|
|
|
|
|
|
|
|
referral_uri = referral_info[len('Referral:\n'):]
|
|
|
|
if not referral_uri.startswith('ldap:///'):
|
|
|
|
logger.debug('LDAP referral URI does not start with ldap:///')
|
|
|
|
return None
|
|
|
|
|
|
|
|
referral_dn = referral_uri[len('ldap:///'):]
|
|
|
|
return referral_dn
|
|
|
|
|
2014-05-13 19:22:31 +00:00
|
|
|
def _ldap_user_search(self, username_or_email):
|
|
|
|
with self._ldap_conn as conn:
|
2015-06-12 19:39:55 +00:00
|
|
|
if conn is None:
|
|
|
|
return (None, 'LDAP Admin dn or password is invalid')
|
|
|
|
|
2014-05-13 19:22:31 +00:00
|
|
|
logger.debug('Incoming username or email param: %s', username_or_email.__repr__())
|
|
|
|
user_search_dn = ','.join(self._user_rdn + self._base_dn)
|
|
|
|
query = u'(|({0}={2})({1}={2}))'.format(self._uid_attr, self._email_attr,
|
|
|
|
username_or_email)
|
2015-05-08 18:19:32 +00:00
|
|
|
|
2015-05-12 01:23:18 +00:00
|
|
|
logger.debug('Conducting user search: %s under %s', query, user_search_dn)
|
2015-05-11 17:01:49 +00:00
|
|
|
try:
|
2015-05-12 16:02:09 +00:00
|
|
|
pairs = conn.search_s(user_search_dn, ldap.SCOPE_SUBTREE, query.encode('utf-8'))
|
2015-05-26 19:46:35 +00:00
|
|
|
except ldap.REFERRAL as re:
|
|
|
|
referral_dn = self._get_ldap_referral_dn(re)
|
|
|
|
if not referral_dn:
|
2015-06-12 19:39:55 +00:00
|
|
|
return (None, 'Failed to follow referral when looking up username')
|
2015-05-26 19:46:35 +00:00
|
|
|
|
|
|
|
try:
|
|
|
|
subquery = u'(%s=%s)' % (self._uid_attr, username_or_email)
|
|
|
|
pairs = conn.search_s(referral_dn, ldap.SCOPE_BASE, subquery)
|
|
|
|
except ldap.LDAPError:
|
|
|
|
logger.exception('LDAP referral search exception')
|
2015-06-12 19:39:55 +00:00
|
|
|
return (None, 'Username not found')
|
2015-05-26 19:46:35 +00:00
|
|
|
|
2015-05-11 17:01:49 +00:00
|
|
|
except ldap.LDAPError:
|
|
|
|
logger.exception('LDAP search exception')
|
2015-06-12 19:39:55 +00:00
|
|
|
return (None, 'Username not found')
|
2014-05-13 19:22:31 +00:00
|
|
|
|
2015-05-12 16:02:09 +00:00
|
|
|
logger.debug('Found matching pairs: %s', pairs)
|
2015-05-26 19:46:35 +00:00
|
|
|
|
2015-06-01 17:51:00 +00:00
|
|
|
results = [LDAPUsers._LDAPResult(*pair) for pair in pairs]
|
|
|
|
|
2015-05-26 19:46:35 +00:00
|
|
|
# Filter out pairs without DNs. Some LDAP impls will return such
|
|
|
|
# pairs.
|
2015-06-01 17:51:00 +00:00
|
|
|
with_dns = [result for result in results if result.dn]
|
2015-05-26 19:46:35 +00:00
|
|
|
if len(with_dns) < 1:
|
2015-06-12 19:39:55 +00:00
|
|
|
return (None, 'Username not found')
|
2014-05-13 19:22:31 +00:00
|
|
|
|
2015-05-26 19:46:35 +00:00
|
|
|
# If we have found a single pair, then return it.
|
|
|
|
if len(with_dns) == 1:
|
2015-06-12 19:39:55 +00:00
|
|
|
return (with_dns[0], None)
|
2015-05-12 16:02:09 +00:00
|
|
|
|
2015-05-26 19:46:35 +00:00
|
|
|
# Otherwise, there are multiple pairs with DNs, so find the one with the mail
|
|
|
|
# attribute (if any).
|
2015-06-01 17:51:00 +00:00
|
|
|
with_mail = [result for result in results if result.attrs.get(self._email_attr)]
|
2015-06-12 19:39:55 +00:00
|
|
|
return (with_mail[0] if with_mail else with_dns[0], None)
|
2014-05-13 19:22:31 +00:00
|
|
|
|
2015-05-20 20:37:09 +00:00
|
|
|
def confirm_existing_user(self, username, password):
|
|
|
|
""" Verify the username and password by looking up the *LDAP* username and confirming the
|
|
|
|
password.
|
|
|
|
"""
|
|
|
|
db_user = model.get_user(username)
|
|
|
|
if not db_user:
|
|
|
|
return (None, 'Invalid user')
|
|
|
|
|
|
|
|
federated_login = model.lookup_federated_login(db_user, 'ldap')
|
|
|
|
if not federated_login:
|
|
|
|
return (None, 'Invalid user')
|
|
|
|
|
|
|
|
return self.verify_user(federated_login.service_ident, password, create_new_user=False)
|
|
|
|
|
|
|
|
def verify_user(self, username_or_email, password, create_new_user=True):
|
2014-05-09 21:39:43 +00:00
|
|
|
""" Verify the credentials with LDAP and if they are valid, create or update the user
|
|
|
|
in our database. """
|
|
|
|
|
2014-05-13 16:17:26 +00:00
|
|
|
# Make sure that even if the server supports anonymous binds, we don't allow it
|
|
|
|
if not password:
|
2015-05-12 01:23:18 +00:00
|
|
|
return (None, 'Anonymous binding not allowed')
|
2014-05-13 16:17:26 +00:00
|
|
|
|
2015-06-12 19:39:55 +00:00
|
|
|
(found_user, err_msg) = self._ldap_user_search(username_or_email)
|
2014-05-13 19:22:31 +00:00
|
|
|
if found_user is None:
|
2015-06-12 19:39:55 +00:00
|
|
|
return (None, err_msg)
|
2014-05-09 21:39:43 +00:00
|
|
|
|
2014-05-13 19:22:31 +00:00
|
|
|
found_dn, found_response = found_user
|
2015-05-26 19:46:35 +00:00
|
|
|
logger.debug('Found user for LDAP username %s; validating password', username_or_email)
|
|
|
|
logger.debug('DN %s found: %s', found_dn, found_response)
|
2014-05-09 21:39:43 +00:00
|
|
|
|
2014-05-13 19:22:31 +00:00
|
|
|
# First validate the password by binding as the user
|
|
|
|
try:
|
|
|
|
with LDAPConnection(self._ldap_uri, found_dn, password.encode('utf-8')):
|
|
|
|
pass
|
2015-05-26 19:46:35 +00:00
|
|
|
except ldap.REFERRAL as re:
|
|
|
|
referral_dn = self._get_ldap_referral_dn(re)
|
|
|
|
if not referral_dn:
|
|
|
|
return (None, 'Invalid username')
|
|
|
|
|
|
|
|
try:
|
|
|
|
with LDAPConnection(self._ldap_uri, referral_dn, password.encode('utf-8')):
|
|
|
|
pass
|
|
|
|
except ldap.INVALID_CREDENTIALS:
|
|
|
|
logger.exception('Invalid LDAP credentials')
|
|
|
|
return (None, 'Invalid password')
|
|
|
|
|
2014-05-13 19:22:31 +00:00
|
|
|
except ldap.INVALID_CREDENTIALS:
|
2015-05-08 18:19:32 +00:00
|
|
|
logger.exception('Invalid LDAP credentials')
|
2015-05-12 01:23:18 +00:00
|
|
|
return (None, 'Invalid password')
|
2014-05-09 21:39:43 +00:00
|
|
|
|
2014-05-13 19:22:31 +00:00
|
|
|
# Now check if we have a federated login for this user
|
2015-05-12 01:23:18 +00:00
|
|
|
if not found_response.get(self._uid_attr):
|
|
|
|
return (None, 'Missing uid field "%s" in user record' % self._uid_attr)
|
|
|
|
|
|
|
|
if not found_response.get(self._email_attr):
|
|
|
|
return (None, 'Missing mail field "%s" in user record' % self._email_attr)
|
|
|
|
|
2014-05-13 19:22:31 +00:00
|
|
|
username = found_response[self._uid_attr][0].decode('utf-8')
|
|
|
|
email = found_response[self._email_attr][0]
|
2015-06-02 22:19:22 +00:00
|
|
|
return _get_federated_user(username, email, 'ldap', create_new_user)
|
2014-05-09 21:39:43 +00:00
|
|
|
|
|
|
|
|
2015-03-26 19:10:58 +00:00
|
|
|
|
2014-05-09 21:39:43 +00:00
|
|
|
class UserAuthentication(object):
|
2015-06-12 21:58:19 +00:00
|
|
|
def __init__(self, app=None, override_config_dir=None):
|
|
|
|
self.app_secret_key = None
|
2014-05-09 21:39:43 +00:00
|
|
|
self.app = app
|
|
|
|
if app is not None:
|
2015-06-12 21:58:19 +00:00
|
|
|
self.state = self.init_app(app, override_config_dir)
|
2014-05-09 21:39:43 +00:00
|
|
|
else:
|
|
|
|
self.state = None
|
|
|
|
|
2015-06-12 21:58:19 +00:00
|
|
|
def init_app(self, app, override_config_dir):
|
|
|
|
self.app_secret_key = app.config['SECRET_KEY']
|
|
|
|
|
2014-05-09 21:39:43 +00:00
|
|
|
authentication_type = app.config.get('AUTHENTICATION_TYPE', 'Database')
|
|
|
|
|
|
|
|
if authentication_type == 'Database':
|
2014-05-13 16:17:26 +00:00
|
|
|
users = DatabaseUsers()
|
2014-05-09 21:39:43 +00:00
|
|
|
elif authentication_type == 'LDAP':
|
|
|
|
ldap_uri = app.config.get('LDAP_URI', 'ldap://localhost')
|
|
|
|
base_dn = app.config.get('LDAP_BASE_DN')
|
|
|
|
admin_dn = app.config.get('LDAP_ADMIN_DN')
|
|
|
|
admin_passwd = app.config.get('LDAP_ADMIN_PASSWD')
|
|
|
|
user_rdn = app.config.get('LDAP_USER_RDN', [])
|
|
|
|
uid_attr = app.config.get('LDAP_UID_ATTR', 'uid')
|
|
|
|
email_attr = app.config.get('LDAP_EMAIL_ATTR', 'mail')
|
|
|
|
|
2014-05-13 19:52:20 +00:00
|
|
|
users = LDAPUsers(ldap_uri, base_dn, admin_dn, admin_passwd, user_rdn, uid_attr, email_attr)
|
2015-06-02 22:19:22 +00:00
|
|
|
elif authentication_type == 'JWT':
|
|
|
|
verify_url = app.config.get('JWT_VERIFY_ENDPOINT')
|
|
|
|
issuer = app.config.get('JWT_AUTH_ISSUER')
|
2015-06-22 22:17:37 +00:00
|
|
|
users = JWTAuthUsers(verify_url, issuer, override_config_dir, app.config['HTTPCLIENT'])
|
2014-05-09 21:39:43 +00:00
|
|
|
else:
|
|
|
|
raise RuntimeError('Unknown authentication type: %s' % authentication_type)
|
|
|
|
|
|
|
|
# register extension with app
|
|
|
|
app.extensions = getattr(app, 'extensions', {})
|
|
|
|
app.extensions['authentication'] = users
|
2015-06-12 21:58:19 +00:00
|
|
|
|
2014-05-09 21:39:43 +00:00
|
|
|
return users
|
|
|
|
|
2015-03-26 19:10:58 +00:00
|
|
|
def _get_secret_key(self):
|
|
|
|
""" Returns the secret key to use for encrypting and decrypting. """
|
2015-03-26 21:45:43 +00:00
|
|
|
secret_key = None
|
2015-03-26 19:10:58 +00:00
|
|
|
|
2015-03-26 19:47:44 +00:00
|
|
|
# First try parsing the key as an int.
|
2015-03-26 19:10:58 +00:00
|
|
|
try:
|
2015-06-12 21:58:19 +00:00
|
|
|
big_int = int(self.app_secret_key)
|
2015-03-26 21:45:43 +00:00
|
|
|
secret_key = str(bytearray.fromhex('{:02x}'.format(big_int)))
|
2015-03-26 19:10:58 +00:00
|
|
|
except ValueError:
|
2015-03-26 21:45:43 +00:00
|
|
|
pass
|
2015-03-26 19:10:58 +00:00
|
|
|
|
|
|
|
# Next try parsing it as an UUID.
|
2015-03-26 21:45:43 +00:00
|
|
|
if secret_key is None:
|
|
|
|
try:
|
2015-06-12 21:58:19 +00:00
|
|
|
secret_key = uuid.UUID(self.app_secret_key).bytes
|
2015-03-26 21:45:43 +00:00
|
|
|
except ValueError:
|
|
|
|
pass
|
|
|
|
|
|
|
|
if secret_key is None:
|
2015-06-12 21:58:19 +00:00
|
|
|
secret_key = str(bytearray(map(ord, self.app_secret_key)))
|
2015-03-26 19:10:58 +00:00
|
|
|
|
|
|
|
# Otherwise, use the bytes directly.
|
|
|
|
return ''.join(itertools.islice(itertools.cycle(secret_key), 32))
|
|
|
|
|
|
|
|
def encrypt_user_password(self, password):
|
|
|
|
""" Returns an encrypted version of the user's password. """
|
|
|
|
data = {
|
|
|
|
'password': password
|
|
|
|
}
|
|
|
|
|
|
|
|
message = json.dumps(data)
|
|
|
|
cipher = AESCipher(self._get_secret_key())
|
|
|
|
return cipher.encrypt(message)
|
|
|
|
|
|
|
|
def _decrypt_user_password(self, encrypted):
|
|
|
|
""" Attempts to decrypt the given password and returns it. """
|
|
|
|
cipher = AESCipher(self._get_secret_key())
|
|
|
|
|
|
|
|
try:
|
|
|
|
message = cipher.decrypt(encrypted)
|
|
|
|
except ValueError:
|
|
|
|
return None
|
|
|
|
except TypeError:
|
|
|
|
return None
|
|
|
|
|
|
|
|
try:
|
|
|
|
data = json.loads(message)
|
|
|
|
except ValueError:
|
|
|
|
return None
|
|
|
|
|
|
|
|
return data.get('password', encrypted)
|
|
|
|
|
2015-05-20 20:37:09 +00:00
|
|
|
def confirm_existing_user(self, username, password):
|
|
|
|
""" Verifies that the given password matches to the given DB username. Unlike verify_user, this
|
|
|
|
call first translates the DB user via the FederatedLogin table (where applicable).
|
|
|
|
"""
|
|
|
|
return self.state.confirm_existing_user(username, password)
|
|
|
|
|
|
|
|
|
2015-03-25 22:43:12 +00:00
|
|
|
def verify_user(self, username_or_email, password, basic_auth=False):
|
|
|
|
# First try to decode the password as a signed token.
|
|
|
|
if basic_auth:
|
|
|
|
import features
|
|
|
|
|
2015-03-26 19:10:58 +00:00
|
|
|
decrypted = self._decrypt_user_password(password)
|
|
|
|
if decrypted is None:
|
2015-03-25 22:43:12 +00:00
|
|
|
# This is a normal password.
|
|
|
|
if features.REQUIRE_ENCRYPTED_BASIC_AUTH:
|
2015-03-26 20:23:28 +00:00
|
|
|
msg = ('Client login with unecrypted passwords is disabled. Please generate an ' +
|
|
|
|
'encrypted password in the user admin panel for use here.')
|
2015-03-25 22:43:12 +00:00
|
|
|
return (None, msg)
|
2015-03-26 19:10:58 +00:00
|
|
|
else:
|
|
|
|
password = decrypted
|
2015-03-25 22:43:12 +00:00
|
|
|
|
2015-05-11 21:13:42 +00:00
|
|
|
(result, err_msg) = self.state.verify_user(username_or_email, password)
|
|
|
|
if not result:
|
|
|
|
return (result, err_msg)
|
|
|
|
|
|
|
|
if not result.enabled:
|
|
|
|
return (None, 'This user has been disabled. Please contact your administrator.')
|
|
|
|
|
|
|
|
return (result, err_msg)
|
2015-03-25 22:43:12 +00:00
|
|
|
|
2014-05-09 21:39:43 +00:00
|
|
|
def __getattr__(self, name):
|
|
|
|
return getattr(self.state, name, None)
|