def get_user(self, user_id): """ Returns the current user (if authenticated) based on the user ID and session data. Note: this required monkey-patching the ``contrib.auth`` middleware to make the ``request`` object available to the auth backend class. """ if user_id == self.request.session["user_id"]: token = Token(TokenManager(None), self.request.session['token'], loaded=True) endpoint = self.request.session['region_endpoint'] return create_user_from_token(self.request, token, endpoint) else: return None
def authenticate(self, request=None, username=None, password=None, tenant=None, auth_url=None, otp=None): """ Authenticates a user via the Keystone Identity API. """ LOG.debug('Beginning user authentication for user "%s".' % username) insecure = getattr(settings, 'OPENSTACK_SSL_NO_VERIFY', False) try: client = keystone_client.Client(username=username, password=password, tenant_id=tenant, auth_url=auth_url, insecure=insecure) unscoped_token_data = {"token": client.service_catalog.get_token()} unscoped_token = Token(TokenManager(None), unscoped_token_data, loaded=True) except (keystone_exceptions.Unauthorized, keystone_exceptions.Forbidden, keystone_exceptions.NotFound) as exc: msg = _('Invalid user name or password.') LOG.debug(exc.message) raise KeystoneAuthException(msg) except (keystone_exceptions.ClientException, keystone_exceptions.AuthorizationFailure) as exc: msg = _("An error occurred authenticating. " "Please try again later.") LOG.debug(exc.message) raise KeystoneAuthException(msg) # Check expiry for our unscoped token. self.check_auth_expiry(unscoped_token) # FIXME: Log in to default tenant when the Keystone API returns it... # For now we list all the user's tenants and iterate through. try: tenants = client.tenants.list() except (keystone_exceptions.ClientException, keystone_exceptions.AuthorizationFailure): msg = _('Unable to retrieve authorized projects.') raise KeystoneAuthException(msg) # Abort if there are no tenants for this user if not tenants: msg = _('You are not authorized for any projects.') raise KeystoneAuthException(msg) while tenants: tenant = tenants.pop() try: client = keystone_client.Client(tenant_id=tenant.id, token=unscoped_token.id, auth_url=auth_url, insecure=insecure) token = client.tokens.authenticate(username=username, token=unscoped_token.id, tenant_id=tenant.id) break except (keystone_exceptions.ClientException, keystone_exceptions.AuthorizationFailure): token = None if token is None: msg = _("Unable to authenticate to any available projects.") raise KeystoneAuthException(msg) # Check expiry for our new scoped token. self.check_auth_expiry(token) # If we made it here we succeeded. Create our User! user = create_user_from_token(request, token, client.service_catalog.url_for()) if request is not None: if is_ans1_token(unscoped_token.id): hashed_token = hashlib.md5(unscoped_token.id).hexdigest() unscoped_token._info['token']['id'] = hashed_token request.session['unscoped_token'] = unscoped_token.id request.user = user # Support client caching to save on auth calls. setattr(request, KEYSTONE_CLIENT_ATTR, client) LOG.debug('Authentication completed for user "%s".' % username) return user
def generate_test_data(): ''' Builds a set of test_data data as returned by Keystone. ''' test_data = TestDataContainer() keystone_service = { 'type': 'identity', 'name': 'keystone', 'endpoints_links': [], 'endpoints': [{ 'region': 'RegionOne', 'adminURL': 'http://admin.localhost:35357/v2.0', 'internalURL': 'http://internal.localhost:5000/v2.0', 'publicURL': 'http://public.localhost:5000/v2.0' }] } # Users user_dict = { 'id': uuid.uuid4().hex, 'name': 'gabriel', 'email': '*****@*****.**', 'password': '******', 'token': '', 'enabled': True } test_data.user = User(UserManager(None), user_dict, loaded=True) # Tenants tenant_dict_1 = { 'id': uuid.uuid4().hex, 'name': 'tenant_one', 'description': '', 'enabled': True } tenant_dict_2 = { 'id': uuid.uuid4().hex, 'name': '', 'description': '', 'enabled': False } test_data.tenant_one = Tenant(TenantManager(None), tenant_dict_1, loaded=True) test_data.tenant_two = Tenant(TenantManager(None), tenant_dict_2, loaded=True) # Roles role_dict = {'id': uuid.uuid4().hex, 'name': 'Member'} test_data.role = Role(RoleManager, role_dict) # Tokens tomorrow = datetime_safe.datetime.now() + timedelta(days=1) expiration = datetime_safe.datetime.isoformat(tomorrow) scoped_token_dict = { 'token': { 'id': uuid.uuid4().hex, 'expires': expiration, 'tenant': tenant_dict_1, 'tenants': [tenant_dict_1, tenant_dict_2] }, 'user': { 'id': user_dict['id'], 'name': user_dict['name'], 'roles': [role_dict] }, 'serviceCatalog': [keystone_service] } test_data.scoped_token = Token(TokenManager(None), scoped_token_dict, loaded=True) unscoped_token_dict = { 'token': { 'id': uuid.uuid4().hex, 'expires': expiration }, 'user': { 'id': user_dict['id'], 'name': user_dict['name'], 'roles': [role_dict] }, 'serviceCatalog': [keystone_service] } test_data.unscoped_token = Token(TokenManager(None), unscoped_token_dict, loaded=True) # Service Catalog test_data.service_catalog = ServiceCatalog({ 'serviceCatalog': [keystone_service], 'token': { 'id': scoped_token_dict['token']['id'], 'expires': scoped_token_dict['token']['expires'], 'user_id': user_dict['id'], 'tenant_id': tenant_dict_1['id'] } }) return test_data
def set_user_admin_token(request): """ Via admin account login again when admin token is expired. """ from keystoneclient.v2_0 import client as keystone_client from keystoneclient import exceptions as keystone_exceptions from keystoneclient.v2_0.tokens import Token, TokenManager from openstack_auth.exceptions import KeystoneAuthException from openstack_auth.utils import is_ans1_token insecure = getattr(settings, 'OPENSTACK_SSL_NO_VERIFY', False) endpoint = request.user.endpoint try: password = getattr(settings, 'OPENSTACK_ADMIN_TOKEN', 'admin') client = keystone_client.Client(username=u'admin', password=password, tenant_id='', auth_url=endpoint, insecure=insecure) unscoped_token_data = {"token": client.service_catalog.get_token()} unscoped_token = Token(TokenManager(None), unscoped_token_data, loaded=True) except (keystone_exceptions.Unauthorized, keystone_exceptions.Forbidden, keystone_exceptions.NotFound) as exc: msg = _('Invalid user name or password.') LOG.debug(exc.message) raise KeystoneAuthException(msg) except (keystone_exceptions.ClientException, keystone_exceptions.AuthorizationFailure) as exc: msg = _("An error occurred authenticating. " "Please try again later.") LOG.debug(exc.message) raise KeystoneAuthException(msg) # FIXME: Log in to default tenant when the Keystone API returns it... # For now we list all the user's tenants and iterate through. try: tenants = client.tenants.list() except (keystone_exceptions.ClientException, keystone_exceptions.AuthorizationFailure): msg = _('Unable to retrieve authorized projects.') raise KeystoneAuthException(msg) # Abort if there are no tenants for this user if not tenants: msg = _('You are not authorized for any projects.') raise KeystoneAuthException(msg) while tenants: tenant = tenants.pop() try: token = api.token_create_scoped(request, tenant.id, unscoped_token.id) break except (keystone_exceptions.ClientException, keystone_exceptions.AuthorizationFailure): token = None if token is None: msg = _("Unable to authenticate to any available projects.") raise KeystoneAuthException(msg) # If we made it here we succeeded. Create our User! user = create_user_from_token(request, token, endpoint) if request is not None: if is_ans1_token(unscoped_token.id): hashed_token = hashlib.md5(unscoped_token.id).hexdigest() unscoped_token._info['token']['id'] = hashed_token request.session['unscoped_token'] = unscoped_token.id request.user = user set_session_from_user(request, request.user) return user