<commit_before>from pylons import request, response, session, tmpl_context as c
from pylons.controllers.util import abort, redirect_to
from pylons.controllers import WSGIController
from pylons.templating import render_mako as render

import re, base64, urllib, uuid, inspect
from core import Auth, SwordError, AuthException, DepositRequest, DeleteRequest
from negotiator import ContentNegotiator, AcceptParameters, ContentType
from spec import Errors, HttpHeaders, ValidationException


import logging
ssslog = logging.getLogger(__name__)

# create the global configuration and import the implementation classes
from sss import Configuration
config = Configuration()
Authenticator = config.get_authenticator_implementation()
SwordServer = config.get_server_implementation()
WebInterface = config.get_webui_implementation()

__controller__ = "SwordController"

HEADER_MAP = {
    HttpHeaders.in_progress : "HTTP_IN_PROGRESS",
    HttpHeaders.metadata_relevant : "HTTP_METADATA_RELEVANT",
    HttpHeaders.on_behalf_of : "HTTP_ON_BEHALF_OF"
}

class SwordController(WSGIController):

    # WSGI Controller Stuff
    #######################

    def __call__(self, environ, start_response):
        """Invoke the Controller"""
        # WSGIController.__call__ dispatches to the Controller method
        # the request is routed to. This routing information is
        # available in environ['pylons.routes_dict']
        return WSGIController.__call__(self, environ, start_response)

    # Generically useful methods
    ############################

    def authenticate(self):
        # first check to see if there's a repoze.who auth
        identity = request.environ.get("repoze.who.identity")
        if identity is not None:
            # we have authenticated with repoze.who already
            return self.repoze_who_authenticate()
        else:
            # try and do HTTP basic
            return self.http_basic_authenticate()
    
    def repoze_who_authenticate(self):
          ssslog.debug("Authentication handled by repoze.who")
          
          # get the auth details
          identity = request.environ.get("repoze.who.identity")
          obo = request.environ.get(HEADER_MAP[HttpHeaders.on_behalf_of])
          
          ssslog.info("Authentication details: " + str(identity["repoze.who.userid"]) + "; On Behalf Of: " + str(obo))
          
          authenticator = Authenticator(config)
          try:
              auth = authenticator.repoze_who_authenticate(identity, obo)
          except AuthException as e:
            if e.authentication_failed:
                raise SwordError(status=401, empty=True)
            elif e.target_owner_unknown:
                raise SwordError(error_uri=Errors.target_owner_unknown, msg="unknown user " + str(obo) + " as on behalf of user")
          
          return auth

    def http_basic_authenticate(self):
        ssslog.debug("Attempting HTTP Basic Authentication")
        
        # extract the appropriate HTTP headers
        auth_header = request.environ.get('HTTP_AUTHORIZATION')
        obo = request.environ.get(HEADER_MAP[HttpHeaders.on_behalf_of])

        # if we're not supplied with an auth header, bounce
        if auth_header is None:
            ssslog.info("No auth header supplied; will return 401 with SSS realm")
            response.headers['WWW-Authenticate'] = 'Basic realm="SSS"'
            raise SwordError(status=401, empty=True)
        
        # deconstruct the BASIC auth header
        try:
            auth_header = re.sub('^Basic ', '', auth_header)
            username, password = base64.decodestring(auth_header).split(':')
            ssslog.debug("successfully interpreted Basic Auth header")
        except Exception as e:
            # could be exceptions in either decoding the header or in doing a split
            ssslog.error("unable to interpret authentication header: " + auth_header)
            raise SwordError(error_uri=Errors.bad_request, msg="unable to interpret authentication header")
        
        ssslog.info("Authentication details: " + str(username) + ":[**password**]; On Behalf Of: " + str(obo))

        authenticator = Authenticator(config)
        try:
            auth = authenticator.basic_authenticate(username, password, obo)
        except AuthException as e:
            if e.authentication_failed:
                raise SwordError(status=401, empty=True)
            elif e.target_owner_unknown:
                raise SwordError(error_uri=Errors.target_owner_unknown, msg="unknown user " + str(obo) + " as on behalf of user")
        
        return auth
    
    def manage_error(self, sword_error):
        response.status_int = sword_error.status
        ssslog.info("Returning error (" + str(sword_error.status) + ") - " + str(sword_error.error_uri))
        if not sword_error.empty:
            response.content_type = "text/xml"
            return sword_error.error_document
        return

    def _map_webpy_headers(self, headers):
        return dict([(c[0][5:].replace("_", "-") if c[0].startswith("HTTP_") else c[0].replace("_", "-"), c[1]) for c in headers.items()])<commit_msg>add minor logging improvements<commit_after>from pylons import request, response, session, tmpl_context as c
from pylons.controllers.util import abort, redirect_to
from pylons.controllers import WSGIController
from pylons.templating import render_mako as render

import re, base64, urllib, uuid, inspect
from core import Auth, SwordError, AuthException, DepositRequest, DeleteRequest
from negotiator import ContentNegotiator, AcceptParameters, ContentType
from spec import Errors, HttpHeaders, ValidationException


import logging
ssslog = logging.getLogger(__name__)

# create the global configuration and import the implementation classes
from sss import Configuration
config = Configuration()
Authenticator = config.get_authenticator_implementation()
SwordServer = config.get_server_implementation()
WebInterface = config.get_webui_implementation()

__controller__ = "SwordController"

HEADER_MAP = {
    HttpHeaders.in_progress : "HTTP_IN_PROGRESS",
    HttpHeaders.metadata_relevant : "HTTP_METADATA_RELEVANT",
    HttpHeaders.on_behalf_of : "HTTP_ON_BEHALF_OF"
}

class SwordController(WSGIController):

    # WSGI Controller Stuff
    #######################

    def __call__(self, environ, start_response):
        """Invoke the Controller"""
        # WSGIController.__call__ dispatches to the Controller method
        # the request is routed to. This routing information is
        # available in environ['pylons.routes_dict']
        return WSGIController.__call__(self, environ, start_response)

    # Generically useful methods
    ############################

    def authenticate(self):
        # first check to see if there's a repoze.who auth
        identity = request.environ.get("repoze.who.identity")
        if identity is not None:
            # we have authenticated with repoze.who already
            return self.repoze_who_authenticate()
        else:
            # try and do HTTP basic
            return self.http_basic_authenticate()
    
    def repoze_who_authenticate(self):
          ssslog.debug("Authentication handled by repoze.who")
          
          # get the auth details
          identity = request.environ.get("repoze.who.identity")
          obo = request.environ.get(HEADER_MAP[HttpHeaders.on_behalf_of])
          
          ssslog.info("Authentication details: " + str(identity["repoze.who.userid"]) + "; On Behalf Of: " + str(obo))
          
          authenticator = Authenticator(config)
          try:
              auth = authenticator.repoze_who_authenticate(identity, obo)
          except AuthException as e:
            if e.authentication_failed:
                raise SwordError(status=401, empty=True)
            elif e.target_owner_unknown:
                raise SwordError(error_uri=Errors.target_owner_unknown, msg="unknown user " + str(obo) + " as on behalf of user")
          
          return auth

    def http_basic_authenticate(self):
        ssslog.debug("Attempting HTTP Basic Authentication")
        
        # extract the appropriate HTTP headers
        auth_header = request.environ.get('HTTP_AUTHORIZATION')
        obo = request.environ.get(HEADER_MAP[HttpHeaders.on_behalf_of])

        # if we're not supplied with an auth header, bounce
        if auth_header is None:
            ssslog.info("No auth header supplied; will return 401 with SSS realm")
            response.headers['WWW-Authenticate'] = 'Basic realm="SSS"'
            raise SwordError(status=401, empty=True)
        
        # deconstruct the BASIC auth header
        try:
            auth_header = re.sub('^Basic ', '', auth_header)
            username, password = base64.decodestring(auth_header).split(':')
            ssslog.debug("successfully interpreted Basic Auth header")
        except Exception as e:
            # could be exceptions in either decoding the header or in doing a split
            ssslog.error("unable to interpret authentication header: " + auth_header)
            raise SwordError(error_uri=Errors.bad_request, msg="unable to interpret authentication header")
        
        ssslog.info("Authentication details: " + str(username) + ":[**password**]; On Behalf Of: " + str(obo))

        authenticator = Authenticator(config)
        try:
            auth = authenticator.basic_authenticate(username, password, obo)
        except AuthException as e:
            if e.authentication_failed:
                raise SwordError(status=401, empty=True)
            elif e.target_owner_unknown:
                raise SwordError(error_uri=Errors.target_owner_unknown, msg="unknown user " + str(obo) + " as on behalf of user")
        
        return auth
    
    def manage_error(self, sword_error):
        response.status_int = sword_error.status
        ssslog.info("Returning error (" + str(sword_error.status) + ") - " + str(sword_error.error_uri))
        if not sword_error.empty:
            ssslog.debug("Returning error document: " + sword_error.error_document)
            response.content_type = "text/xml"
            return sword_error.error_document
        ssslog.debug("Returning empty body in error response")
        return

    def _map_webpy_headers(self, headers):
        return dict([(c[0][5:].replace("_", "-") if c[0].startswith("HTTP_") else c[0].replace("_", "-"), c[1]) for c in headers.items()])
{'fraction_non_alphanumeric': 0.09516067329762816, 'fraction_numerical': 0.004016832440703902, 'mean_word_length': 2.956488838441165, 'pattern_counts': {'":': 2, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 2}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6177084', 'n_tokens_mistral': 2927, 'n_tokens_neox': 2814, 'n_words': 742}