<commit_before>import logging
from contextlib import contextmanager
from datetime import datetime, timedelta

import pylons
from tg import config
from tg.decorators import with_trailing_slash
from formencode import validators as V

from allura import version
from allura.app import Application
from allura.lib.decorators import react
from allura.lib import search
from allura.lib import helpers as h
from allura.lib import plugin
from allura import model as M

from .lib.sfx_api import SFXProjectApi, SFXUserApi
from .lib import exceptions as sfx_exc

log = logging.getLogger(__name__)

class SFXApp(Application):
    '''Handles reflecting project changes over to SFX'''
    __version__ = version.__version__
    installable = False
    sitemap=[]
    root=None
    templates=None

    @classmethod
    @react('forge.project_created')
    def project_created(cls, routing_key, doc):
        if config['registration.method'] != 'sfx': return
        api = SFXProjectApi()
        api.update(pylons.c.user, pylons.c.project)

    @classmethod
    @react('forge.project_updated')
    def project_updated(cls, routing_key, doc):
        if config['registration.method'] != 'sfx': return
        api = SFXProjectApi()
        api.update(pylons.c.user, pylons.c.project)

    @classmethod
    @react('forge.project_deleted')
    def project_deleted(cls, routing_key, doc):
        if config['registration.method'] != 'sfx': return
        api = SFXProjectApi()
        api.delete(pylons.c.user, pylons.c.project)

    def sidebar_menu(self):
        return [ ]

    def admin_menu(self):
        return []

    def install(self, project):
        pass # pragma no cover

    def uninstall(self, project):
        pass # pragma no cover

class SFXAuthenticationProvider(plugin.AuthenticationProvider):

    def __init__(self, request):
        super(SFXAuthenticationProvider, self).__init__(request)
        try:
            self.sfx_session_manager = request.environ['allura.sfx_session_manager']
        except TypeError:
            from sf.phpsession import SFXSessionMgr
            self.sfx_session_manager = SFXSessionMgr()
        self.local_ap = plugin.LocalAuthenticationProvider(request)

    def register_user(self, user_doc):
        log.warning("We don't provide user registration; that's SFX's job."
                    "  Delegating to a LocalAuthenticationProvider...")
        return self.local_ap.register_user(user_doc)

    def set_password(self, user, old_password, new_password):
        log.warning("We don't provide password services; that's SFX's job."
                    "  Delegating to a LocalAuthenticationProvider...")
        return self.local_ap.set_password(user, old_password, new_password)

    def authenticate_request(self):
        cookie_name = self.sfx_session_manager.cookie_name
        mgr = self.sfx_session_manager
        if 'userid' in self.session:
            user = super(SFXAuthenticationProvider, self).authenticate_request()
            if user != M.User.anonymous():
                if cookie_name not in self.request.cookies:
                    self.logout()
                    return M.User.anonymous()
                elif self.request.cookies[cookie_name] == self.session.get('sfx-sessid'):
                    return user
        sfx_user_id = mgr.userid_from_session_cookie(self.request.cookies)
        if sfx_user_id:
            server_name = self.request.environ['HTTP_HOST']
            user_data = mgr.user_data(server_name, sfx_user_id)
            user = self.by_username(user_data['username'], user_data)
            self.session['sfx-sessid'] = self.request.cookies[cookie_name]
            self.session['userid'] = user._id
            self.session.save()
            return user
        else:
            return M.User.anonymous()

    def logout(self):
        self.session['sfx-sessid'] = None
        try:
            from pylons import response
            response.delete_cookie(self.sfx_session_manager.cookie_name)
        except:
            pass
        super(SFXAuthenticationProvider, self).logout()

    def _login(self):
        raise TypeError, "We don't provide user login; that's SFX's job"

    def by_username(self, username, extra=None):
        api = SFXUserApi()
        try:
            return api.upsert_user(username, extra)
        except:<commit_msg>[#882] - log and flash sfx api errors<commit_after>import logging
import urllib2
from contextlib import contextmanager
from datetime import datetime, timedelta

import pylons
from tg import config, flash
from tg.decorators import with_trailing_slash
from formencode import validators as V

from allura import version
from allura.app import Application
from allura.lib.decorators import react
from allura.lib import search
from allura.lib import helpers as h
from allura.lib import plugin
from allura import model as M

from .lib.sfx_api import SFXProjectApi, SFXUserApi
from .lib import exceptions as sfx_exc

log = logging.getLogger(__name__)

class SFXApp(Application):
    '''Handles reflecting project changes over to SFX'''
    __version__ = version.__version__
    installable = False
    sitemap=[]
    root=None
    templates=None

    @classmethod
    @react('forge.project_created')
    def project_created(cls, routing_key, doc):
        if config['registration.method'] != 'sfx': return
        api = SFXProjectApi()
        api.update(pylons.c.user, pylons.c.project)

    @classmethod
    @react('forge.project_updated')
    def project_updated(cls, routing_key, doc):
        if config['registration.method'] != 'sfx': return
        api = SFXProjectApi()
        api.update(pylons.c.user, pylons.c.project)

    @classmethod
    @react('forge.project_deleted')
    def project_deleted(cls, routing_key, doc):
        if config['registration.method'] != 'sfx': return
        api = SFXProjectApi()
        api.delete(pylons.c.user, pylons.c.project)

    def sidebar_menu(self):
        return [ ]

    def admin_menu(self):
        return []

    def install(self, project):
        pass # pragma no cover

    def uninstall(self, project):
        pass # pragma no cover

class SFXAuthenticationProvider(plugin.AuthenticationProvider):

    def __init__(self, request):
        super(SFXAuthenticationProvider, self).__init__(request)
        try:
            self.sfx_session_manager = request.environ['allura.sfx_session_manager']
        except TypeError:
            from sf.phpsession import SFXSessionMgr
            self.sfx_session_manager = SFXSessionMgr()
        self.local_ap = plugin.LocalAuthenticationProvider(request)

    def register_user(self, user_doc):
        log.warning("We don't provide user registration; that's SFX's job."
                    "  Delegating to a LocalAuthenticationProvider...")
        return self.local_ap.register_user(user_doc)

    def set_password(self, user, old_password, new_password):
        log.warning("We don't provide password services; that's SFX's job."
                    "  Delegating to a LocalAuthenticationProvider...")
        return self.local_ap.set_password(user, old_password, new_password)

    def authenticate_request(self):
        cookie_name = self.sfx_session_manager.cookie_name
        mgr = self.sfx_session_manager
        if 'userid' in self.session:
            user = super(SFXAuthenticationProvider, self).authenticate_request()
            if user != M.User.anonymous():
                if cookie_name not in self.request.cookies:
                    self.logout()
                    return M.User.anonymous()
                elif self.request.cookies[cookie_name] == self.session.get('sfx-sessid'):
                    return user
        sfx_user_id = mgr.userid_from_session_cookie(self.request.cookies)
        if sfx_user_id:
            server_name = self.request.environ['HTTP_HOST']
            user_data = mgr.user_data(server_name, sfx_user_id)
            user = self.by_username(user_data['username'], user_data)
            self.session['sfx-sessid'] = self.request.cookies[cookie_name]
            self.session['userid'] = user._id
            self.session.save()
            return user
        else:
            return M.User.anonymous()

    def logout(self):
        self.session['sfx-sessid'] = None
        try:
            from pylons import response
            response.delete_cookie(self.sfx_session_manager.cookie_name)
        except:
            pass
        super(SFXAuthenticationProvider, self).logout()

    def _login(self):
        raise TypeError, "We don't provide user login; that's SFX's job"

    def by_username(self, username, extra=None):
        api = SFXUserApi()
        try:
            return api.upsert_user(username, extra)
        except urllib2.HTTPError, exc:
            log.error('Received error from SFX API: %r', exc)
            flash('Error looking up user with username "%s"',
                  username)
            return None
        except:
{'fraction_non_alphanumeric': 0.09024907852116609, 'fraction_numerical': 0.0005584720205517703, 'mean_word_length': 2.687808896210873, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, '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': '6859178', 'n_tokens_mistral': 2626, 'n_tokens_neox': 2537, 'n_words': 620}