示例#1
0
    def handle(self, request, data):
        def is_admin(token):
            for role in token.user["roles"]:
                if role["name"].lower() == "admin":
                    return True
            return False

        try:
            if data.get("tenant"):
                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
            else:
                token = api.token_create(request, "", data["username"], data["password"])

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

                def get_first_tenant_for_user():
                    tenants = api.tenant_list_for_token(request, token.id)
                    return tenants[0] if len(tenants) else None

                # Get the tenant list, and log in using first tenant
                # FIXME (anthony): add tenant chooser here?
                tenant = get_first_tenant_for_user()

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

                # Create a token
                token = api.token_create_scoped(request, tenant.id, token.id)

            request.session["admin"] = is_admin(token)
            request.session["serviceCatalog"] = token.serviceCatalog

            LOG.info('Login form for user "%s". Service Catalog data:\n%s' % (data["username"], token.serviceCatalog))

            request.session["tenant"] = tenant.name
            request.session["tenant_id"] = tenant.id
            request.session["token"] = token.id
            request.session["user"] = data["username"]

            return shortcuts.redirect("dash_overview")

        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)
示例#2
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('auth_login'), form_data)

        self.assertRedirectsNoFollow(res, reverse('dash_overview'))

        self.mox.VerifyAll()
示例#3
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')
        aToken = api.Token(id=TOKEN_ID,
                           user={'roles': [{
                               'name': 'fake'
                           }]},
                           serviceCatalog={})
        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

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

        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('auth_login'), form_data)

        self.assertRedirectsNoFollow(res, reverse('dash_overview'))

        self.mox.VerifyAll()
示例#4
0
def switch_tenants(request, tenant_id):
    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)
            return shortcuts.redirect('dash_overview')
        except exceptions.Unauthorized as e:
            messages.error(_("You are not authorized for that tenant."))

    return shortcuts.render_to_response('switch_tenants.html', {
        'to_tenant': tenant_id,
        'form': form,
    }, context_instance=template.RequestContext(request))
示例#5
0
文件: views.py 项目: Lezval/horizon
    def handle(self, request, data):

        def is_admin(token):
            for role in token.user['roles']:
                if role['name'].lower() == 'admin':
                    return True
            return False

        try:
            if data.get('tenant'):
                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
            else:
                token = api.token_create(request,
                                         '',
                                         data['username'],
                                         data['password'])

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

                def get_first_tenant_for_user():
                    tenants = api.tenant_list_for_token(request, token.id)
                    return tenants[0] if len(tenants) else None

                # Get the tenant list, and log in using first tenant
                # FIXME (anthony): add tenant chooser here?
                tenant = get_first_tenant_for_user()

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

                # Create a token
                token = api.token_create_scoped(request, tenant.id, token.id)


            request.session['admin'] = is_admin(token)
            request.session['serviceCatalog'] = token.serviceCatalog

            LOG.info('Login form for user "%s". Service Catalog data:\n%s' %
                     (data['username'], token.serviceCatalog))

            request.session['tenant'] = tenant.name
            request.session['tenant_id'] = tenant.id
            request.session['token'] = token.id
            request.session['user'] = data['username']

            return shortcuts.redirect('dash_overview')

        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)
示例#6
0
    def handle(self, request, data):
        try:
            if data.get('tenant'):
                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
            else:
                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 exceptions.Unauthorized as e:
                        token = None
                if token is None:
                    raise exceptions.Unauthorized(
                        _("You are not authorized for any available tenants."))

            LOG.info('Login form for user "%s". Service Catalog data:\n%s' %
                     (data['username'], token.serviceCatalog))
            _set_session_data(request, token)

            return shortcuts.redirect('dash_overview')

        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)