コード例 #1
0
    def test_login(self):
        form_data = {
            'method': 'Login',
            'region': 'http://localhost:5000/v2.0',
            'password': self.user.password,
            'username': self.user.name
        }

        self.mox.StubOutWithMock(api, 'token_create')
        self.mox.StubOutWithMock(api, 'tenant_list_for_token')
        self.mox.StubOutWithMock(api, 'token_create_scoped')

        aToken = self.tokens.unscoped_token
        bToken = self.tokens.scoped_token

        api.token_create(IsA(http.HttpRequest), "", self.user.name,
                         self.user.password).AndReturn(aToken)
        api.tenant_list_for_token(IsA(http.HttpRequest),
                                  aToken.id).AndReturn([self.tenants.first()])
        api.token_create_scoped(IsA(http.HttpRequest), self.tenant.id,
                                aToken.id).AndReturn(bToken)

        self.mox.ReplayAll()

        res = self.client.post(reverse('horizon:auth_login'), form_data)
        self.assertRedirectsNoFollow(res, DASH_INDEX_URL)
コード例 #2
0
    def test_login_first_tenant_invalid(self):
        form_data = {
            'method': 'Login',
            'region': 'http://localhost:5000/v2.0',
            'password': self.user.password,
            'username': self.user.name
        }

        self.mox.StubOutWithMock(api, 'token_create')
        self.mox.StubOutWithMock(api, 'tenant_list_for_token')
        self.mox.StubOutWithMock(api, 'token_create_scoped')

        aToken = self.tokens.unscoped_token
        bToken = self.tokens.scoped_token
        disabled_tenant = self.tenants.get(name="disabled_tenant")
        tenant = self.tenants.get(name="test_tenant")
        tenants = [tenant, disabled_tenant]
        api.token_create(IsA(http.HttpRequest), "", self.user.name,
                         self.user.password).AndReturn(aToken)
        api.tenant_list_for_token(IsA(http.HttpRequest),
                                  aToken.id).AndReturn(tenants)
        exc = keystone_exceptions.Unauthorized("Not authorized.")
        api.token_create_scoped(IsA(http.HttpRequest), disabled_tenant.id,
                                aToken.id).AndRaise(exc)
        api.token_create_scoped(IsA(http.HttpRequest), tenant.id,
                                aToken.id).AndReturn(bToken)

        self.mox.ReplayAll()

        res = self.client.post(reverse('horizon:auth_login'), form_data)
        self.assertNoFormErrors(res)
        self.assertNoMessages()
        self.assertRedirectsNoFollow(res, DASH_INDEX_URL)
コード例 #3
0
ファイル: auth_tests.py プロジェクト: ttrifonov/horizon
    def test_login(self):
        form_data = {'method': 'Login',
                     'region': 'http://localhost:5000/v2.0',
                     'password': self.PASSWORD,
                     'username': self.TEST_USER}

        self.mox.StubOutWithMock(api, 'token_create')
        self.mox.StubOutWithMock(api, 'tenant_list_for_token')
        self.mox.StubOutWithMock(api, 'token_create_scoped')

        class FakeToken(object):
            id = 1,
            user = {"id": "1",
                    "roles": [{"id": "1", "name": "fake"}], "name": "user"}
            serviceCatalog = {}
            tenant = None

        aToken = api.Token(FakeToken())
        bToken = aToken
        bToken.tenant = {'id': self.tenant.id, 'name': self.tenant.name}

        api.token_create(IsA(http.HttpRequest), "", self.TEST_USER,
                         self.PASSWORD).AndReturn(aToken)
        api.tenant_list_for_token(IsA(http.HttpRequest),
                                  aToken.id).AndReturn(self.tenants)
        api.token_create_scoped(IsA(http.HttpRequest),
                                self.tenant.id,
                                aToken.id).AndReturn(bToken)

        self.mox.ReplayAll()

        res = self.client.post(reverse('horizon:auth_login'), form_data)
        self.assertRedirectsNoFollow(res, DASH_INDEX_URL)
コード例 #4
0
ファイル: auth_tests.py プロジェクト: asomya/horizon
    def test_login(self):
        form_data = {'method': 'Login',
                     'region': 'http://localhost:5000/v2.0',
                     'password': self.user.password,
                     'username': self.user.name}

        self.mox.StubOutWithMock(api, 'token_create')
        self.mox.StubOutWithMock(api, 'tenant_list_for_token')
        self.mox.StubOutWithMock(api, 'token_create_scoped')

        aToken = self.tokens.unscoped_token
        bToken = self.tokens.scoped_token

        api.token_create(IsA(http.HttpRequest), "", self.user.name,
                         self.user.password).AndReturn(aToken)
        api.tenant_list_for_token(IsA(http.HttpRequest),
                                  aToken.id).AndReturn(self.tenants.list())
        api.token_create_scoped(IsA(http.HttpRequest),
                                self.tenant.id,
                                aToken.id).AndReturn(bToken)

        self.mox.ReplayAll()

        res = self.client.post(reverse('horizon:auth_login'), form_data)
        self.assertRedirectsNoFollow(res, DASH_INDEX_URL)
コード例 #5
0
ファイル: auth_tests.py プロジェクト: andycjw/horizon
    def test_login(self):
        form_data = {'method': 'Login',
                     'region': 'http://localhost:5000/v2.0',
                     'password': self.user.password,
                     'username': self.user.name}

        aToken = self.tokens.unscoped_token
        bToken = self.tokens.scoped_token

        api.token_create(IsA(http.HttpRequest), "", self.user.name,
                         self.user.password).AndReturn(aToken)
        api.tenant_list_for_token(IsA(http.HttpRequest),
                                  aToken.id).AndReturn([self.tenants.first()])
        api.token_create_scoped(IsA(http.HttpRequest),
                                self.tenant.id,
                                aToken.id).AndReturn(bToken)

        api.token_create(IsA(http.HttpRequest), "", self.user.name,
                         self.user.password).AndReturn(aToken)
        api.tenant_list_for_token(IsA(http.HttpRequest),
                                  aToken.id).AndReturn([self.tenants.first()])
        api.token_create_scoped(IsA(http.HttpRequest),
                                self.tenant.id,
                                aToken.id).AndReturn(bToken)

        self.mox.ReplayAll()

        res = self.client.post(reverse('horizon:auth_login'), form_data)
        self.assertRedirectsNoFollow(res, DASH_INDEX_URL)

        # Test default Django LOGIN_REDIRECT_URL
        user_home = settings.HORIZON_CONFIG.pop('user_home')
        res = self.client.post(reverse('horizon:auth_login'), form_data)
        self.assertRedirectsNoFollow(res, settings.LOGIN_REDIRECT_URL)
        settings.HORIZON_CONFIG['user_home'] = user_home
コード例 #6
0
ファイル: auth_tests.py プロジェクト: AsylumCorp/horizon
    def test_login_first_tenant_invalid(self):
        form_data = {'method': 'Login',
                     'region': 'http://localhost:5000/v2.0',
                     'password': self.user.password,
                     'username': self.user.name}

        self.mox.StubOutWithMock(api, 'token_create')
        self.mox.StubOutWithMock(api, 'tenant_list_for_token')
        self.mox.StubOutWithMock(api, 'token_create_scoped')

        aToken = self.tokens.unscoped_token
        bToken = self.tokens.scoped_token
        disabled_tenant = self.tenants.get(name="disabled_tenant")
        tenant = self.tenants.get(name="test_tenant")
        tenants = [tenant, disabled_tenant]
        api.token_create(IsA(http.HttpRequest), "", self.user.name,
                         self.user.password).AndReturn(aToken)
        api.tenant_list_for_token(IsA(http.HttpRequest),
                                  aToken.id).AndReturn(tenants)
        exc = keystone_exceptions.Unauthorized("Not authorized.")
        exc.silence_logging = True
        api.token_create_scoped(IsA(http.HttpRequest),
                                disabled_tenant.id,
                                aToken.id).AndRaise(exc)
        api.token_create_scoped(IsA(http.HttpRequest),
                                tenant.id,
                                aToken.id).AndReturn(bToken)

        self.mox.ReplayAll()

        res = self.client.post(reverse('horizon:auth_login'), form_data)
        self.assertNoFormErrors(res)
        self.assertNoMessages()
        self.assertRedirectsNoFollow(res, DASH_INDEX_URL)
コード例 #7
0
    def test_login(self):
        NEW_TENANT_ID = '6'
        NEW_TENANT_NAME = 'FAKENAME'
        TOKEN_ID = 1

        form_data = {
            'method': 'Login',
            'password': self.PASSWORD,
            'username': self.TEST_USER
        }

        self.mox.StubOutWithMock(api, 'token_create')

        class FakeToken(object):
            id = TOKEN_ID,
            user = {
                "id": "1",
                "roles": [{
                    "id": "1",
                    "name": "fake"
                }],
                "name": "user"
            }
            serviceCatalog = {}
            tenant = None

        aToken = api.Token(FakeToken())
        bToken = aToken

        api.token_create(IsA(http.HttpRequest), "", self.TEST_USER,
                         self.PASSWORD).AndReturn(aToken)

        aTenant = self.mox.CreateMock(api.Token)
        aTenant.id = NEW_TENANT_ID
        aTenant.name = NEW_TENANT_NAME
        bToken.tenant = {'id': aTenant.id, 'name': aTenant.name}

        self.mox.StubOutWithMock(api, 'tenant_list_for_token')
        api.tenant_list_for_token(IsA(http.HttpRequest), aToken.id).\
                                  AndReturn([aTenant])

        self.mox.StubOutWithMock(api, 'token_create_scoped')
        api.token_create_scoped(IsA(http.HttpRequest), aTenant.id,
                                aToken.id).AndReturn(bToken)

        self.mox.ReplayAll()

        res = self.client.post(reverse('horizon:auth_login'), form_data)

        self.assertRedirectsNoFollow(res, DASH_INDEX_URL)
コード例 #8
0
ファイル: auth_tests.py プロジェクト: AsylumCorp/horizon
    def test_session_fixation(self):
        session_ids = []
        form_data = {'method': 'Login',
                     'region': 'http://localhost:5000/v2.0',
                     'password': self.user.password,
                     'username': self.user.name}

        self.mox.StubOutWithMock(api, 'token_create')
        self.mox.StubOutWithMock(api, 'tenant_list_for_token')
        self.mox.StubOutWithMock(api, 'token_create_scoped')

        aToken = self.tokens.unscoped_token
        bToken = self.tokens.scoped_token

        api.token_create(IsA(http.HttpRequest), "", self.user.name,
                         self.user.password).AndReturn(aToken)
        api.tenant_list_for_token(IsA(http.HttpRequest),
                                  aToken.id).AndReturn([self.tenants.first()])
        api.token_create_scoped(IsA(http.HttpRequest),
                                self.tenant.id,
                                aToken.id).AndReturn(bToken)

        api.token_create(IsA(http.HttpRequest), "", self.user.name,
                         self.user.password).AndReturn(aToken)
        api.tenant_list_for_token(IsA(http.HttpRequest),
                                  aToken.id).AndReturn([self.tenants.first()])
        api.token_create_scoped(IsA(http.HttpRequest),
                                self.tenant.id,
                                aToken.id).AndReturn(bToken)
        self.mox.ReplayAll()

        res = self.client.get(reverse('horizon:auth_login'))
        self.assertEqual(res.cookies.get('sessionid'), None)
        res = self.client.post(reverse('horizon:auth_login'), form_data)
        session_ids.append(res.cookies['sessionid'].value)

        self.assertEquals(self.client.session['user_name'],
                          self.user.name)
        self.client.session['foobar'] = 'MY TEST VALUE'
        res = self.client.get(reverse('horizon:auth_logout'))
        session_ids.append(res.cookies['sessionid'].value)
        self.assertEqual(len(self.client.session.items()), 0)
        # Sleep for 1 second so the session values are different if
        # using the signed_cookies backend.
        time.sleep(1)
        res = self.client.post(reverse('horizon:auth_login'), form_data)
        session_ids.append(res.cookies['sessionid'].value)
        # Make sure all 3 session id values are different
        self.assertEqual(len(session_ids), len(set(session_ids)))
コード例 #9
0
    def test_session_fixation(self):
        session_ids = []
        form_data = {
            'method': 'Login',
            'region': 'http://localhost:5000/v2.0',
            'password': self.user.password,
            'username': self.user.name
        }

        self.mox.StubOutWithMock(api, 'token_create')
        self.mox.StubOutWithMock(api, 'tenant_list_for_token')
        self.mox.StubOutWithMock(api, 'token_create_scoped')

        aToken = self.tokens.unscoped_token
        bToken = self.tokens.scoped_token

        api.token_create(IsA(http.HttpRequest), "", self.user.name,
                         self.user.password).AndReturn(aToken)
        api.tenant_list_for_token(IsA(http.HttpRequest),
                                  aToken.id).AndReturn([self.tenants.first()])
        api.token_create_scoped(IsA(http.HttpRequest), self.tenant.id,
                                aToken.id).AndReturn(bToken)

        api.token_create(IsA(http.HttpRequest), "", self.user.name,
                         self.user.password).AndReturn(aToken)
        api.tenant_list_for_token(IsA(http.HttpRequest),
                                  aToken.id).AndReturn([self.tenants.first()])
        api.token_create_scoped(IsA(http.HttpRequest), self.tenant.id,
                                aToken.id).AndReturn(bToken)
        self.mox.ReplayAll()

        res = self.client.get(reverse('horizon:auth_login'))
        self.assertEqual(res.cookies.get('sessionid'), None)
        res = self.client.post(reverse('horizon:auth_login'), form_data)
        session_ids.append(res.cookies['sessionid'].value)

        self.assertEquals(self.client.session['user_name'], self.user.name)
        self.client.session['foobar'] = 'MY TEST VALUE'
        res = self.client.get(reverse('horizon:auth_logout'))
        session_ids.append(res.cookies['sessionid'].value)
        self.assertEqual(len(self.client.session.items()), 0)
        # Sleep for 1 second so the session values are different if
        # using the signed_cookies backend.
        time.sleep(1)
        res = self.client.post(reverse('horizon:auth_login'), form_data)
        session_ids.append(res.cookies['sessionid'].value)
        # Make sure all 3 session id values are different
        self.assertEqual(len(session_ids), len(set(session_ids)))
コード例 #10
0
def switch_tenants(request, tenant_id):
    """
    Swaps a user from one tenant to another using the unscoped token from
    Keystone to exchange scoped tokens for the new tenant.
    """
    form, handled = LoginWithTenant.maybe_handle(request,
                                                 initial={
                                                     'tenant':
                                                     tenant_id,
                                                     'username':
                                                     request.user.username
                                                 })
    if handled:
        return handled

    unscoped_token = request.session.get('unscoped_token', None)
    if unscoped_token:
        try:
            token = api.token_create_scoped(request, tenant_id, unscoped_token)
            _set_session_data(request, token)
            user = users.User(users.get_user_from_request(request))
            return shortcuts.redirect(Horizon.get_user_home(user))
        except:
            exceptions.handle(request,
                              _("You are not authorized for that tenant."))

    return shortcuts.redirect("horizon:auth_login")
コード例 #11
0
ファイル: auth.py プロジェクト: nooryameen1995/horizon
def switch_tenants(request, tenant_id):
    """
    Swaps a user from one tenant to another using the unscoped token from
    Keystone to exchange scoped tokens for the new tenant.
    """
    form, handled = LoginWithTenant.maybe_handle(request,
                                                 initial={
                                                     'tenant':
                                                     tenant_id,
                                                     'username':
                                                     request.user.username
                                                 })
    if handled:
        return handled

    unscoped_token = request.session.get('unscoped_token', None)
    if unscoped_token:
        try:
            token = api.token_create_scoped(request, tenant_id, unscoped_token)
            _set_session_data(request, token)
            user = users.User(users.get_user_from_request(request))
            return shortcuts.redirect(Horizon.get_user_home(user))
        except exceptions.Unauthorized as e:
            messages.error(_("You are not authorized for that tenant."))

    # FIXME(gabriel): we don't ship switch_tenants.html
    return shortcuts.render(request, 'switch_tenants.html', {
        'to_tenant': tenant_id,
        'form': form
    })
コード例 #12
0
ファイル: auth.py プロジェクト: termie/horizon
def switch_tenants(request, tenant_id):
    """
    Swaps a user from one tenant to another using the unscoped token from
    Keystone to exchange scoped tokens for the new tenant.
    """
    form, handled = LoginWithTenant.maybe_handle(
            request, initial={'tenant': tenant_id,
                              'username': request.user.username})
    if handled:
        return handled

    unscoped_token = request.session.get('unscoped_token', None)
    if unscoped_token:
        try:
            token = api.token_create_scoped(request,
                                            tenant_id,
                                            unscoped_token)
            _set_session_data(request, token)
            user = users.User(users.get_user_from_request(request))
            return shortcuts.redirect(Horizon.get_user_home(user))
        except exceptions.Unauthorized as e:
            messages.error(_("You are not authorized for that tenant."))

    # FIXME(gabriel): we don't ship switch_tenants.html
    return shortcuts.render(request,
                            'switch_tenants.html', {
                                'to_tenant': tenant_id,
                                'form': form})
コード例 #13
0
ファイル: auth.py プロジェクト: Cygnet/horizon
def switch_tenants(request, tenant_id):
    """
    Swaps a user from one tenant to another using the unscoped token from
    Keystone to exchange scoped tokens for the new tenant.
    """
    form, handled = LoginWithTenant.maybe_handle(
            request, initial={'tenant': tenant_id,
                              'username': request.user.username})
    if handled:
        return handled

    unscoped_token = request.session.get('unscoped_token', None)
    if unscoped_token:
        try:
            token = api.token_create_scoped(request,
                                            tenant_id,
                                            unscoped_token)
            _set_session_data(request, token)
            user = users.User(users.get_user_from_request(request))
            return shortcuts.redirect(Horizon.get_user_home(user))
        except:
            exceptions.handle(request,
                              _("You are not authorized for that tenant."))

    return shortcuts.redirect("horizon:auth_login")
コード例 #14
0
ファイル: auth_tests.py プロジェクト: katzj/horizon
    def test_login(self):
        NEW_TENANT_ID = '6'
        NEW_TENANT_NAME = 'FAKENAME'
        TOKEN_ID = 1

        form_data = {'method': 'Login',
                    'password': self.PASSWORD,
                    'username': self.TEST_USER}

        self.mox.StubOutWithMock(api, 'token_create')

        class FakeToken(object):
            id = TOKEN_ID,
            user = {"id": "1",
                    "roles": [{"id": "1", "name": "fake"}], "name": "user"}
            serviceCatalog = {}
            tenant = None
        aToken = api.Token(FakeToken())
        bToken = aToken

        api.token_create(IsA(http.HttpRequest), "", self.TEST_USER,
                         self.PASSWORD).AndReturn(aToken)

        aTenant = self.mox.CreateMock(api.Token)
        aTenant.id = NEW_TENANT_ID
        aTenant.name = NEW_TENANT_NAME
        bToken.tenant = {'id': aTenant.id, 'name': aTenant.name}

        self.mox.StubOutWithMock(api, 'tenant_list_for_token')
        api.tenant_list_for_token(IsA(http.HttpRequest), aToken.id).\
                                  AndReturn([aTenant])

        self.mox.StubOutWithMock(api, 'token_create_scoped')
        api.token_create_scoped(IsA(http.HttpRequest), aTenant.id,
                                    aToken.id).AndReturn(bToken)

        self.mox.ReplayAll()

        res = self.client.post(reverse('horizon:auth_login'), form_data)

        self.assertRedirectsNoFollow(res, DASH_INDEX_URL)

        self.mox.VerifyAll()
コード例 #15
0
ファイル: auth_forms.py プロジェクト: katzj/horizon
    def handle(self, request, data):
        try:
            if data.get("tenant", None):
                token = api.token_create(request, data.get("tenant"), data["username"], data["password"])

                tenants = api.tenant_list_for_token(request, token.id)
                tenant = None
                for t in tenants:
                    if t.id == data.get("tenant"):
                        tenant = t
                _set_session_data(request, token)
                user = users.get_user_from_request(request)
                return shortcuts.redirect(base.Horizon.get_user_home(user))

            elif data.get("username", None):
                token = api.token_create(request, "", data["username"], data["password"])

                # Unscoped token
                request.session["unscoped_token"] = token.id
                request.user.username = data["username"]

                # Get the tenant list, and log in using first tenant
                # FIXME (anthony): add tenant chooser here?
                tenants = api.tenant_list_for_token(request, token.id)

                # Abort if there are no valid tenants for this user
                if not tenants:
                    messages.error(request, _("No tenants present for user: %(user)s") % {"user": data["username"]})
                    return

                # Create a token.
                # NOTE(gabriel): Keystone can return tenants that you're
                # authorized to administer but not to log into as a user, so in
                # the case of an Unauthorized error we should iterate through
                # the tenants until one succeeds or we've failed them all.
                while tenants:
                    tenant = tenants.pop()
                    try:
                        token = api.token_create_scoped(request, tenant.id, token.id)
                        break
                    except api_exceptions.Unauthorized as e:
                        token = None
                if token is None:
                    raise exceptions.NotAuthorized(_("You are not authorized for any available tenants."))

                _set_session_data(request, token)
                user = users.get_user_from_request(request)
                return shortcuts.redirect(base.Horizon.get_user_home(user))

        except api_exceptions.Unauthorized as e:
            msg = _("Error authenticating: %s") % e.message
            LOG.exception(msg)
            messages.error(request, msg)
        except api_exceptions.ApiException as e:
            messages.error(request, _("Error authenticating with keystone: %s") % e.message)
コード例 #16
0
ファイル: auth_forms.py プロジェクト: Cygnet/horizon
    def handle(self, request, data):
        # For now we'll allow fallback to OPENSTACK_KEYSTONE_URL if the
        # form post doesn't include a region.
        endpoint = data.get('region', None) or settings.OPENSTACK_KEYSTONE_URL
        region_name = dict(self.fields['region'].choices)[endpoint]
        request.session['region_endpoint'] = endpoint
        request.session['region_name'] = region_name

        redirect_to = request.REQUEST.get(REDIRECT_FIELD_NAME, "")

        if data.get('tenant', None):
            try:
                token = api.token_create(request,
                                         data.get('tenant'),
                                         data['username'],
                                         data['password'])
                tenants = api.tenant_list_for_token(request, token.id)
            except:
                msg = _('Unable to authenticate for that project.')
                exceptions.handle(request,
                                  message=msg,
                                  escalate=True)
            _set_session_data(request, token)
            user = users.get_user_from_request(request)
            redirect = redirect_to or base.Horizon.get_user_home(user)
            return shortcuts.redirect(redirect)

        elif data.get('username', None):
            try:
                unscoped_token = api.token_create(request,
                                                  '',
                                                  data['username'],
                                                  data['password'])
            except keystone_exceptions.Unauthorized:
                exceptions.handle(request,
                                  _('Invalid user name or password.'))
            except:
                # If we get here we don't want to show a stack trace to the
                # user. However, if we fail here, there may be bad session
                # data that's been cached already.
                request.session.clear()
                exceptions.handle(request,
                                  message=_("An error occurred authenticating."
                                            " Please try again later."),
                                  escalate=True)

            # Unscoped token
            request.session['unscoped_token'] = unscoped_token.id
            request.user.username = data['username']

            # Get the tenant list, and log in using first tenant
            # FIXME (anthony): add tenant chooser here?
            try:
                tenants = api.tenant_list_for_token(request, unscoped_token.id)
            except:
                exceptions.handle(request)
                tenants = []

            # Abort if there are no valid tenants for this user
            if not tenants:
                messages.error(request,
                               _('You are not authorized for any projects.') %
                                {"user": data['username']},
                               extra_tags="login")
                return

            # Create a token.
            # NOTE(gabriel): Keystone can return tenants that you're
            # authorized to administer but not to log into as a user, so in
            # the case of an Unauthorized error we should iterate through
            # the tenants until one succeeds or we've failed them all.
            while tenants:
                tenant = tenants.pop()
                try:
                    token = api.token_create_scoped(request,
                                                    tenant.id,
                                                    unscoped_token.id)
                    break
                except:
                    # This will continue for recognized Unauthorized
                    # exceptions from keystoneclient.
                    exceptions.handle(request, ignore=True)
                    token = None
            if token is None:
                raise exceptions.NotAuthorized(
                    _("You are not authorized for any available projects."))

            _set_session_data(request, token)
            user = users.get_user_from_request(request)
        redirect = redirect_to or base.Horizon.get_user_home(user)
        return shortcuts.redirect(redirect)
コード例 #17
0
ファイル: auth_forms.py プロジェクト: OpenStack-Kha/horizon
    def handle(self, request, data):
        region = data.get('region', '').split(',')
        if len(region) > 1:
            request.session['region_endpoint'] = region[0]
            request.session['region_name'] = region[1]

        if data.get('tenant', None):
            try:
                token = api.token_create(request,
                                         data.get('tenant'),
                                         data['username'],
                                         data['password'])
                tenants = api.tenant_list_for_token(request, token.id)
            except:
                exceptions.handle(request,
                                  message=_('Unable to authenticate tenant.'),
                                  escalate=True)
            tenant = None
            for t in tenants:
                if t.id == data.get('tenant'):
                    tenant = t
            _set_session_data(request, token)
            user = users.get_user_from_request(request)
            return shortcuts.redirect(base.Horizon.get_user_home(user))

        elif data.get('username', None):
            try:
                token = api.token_create(request,
                                         '',
                                         data['username'],
                                         data['password'])
            except keystone_exceptions.Unauthorized:
                exceptions.handle(request,
                                  _('Invalid user name or password.'))
            except:
                exceptions.handle(request, escalate=True)

            # Unscoped token
            request.session['unscoped_token'] = token.id
            request.user.username = data['username']

            # Get the tenant list, and log in using first tenant
            # FIXME (anthony): add tenant chooser here?
            try:
                tenants = api.tenant_list_for_token(request, token.id)
            except:
                exceptions.handle(request)
                tenants = []

            # Abort if there are no valid tenants for this user
            if not tenants:
                messages.error(request,
                               _('No tenants present for user: %(user)s') %
                                {"user": data['username']},
                               extra_tags="login")
                return

            # Create a token.
            # NOTE(gabriel): Keystone can return tenants that you're
            # authorized to administer but not to log into as a user, so in
            # the case of an Unauthorized error we should iterate through
            # the tenants until one succeeds or we've failed them all.
            while tenants:
                tenant = tenants.pop()
                try:
                    token = api.token_create_scoped(request,
                                                    tenant.id,
                                                    token.id)
                    break
                except:
                    # This will continue for recognized "unauthorized"
                    # exceptions from keystoneclient.
                    exceptions.handle(request, ignore=True)
                    token = None
            if token is None:
                raise exceptions.NotAuthorized(
                    _("You are not authorized for any available tenants."))

            _set_session_data(request, token)
            user = users.get_user_from_request(request)
        return shortcuts.redirect(base.Horizon.get_user_home(user))
コード例 #18
0
ファイル: auth_forms.py プロジェクト: samsu/horizon
    def handle(self, request, data):
        # For now we'll allow fallback to OPENSTACK_KEYSTONE_URL if the
        # form post doesn't include a region.
        endpoint = data.get("region", None) or settings.OPENSTACK_KEYSTONE_URL
        region_name = dict(self.fields["region"].choices)[endpoint]
        request.session["region_endpoint"] = endpoint
        request.session["region_name"] = region_name

        redirect_to = request.REQUEST.get(REDIRECT_FIELD_NAME, "")

        if data.get("tenant", None):
            try:
                token = api.token_create(request, data.get("tenant"), data["username"], data["password"])
                tenants = api.tenant_list_for_token(request, token.id)
            except:
                exceptions.handle(request, message=_("Unable to authenticate tenant."), escalate=True)
            tenant = None
            for t in tenants:
                if t.id == data.get("tenant"):
                    tenant = t
            _set_session_data(request, token)
            user = users.get_user_from_request(request)
            redirect = redirect_to or base.Horizon.get_user_home(user)
            return shortcuts.redirect(redirect)

        elif data.get("username", None):
            try:
                token = api.token_create(request, "", data["username"], data["password"])
            except keystone_exceptions.Unauthorized:
                exceptions.handle(request, _("Invalid user name or password."))
            except:
                exceptions.handle(request, escalate=True)

            # Unscoped token
            request.session["unscoped_token"] = token.id
            request.user.username = data["username"]

            # Get the tenant list, and log in using first tenant
            # FIXME (anthony): add tenant chooser here?
            try:
                tenants = api.tenant_list_for_token(request, token.id)
            except:
                exceptions.handle(request)
                tenants = []

            # Abort if there are no valid tenants for this user
            if not tenants:
                messages.error(
                    request, _("No tenants present for user: %(user)s") % {"user": data["username"]}, extra_tags="login"
                )
                return

            # Create a token.
            # NOTE(gabriel): Keystone can return tenants that you're
            # authorized to administer but not to log into as a user, so in
            # the case of an Unauthorized error we should iterate through
            # the tenants until one succeeds or we've failed them all.
            while tenants:
                tenant = tenants.pop()
                try:
                    token = api.token_create_scoped(request, tenant.id, token.id)
                    break
                except:
                    # This will continue for recognized "unauthorized"
                    # exceptions from keystoneclient.
                    exceptions.handle(request, ignore=True)
                    token = None
            if token is None:
                raise exceptions.NotAuthorized(_("You are not authorized for any available tenants."))

            _set_session_data(request, token)
            user = users.get_user_from_request(request)
        redirect = redirect_to or base.Horizon.get_user_home(user)
        return shortcuts.redirect(redirect)
コード例 #19
0
    def handle(self, request, data):
        if 'user_name' in request.session:
            if request.session['user_name'] != data['username']:
                # To avoid reusing another user's session, create a
                # new, empty session if the existing session
                # corresponds to a different authenticated user.
                request.session.flush()
        # Always cycle the session key when viewing the login form to
        # prevent session fixation
        request.session.cycle_key()

        # For now we'll allow fallback to OPENSTACK_KEYSTONE_URL if the
        # form post doesn't include a region.
        # jt
        default_region = (settings.OPENSTACK_KEYSTONE_URL, "Default Region") 
        regions = getattr(settings, 'AVAILABLE_REGIONS', [default_region])
        #endpoint = data.get('region', None) or settings.OPENSTACK_KEYSTONE_URL
        #region_name = dict(self.fields['region'].choices)[endpoint]
        region_name = data.get('region', None) or "Default Region"
        endpoint = [r[0] for r in regions if r[1] == region_name][0]
        request.session['region_endpoint'] = endpoint
        request.session['region_name'] = region_name

        redirect_to = request.REQUEST.get(REDIRECT_FIELD_NAME, None)
        # Make sure the requested redirect matches the protocol,
        # domain, and port of this request
        if redirect_to and not same_origin(
                request.build_absolute_uri(redirect_to),
                request.build_absolute_uri()):
            redirect_to = None

        if data.get('tenant', None):
            try:
                token = api.token_create(request,
                                         data.get('tenant'),
                                         data['username'],
                                         data['password'])
                tenants = api.tenant_list_for_token(request, token.id)
            except:
                msg = _('Unable to authenticate for that project.')
                exceptions.handle(request,
                                  message=msg,
                                  escalate=True)
            _set_session_data(request, token)
            user = users.get_user_from_request(request)
            redirect = redirect_to or base.Horizon.get_user_home(user)
            return shortcuts.redirect(redirect)

        elif data.get('username', None):
            try:
                unscoped_token = api.token_create(request,
                                                  '',
                                                  data['username'],
                                                  data['password'])
            except keystone_exceptions.Unauthorized:
                exceptions.handle(request,
                                  _('Invalid user name or password.'))
            except:
                # If we get here we don't want to show a stack trace to the
                # user. However, if we fail here, there may be bad session
                # data that's been cached already.
                request.user_logout()
                exceptions.handle(request,
                                  message=_("An error occurred authenticating."
                                            " Please try again later."),
                                  escalate=True)

            # Unscoped token
            request.session['unscoped_token'] = unscoped_token.id
            request.user.username = data['username']

            # Get the tenant list, and log in using first tenant
            # FIXME (anthony): add tenant chooser here?
            try:
                tenants = api.tenant_list_for_token(request, unscoped_token.id)
            except:
                exceptions.handle(request)
                tenants = []

            # Abort if there are no valid tenants for this user
            if not tenants:
                messages.error(request,
                               _('You are not authorized for any projects.') %
                                {"user": data['username']},
                               extra_tags="login")
                return

            # Create a token.
            # NOTE(gabriel): Keystone can return tenants that you're
            # authorized to administer but not to log into as a user, so in
            # the case of an Unauthorized error we should iterate through
            # the tenants until one succeeds or we've failed them all.
            while tenants:
                tenant = tenants.pop()
                try:
                    token = api.token_create_scoped(request,
                                                    tenant.id,
                                                    unscoped_token.id)
                    break
                except:
                    # This will continue for recognized Unauthorized
                    # exceptions from keystoneclient.
                    exceptions.handle(request, ignore=True)
                    token = None
            if token is None:
                raise exceptions.NotAuthorized(
                    _("You are not authorized for any available projects."))

            _set_session_data(request, token)
            user = users.get_user_from_request(request)
        redirect = redirect_to or base.Horizon.get_user_home(user)
        return shortcuts.redirect(redirect)
コード例 #20
0
    def handle(self, request, data):
        """ Process the user's login via Keystone.

        Note: We don't use the messages framework here (including messages
        created by ``exceptions.handle`` beause they will not be displayed
        on the login page (intentionally). Instead we add all error messages
        to the form's ``non_field_errors``, causing them to appear as
        errors on the form itself.
        """
        if 'user_name' in request.session:
            if request.session['user_name'] != data['username']:
                # To avoid reusing another user's session, create a
                # new, empty session if the existing session
                # corresponds to a different authenticated user.
                request.session.flush()
        # Always cycle the session key when viewing the login form to
        # prevent session fixation
        request.session.cycle_key()

        # For now we'll allow fallback to OPENSTACK_KEYSTONE_URL if the
        # form post doesn't include a region.
        endpoint = data.get('region', None) or settings.OPENSTACK_KEYSTONE_URL
        if endpoint != request.session.get('region_endpoint', None):
            region_name = dict(self.fields['region'].choices)[endpoint]
            request.session['region_endpoint'] = endpoint
            request.session['region_name'] = region_name
            request.user.service_catalog = None

        redirect_to = request.REQUEST.get(REDIRECT_FIELD_NAME, "")

        if data.get('tenant', None):
            try:
                token = api.token_create(request,
                                         data.get('tenant'),
                                         data['username'],
                                         data['password'])
                tenants = api.tenant_list_for_token(request, token.id)
            except:
                msg = _('Unable to authenticate for that project.')
                exceptions.handle(request, ignore=True)
                return self.api_error(msg)
            _set_session_data(request, token)
            user = users.get_user_from_request(request)
            redirect = redirect_to or base.Horizon.get_user_home(user)
            return shortcuts.redirect(redirect)

        elif data.get('username', None):
            try:
                unscoped_token = api.token_create(request,
                                                  '',
                                                  data['username'],
                                                  data['password'])
            except keystone_exceptions.Unauthorized:
                msg = _('Invalid user name or password.')
                exceptions.handle(request, ignore=True)
                return self.api_error(msg)
            except:
                # If we get here we don't want to show a stack trace to the
                # user. However, if we fail here, there may be bad session
                # data that's been cached already.
                request.user_logout()
                msg = _("An error occurred authenticating. "
                        "Please try again later.")
                exceptions.handle(request, ignore=True)
                return self.api_error(msg)

            # Unscoped token
            request.session['unscoped_token'] = unscoped_token.id
            request.user.username = data['username']

            # Get the tenant list, and log in using first tenant
            # FIXME (anthony): add tenant chooser here?
            try:
                tenants = api.tenant_list_for_token(request, unscoped_token.id)
            except:
                exceptions.handle(request, ignore=True)
                tenants = []

            # Abort if there are no valid tenants for this user
            if not tenants:
                msg = _('You are not authorized for any projects.')
                return self.api_error(msg)

            # Create a token.
            # NOTE(gabriel): Keystone can return tenants that you're
            # authorized to administer but not to log into as a user, so in
            # the case of an Unauthorized error we should iterate through
            # the tenants until one succeeds or we've failed them all.
            while tenants:
                tenant = tenants.pop()
                try:
                    token = api.token_create_scoped(request,
                                                    tenant.id,
                                                    unscoped_token.id)
                    break
                except:
                    # This will continue for recognized Unauthorized
                    # exceptions from keystoneclient.
                    exceptions.handle(request, ignore=True)
                    token = None
            if token is None:
                msg = _("You are not authorized for any available projects.")
                return self.api_error(msg)

            _set_session_data(request, token)
            user = users.get_user_from_request(request)
        redirect = redirect_to or base.Horizon.get_user_home(user)
        return shortcuts.redirect(redirect)
コード例 #21
0
    def handle(self, request, data):
        region = data.get('region', '').split(',')
        if len(region) > 1:
            request.session['region_endpoint'] = region[0]
            request.session['region_name'] = region[1]

        if data.get('tenant', None):
            try:
                token = api.token_create(request, data.get('tenant'),
                                         data['username'], data['password'])
                tenants = api.tenant_list_for_token(request, token.id)
            except:
                exceptions.handle(request,
                                  message=_('Unable to authenticate tenant.'),
                                  escalate=True)
            tenant = None
            for t in tenants:
                if t.id == data.get('tenant'):
                    tenant = t
            _set_session_data(request, token)
            user = users.get_user_from_request(request)
            return shortcuts.redirect(base.Horizon.get_user_home(user))

        elif data.get('username', None):
            try:
                token = api.token_create(request, '', data['username'],
                                         data['password'])
            except keystone_exceptions.Unauthorized:
                exceptions.handle(request, _('Invalid user name or password.'))
            except:
                exceptions.handle(request, escalate=True)

            # Unscoped token
            request.session['unscoped_token'] = token.id
            request.user.username = data['username']

            # Get the tenant list, and log in using first tenant
            # FIXME (anthony): add tenant chooser here?
            try:
                tenants = api.tenant_list_for_token(request, token.id)
            except:
                exceptions.handle(request)
                tenants = []

            # Abort if there are no valid tenants for this user
            if not tenants:
                messages.error(request,
                               _('No tenants present for user: %(user)s') %
                               {"user": data['username']},
                               extra_tags="login")
                return

            # Create a token.
            # NOTE(gabriel): Keystone can return tenants that you're
            # authorized to administer but not to log into as a user, so in
            # the case of an Unauthorized error we should iterate through
            # the tenants until one succeeds or we've failed them all.
            while tenants:
                tenant = tenants.pop()
                try:
                    token = api.token_create_scoped(request, tenant.id,
                                                    token.id)
                    break
                except:
                    # This will continue for recognized "unauthorized"
                    # exceptions from keystoneclient.
                    exceptions.handle(request, ignore=True)
                    token = None
            if token is None:
                raise exceptions.NotAuthorized(
                    _("You are not authorized for any available tenants."))

            _set_session_data(request, token)
            user = users.get_user_from_request(request)
        return shortcuts.redirect(base.Horizon.get_user_home(user))
コード例 #22
0
ファイル: auth_forms.py プロジェクト: termie/horizon
    def handle(self, request, data):
        try:
            if data.get('tenant', None):
                token = api.token_create(request,
                                         data.get('tenant'),
                                         data['username'],
                                         data['password'])

                tenants = api.tenant_list_for_token(request, token.id)
                tenant = None
                for t in tenants:
                    if t.id == data.get('tenant'):
                        tenant = t
                _set_session_data(request, token)
                user = users.get_user_from_request(request)
                return shortcuts.redirect(base.Horizon.get_user_home(user))

            elif data.get('username', None):
                try:
                    token = api.token_create(request,
                                             '',
                                             data['username'],
                                             data['password'])
                except keystone_exceptions.Unauthorized:
                    messages.error(request, _('Bad user name or password.'),
                            extra_tags="login")
                    return

                # Unscoped token
                request.session['unscoped_token'] = token.id
                request.user.username = data['username']

                # Get the tenant list, and log in using first tenant
                # FIXME (anthony): add tenant chooser here?
                tenants = api.tenant_list_for_token(request, token.id)

                # Abort if there are no valid tenants for this user
                if not tenants:
                    messages.error(request,
                                   _('No tenants present for user: %(user)s') %
                                    {"user": data['username']},
                                   extra_tags="login")
                    return

                # Create a token.
                # NOTE(gabriel): Keystone can return tenants that you're
                # authorized to administer but not to log into as a user, so in
                # the case of an Unauthorized error we should iterate through
                # the tenants until one succeeds or we've failed them all.
                while tenants:
                    tenant = tenants.pop()
                    try:
                        token = api.token_create_scoped(request,
                                                        tenant.id,
                                                        token.id)
                        break
                    except api_exceptions.Unauthorized as e:
                        token = None
                if token is None:
                    raise exceptions.NotAuthorized(
                        _("You are not authorized for any available tenants."))

                _set_session_data(request, token)
                user = users.get_user_from_request(request)
                return shortcuts.redirect(base.Horizon.get_user_home(user))

        except api_exceptions.Unauthorized as e:
            msg = _('Error authenticating: %s') % e.message
            LOG.exception(msg)
            messages.error(request, msg, extra_tags="login")
        except api_exceptions.ApiException as e:
            messages.error(request,
                           _('Error authenticating with keystone: %s') %
                           e.message, extra_tags="login")
コード例 #23
0
    def handle(self, request, data):
        if 'user_name' in request.session:
            if request.session['user_name'] != data['username']:
                # To avoid reusing another user's session, create a
                # new, empty session if the existing session
                # corresponds to a different authenticated user.
                request.session.flush()
        # Always cycle the session key when viewing the login form to
        # prevent session fixation
        request.session.cycle_key()

        # For now we'll allow fallback to OPENSTACK_KEYSTONE_URL if the
        # form post doesn't include a region.
        # jt
        default_region = (settings.OPENSTACK_KEYSTONE_URL, "Default Region")
        regions = getattr(settings, 'AVAILABLE_REGIONS', [default_region])
        #endpoint = data.get('region', None) or settings.OPENSTACK_KEYSTONE_URL
        #region_name = dict(self.fields['region'].choices)[endpoint]
        region_name = data.get('region', None) or "Default Region"
        endpoint = [r[0] for r in regions if r[1] == region_name][0]
        request.session['region_endpoint'] = endpoint
        request.session['region_name'] = region_name

        redirect_to = request.REQUEST.get(REDIRECT_FIELD_NAME, None)
        # Make sure the requested redirect matches the protocol,
        # domain, and port of this request
        if redirect_to and not same_origin(
                request.build_absolute_uri(redirect_to),
                request.build_absolute_uri()):
            redirect_to = None

        if data.get('tenant', None):
            try:
                token = api.token_create(request, data.get('tenant'),
                                         data['username'], data['password'])
                tenants = api.tenant_list_for_token(request, token.id)
            except:
                msg = _('Unable to authenticate for that project.')
                exceptions.handle(request, message=msg, escalate=True)
            _set_session_data(request, token)
            user = users.get_user_from_request(request)
            redirect = redirect_to or base.Horizon.get_user_home(user)
            return shortcuts.redirect(redirect)

        elif data.get('username', None):
            try:
                unscoped_token = api.token_create(request, '',
                                                  data['username'],
                                                  data['password'])
            except keystone_exceptions.Unauthorized:
                exceptions.handle(request, _('Invalid user name or password.'))
            except:
                # If we get here we don't want to show a stack trace to the
                # user. However, if we fail here, there may be bad session
                # data that's been cached already.
                request.user_logout()
                exceptions.handle(request,
                                  message=_("An error occurred authenticating."
                                            " Please try again later."),
                                  escalate=True)

            # Unscoped token
            request.session['unscoped_token'] = unscoped_token.id
            request.user.username = data['username']

            # Get the tenant list, and log in using first tenant
            # FIXME (anthony): add tenant chooser here?
            try:
                tenants = api.tenant_list_for_token(request, unscoped_token.id)
            except:
                exceptions.handle(request)
                tenants = []

            # Abort if there are no valid tenants for this user
            if not tenants:
                messages.error(request,
                               _('You are not authorized for any projects.') %
                               {"user": data['username']},
                               extra_tags="login")
                return

            # Create a token.
            # NOTE(gabriel): Keystone can return tenants that you're
            # authorized to administer but not to log into as a user, so in
            # the case of an Unauthorized error we should iterate through
            # the tenants until one succeeds or we've failed them all.
            while tenants:
                tenant = tenants.pop()
                try:
                    token = api.token_create_scoped(request, tenant.id,
                                                    unscoped_token.id)
                    break
                except:
                    # This will continue for recognized Unauthorized
                    # exceptions from keystoneclient.
                    exceptions.handle(request, ignore=True)
                    token = None
            if token is None:
                raise exceptions.NotAuthorized(
                    _("You are not authorized for any available projects."))

            _set_session_data(request, token)
            user = users.get_user_from_request(request)
        redirect = redirect_to or base.Horizon.get_user_home(user)
        return shortcuts.redirect(redirect)