<commit_before>from moksha.connector import IConnector, ICall, IQuery, ISearch, ParamFilter
from pylons import config
from fedora.client import ProxyClient
from beaker.cache import Cache
from moksha.connector.utils import DateTimeDisplay

USERINFO_CACHE_TIMEOUT= 60 * 5 # s * m = 5 minutes
fas_cache = Cache('fas_connector_cache')

class FasConnector(IConnector, ICall, ISearch, IQuery):
    def __init__(self, environ=None, request=None):
        super(FasConnector, self).__init__(environ, request)
        self._fas_client = ProxyClient(self._base_url,
                                       session_as_cookie=False,
                                       insecure = self._insecure)

    # IConnector
    @classmethod
    def register(cls):
        cls._base_url = config.get('fedoracommunity.connector.fas.baseurl',
                                   'https://admin.fedoraproject.org/accounts')

        check_certs = config.get('fedora.clients.check_certs', 'True').lower()
        if check_certs in ('false', '0', 'no'):
            insecure = True
        else:
            # fail safe
            insecure = False

        cls._insecure = insecure

        cls.register_query_usermemberships()
        cls.register_query_userinfo()
        cls.register_query_people()
        cls.register_search_people()

    def request_data(self, resource_path, params, _cookies):
        fas_info = self._environ.get('FAS_LOGIN_INFO')

        auth_params={}
        if fas_info:
            session_id = fas_info[0]
            auth_params={'session_id': session_id}

        return self._fas_client.send_request(resource_path,
                                             auth_params = auth_params,
                                             req_params = params)

    def introspect(self):
        # FIXME: return introspection data
        return None

    #ICall
    def call(self, resource_path, params={}, _cookies=None):
        # proxy client only returns structured data so we can pass
        # this off to request_data but we should fix that in ProxyClient
        return self.request_data(resource_path, params, _cookies)

    def request_user_view(self, user):
        view = self.call('user/view', {'username': user})
        if not view:
            return None

        view = view[1]
        extra = {'cla':view['cla'],
                 'admin':view['admin'],
                 'personal':view['personal']
                 }

        view = view['person']
        view.update(extra)
        return view

    def get_user_view(self, user, invalidate=False):
        if not isinstance(user, basestring):
            return None

        key = '_fas_user_info_' + user
        if invalidate:
            fas_cache.remove_value(key)

        info = fas_cache.get_value(key = key ,
                                   createfunc=lambda : self.request_user_view(user),
                                   type="memory",
                                   expiretime=USERINFO_CACHE_TIMEOUT)
        return info

    # ISearch
    @classmethod
    def register_search_people(cls):
        path = cls.register_search_path(
                      'search_people',
                      cls.search_people,
                      primary_key_col = 'username',
                      default_sort_col = 'username',
                      default_sort_order = -1,
                      can_paginate = True)

        path.register_column('username',
                        default_visible = True,
                        can_sort = False,
                        can_filter_wildcards = False)
        path.register_column('human_name',
                        default_visible = True,
                        can_sort = False,
                        can_filter_wildcards = False)

    def search_people(self, search_term):
        result = self.call('user/list',
                           params={'search': '*' + search_term + '*'})
        return result[1]['people']

    # IQuery
    @classmethod
    def register_query_people(cls):
        path = cls.register_path(
                      'query_people',
                      cls.query_people,
                      primary_key_col = 'username',
                      default_sort_col = 'username',
                      default_sort_order = -1,
                      can_paginate = True)

        path.register_column('username',
                        default_visible = True,
                        can_sort = False,
                        can_filter_wildcards = False)
        path.register_column('human_name',
                        default_visible = True,
                        can_sort = False,
                        can_filter_wildcards = False)

        f = ParamFilter()
        f.add_filter('prefix',
                     allow_none = False)

        cls._query_people_filter = f

    def query_people(self, start_row=None,
                           rows_per_page=None,
                           order=-1,
                           sort_col=None,
                           filters = {},
                           **params):

        filters = self._query_people_filter.filter(filters, conn=self)
        f = {}
        p = filters.get('prefix','a').lower()
        p.replace('*', '')
        p += '*'
        f['search'] = p
        result = self.call('user/list',
                           params=f)


        people = result[1]['people']
        return (len(people), people[start_row:rows_per_page + start_row])

    @classmethod
    def register_query_usermemberships(cls):
        path = cls.register_path(
                      'query_usermemberships',
                      cls.query_usermemberships,<commit_msg>Stop passing mutable keyword arguments in the fas connector<commit_after>from moksha.connector import IConnector, ICall, IQuery, ISearch, ParamFilter
from pylons import config
from fedora.client import ProxyClient
from beaker.cache import Cache
from moksha.connector.utils import DateTimeDisplay

USERINFO_CACHE_TIMEOUT= 60 * 5 # s * m = 5 minutes
fas_cache = Cache('fas_connector_cache')

class FasConnector(IConnector, ICall, ISearch, IQuery):
    def __init__(self, environ=None, request=None):
        super(FasConnector, self).__init__(environ, request)
        self._fas_client = ProxyClient(self._base_url,
                                       session_as_cookie=False,
                                       insecure = self._insecure)

    # IConnector
    @classmethod
    def register(cls):
        cls._base_url = config.get('fedoracommunity.connector.fas.baseurl',
                                   'https://admin.fedoraproject.org/accounts')

        check_certs = config.get('fedora.clients.check_certs', 'True').lower()
        if check_certs in ('false', '0', 'no'):
            insecure = True
        else:
            # fail safe
            insecure = False

        cls._insecure = insecure

        cls.register_query_usermemberships()
        cls.register_query_userinfo()
        cls.register_query_people()
        cls.register_search_people()

    def request_data(self, resource_path, params, _cookies):
        fas_info = self._environ.get('FAS_LOGIN_INFO')

        auth_params={}
        if fas_info:
            session_id = fas_info[0]
            auth_params={'session_id': session_id}

        return self._fas_client.send_request(resource_path,
                                             auth_params = auth_params,
                                             req_params = params)

    def introspect(self):
        # FIXME: return introspection data
        return None

    #ICall
    def call(self, resource_path, params=None, _cookies=None):
        # proxy client only returns structured data so we can pass
        # this off to request_data but we should fix that in ProxyClient
        if not params:
            params = {}
        return self.request_data(resource_path, params, _cookies)

    def request_user_view(self, user):
        view = self.call('user/view', {'username': user})
        if not view:
            return None

        view = view[1]
        extra = {'cla':view['cla'],
                 'admin':view['admin'],
                 'personal':view['personal']
                 }

        view = view['person']
        view.update(extra)
        return view

    def get_user_view(self, user, invalidate=False):
        if not isinstance(user, basestring):
            return None

        key = '_fas_user_info_' + user
        if invalidate:
            fas_cache.remove_value(key)

        info = fas_cache.get_value(key = key ,
                                   createfunc=lambda : self.request_user_view(user),
                                   type="memory",
                                   expiretime=USERINFO_CACHE_TIMEOUT)
        return info

    # ISearch
    @classmethod
    def register_search_people(cls):
        path = cls.register_search_path(
                      'search_people',
                      cls.search_people,
                      primary_key_col = 'username',
                      default_sort_col = 'username',
                      default_sort_order = -1,
                      can_paginate = True)

        path.register_column('username',
                        default_visible = True,
                        can_sort = False,
                        can_filter_wildcards = False)
        path.register_column('human_name',
                        default_visible = True,
                        can_sort = False,
                        can_filter_wildcards = False)

    def search_people(self, search_term):
        result = self.call('user/list',
                           params={'search': '*' + search_term + '*'})
        return result[1]['people']

    # IQuery
    @classmethod
    def register_query_people(cls):
        path = cls.register_path(
                      'query_people',
                      cls.query_people,
                      primary_key_col = 'username',
                      default_sort_col = 'username',
                      default_sort_order = -1,
                      can_paginate = True)

        path.register_column('username',
                        default_visible = True,
                        can_sort = False,
                        can_filter_wildcards = False)
        path.register_column('human_name',
                        default_visible = True,
                        can_sort = False,
                        can_filter_wildcards = False)

        f = ParamFilter()
        f.add_filter('prefix',
                     allow_none = False)

        cls._query_people_filter = f

    def query_people(self, start_row=None,
                           rows_per_page=None,
                           order=-1,
                           sort_col=None,
                           filters = None,
                           **params):

        if not filters:
            filters = {}
        filters = self._query_people_filter.filter(filters, conn=self)
        f = {}
        p = filters.get('prefix','a').lower()
        p.replace('*', '')
        p += '*'
        f['search'] = p
        result = self.call('user/list',
                           params=f)


        people = result[1]['people']
        return (len(people), people[start_row:rows_per_page + start_row])

    @classmethod
    def register_query_usermemberships(cls):
        path = cls.register_path(
                      'query_usermemberships',
                      cls.query_usermemberships,
{'fraction_non_alphanumeric': 0.08762797154259934, 'fraction_numerical': 0.002082248828735034, 'mean_word_length': 1.5496571554965715, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 22, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7047526', 'n_tokens_mistral': 3088, 'n_tokens_neox': 2980, 'n_words': 608}