Example #1
0
def validate_user(user):
    # Check if the user is active.
    if not user.is_active:
        raise faults.Unauthorized('User inactive')

    # Check if the token has expired.
    if user.token_expired():
        raise faults.Unauthorized('Authentication expired')

    # Check if the user has accepted the terms.
    if not user.signed_terms:
        raise faults.Unauthorized('Pending approval terms')
Example #2
0
    def wrapper(request, *args, **kwargs):
        try:
            token = request.x_auth_token
        except AttributeError:
            raise faults.Unauthorized("No authentication token")

        if not token:
            raise faults.Unauthorized("Invalid X-Auth-Token")

        try:
            user = AstakosUser.objects.get(auth_token=token)
        except AstakosUser.DoesNotExist:
            raise faults.Unauthorized('Invalid X-Auth-Token')

        validate_user(user)

        request.user = user
        return func(request, *args, **kwargs)
Example #3
0
    def wrapper(request, *args, **kwargs):
        try:
            token = request.x_auth_token
        except AttributeError:
            raise faults.Unauthorized("No authentication token")

        if not token:
            raise faults.Unauthorized("Invalid X-Auth-Token")
        try:
            component = Component.objects.get(auth_token=token)
        except Component.DoesNotExist:
            raise faults.Unauthorized("Invalid X-Auth-Token")

        # Check if the token has expired
        expiration_date = component.auth_token_expires
        if expiration_date:
            expires_at = mktime(expiration_date.timetuple())
            if time() > expires_at:
                raise faults.Unauthorized("Authentication expired")

        request.component_instance = component
        return func(request, *args, **kwargs)
Example #4
0
        def wrapper(request, *args, **kwargs):
            try:
                # Get the requested serialization format
                serialization = get_serialization(
                    request, format_allowed, serializations[0])

                # If guessed serialization is not supported, fallback to
                # the default serialization or return an API error in case
                # strict serialization flag is set.
                if not serialization in serializations:
                    if strict_serlization:
                        raise faults.BadRequest(("%s serialization not "
                                                "supported") % serialization)
                    serialization = serializations[0]
                request.serialization = serialization

                # Check HTTP method
                if http_method and request.method != http_method:
                    raise faults.BadRequest("Method not allowed")

                # Get authentication token
                request.x_auth_token = None
                if token_required or user_required:
                    token = get_token(request)
                    if not token:
                        msg = "Access denied. No authentication token"
                        raise faults.Unauthorized(msg)
                    request.x_auth_token = token

                # Authenticate
                if user_required:
                    assert(token_required), "Can not get user without token"
                    astakos = astakos_url or settings.ASTAKOS_BASE_URL
                    astakos = AstakosClient(astakos,
                                            use_pool=True,
                                            retry=2,
                                            logger=logger)
                    user_info = astakos.get_user_info(token)
                    request.user_uniq = user_info["uuid"]
                    request.user = user_info

                # Get the response object
                response = func(request, *args, **kwargs)

                # Fill in response variables
                update_response_headers(request, response)
                return response
            except faults.Fault, fault:
                if fault.code >= 500:
                    logger.exception("API ERROR")
                return render_fault(request, fault)
Example #5
0
        def wrapper(request, *args, **kwargs):
            try:
                # Explicitly set request encoding to UTF-8 instead of relying
                # to the DEFAULT_CHARSET setting. See:
                # https://docs.djangoproject.com/en/1.4/ref/unicode/#form-submission # flake8: noqa
                request.encoding = 'utf-8'

                # Get the requested serialization format
                serialization = get_serialization(request, format_allowed,
                                                  serializations[0])

                # If guessed serialization is not supported, fallback to
                # the default serialization or return an API error in case
                # strict serialization flag is set.
                if not serialization in serializations:
                    if strict_serlization:
                        raise faults.BadRequest(("%s serialization not "
                                                 "supported") % serialization)
                    serialization = serializations[0]
                request.serialization = serialization

                # Check HTTP method
                if http_method and request.method != http_method:
                    raise faults.NotAllowed("Method not allowed",
                                            allowed_methods=[http_method])

                # Get authentication token
                request.x_auth_token = None
                if token_required or user_required:
                    token = get_token(request)
                    if not token:
                        msg = "Access denied. No authentication token"
                        raise faults.Unauthorized(msg)
                    request.x_auth_token = token

                # Authenticate
                if user_required:
                    assert (token_required), "Can not get user without token"
                    client_ip = get_client_ip(request)
                    user_info = retrieve_user(token,
                                              astakos_auth_url,
                                              logger=logger,
                                              client_ip=client_ip)
                    _user_access = user_info["access"]["user"]
                    request.user_uniq = _user_access["id"]
                    request.user_projects = _user_access.get("projects", None)
                    request.user = user_info

                # Get the response object
                response = func(request, *args, **kwargs)

                # Fill in response variables
                update_response_headers(request, response)
                return response
            except faults.Fault as fault:
                if fault.code >= 500:
                    django_logger.error("Unexpected API Error: %s",
                                        request.path,
                                        exc_info=sys.exc_info(),
                                        extra={
                                            "status_code": fault.code,
                                            "request": request
                                        })
                return render_fault(request, fault)
            except AstakosClientException as err:
                fault = faults.Fault(message=err.message,
                                     details=err.details,
                                     code=err.status)
                if fault.code >= 500:
                    django_logger.error("Unexpected AstakosClient Error: %s",
                                        request.path,
                                        exc_info=sys.exc_info(),
                                        extra={
                                            "status_code": fault.code,
                                            "request": request
                                        })
                return render_fault(request, fault)
            except:
                django_logger.error("Internal Server Error: %s",
                                    request.path,
                                    exc_info=sys.exc_info(),
                                    extra={
                                        "status_code": '500',
                                        "request": request
                                    })
                fault = faults.InternalServerError("Unexpected error")
                return render_fault(request, fault)
Example #6
0
def authenticate(request):
    try:
        content_length = get_content_length(request)
    except faults.LengthRequired:
        content_length = None

    public_mode = True if not content_length else False

    d = defaultdict(dict)
    if not public_mode:
        req = utils.get_json_body(request)

        uuid = None
        try:
            token_id = req['auth']['token']['id']
        except KeyError:
            try:
                token_id = req['auth']['passwordCredentials']['password']
                uuid = req['auth']['passwordCredentials']['username']
            except KeyError:
                raise faults.BadRequest(
                    'Malformed request: missing credentials')

        tenant = req['auth'].get('tenantName')

        if token_id is None:
            raise faults.BadRequest('Malformed request: missing token')

        try:
            user = AstakosUser.objects.get(auth_token=token_id)
        except AstakosUser.DoesNotExist:
            raise faults.Unauthorized('Invalid token')

        validate_user(user)

        if uuid is not None:
            if user.uuid != uuid:
                raise faults.Unauthorized('Invalid credentials')

        if tenant:
            if user.uuid != tenant:
                raise faults.BadRequest('Not conforming tenantName')

        user_projects = user.project_set.filter(projectmembership__state__in=\
            ProjectMembership.ACCEPTED_STATES).values_list("uuid", flat=True)

        d["access"]["token"] = {
            "id": user.auth_token,
            "expires": utils.isoformat(user.auth_token_expires),
            "tenant": {
                "id": user.uuid,
                "name": user.realname
            }
        }
        d["access"]["user"] = {
            "id":
            user.uuid,
            'name':
            user.realname,
            "roles": [
                dict(id=str(g['id']), name=g['name'])
                for g in user.groups.values('id', 'name')
            ],
            "roles_links": [],
            "projects":
            list(user_projects),
        }

    d["access"]["serviceCatalog"] = get_endpoints()

    if request.serialization == 'xml':
        return xml_response({'d': d}, 'api/access.xml')
    else:
        return json_response(d)