<fim-prefix>ge governing permissions and limitations
#    under the License.
"""
Classes and methods related to user handling in Horizon.
"""

import logging

from django.utils.translation import ugettext as _

from horizon import api
from horizon import exceptions


LOG = logging.getLogger(__name__)


def get_user_from_request(request):
    """ Checks the current session and returns a :class:`~horizon.users.User`.

    If the session contains user data the User will be treated as
    authenticated and the :class:`~horizon.users.User` will have all
    its attributes set.

    If not, the :class:`~horizon.users.User` will have no attributes set.

    If the session contains invalid data,
    :exc:`~horizon.exceptions.NotAuthorized` will be raised.
    """
    if 'user_id' not in request.session:
        return User()
    try:
        return User(id=request.session['user_id'],
                    token=request.session['token'],
                    user=request.session['user_name'],
                    tenant_id=request.session['tenant_id'],
                    tenant_name=request.session['tenant'],
                    service_catalog=request.session['serviceCatalog'],
                    roles=request.session['roles'],
                    request=request)
    except KeyError:
        # If any of those keys are missing from the session it is
        # overwhelmingly likely that we're dealing with an outdated session.
        LOG.exception("Error while creating User from session.")
        # BUG: NVD-CWE-Other Other
        # request.session.clear()
        # FIXED: 
 <fim-middle>       request.user_logout()
        raise exceptions.NotAuthorized(_("Your session has expired. "
                                         "Please log in again."))


class LazyUser(object):
    def __<fix-suffix>get__(self, request, obj_type=None):
        if not hasattr(request, '_cached_user'):
            request._cached_user = get_user_from_request(request)
        return request._cached_user


class User(object):
    """ The main user class which Horizon expects.

    .. attribute:: token

        The id of the Keystone token associated with the current user/tenant.

    .. attribute:: username

        The name of the current user.

    .. attribute:: tenant_id

        The id of the Keystone tenant for the current user/token.

    .. attribute:: tenant_name

        The name of the Keystone tenant for the current user/token.

    .. attribute:: service_catalog

        The ``ServiceCatalog`` data returned by Keystone.

    .. attribute:: roles

        A list of dictionaries containing role names and ids as returned
        by Keystone.

    .. attribute:: admin

        Boolean value indicating whether or not this user has admin
        privileges. Internally mapped to :meth:`horizon.u<|endoftext|>