Beispiel #1
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.
    """
    if request.user.tenant_id == tenant_id:
        return True

    endpoint = request.user.endpoint
    unscoped_token = request.session.get('unscoped_token', None)

    if unscoped_token:
        try:
            token = api.token_create_scoped(request,
                                            tenant_id,
                                            unscoped_token)
            user = create_user_from_token(request, token, endpoint)
            request.user = user
            set_session_from_user(request, user)
            return request.user
        except Unauthorized:
            raise
        except Exception, e:
            LOG.error('User(%s) can not authorize project %s. Error: %s'
                      % (request.user.id, tenant_id, e))
        return None
Beispiel #2
0
def authorize_login(request):
    initial = {}
    login_url = 'get_login_view'

    if request.method == "POST":
        form = curry(Login, request)
    else:
        form = curry(Login, initial=initial)

    extra_context = {'redirect_field_name': REDIRECT_FIELD_NAME}

    if request.is_ajax():
        template_name = 'auth/_login.html'
        extra_context['hide'] = True
    else:
        template_name = login_url

    django_login(request,
                template_name=login_url,
                authentication_form=form,
                extra_context=extra_context)

    if request.user.is_authenticated():
        set_session_from_user(request, request.user)

    redirect = request.POST.get('next', None) or login_url
    return shortcuts.redirect(redirect)
Beispiel #3
0
def websso(request):
    """Logs a user in using a token from Keystone's POST."""
    if settings.WEBSSO_USE_HTTP_REFERER:
        referer = request.META.get('HTTP_REFERER',
                                   settings.OPENSTACK_KEYSTONE_URL)
        auth_url = utils.clean_up_auth_url(referer)
    else:
        auth_url = settings.OPENSTACK_KEYSTONE_URL
    token = request.POST.get('token')
    try:
        request.user = auth.authenticate(request,
                                         auth_url=auth_url,
                                         token=token)
    except exceptions.KeystoneAuthException as exc:
        if settings.WEBSSO_DEFAULT_REDIRECT:
            res = django_http.HttpResponseRedirect(settings.LOGIN_ERROR)
        else:
            msg = 'Login failed: %s' % exc
            res = django_http.HttpResponseRedirect(settings.LOGIN_URL)
            set_logout_reason(res, msg)
        return res

    auth_user.set_session_from_user(request, request.user)
    auth.login(request, request.user)
    if request.session.test_cookie_worked():
        request.session.delete_test_cookie()
    return django_http.HttpResponseRedirect(settings.LOGIN_REDIRECT_URL)
Beispiel #4
0
def authorize_login(request):
    initial = {}
    login_url = 'get_login_view'

    if request.method == "POST":
        form = curry(Login, request)
    else:
        form = curry(Login, initial=initial)

    extra_context = {'redirect_field_name': REDIRECT_FIELD_NAME}

    if request.is_ajax():
        template_name = 'auth/_login.html'
        extra_context['hide'] = True
    else:
        template_name = login_url

    django_login(request,
                 template_name=login_url,
                 authentication_form=form,
                 extra_context=extra_context)

    if request.user.is_authenticated():
        set_session_from_user(request, request.user)

    redirect = request.POST.get('next', None) or login_url
    return shortcuts.redirect(redirect)
Beispiel #5
0
def login(request):

    try:

        attributes = get_manager(request)
        domain, auth_url = get_ostack_attributes(request)

        if attributes:

            map_entry = UserMapping.objects.get(globaluser=attributes.username)
            localuser = map_entry.registration.username
            LOG.debug("Mapped user %s on %s" %
                      (attributes.username, localuser))

            kwargs = {
                'auth_url': auth_url,
                'request': request,
                'username': localuser,
                'password': None,
                'user_domain_name': domain
            }
            user = authenticate(**kwargs)

            auth_login(request, user)
            if request.user.is_authenticated():
                set_session_from_user(request, request.user)

                default_region = (settings.OPENSTACK_KEYSTONE_URL,
                                  "Default Region")
                regions = dict(
                    getattr(settings, 'AVAILABLE_REGIONS', [default_region]))

                region = request.user.endpoint
                region_name = regions.get(region)
                request.session['region_endpoint'] = region
                request.session['region_name'] = region_name
                request.session['global_user'] = attributes.username

            return shortcuts.redirect(get_user_home(user))

    except (UserMapping.DoesNotExist, keystone_exceptions.NotFound):

        LOG.debug("User %s authenticated but not authorized" %
                  attributes.username)
        return shortcuts.redirect(reverse_lazy('register'))

    except (keystone_exceptions.Unauthorized,
            auth_exceptions.KeystoneAuthException):

        return build_err_response(
            request, _("User not authorized: invalid or disabled"), attributes)

    except Exception as exc:

        LOG.error(exc.message, exc_info=True)
        err_msg = "A failure occurs authenticating user\nPlease, contact the cloud managers"
        return build_err_response(request, _(err_msg), attributes)

    return basic_login(request)
def login(request, template_name=None, extra_context=None, **kwargs):
    """Logs a user in using the :class:`~openstack_auth.forms.Login` form."""
    if not request.is_ajax():
        # If the user is already authenticated, redirect them to the
        # dashboard straight away, unless the 'next' parameter is set as it
        # usually indicates requesting access to a page that requires different
        # permissions.
        if (request.user.is_authenticated() and
                auth.REDIRECT_FIELD_NAME not in request.GET and
                auth.REDIRECT_FIELD_NAME not in request.POST):
            return shortcuts.redirect(settings.LOGIN_REDIRECT_URL)

    # Get our initial region for the form.
    initial = {}
    current_region = request.session.get('region_endpoint', None)
    requested_region = request.GET.get('region', None)
    regions = dict(getattr(settings, "AVAILABLE_REGIONS", []))
    if requested_region in regions and requested_region != current_region:
        initial.update({'region': requested_region})

    if request.method == "POST":
        # NOTE(saschpe): Since https://code.djangoproject.com/ticket/15198,
        # the 'request' object is passed directly to AuthenticationForm in
        # django.contrib.auth.views#login:
        if django.VERSION >= (1, 6):
            form = functional.curry(forms.Login)
        else:
            form = functional.curry(forms.Login, request)
    else:
        form = functional.curry(forms.Login, initial=initial)

    if extra_context is None:
        extra_context = {'redirect_field_name': auth.REDIRECT_FIELD_NAME}

    if not template_name:
        if request.is_ajax():
            template_name = 'auth/_login.html'
            extra_context['hide'] = True
        else:
            template_name = 'auth/login.html'

    res = django_auth_views.login(request,
                                  template_name=template_name,
                                  authentication_form=form,
                                  extra_context=extra_context,
                                  **kwargs)
    # Set the session data here because django's session key rotation
    # will erase it if we set it earlier.
    if request.user.is_authenticated():
        auth_user.set_session_from_user(request, request.user)
        regions = dict(forms.Login.get_region_choices())
        region = request.user.endpoint
        region_name = regions.get(region)
        request.session['region_endpoint'] = region
        request.session['region_name'] = region_name
    return res
Beispiel #7
0
def login(request, template_name=None, extra_context=None, **kwargs):
    """Logs a user in using the :class:`~openstack_auth.forms.Login` form."""
    if not request.is_ajax():
        # If the user is already authenticated, redirect them to the
        # dashboard straight away, unless the 'next' parameter is set as it
        # usually indicates requesting access to a page that requires different
        # permissions.
        if (request.user.is_authenticated()
                and auth.REDIRECT_FIELD_NAME not in request.GET
                and auth.REDIRECT_FIELD_NAME not in request.POST):
            return shortcuts.redirect(settings.LOGIN_REDIRECT_URL)

    # Get our initial region for the form.
    initial = {}
    current_region = request.session.get('region_endpoint', None)
    requested_region = request.GET.get('region', None)
    regions = dict(getattr(settings, "AVAILABLE_REGIONS", []))
    if requested_region in regions and requested_region != current_region:
        initial.update({'region': requested_region})

    if request.method == "POST":
        # NOTE(saschpe): Since https://code.djangoproject.com/ticket/15198,
        # the 'request' object is passed directly to AuthenticationForm in
        # django.contrib.auth.views#login:
        if django.VERSION >= (1, 6):
            form = functional.curry(forms.Login)
        else:
            form = functional.curry(forms.Login, request)
    else:
        form = functional.curry(forms.Login, initial=initial)

    if extra_context is None:
        extra_context = {'redirect_field_name': auth.REDIRECT_FIELD_NAME}

    if not template_name:
        if request.is_ajax():
            template_name = 'auth/_login.html'
            extra_context['hide'] = True
        else:
            template_name = 'auth/login.html'

    res = django_auth_views.login(request,
                                  template_name=template_name,
                                  authentication_form=form,
                                  extra_context=extra_context,
                                  **kwargs)
    # Set the session data here because django's session key rotation
    # will erase it if we set it earlier.
    if request.user.is_authenticated():
        auth_user.set_session_from_user(request, request.user)
        regions = dict(forms.Login.get_region_choices())
        region = request.user.endpoint
        region_name = regions.get(region)
        request.session['region_endpoint'] = region
        request.session['region_name'] = region_name
    return res
def login(request):

    try:
    
        attributes = IdPAttributes(request)
        domain, region = get_ostack_attributes(request)
        
        if attributes:
        
            map_entry = UserMapping.objects.get(globaluser=attributes.username)
            localuser = map_entry.registration.username
            LOG.debug("Mapped user %s on %s" % (attributes.username, localuser))

            user = authenticate(request=request,
                                username=localuser,
                                password=None,
                                user_domain_name=domain,
                                auth_url=region)

            auth_login(request, user)
            if request.user.is_authenticated():
                set_session_from_user(request, request.user)
                
                default_region = (settings.OPENSTACK_KEYSTONE_URL, "Default Region")
                regions = dict(getattr(settings, 'AVAILABLE_REGIONS', [default_region]))
                
                region = request.user.endpoint
                region_name = regions.get(region)
                request.session['region_endpoint'] = region
                request.session['region_name'] = region_name
            return shortcuts.redirect( '%s/project' % attributes.root_url)
            
    except (UserMapping.DoesNotExist, keystone_exceptions.NotFound):
        LOG.debug("User %s authenticated but not authorized" % attributes.username)
        return _register(request, attributes)
    except keystone_exceptions.Unauthorized:
        tempDict = {
            'error_header' : _("Authentication failed"),
            'error_text' : _("User not authenticated"),
            'redirect_url' : '/dashboard',
            'redirect_label' : _("Home")
        }
        return shortcuts.render(request, 'aai_error.html', tempDict)
    except Exception as exc:
        LOG.error(exc.message, exc_info=True)
        tempDict = {
            'error_header' : _("Authentication error"),
            'error_text' : _("A failure occurs authenticating user"),
            'contacts' : settings.MANAGERS,
            'redirect_url' : '/dashboard',
            'redirect_label' : _("Home")
        }
        return shortcuts.render(request, 'aai_error.html', tempDict)
        
    return basic_login(request)
def login(request, **kwargs):
    '''
    Logs a user in using the :class:`~openstack_auth.forms.Login` form.
    Referenced from openstack_auth.views.login
    '''
    if not request.is_ajax():
        # If the user is already authenticated, redirect them to the
        # dashboard straight away, unless the 'next' parameter is set as it
        # usually indicates requesting access to a page that requires different
        # permissions.
        if request.user.is_authenticated():
            return HttpResponseRedirect('/')

    # Get our initial region for the form.
    form = functional.curry(openstack_auth_form)
    template_name = 'auth/login.html'
    res = django_auth_views.login(request,
                                  template_name=template_name,
                                  authentication_form=form,
                                  **kwargs)

    # Save the region in the cookie, this is used as the default
    # selected region next time the Login form loads.
    if request.method == "POST":
        openstack_auth_utils.set_response_cookie(
            res, 'login_region', request.POST.get('region', ''))
        openstack_auth_utils.set_response_cookie(
            res, 'login_domain', request.POST.get('domain', ''))

    # Set the session data here because django's session key rotation
    # will erase it if we set it earlier.
    print request.user.is_authenticated()
    if request.user.is_authenticated():
        openstack_auth_user.set_session_from_user(request, request.user)
        session = openstack_auth_utils.get_session()
        user_endpoint = settings.OPENSTACK_KEYSTONE_URL
        auth = openstack_auth_utils.get_token_auth_plugin(
            auth_url=user_endpoint,
            token=request.user.unscoped_token,
            project_id=settings.ADMIN_TENANT_ID)

        try:
            auth_ref = auth.get_access(session)
        except keystone_client_exceptions.ClientException as e:
            auth_ref = None

        if auth_ref:
            new_user = openstack_auth_user.create_user_from_token(
                request,
                openstack_auth_user.Token(auth_ref),
                endpoint=request.user.endpoint)
            openstack_auth_user.set_session_from_user(request, new_user)

    return res
Beispiel #10
0
def login(request):
    if request.method == "POST":
        # print(request.POST)
        data = json.loads(request.body)
        data['region'] = 'default'
        request.POST = data

        APILoginView.as_view(template_name='',
                             redirect_field_name=auth.REDIRECT_FIELD_NAME,
                             form_class=functional.curry(forms.Login),
                             extra_context={},
                             redirect_authenticated_user=False)(request)

        if request.user.is_authenticated:
            # print("is_authenticated")
            auth_user.set_session_from_user(request, request.user)
            regions = dict(forms.get_region_choices())
            region = request.user.endpoint
            login_region = request.POST.get('region')
            region_name = regions.get(login_region)
            request.session['region_endpoint'] = region
            request.session['region_name'] = region_name
            expiration_time = request.user.time_until_expiration()
            threshold_days = settings.PASSWORD_EXPIRES_WARNING_THRESHOLD_DAYS
            if (expiration_time is not None
                    and expiration_time.days <= threshold_days
                    and expiration_time > datetime.timedelta(0)):
                expiration_time = str(expiration_time).rsplit(':', 1)[0]
                msg = (
                    _('Please consider changing your password, it will expire'
                      ' in %s minutes') % expiration_time).replace(
                          ':', ' Hours and ')
                messages.warning(request, msg)
        else:
            return JsonResponse("Password is wrong. Ensure your password.",
                                status=400,
                                safe=False)

        res = dict(
            items=[d.to_dict() for d in request.user.authorized_tenants])

        for project in res['items']:
            if project['name'] == 'admin':
                break
        switch(request, project['id'])
        # print(request.session.session_key)
        return JsonResponse(
            {
                "sid": request.session.session_key,
                "project_id": request.user.tenant_id,
                "token_expires": request.user.token.expires
            },
            safe=False)
Beispiel #11
0
def login(request):

    try:
    
        attributes = get_manager(request)
        domain, auth_url = get_ostack_attributes(request)
        
        if attributes:
        
            map_entry = UserMapping.objects.get(globaluser=attributes.username)
            localuser = map_entry.registration.username
            LOG.debug("Mapped user %s on %s" % (attributes.username, localuser))

            kwargs = {
                'auth_url' : auth_url,
                'request' : request,
                'username' : localuser,
                'password' : None,
                'user_domain_name' : domain
            }
            user = authenticate(**kwargs)

            auth_login(request, user)
            if request.user.is_authenticated():
                set_session_from_user(request, request.user)
                
                default_region = (settings.OPENSTACK_KEYSTONE_URL, "Default Region")
                regions = dict(getattr(settings, 'AVAILABLE_REGIONS', [default_region]))
                
                region = request.user.endpoint
                region_name = regions.get(region)
                request.session['region_endpoint'] = region
                request.session['region_name'] = region_name
                request.session['global_user'] = attributes.username
            
            return shortcuts.redirect(get_user_home(user))
            
    except (UserMapping.DoesNotExist, keystone_exceptions.NotFound):

        LOG.debug("User %s authenticated but not authorized" % attributes.username)
        return shortcuts.redirect(reverse_lazy('register'))

    except (keystone_exceptions.Unauthorized, auth_exceptions.KeystoneAuthException):

        return build_err_response(request, _("User not authorized: invalid or disabled"), attributes)

    except Exception as exc:

        LOG.error(exc.message, exc_info=True)
        err_msg = "A failure occurs authenticating user\nPlease, contact the cloud managers"
        return build_err_response(request, _(err_msg), attributes)
        
    return basic_login(request)
def login(request, **kwargs):
    '''
    Logs a user in using the :class:`~openstack_auth.forms.Login` form.
    Referenced from openstack_auth.views.login
    '''
    if not request.is_ajax():
        # If the user is already authenticated, redirect them to the
        # dashboard straight away, unless the 'next' parameter is set as it
        # usually indicates requesting access to a page that requires different
        # permissions.
        if request.user.is_authenticated():
            return HttpResponseRedirect('/')

    # Get our initial region for the form.
    form = functional.curry(openstack_auth_form)
    template_name = 'auth/login.html'
    res = django_auth_views.login(request,
                                  template_name=template_name,
                                  authentication_form=form,
                                  **kwargs)

    # Save the region in the cookie, this is used as the default
    # selected region next time the Login form loads.
    if request.method == "POST":
        openstack_auth_utils.set_response_cookie(res, 'login_region',
                                                 request.POST.get('region', ''))
        openstack_auth_utils.set_response_cookie(res, 'login_domain',
                                                 request.POST.get('domain', ''))

    # Set the session data here because django's session key rotation
    # will erase it if we set it earlier.
    print request.user.is_authenticated()
    if request.user.is_authenticated():
        openstack_auth_user.set_session_from_user(request, request.user)
        session = openstack_auth_utils.get_session()
        user_endpoint = settings.OPENSTACK_KEYSTONE_URL
        auth = openstack_auth_utils.get_token_auth_plugin(auth_url=user_endpoint,
                                       token=request.user.unscoped_token,
                                       project_id=settings.ADMIN_TENANT_ID)

        try:
            auth_ref = auth.get_access(session)
        except keystone_client_exceptions.ClientException as e:
            auth_ref = None

        if auth_ref:
            new_user = openstack_auth_user.create_user_from_token(request,
                                                                  openstack_auth_user.Token(auth_ref),
                                                                  endpoint=request.user.endpoint)
            openstack_auth_user.set_session_from_user(request, new_user)

    return res
Beispiel #13
0
def switch(request, tenant_id, redirect_field_name=auth.REDIRECT_FIELD_NAME):
    """Switches an authenticated user from one project to another."""
    LOG.debug('Switching to tenant %s for user "%s".'
              % (tenant_id, request.user.username))

    endpoint = utils.fix_auth_url_version(request.user.endpoint)
    session = utils.get_session()
    # Keystone can be configured to prevent exchanging a scoped token for
    # another token. Always use the unscoped token for requesting a
    # scoped token.
    unscoped_token = request.user.unscoped_token
    auth = utils.get_token_auth_plugin(auth_url=endpoint,
                                       token=unscoped_token,
                                       project_id=tenant_id)

    try:
        auth_ref = auth.get_access(session)
        msg = 'Project switch successful for user "%(username)s".' % \
            {'username': request.user.username}
        LOG.info(msg)
    except keystone_exceptions.ClientException:
        msg = (
            _('Project switch failed for user "%(username)s".') %
            {'username': request.user.username})
        messages.error(request, msg)
        auth_ref = None
        LOG.exception('An error occurred while switching sessions.')

    # Ensure the user-originating redirection url is safe.
    # Taken from django.contrib.auth.views.login()
    redirect_to = request.REQUEST.get(redirect_field_name, '')
    if not is_safe_url(url=redirect_to, host=request.get_host()):
        redirect_to = settings.LOGIN_REDIRECT_URL

    if auth_ref:
        old_endpoint = request.session.get('region_endpoint')
        old_token = request.session.get('token')
        if old_token and old_endpoint and old_token.id != auth_ref.auth_token:
            delete_token(endpoint=old_endpoint, token_id=old_token.id)
        user = auth_user.create_user_from_token(
            request,
            auth_user.Token(auth_ref, unscoped_token=unscoped_token),
            endpoint)
        auth_user.set_session_from_user(request, user)
        message = (
            _('Switch to project "%(project_name)s" successful.') %
            {'project_name': request.user.project_name})
        messages.success(request, message)
    response = shortcuts.redirect(redirect_to)
    utils.set_response_cookie(response, 'recent_project',
                              request.user.project_id)
    return response
Beispiel #14
0
def switch(request, project_id=None):
    if not project_id:
        data = json.loads(request.body)
        tenant_id = data['project_id']
    else:
        tenant_id = project_id
    LOG.debug('Switching to tenant %s for user "%s".', tenant_id,
              request.user.username)

    endpoint, __ = utils.fix_auth_url_version_prefix(request.user.endpoint)
    session = utils.get_session()

    unscoped_token = request.user.unscoped_token
    auth = utils.get_token_auth_plugin(auth_url=endpoint,
                                       token=unscoped_token,
                                       project_id=tenant_id)

    try:
        auth_ref = auth.get_access(session)
        msg = 'Project switch successful for user "%(username)s".' % \
            {'username': request.user.username}
        LOG.info(msg)
    except keystone_exceptions.ClientException:
        msg = (_('Project switch failed for user "%(username)s".') % {
            'username': request.user.username
        })
        messages.error(request, msg)
        auth_ref = None
        LOG.exception('An error occurred while switching sessions.')

    if auth_ref:
        user = auth_user.create_user_from_token(
            request, auth_user.Token(auth_ref, unscoped_token=unscoped_token),
            endpoint)
        auth_user.set_session_from_user(request, user)
        message = (_('Switch to project "%(project_name)s" successful.') % {
            'project_name': request.user.project_name
        })
        messages.success(request, message)
        # utils.set_response_cookie(response, 'recent_project',
        #                           request.user.project_id)

        print({
            "tenant_id": request.user.tenant_id,
            "tenant_name": request.user.tenant_name,
            "username": request.user.username
        })
        return JsonResponse("success", safe=False)

    else:
        return JsonResponse("failed", status=400, safe=False)
Beispiel #15
0
def authentication_callback(request):
    """ Second step of the login process.
    It reads in a code from Facebook, then redirects back to the home page. """
    code = request.GET.get('code')
    user = authenticate(token=code, request=request)
    auth_login(request, user)
    set_session_from_user(request, user)
    region = request.user.endpoint
    region_name = dict(Login.get_region_choices()).get(region)
    request.session['region_endpoint'] = region
    request.session['region_name'] = region_name
    url = getattr(settings, "LOGIN_REDIRECT_URL", "/")
    resp = HttpResponseRedirect(url)

    return resp
def authentication_callback(request):
    """ Second step of the login process.
    It reads in a code from Facebook, then redirects back to the home page. """
    code = request.GET.get('code')
    user = authenticate(token=code, request=request)
    auth_login(request, user)
    set_session_from_user(request, user)
    region = request.user.endpoint
    region_name = dict(Login.get_region_choices()).get(region)
    request.session['region_endpoint'] = region
    request.session['region_name'] = region_name
    url = getattr(settings, "LOGIN_REDIRECT_URL", "/")
    resp = HttpResponseRedirect(url)

    return resp
def switch(request, tenant_id, redirect_field_name=auth.REDIRECT_FIELD_NAME):
    """Switches an authenticated user from one project to another."""
    LOG.debug('Switching to tenant %s for user "%s".' %
              (tenant_id, request.user.username))
    insecure = getattr(settings, 'OPENSTACK_SSL_NO_VERIFY', False)
    ca_cert = getattr(settings, "OPENSTACK_SSL_CACERT", None)
    endpoint = request.user.endpoint
    try:
        if utils.get_keystone_version() >= 3:
            if not utils.has_in_url_path(endpoint, '/v3'):
                endpoint = utils.url_path_replace(endpoint, '/v2.0', '/v3', 1)
        client = utils.get_keystone_client().Client(
            tenant_id=tenant_id,
            token=request.user.token.id,
            auth_url=endpoint,
            insecure=insecure,
            cacert=ca_cert,
            debug=settings.DEBUG)
        auth_ref = client.auth_ref
        msg = 'Project switch successful for user "%(username)s".' % \
            {'username': request.user.username}
        LOG.info(msg)
    except keystone_exceptions.ClientException:
        msg = 'Project switch failed for user "%(username)s".' % \
            {'username': request.user.username}
        LOG.warning(msg)
        auth_ref = None
        LOG.exception('An error occurred while switching sessions.')

    # Ensure the user-originating redirection url is safe.
    # Taken from django.contrib.auth.views.login()
    redirect_to = request.REQUEST.get(redirect_field_name, '')
    if not is_safe_url(url=redirect_to, host=request.get_host()):
        redirect_to = settings.LOGIN_REDIRECT_URL

    if auth_ref:
        old_endpoint = request.session.get('region_endpoint')
        old_token = request.session.get('token')
        if old_token and old_endpoint and old_token.id != auth_ref.auth_token:
            delete_token(endpoint=old_endpoint, token_id=old_token.id)
        user = auth_user.create_user_from_token(request,
                                                auth_user.Token(auth_ref),
                                                endpoint)
        auth_user.set_session_from_user(request, user)
    response = shortcuts.redirect(redirect_to)
    utils.set_response_cookie(response, 'recent_project',
                              request.user.project_id)
    return response
Beispiel #18
0
    def form_valid(self, form):
        usr = self.kwargs.get('user_cache') or form.user_cache

        auth_login(self.request, usr)

        if self.request.session.test_cookie_worked():
            self.request.session.delete_test_cookie()

        if self.request.user.is_authenticated():
            auth_user.set_session_from_user(self.request, usr)
            regions = dict(getattr(settings, "AVAILABLE_REGIONS", []))
            region = self.request.user.endpoint
            region_name = regions.get(region)
            self.request.session['region_endpoint'] = region
            self.request.session['region_name'] = region_name
        return HttpResponseRedirect(self.kwargs[self.redirect_field])
def switch(request, tenant_id, redirect_field_name=auth.REDIRECT_FIELD_NAME):
    """Switches an authenticated user from one project to another."""
    LOG.debug('Switching to tenant %s for user "%s".'
              % (tenant_id, request.user.username))
    insecure = getattr(settings, 'OPENSTACK_SSL_NO_VERIFY', False)
    ca_cert = getattr(settings, "OPENSTACK_SSL_CACERT", None)
    endpoint = request.user.endpoint
    try:
        if utils.get_keystone_version() >= 3:
            if not utils.has_in_url_path(endpoint, '/v3'):
                endpoint = utils.url_path_replace(endpoint, '/v2.0', '/v3', 1)
        client = utils.get_keystone_client().Client(
            tenant_id=tenant_id,
            token=request.user.token.id,
            auth_url=endpoint,
            insecure=insecure,
            cacert=ca_cert,
            debug=settings.DEBUG)
        auth_ref = client.auth_ref
        msg = 'Project switch successful for user "%(username)s".' % \
            {'username': request.user.username}
        LOG.info(msg)
    except keystone_exceptions.ClientException:
        msg = 'Project switch failed for user "%(username)s".' % \
            {'username': request.user.username}
        LOG.warning(msg)
        auth_ref = None
        LOG.exception('An error occurred while switching sessions.')

    # Ensure the user-originating redirection url is safe.
    # Taken from django.contrib.auth.views.login()
    redirect_to = request.REQUEST.get(redirect_field_name, '')
    if not is_safe_url(url=redirect_to, host=request.get_host()):
        redirect_to = settings.LOGIN_REDIRECT_URL

    if auth_ref:
        old_endpoint = request.session.get('region_endpoint')
        old_token = request.session.get('token')
        if old_token and old_endpoint and old_token.id != auth_ref.auth_token:
            delete_token(endpoint=old_endpoint, token_id=old_token.id)
        user = auth_user.create_user_from_token(
            request, auth_user.Token(auth_ref), endpoint)
        auth_user.set_session_from_user(request, user)
    response = shortcuts.redirect(redirect_to)
    utils.set_response_cookie(response, 'recent_project',
                              request.user.project_id)
    return response
Beispiel #20
0
def authorize_client_login(request):
    login_url = 'get_login_client_view'
    translation.activate('zh')
    request.LANGUAGE_CODE = 'zh'
    form = curry(Login, request)
    extra_context = {'redirect_field_name': REDIRECT_FIELD_NAME}

    django_login(request,
                 template_name=login_url,
                 authentication_form=form,
                 extra_context=extra_context)

    if request.user.is_authenticated():
        set_session_from_user(request, request.user)
        return shortcuts.redirect('get_client_instances')
    else:
        return shortcuts.redirect(login_url)
Beispiel #21
0
def authorize_client_login(request):
    login_url = 'get_login_client_view'
    translation.activate('zh')
    request.LANGUAGE_CODE = 'zh'
    form = curry(Login, request)
    extra_context = {'redirect_field_name': REDIRECT_FIELD_NAME}

    django_login(request,
                template_name=login_url,
                authentication_form=form,
                extra_context=extra_context)

    if request.user.is_authenticated():
        set_session_from_user(request, request.user)
        return shortcuts.redirect('get_client_instances')
    else:
        return shortcuts.redirect(login_url)
Beispiel #22
0
def switch_system_scope(request, redirect_field_name=auth.REDIRECT_FIELD_NAME):
    """Switches an authenticated user from one system to another."""
    LOG.debug('Switching to system scope for user "%s".',
              request.user.username)

    endpoint, __ = utils.fix_auth_url_version_prefix(request.user.endpoint)
    session = utils.get_session()
    # Keystone can be configured to prevent exchanging a scoped token for
    # another token. Always use the unscoped token for requesting a
    # scoped token.
    unscoped_token = request.user.unscoped_token
    auth = utils.get_token_auth_plugin(auth_url=endpoint,
                                       token=unscoped_token,
                                       system_scope='all')

    try:
        auth_ref = auth.get_access(session)
    except keystone_exceptions.ClientException:
        msg = (_('System switch failed for user "%(username)s".') % {
            'username': request.user.username
        })
        messages.error(request, msg)
        auth_ref = None
        LOG.exception('An error occurred while switching sessions.')
    else:
        msg = 'System switch successful for user "%(username)s".' % \
            {'username': request.user.username}
        LOG.info(msg)

    # Ensure the user-originating redirection url is safe.
    # Taken from django.contrib.auth.views.login()
    redirect_to = request.GET.get(redirect_field_name, '')
    if not http.is_safe_url(url=redirect_to,
                            allowed_hosts=[request.get_host()]):
        redirect_to = settings.LOGIN_REDIRECT_URL

    if auth_ref:
        user = auth_user.create_user_from_token(
            request, auth_user.Token(auth_ref, unscoped_token=unscoped_token),
            endpoint)
        auth_user.set_session_from_user(request, user)
        message = _('Switch to system scope successful.')
        messages.success(request, message)
    response = shortcuts.redirect(redirect_to)
    return response
Beispiel #23
0
def websso(request):
    """Logs a user in using a token from Keystone's POST."""
    referer = request.META.get("HTTP_REFERER", settings.OPENSTACK_KEYSTONE_URL)
    auth_url = re.sub(r"/auth.*", "", referer)
    token = request.POST.get("token")
    try:
        request.user = auth.authenticate(request=request, auth_url=auth_url, token=token)
    except exceptions.KeystoneAuthException as exc:
        msg = "Login failed: %s" % unicode(exc)
        res = django_http.HttpResponseRedirect(settings.LOGIN_URL)
        res.set_cookie("logout_reason", msg, max_age=10)
        return res

    auth_user.set_session_from_user(request, request.user)
    auth.login(request, request.user)
    if request.session.test_cookie_worked():
        request.session.delete_test_cookie()
    return django_http.HttpResponseRedirect(settings.LOGIN_REDIRECT_URL)
def sso(request):
    referer = request.META.get('HTTP_REFERER', settings.OPENSTACK_KEYSTONE_URL)
    scheme, netloc, path, query, fragment = urlparse.urlsplit(referer)
    auth_url = urlparse.urlunsplit((scheme, netloc, re.sub(r'/auth.*', '', path), '', ''))
    token = request.REQUEST.get('token')
    project_id = request.REQUEST.get('vdcId')
    if token is None or project_id is None:
        return None
    token = token.replace(' ', '+')
    try:
        request.user = auth.authenticate(request=request, auth_url=auth_url, token=token, project_id=project_id)
        auth_user.set_session_from_user(request, request.user)
        auth.login(request, request.user)
        if request.session.test_cookie_worked():
            request.session.delete_test_cookie()
        return request.user
    except Exception:
        return None
Beispiel #25
0
def websso(request):
    """Logs a user in using a token from Keystone's POST."""
    referer = request.META.get('HTTP_REFERER', settings.OPENSTACK_KEYSTONE_URL)
    auth_url = re.sub(r'/auth.*', '', referer)
    token = request.POST.get('token')
    try:
        request.user = auth.authenticate(request=request, auth_url=auth_url,
                                         token=token)
    except exceptions.KeystoneAuthException as exc:
        msg = 'Login failed: %s' % six.text_type(exc)
        res = django_http.HttpResponseRedirect(settings.LOGIN_URL)
        res.set_cookie('logout_reason', msg, max_age=10)
        return res

    auth_user.set_session_from_user(request, request.user)
    auth.login(request, request.user)
    if request.session.test_cookie_worked():
        request.session.delete_test_cookie()
    return django_http.HttpResponseRedirect(settings.LOGIN_REDIRECT_URL)
def websso(request):
    """Logs a user in using a token from Keystone's POST."""
    referer = request.META.get('HTTP_REFERER', settings.OPENSTACK_KEYSTONE_URL)
    auth_url = utils.clean_up_auth_url(referer)
    token = request.POST.get('token')
    try:
        request.user = auth.authenticate(request=request, auth_url=auth_url,
                                         token=token)
    except exceptions.KeystoneAuthException as exc:
        msg = 'Login failed: %s' % six.text_type(exc)
        res = django_http.HttpResponseRedirect(settings.LOGIN_URL)
        res.set_cookie('logout_reason', msg, max_age=10)
        return res

    auth_user.set_session_from_user(request, request.user)
    auth.login(request, request.user)
    if request.session.test_cookie_worked():
        request.session.delete_test_cookie()
    return django_http.HttpResponseRedirect(settings.LOGIN_REDIRECT_URL)
def authentication_callback(request):
    """ Second step of the login process.
    It reads in a code from Sina, then redirects back to the home page. """
    code = request.GET.get('code')
    user = authenticate(token=code, request=request)
    try:
        auth_login(request, user)
    except AttributeError:
        # No valid user returned
        return HttpResponseRedirect(request.build_absolute_uri('/'))
    set_session_from_user(request, user)
    region = request.user.endpoint
    region_name = dict(Login.get_region_choices()).get(region)
    request.session['region_endpoint'] = region
    request.session['region_name'] = region_name
    url = getattr(settings, "LOGIN_REDIRECT_URL", "/")
    resp = HttpResponseRedirect(url)

    return resp
Beispiel #28
0
def login_view(request):
    """
    Đăng nhập
    """

    print('------------------')
    if request.user.is_authenticated:
        print('Session is authenticate')
    for key, value in request.session.items():
        print('{} => {}'.format(key, value))

    print('Check value')
    print(request.user.is_authenticated)
    print('------------------')
    form = LoginForm(request.POST or None)
    if form.is_valid():
        username = form.cleaned_data.get("username")
        password = form.cleaned_data.get('password')
        try:
            # user = authenticate(request=request,
            #                     username=username,
            #                     password=password,)
            # #print(user)
            # #json.dumps(user.token)
            # auth_user.set_session_from_user(request, user)
            user_cache = authenticate(request=request,
                                      username=username,
                                      password=password,
                                      user_domain_name='Default',
                                      auth_url=settings.OPENSTACK_KEYSTONE_URL)
            if request.user.is_authenticated:
                auth_user.set_session_from_user(request, request.user)
                login(request, request.user)

        except exceptions.KeystoneAuthException as exc:
            print('Login fail')

        return redirect('log_view')

    print(request.user.is_authenticated)
    return render(request, 'authentication/login.html')
def login(request, user):
    if user is None:
        user = request.user
    # TODO: It would be nice to support different login methods, like signed cookies.
    if auth.SESSION_KEY in request.session:
        if request.session[auth.SESSION_KEY] != user.id:
            # 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()
    else:
        request.session.cycle_key()
    request.session[auth.SESSION_KEY] = user.id
    request.session[auth.BACKEND_SESSION_KEY] = user.backend

    set_session_from_user(request, user)

    if hasattr(request, 'user'):
        request.user = user

    user_logged_in.send(sender=user.__class__, request=request, user=user)
Beispiel #30
0
def login(request, user):
    if user is None:
        user = request.user
    # TODO: It would be nice to support different login methods, like signed cookies.
    if auth.SESSION_KEY in request.session:
        if request.session[auth.SESSION_KEY] != user.id:
            # 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()
    else:
        request.session.cycle_key()
    request.session[auth.SESSION_KEY] = user.id
    request.session[auth.BACKEND_SESSION_KEY] = user.backend

    set_session_from_user(request, user)

    if hasattr(request, 'user'):
        request.user = user

    user_logged_in.send(sender=user.__class__, request=request, user=user)
Beispiel #31
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.
    """
    if request.user.tenant_id == tenant_id:
        return True

    endpoint = request.user.endpoint
    unscoped_token = request.session.get('unscoped_token', None)

    if unscoped_token:
        try:
            token = api.token_create_scoped(request, tenant_id, unscoped_token)
            user = create_user_from_token(request, token, endpoint)
            request.user = user
            set_session_from_user(request, user)
            return request.user
        except Unauthorized:
            raise
        except Exception, e:
            LOG.error('User(%s) can not authorize project %s. Error: %s' %
                      (request.user.id, tenant_id, e))
        return None
Beispiel #32
0
    def authenticate(self, request=None, username=None, password=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)
        ca_cert = getattr(settings, "OPENSTACK_SSL_CACERT", None)
        endpoint_type = getattr(
            settings, 'OPENSTACK_ENDPOINT_TYPE', 'publicURL')
        auth_url = getattr(
            settings, "OPENSTACK_KEYSTONE_URL", "http://0.0.0.0:5000/v2.0")

        keystone_client = utils.get_keystone_client()
        try:
            client = keystone_client.Client(
                username=username,
                password=password,
                auth_url=auth_url,
                insecure=insecure,
                cacert=ca_cert,
                debug=settings.DEBUG)

            unscoped_auth_ref = client.auth_ref
            unscoped_token = auth_user.Token(auth_ref=unscoped_auth_ref)
        except (keystone_exceptions.Unauthorized,
                keystone_exceptions.Forbidden,
                keystone_exceptions.NotFound) as exc:
            msg = _('Invalid user name or password.')
            LOG.debug(str(exc))
            return None
        except (keystone_exceptions.ClientException,
                keystone_exceptions.AuthorizationFailure) as exc:
            msg = _("An error occurred authenticating. "
                    "Please try again later.")
            LOG.debug(str(exc))
            return None

        # Check expiry for our unscoped auth ref.
        self.check_auth_expiry(unscoped_auth_ref)

        # Check if token is automatically scoped to default_project
        if unscoped_auth_ref.project_scoped:
            auth_ref = unscoped_auth_ref
        else:
            return None

        # Check expiry for our new scoped token.
        self.check_auth_expiry(auth_ref)

        # If we made it here we succeeded. Create our User!
        user = auth_user.create_user_from_token(
            request,
            auth_user.Token(auth_ref),
            auth_url)

        if request is not None:
            auth_user.set_session_from_user(request, user)

            # Support client caching to save on auth calls.
            setattr(request, KEYSTONE_CLIENT_ATTR, client)

        logging.error('Authentication completed for user "%s".' % username)
        return user
Beispiel #33
0
def login(request, template_name=None, extra_context=None, **kwargs):
    """Logs a user in using the :class:`~openstack_auth.forms.Login` form."""

    # If the user enabled websso and selects default protocol
    # from the dropdown, We need to redirect user to the websso url
    if request.method == 'POST':
        protocol = request.POST.get('auth_type', 'credentials')
        if utils.is_websso_enabled() and protocol != 'credentials':
            region = request.POST.get('region')
            origin = utils.build_absolute_uri(request, '/auth/websso/')
            url = ('%s/auth/OS-FEDERATION/websso/%s?origin=%s' %
                   (region, protocol, origin))
            return shortcuts.redirect(url)

    if not request.is_ajax():
        # If the user is already authenticated, redirect them to the
        # dashboard straight away, unless the 'next' parameter is set as it
        # usually indicates requesting access to a page that requires different
        # permissions.
        if (request.user.is_authenticated()
                and auth.REDIRECT_FIELD_NAME not in request.GET
                and auth.REDIRECT_FIELD_NAME not in request.POST):
            return shortcuts.redirect(settings.LOGIN_REDIRECT_URL)

    # Get our initial region for the form.
    initial = {}
    current_region = request.session.get('region_endpoint', None)
    requested_region = request.GET.get('region', None)
    regions = dict(getattr(settings, "AVAILABLE_REGIONS", []))
    if requested_region in regions and requested_region != current_region:
        initial.update({'region': requested_region})

    if request.method == "POST":
        # NOTE(saschpe): Since https://code.djangoproject.com/ticket/15198,
        # the 'request' object is passed directly to AuthenticationForm in
        # django.contrib.auth.views#login:
        if django.VERSION >= (1, 6):
            form = functional.curry(forms.Login)
        else:
            form = functional.curry(forms.Login, request)
    else:
        form = functional.curry(forms.Login, initial=initial)

    if extra_context is None:
        extra_context = {'redirect_field_name': auth.REDIRECT_FIELD_NAME}

    if not template_name:
        if request.is_ajax():
            template_name = 'auth/_login.html'
            extra_context['hide'] = True
        else:
            template_name = 'auth/login.html'

    res = django_auth_views.login(request,
                                  template_name=template_name,
                                  authentication_form=form,
                                  extra_context=extra_context,
                                  **kwargs)
    # Save the region in the cookie, this is used as the default
    # selected region next time the Login form loads.
    if request.method == "POST":
        utils.set_response_cookie(res, 'login_region',
                                  request.POST.get('region', ''))

    # Set the session data here because django's session key rotation
    # will erase it if we set it earlier.
    if request.user.is_authenticated():
        auth_user.set_session_from_user(request, request.user)
        regions = dict(forms.Login.get_region_choices())
        region = request.user.endpoint
        region_name = regions.get(region)
        request.session['region_endpoint'] = region
        request.session['region_name'] = region_name
        request.session['last_activity'] = int(time.time())
    return res
Beispiel #34
0
def login(request, template_name=None, extra_context=None, **kwargs):
    """Logs a user in using the :class:`~openstack_auth.forms.Login` form."""

    # If the user enabled websso and selects default protocol
    # from the dropdown, We need to redirect user to the websso url
    if request.method == 'POST':
        auth_type = request.POST.get('auth_type', 'credentials')
        if utils.is_websso_enabled() and auth_type != 'credentials':
            auth_url = request.POST.get('region')
            url = utils.get_websso_url(request, auth_url, auth_type)
            return shortcuts.redirect(url)

    if not request.is_ajax():
        # If the user is already authenticated, redirect them to the
        # dashboard straight away, unless the 'next' parameter is set as it
        # usually indicates requesting access to a page that requires different
        # permissions.
        if (request.user.is_authenticated()
                and auth.REDIRECT_FIELD_NAME not in request.GET
                and auth.REDIRECT_FIELD_NAME not in request.POST):
            return shortcuts.redirect(settings.LOGIN_REDIRECT_URL)

    # Get our initial region for the form.
    initial = {}
    current_region = request.session.get('region_endpoint', None)
    requested_region = request.GET.get('region', None)
    regions = dict(getattr(settings, "AVAILABLE_REGIONS", []))
    if requested_region in regions and requested_region != current_region:
        initial.update({'region': requested_region})

    if request.method == "POST":
        form = functional.curry(forms.Login)
    else:
        form = functional.curry(forms.Login, initial=initial)

    if extra_context is None:
        extra_context = {'redirect_field_name': auth.REDIRECT_FIELD_NAME}

    if not template_name:
        if request.is_ajax():
            template_name = 'auth/_login.html'
            extra_context['hide'] = True
        else:
            template_name = 'auth/login.html'

    res = django_auth_views.login(request,
                                  template_name=template_name,
                                  authentication_form=form,
                                  extra_context=extra_context,
                                  **kwargs)
    # Save the region in the cookie, this is used as the default
    # selected region next time the Login form loads.
    if request.method == "POST":
        utils.set_response_cookie(res, 'login_region',
                                  request.POST.get('region', ''))
        utils.set_response_cookie(res, 'login_domain',
                                  request.POST.get('domain', ''))

    # Set the session data here because django's session key rotation
    # will erase it if we set it earlier.
    if request.user.is_authenticated():
        auth_user.set_session_from_user(request, request.user)
        regions = dict(forms.Login.get_region_choices())
        region = request.user.endpoint
        login_region = request.POST.get('region')
        region_name = regions.get(login_region)
        request.session['region_endpoint'] = region
        request.session['region_name'] = region_name
        expiration_time = request.user.time_until_expiration()
        threshold_days = getattr(settings,
                                 'PASSWORD_EXPIRES_WARNING_THRESHOLD_DAYS', -1)
        if expiration_time is not None and \
                expiration_time.days <= threshold_days:
            expiration_time = str(expiration_time).rsplit(':', 1)[0]
            msg = (_('Please consider changing your password, it will expire'
                     ' in %s minutes') % expiration_time).replace(
                         ':', ' Hours and ')
            messages.warning(request, msg)
    return res
def login(request, template_name=None, extra_context=None, **kwargs):
    """Logs a user in using the :class:`~openstack_auth.forms.Login` form."""

    # If the user enabled websso and selects default protocol
    # from the dropdown, We need to redirect user to the websso url
    if request.method == 'POST':
        auth_type = request.POST.get('auth_type', 'credentials')
        if utils.is_websso_enabled() and auth_type != 'credentials':
            auth_url = request.POST.get('region')
            url = utils.get_websso_url(request, auth_url, auth_type)
            return shortcuts.redirect(url)

    if not request.is_ajax():
        # If the user is already authenticated, redirect them to the
        # dashboard straight away, unless the 'next' parameter is set as it
        # usually indicates requesting access to a page that requires different
        # permissions.
        if (request.user.is_authenticated() and
                auth.REDIRECT_FIELD_NAME not in request.GET and
                auth.REDIRECT_FIELD_NAME not in request.POST):
            return shortcuts.redirect(settings.LOGIN_REDIRECT_URL)

    # Get our initial region for the form.
    initial = {}
    current_region = request.session.get('region_endpoint', None)
    requested_region = request.GET.get('region', None)
    regions = dict(getattr(settings, "AVAILABLE_REGIONS", []))
    if requested_region in regions and requested_region != current_region:
        initial.update({'region': requested_region})

    if request.method == "POST":
        form = functional.curry(forms.Login)
    else:
        form = functional.curry(forms.Login, initial=initial)

    if extra_context is None:
        extra_context = {'redirect_field_name': auth.REDIRECT_FIELD_NAME}

    if not template_name:
        if request.is_ajax():
            template_name = 'auth/_login.html'
            extra_context['hide'] = True
        else:
            template_name = 'auth/login.html'

    res = django_auth_views.login(request,
                                  template_name=template_name,
                                  authentication_form=form,
                                  extra_context=extra_context,
                                  **kwargs)
    # Save the region in the cookie, this is used as the default
    # selected region next time the Login form loads.
    if request.method == "POST":
        utils.set_response_cookie(res, 'login_region',
                                  request.POST.get('region', ''))
        utils.set_response_cookie(res, 'login_domain',
                                  request.POST.get('domain', ''))

    # Set the session data here because django's session key rotation
    # will erase it if we set it earlier.
    if request.user.is_authenticated():
        auth_user.set_session_from_user(request, request.user)
        regions = dict(forms.Login.get_region_choices())
        region = request.user.endpoint
        login_region = request.POST.get('region')
        region_name = regions.get(login_region)
        request.session['region_endpoint'] = region
        request.session['region_name'] = region_name
    return res
Beispiel #36
0
def switch_keystone_provider(request,
                             keystone_provider=None,
                             redirect_field_name=auth.REDIRECT_FIELD_NAME):
    """Switches the user's keystone provider using K2K Federation

    If keystone_provider is given then we switch the user to
    the keystone provider using K2K federation. Otherwise if keystone_provider
    is None then we switch the user back to the Identity Provider Keystone
    which a non federated token auth will be used.
    """
    base_token = request.session.get('k2k_base_unscoped_token', None)
    k2k_auth_url = request.session.get('k2k_auth_url', None)
    keystone_providers = request.session.get('keystone_providers', None)
    recent_project = request.COOKIES.get('recent_project')

    if not base_token or not k2k_auth_url:
        msg = _('K2K Federation not setup for this session')
        raise exceptions.KeystoneAuthException(msg)

    redirect_to = request.GET.get(redirect_field_name, '')
    if not http.is_safe_url(url=redirect_to,
                            allowed_hosts=[request.get_host()]):
        redirect_to = settings.LOGIN_REDIRECT_URL

    unscoped_auth_ref = None
    keystone_idp_id = settings.KEYSTONE_PROVIDER_IDP_ID

    if keystone_provider == keystone_idp_id:
        current_plugin = plugin.TokenPlugin()
        unscoped_auth = current_plugin.get_plugin(auth_url=k2k_auth_url,
                                                  token=base_token)
    else:
        # Switch to service provider using K2K federation
        plugins = [plugin.TokenPlugin()]
        current_plugin = plugin.K2KAuthPlugin()

        unscoped_auth = current_plugin.get_plugin(
            auth_url=k2k_auth_url,
            service_provider=keystone_provider,
            plugins=plugins,
            token=base_token,
            recent_project=recent_project)

    try:
        # Switch to identity provider using token auth
        unscoped_auth_ref = current_plugin.get_access_info(unscoped_auth)
    except exceptions.KeystoneAuthException as exc:
        msg = 'Switching to Keystone Provider %s has failed. %s' \
              % (keystone_provider, exc)
        messages.error(request, msg)

    if unscoped_auth_ref:
        try:
            request.user = auth.authenticate(
                request,
                auth_url=unscoped_auth.auth_url,
                token=unscoped_auth_ref.auth_token)
        except exceptions.KeystoneAuthException as exc:
            msg = 'Keystone provider switch failed: %s' % exc
            res = django_http.HttpResponseRedirect(settings.LOGIN_URL)
            set_logout_reason(res, msg)
            return res
        auth.login(request, request.user)
        auth_user.set_session_from_user(request, request.user)
        request.session['keystone_provider_id'] = keystone_provider
        request.session['keystone_providers'] = keystone_providers
        request.session['k2k_base_unscoped_token'] = base_token
        request.session['k2k_auth_url'] = k2k_auth_url
        message = (_('Switch to Keystone Provider "%(keystone_provider)s" '
                     'successful.') % {
                         'keystone_provider': keystone_provider
                     })
        messages.success(request, message)

    response = shortcuts.redirect(redirect_to)
    return response
def login(request, extra_context=None, **kwargs):
    redirect = request.GET.get('redirect',
        request.POST.get('redirect', kwargs.get('redirect', '')))
    template_name = kwargs.get('template', 'auth/login.html')


    if (request.user.is_authenticated() and
            auth.REDIRECT_FIELD_NAME not in request.GET and
            auth.REDIRECT_FIELD_NAME not in request.POST):
        return shortcuts.redirect(settings.LOGIN_REDIRECT_URL)

    initial = {}
    current_region = request.session.get('region_endpoint', None)
    requested_region = request.GET.get('region', None)
    regions = dict(getattr(settings, "AVAILABLE_REGIONS", []))
    if requested_region in regions and requested_region != current_region:
        initial.update({'region': requested_region})

    if request.method == "POST":
        if django.VERSION >= (1, 6):
            authentication_form = functional.curry(forms.Login)
        else:
            authentication_form = functional.curry(forms.Login, request)
    else:
        authentication_form = functional.curry(forms.Login, initial=initial)

    if request.method == "POST":
        form = authentication_form(request, data=request.POST)
        if form.is_valid():
            django_auth_login(request, form.get_user())

    else:
        form = authentication_form(request)


    if request.user.is_authenticated():
        print 'user.is_authenticated'
        auth_user.set_session_from_user(
            request,
            request.user
        )
        regions = dict(forms.Login.get_region_choices())
        region = request.user.endpoint
        region_name = regions.get(region)
        request.session['region_endpoint'] = region
        request.session['region_name'] = region_name
        print u'验证'
        u = request.user
        c = getattr(request, KEYSTONE_CLIENT_ATTR)
        print '-+' * 20
        print type(c)
        print '-' * 20
        d = u.__dict__
        return JsonResponseSuccess(msg='success', user=d)

    context = {
        'form': form,
        'redirect': redirect,
    }
    return TemplateResponse(request, template_name, context)















    # Get our initial region for the form.
    initial = {}
    current_region = request.session.get('region_endpoint', None)
    requested_region = request.GET.get('region', 'http://controller:5000/v3')
    regions = dict(getattr(settings, "AVAILABLE_REGIONS", []))
    if requested_region in regions and requested_region != current_region:
        initial.update({'region': requested_region})

    if request.method == "POST":
        # NOTE(saschpe): Since https://code.djangoproject.com/ticket/15198,
        # the 'request' object is passed directly to AuthenticationForm in
        # django.contrib.auth.views#login:
        if django.VERSION >= (1, 6):
            authentication_form = functional.curry(forms.Login)
        else:
            authentication_form = functional.curry(forms.Login, request)
    else:
        authentication_form = functional.curry(forms.Login, initial=initial)

    if request.method == "POST":
        form = authentication_form(request, data=request.POST)
        if form.is_valid():
            django_auth_login(request, form.get_user())

        else:
            print 3333333, form.errors

    # Set the session data here because django's session key rotation
    # will erase it if we set it earlier.
    if request.user.is_authenticated():
        print 'user.is_authenticated'
        auth_user.set_session_from_user(
            request,
            request.user
        )
        regions = dict(forms.Login.get_region_choices())
        region = request.user.endpoint
        region_name = regions.get(region)
        request.session['region_endpoint'] = region
        request.session['region_name'] = region_name
        print u'验证'
        u = request.user
        lst = [
            'authorized_tenants',
            'available_services_regions',
            'backend',
            'check_password',
            'default_services_region',
            'delete',
            'domain_id',
            'domain_name',
            'enabled',
            'endpoint',
            'get_all_permissions',
            'get_group_permissions',
            'groups',
            'has_a_matching_perm',
            'has_module_perms',
            'has_perm',
            'has_perms',
            'id',
            'is_active',
            'is_anonymous',
            'is_authenticated',
            'is_staff',
            'is_superuser',
            'is_token_expired',
            'last_login',
            'pk',
            'project_id',
            'project_name',
            'roles',
            'save',
            'service_catalog',
            'services_region',
            'set_password',
            'tenant_id',
            'tenant_name',
            'token',
            'user_domain_id',
            'user_domain_name',
            'user_permissions',
            'username'
            ]
        for k in lst:
            print k, ':', getattr(u, k), '\n', '-' * 20
        return HttpResponse('success')
    else:
        return HttpResponseRedirect('/demo/login')
Beispiel #38
0
def login(request, template_name=None, extra_context=None, **kwargs):
    """Logs a user in using the :class:`~openstack_auth.forms.Login` form."""

    # If the user enabled websso and the default redirect
    # redirect to the default websso url
    if (request.method == 'GET' and utils.is_websso_enabled and
            utils.is_websso_default_redirect()):
        protocol = utils.get_websso_default_redirect_protocol()
        region = utils.get_websso_default_redirect_region()
        origin = utils.build_absolute_uri(request, '/auth/websso/')
        url = ('%s/auth/OS-FEDERATION/websso/%s?origin=%s' %
               (region, protocol, origin))
        return shortcuts.redirect(url)

    # If the user enabled websso and selects default protocol
    # from the dropdown, We need to redirect user to the websso url
    if request.method == 'POST':
        auth_type = request.POST.get('auth_type', 'credentials')
        if utils.is_websso_enabled() and auth_type != 'credentials':
            region_id = request.POST.get('region')
            auth_url = getattr(settings, 'WEBSSO_KEYSTONE_URL',
                               forms.get_region_endpoint(region_id))
            url = utils.get_websso_url(request, auth_url, auth_type)
            return shortcuts.redirect(url)

    if not request.is_ajax():
        # If the user is already authenticated, redirect them to the
        # dashboard straight away, unless the 'next' parameter is set as it
        # usually indicates requesting access to a page that requires different
        # permissions.
        if (request.user.is_authenticated and
                auth.REDIRECT_FIELD_NAME not in request.GET and
                auth.REDIRECT_FIELD_NAME not in request.POST):
            return shortcuts.redirect(settings.LOGIN_REDIRECT_URL)

    # Get our initial region for the form.
    initial = {}
    current_region = request.session.get('region_endpoint', None)
    requested_region = request.GET.get('region', None)
    regions = dict(getattr(settings, "AVAILABLE_REGIONS", []))
    if requested_region in regions and requested_region != current_region:
        initial.update({'region': requested_region})

    if request.method == "POST":
        form = functional.curry(forms.Login)
    else:
        form = functional.curry(forms.Login, initial=initial)

    if extra_context is None:
        extra_context = {'redirect_field_name': auth.REDIRECT_FIELD_NAME}

    extra_context['csrf_failure'] = request.GET.get('csrf_failure')

    choices = getattr(settings, 'WEBSSO_CHOICES', ())
    extra_context['show_sso_opts'] = (utils.is_websso_enabled() and
                                      len(choices) > 1)

    if not template_name:
        if request.is_ajax():
            template_name = 'auth/_login.html'
            extra_context['hide'] = True
        else:
            template_name = 'auth/login.html'

    res = django_auth_views.login(request,
                                  template_name=template_name,
                                  authentication_form=form,
                                  extra_context=extra_context,
                                  **kwargs)
    # Save the region in the cookie, this is used as the default
    # selected region next time the Login form loads.
    if request.method == "POST":
        utils.set_response_cookie(res, 'login_region',
                                  request.POST.get('region', ''))
        utils.set_response_cookie(res, 'login_domain',
                                  request.POST.get('domain', ''))

    # Set the session data here because django's session key rotation
    # will erase it if we set it earlier.
    if request.user.is_authenticated:
        auth_user.set_session_from_user(request, request.user)
        regions = dict(forms.Login.get_region_choices())
        region = request.user.endpoint
        login_region = request.POST.get('region')
        region_name = regions.get(login_region)
        request.session['region_endpoint'] = region
        request.session['region_name'] = region_name
        expiration_time = request.user.time_until_expiration()
        threshold_days = getattr(
            settings, 'PASSWORD_EXPIRES_WARNING_THRESHOLD_DAYS', -1)
        if expiration_time is not None and \
                expiration_time.days <= threshold_days:
            expiration_time = str(expiration_time).rsplit(':', 1)[0]
            msg = (_('Please consider changing your password, it will expire'
                     ' in %s minutes') %
                   expiration_time).replace(':', ' Hours and ')
            messages.warning(request, msg)
    return res
Beispiel #39
0
def switch_keystone_provider(request, keystone_provider=None,
                             redirect_field_name=auth.REDIRECT_FIELD_NAME):
    """Switches the user's keystone provider using K2K Federation

    If keystone_provider is given then we switch the user to
    the keystone provider using K2K federation. Otherwise if keystone_provider
    is None then we switch the user back to the Identity Provider Keystone
    which a non federated token auth will be used.
    """
    base_token = request.session.get('k2k_base_unscoped_token', None)
    k2k_auth_url = request.session.get('k2k_auth_url', None)
    keystone_providers = request.session.get('keystone_providers', None)
    recent_project = request.COOKIES.get('recent_project')

    if not base_token or not k2k_auth_url:
        msg = _('K2K Federation not setup for this session')
        raise exceptions.KeystoneAuthException(msg)

    redirect_to = request.GET.get(redirect_field_name, '')
    if not is_safe_url(url=redirect_to, host=request.get_host()):
        redirect_to = settings.LOGIN_REDIRECT_URL

    unscoped_auth_ref = None
    keystone_idp_id = getattr(
        settings, 'KEYSTONE_PROVIDER_IDP_ID', 'localkeystone')

    if keystone_provider == keystone_idp_id:
        current_plugin = plugin.TokenPlugin()
        unscoped_auth = current_plugin.get_plugin(auth_url=k2k_auth_url,
                                                  token=base_token)
    else:
        # Switch to service provider using K2K federation
        plugins = [plugin.TokenPlugin()]
        current_plugin = plugin.K2KAuthPlugin()

        unscoped_auth = current_plugin.get_plugin(
            auth_url=k2k_auth_url, service_provider=keystone_provider,
            plugins=plugins, token=base_token, recent_project=recent_project)

    try:
        # Switch to identity provider using token auth
        unscoped_auth_ref = current_plugin.get_access_info(unscoped_auth)
    except exceptions.KeystoneAuthException as exc:
        msg = 'Switching to Keystone Provider %s has failed. %s' \
              % (keystone_provider, (six.text_type(exc)))
        messages.error(request, msg)

    if unscoped_auth_ref:
        try:
            request.user = auth.authenticate(
                request=request, auth_url=unscoped_auth.auth_url,
                token=unscoped_auth_ref.auth_token)
        except exceptions.KeystoneAuthException as exc:
            msg = 'Keystone provider switch failed: %s' % six.text_type(exc)
            res = django_http.HttpResponseRedirect(settings.LOGIN_URL)
            res.set_cookie('logout_reason', msg, max_age=10)
            return res
        auth.login(request, request.user)
        auth_user.set_session_from_user(request, request.user)
        request.session['keystone_provider_id'] = keystone_provider
        request.session['keystone_providers'] = keystone_providers
        request.session['k2k_base_unscoped_token'] = base_token
        request.session['k2k_auth_url'] = k2k_auth_url
        message = (
            _('Switch to Keystone Provider "%(keystone_provider)s"'
              'successful.') % {'keystone_provider': keystone_provider})
        messages.success(request, message)

    response = shortcuts.redirect(redirect_to)
    return response
def login(request, extra_context=None, **kwargs):
    redirect = request.GET.get(
        'redirect', request.POST.get('redirect', kwargs.get('redirect', '')))
    template_name = kwargs.get('template', 'auth/login.html')

    if (request.user.is_authenticated()
            and auth.REDIRECT_FIELD_NAME not in request.GET
            and auth.REDIRECT_FIELD_NAME not in request.POST):
        return shortcuts.redirect(settings.LOGIN_REDIRECT_URL)

    initial = {}
    current_region = request.session.get('region_endpoint', None)
    requested_region = request.GET.get('region', None)
    regions = dict(getattr(settings, "AVAILABLE_REGIONS", []))
    if requested_region in regions and requested_region != current_region:
        initial.update({'region': requested_region})

    if request.method == "POST":
        if django.VERSION >= (1, 6):
            authentication_form = functional.curry(forms.Login)
        else:
            authentication_form = functional.curry(forms.Login, request)
    else:
        authentication_form = functional.curry(forms.Login, initial=initial)

    if request.method == "POST":
        form = authentication_form(request, data=request.POST)
        if form.is_valid():
            django_auth_login(request, form.get_user())

    else:
        form = authentication_form(request)

    if request.user.is_authenticated():
        print 'user.is_authenticated'
        auth_user.set_session_from_user(request, request.user)
        regions = dict(forms.Login.get_region_choices())
        region = request.user.endpoint
        region_name = regions.get(region)
        request.session['region_endpoint'] = region
        request.session['region_name'] = region_name
        print u'验证'
        u = request.user
        c = getattr(request, KEYSTONE_CLIENT_ATTR)
        print '-+' * 20
        print type(c)
        print '-' * 20
        d = u.__dict__
        return JsonResponseSuccess(msg='success', user=d)

    context = {
        'form': form,
        'redirect': redirect,
    }
    return TemplateResponse(request, template_name, context)

    # Get our initial region for the form.
    initial = {}
    current_region = request.session.get('region_endpoint', None)
    requested_region = request.GET.get('region', 'http://controller:5000/v3')
    regions = dict(getattr(settings, "AVAILABLE_REGIONS", []))
    if requested_region in regions and requested_region != current_region:
        initial.update({'region': requested_region})

    if request.method == "POST":
        # NOTE(saschpe): Since https://code.djangoproject.com/ticket/15198,
        # the 'request' object is passed directly to AuthenticationForm in
        # django.contrib.auth.views#login:
        if django.VERSION >= (1, 6):
            authentication_form = functional.curry(forms.Login)
        else:
            authentication_form = functional.curry(forms.Login, request)
    else:
        authentication_form = functional.curry(forms.Login, initial=initial)

    if request.method == "POST":
        form = authentication_form(request, data=request.POST)
        if form.is_valid():
            django_auth_login(request, form.get_user())

        else:
            print 3333333, form.errors

    # Set the session data here because django's session key rotation
    # will erase it if we set it earlier.
    if request.user.is_authenticated():
        print 'user.is_authenticated'
        auth_user.set_session_from_user(request, request.user)
        regions = dict(forms.Login.get_region_choices())
        region = request.user.endpoint
        region_name = regions.get(region)
        request.session['region_endpoint'] = region
        request.session['region_name'] = region_name
        print u'验证'
        u = request.user
        lst = [
            'authorized_tenants', 'available_services_regions', 'backend',
            'check_password', 'default_services_region', 'delete', 'domain_id',
            'domain_name', 'enabled', 'endpoint', 'get_all_permissions',
            'get_group_permissions', 'groups', 'has_a_matching_perm',
            'has_module_perms', 'has_perm', 'has_perms', 'id', 'is_active',
            'is_anonymous', 'is_authenticated', 'is_staff', 'is_superuser',
            'is_token_expired', 'last_login', 'pk', 'project_id',
            'project_name', 'roles', 'save', 'service_catalog',
            'services_region', 'set_password', 'tenant_id', 'tenant_name',
            'token', 'user_domain_id', 'user_domain_name', 'user_permissions',
            'username'
        ]
        for k in lst:
            print k, ':', getattr(u, k), '\n', '-' * 20
        return HttpResponse('success')
    else:
        return HttpResponseRedirect('/demo/login')
Beispiel #41
0
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
Beispiel #42
0
def login(request, template_name=None, extra_context=None, **kwargs):
    """Logs a user in using the :class:`~openstack_auth.forms.Login` form."""

    # If the user enabled websso and selects default protocol
    # from the dropdown, We need to redirect user to the websso url
    if request.method == "POST":
        protocol = request.POST.get("auth_type", "credentials")
        if utils.is_websso_enabled() and protocol != "credentials":
            region = request.POST.get("region")
            origin = request.build_absolute_uri("/auth/websso/")
            url = "%s/auth/OS-FEDERATION/websso/%s?origin=%s" % (region, protocol, origin)
            return shortcuts.redirect(url)

    if not request.is_ajax():
        # If the user is already authenticated, redirect them to the
        # dashboard straight away, unless the 'next' parameter is set as it
        # usually indicates requesting access to a page that requires different
        # permissions.
        if (
            request.user.is_authenticated()
            and auth.REDIRECT_FIELD_NAME not in request.GET
            and auth.REDIRECT_FIELD_NAME not in request.POST
        ):
            return shortcuts.redirect(settings.LOGIN_REDIRECT_URL)

    # Get our initial region for the form.
    initial = {}
    current_region = request.session.get("region_endpoint", None)
    requested_region = request.GET.get("region", None)
    regions = dict(getattr(settings, "AVAILABLE_REGIONS", []))
    if requested_region in regions and requested_region != current_region:
        initial.update({"region": requested_region})

    if request.method == "POST":
        # NOTE(saschpe): Since https://code.djangoproject.com/ticket/15198,
        # the 'request' object is passed directly to AuthenticationForm in
        # django.contrib.auth.views#login:
        if django.VERSION >= (1, 6):
            form = functional.curry(forms.Login)
        else:
            form = functional.curry(forms.Login, request)
    else:
        form = functional.curry(forms.Login, initial=initial)

    if extra_context is None:
        extra_context = {"redirect_field_name": auth.REDIRECT_FIELD_NAME}

    if not template_name:
        if request.is_ajax():
            template_name = "auth/_login.html"
            extra_context["hide"] = True
        else:
            template_name = "auth/login.html"

    res = django_auth_views.login(
        request, template_name=template_name, authentication_form=form, extra_context=extra_context, **kwargs
    )
    # Save the region in the cookie, this is used as the default
    # selected region next time the Login form loads.
    if request.method == "POST":
        utils.set_response_cookie(res, "login_region", request.POST.get("region", ""))

    # Set the session data here because django's session key rotation
    # will erase it if we set it earlier.
    if request.user.is_authenticated():
        auth_user.set_session_from_user(request, request.user)
        regions = dict(forms.Login.get_region_choices())
        region = request.user.endpoint
        region_name = regions.get(region)
        request.session["region_endpoint"] = region
        request.session["region_name"] = region_name
        request.session["last_activity"] = int(time.time())
    return res
Beispiel #43
0
def login(request):
    """Logs a user in using the :class:`~openstack_auth.forms.Login` form."""

    # If the user enabled websso and the default redirect
    # redirect to the default websso url
    if (request.method == 'GET' and settings.WEBSSO_ENABLED
            and settings.WEBSSO_DEFAULT_REDIRECT):
        protocol = settings.WEBSSO_DEFAULT_REDIRECT_PROTOCOL
        region = settings.WEBSSO_DEFAULT_REDIRECT_REGION
        origin = utils.build_absolute_uri(request, '/auth/websso/')
        url = ('%s/auth/OS-FEDERATION/websso/%s?origin=%s' %
               (region, protocol, origin))
        return shortcuts.redirect(url)

    # If the user enabled websso and selects default protocol
    # from the dropdown, We need to redirect user to the websso url
    if request.method == 'POST':
        auth_type = request.POST.get('auth_type', 'credentials')
        request.session['auth_type'] = auth_type
        if settings.WEBSSO_ENABLED and auth_type != 'credentials':
            region_id = request.POST.get('region')
            auth_url = getattr(settings, 'WEBSSO_KEYSTONE_URL', None)
            if auth_url is None:
                auth_url = forms.get_region_endpoint(region_id)
            url = utils.get_websso_url(request, auth_url, auth_type)
            return shortcuts.redirect(url)

    if not request.is_ajax():
        # If the user is already authenticated, redirect them to the
        # dashboard straight away, unless the 'next' parameter is set as it
        # usually indicates requesting access to a page that requires different
        # permissions.
        if (request.user.is_authenticated
                and auth.REDIRECT_FIELD_NAME not in request.GET
                and auth.REDIRECT_FIELD_NAME not in request.POST):
            return shortcuts.redirect(settings.LOGIN_REDIRECT_URL)

    # Get our initial region for the form.
    initial = {}
    current_region = request.session.get('region_endpoint', None)
    requested_region = request.GET.get('region', None)
    regions = dict(settings.AVAILABLE_REGIONS)
    if requested_region in regions and requested_region != current_region:
        initial.update({'region': requested_region})

    if request.method == "POST":
        form = functools.partial(forms.Login)
    else:
        form = functools.partial(forms.Login, initial=initial)

    choices = settings.WEBSSO_CHOICES
    reason = get_csrf_reason(request.GET.get('csrf_failure'))
    logout_reason = request.COOKIES.get(
        'logout_reason', '').encode('ascii').decode('unicode_escape')
    logout_status = request.COOKIES.get('logout_status')
    extra_context = {
        'redirect_field_name': auth.REDIRECT_FIELD_NAME,
        'csrf_failure': reason,
        'show_sso_opts': settings.WEBSSO_ENABLED and len(choices) > 1,
        'classes': {
            'value': '',
            'single_value': '',
            'label': '',
        },
        'logout_reason': logout_reason,
        'logout_status': logout_status,
    }

    if request.is_ajax():
        template_name = 'auth/_login.html'
        extra_context['hide'] = True
    else:
        template_name = 'auth/login.html'

    try:
        res = django_auth_views.LoginView.as_view(
            template_name=template_name,
            redirect_field_name=auth.REDIRECT_FIELD_NAME,
            form_class=form,
            extra_context=extra_context,
            redirect_authenticated_user=False)(request)
    except exceptions.KeystonePassExpiredException as exc:
        res = django_http.HttpResponseRedirect(
            reverse('password', args=[exc.user_id]))
        msg = _("Your password has expired. Please set a new password.")
        set_logout_reason(res, msg)

    # Save the region in the cookie, this is used as the default
    # selected region next time the Login form loads.
    if request.method == "POST":
        utils.set_response_cookie(res, 'login_region',
                                  request.POST.get('region', ''))
        utils.set_response_cookie(res, 'login_domain',
                                  request.POST.get('domain', ''))

    # Set the session data here because django's session key rotation
    # will erase it if we set it earlier.
    if request.user.is_authenticated:
        auth_user.set_session_from_user(request, request.user)
        regions = dict(forms.get_region_choices())
        region = request.user.endpoint
        login_region = request.POST.get('region')
        region_name = regions.get(login_region)
        request.session['region_endpoint'] = region
        request.session['region_name'] = region_name
        expiration_time = request.user.time_until_expiration()
        threshold_days = settings.PASSWORD_EXPIRES_WARNING_THRESHOLD_DAYS
        if (expiration_time is not None
                and expiration_time.days <= threshold_days
                and expiration_time > datetime.timedelta(0)):
            expiration_time = str(expiration_time).rsplit(':', 1)[0]
            msg = (_('Please consider changing your password, it will expire'
                     ' in %s minutes') % expiration_time).replace(
                         ':', ' Hours and ')
            messages.warning(request, msg)
    return res
Beispiel #44
0
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