示例#1
0
文件: user.py 项目: zarumaru/trytond
 def validate_password(cls, password, users):
     password_b = password
     if isinstance(password, str):
         password_b = password.encode('utf-8')
     length = config.getint('password', 'length', default=0)
     if length > 0:
         if len(password_b) < length:
             raise PasswordError(
                 gettext(
                     'res.msg_password_length',
                     length=length,
                 ))
     path = config.get('password', 'forbidden', default=None)
     if path:
         with open(path, 'r') as f:
             forbidden = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
             if forbidden.find(password_b) >= 0:
                 raise PasswordError(gettext('res.msg_password_forbidden'))
     entropy = config.getfloat('password', 'entropy', default=0)
     if entropy:
         if len(set(password)) / len(password) < entropy:
             raise PasswordError(gettext('res.msg_password_entropy'))
     for user in users:
         # Use getattr to allow to use non User instances
         for test, message in [
             (getattr(user, 'name', ''), 'res.msg_password_name'),
             (getattr(user, 'login', ''), 'res.msg_password_login'),
             (getattr(user, 'email', ''), 'res.msg_password_email'),
         ]:
             if test and password.lower() == test.lower():
                 raise PasswordError(gettext(message))
示例#2
0
from trytond.config import config
from trytond import __version__
from trytond.transaction import Transaction
from trytond.exceptions import (UserError, UserWarning, ConcurrencyException,
                                LoginException, RateLimitException)
from trytond.tools import is_instance_method
from trytond.wsgi import app
from trytond.perf_analyzer import PerfLog, profile
from trytond.perf_analyzer import logger as perf_logger
from trytond.sentry import sentry_wrap
from .wrappers import with_pool

logger = logging.getLogger(__name__)

# JCA: log slow RPC (> log_time_threshold)
slow_threshold = config.getfloat('web', 'log_time_threshold', default=-1)
if slow_threshold >= 0:
    slow_logger = logging.getLogger('slowness')

ir_configuration = Table('ir_configuration')
ir_lang = Table('ir_lang')
ir_module = Table('ir_module')
res_user = Table('res_user')


# JCA: log slow RPC
def log_exception(method, *args, **kwargs):
    kwargs['exc_info'] = False
    method(*args, **kwargs)
    for elem in traceback.format_exc().split('\n'):
        method(elem)
示例#3
0
def activate_auto_profile(pool, update):
    if update:
        return

    from configparser import NoSectionError
    from trytond.config import config
    from trytond.pool import PoolMeta

    logger = logging.getLogger('trytond.autoprofile')
    try:
        from profilehooks import profile
        threshold = config.getfloat('debug', 'auto_profile_threshold') or 0

        def is_class_or_dual_method(method):
            return hasattr(method, '_dualmethod') or (
                isinstance(method, types.MethodType) and
                isinstance(method.__self__, PoolMeta))

        def auto_profile(f):
            def wrapped(self, *args, **kwargs):
                old_stdout = sys.stdout
                my_stdout = sys.stdout = StringIO()
                start = time.time()
                res = profile(f, immediate=True, sort=['cumulative'],
                    entries=80)(self, *args, **kwargs)
                end = time.time()
                sys.stdout = old_stdout
                if end - start >= threshold:
                    for line in my_stdout.getvalue().split('\n'):
                        logger.info(line)
                return res
            return wrapped

        def auto_profile_cls(f):
            @classmethod
            def wrapped(cls, *args, **kwargs):
                old_stdout = sys.stdout
                my_stdout = sys.stdout = StringIO()
                start = time.time()
                res = profile(f, immediate=True, sort=['cumulative'],
                    entries=80)(
                    *args, **kwargs)
                end = time.time()
                sys.stdout = old_stdout
                if end - start >= threshold:
                    for line in my_stdout.getvalue().split('\n'):
                        logger.info(line)
                return res
            return wrapped

        for model, methods in config.items('auto_profile'):
            logger.warning('Enabling auto-profile for %s' % model)

            Model = pool._pool[pool.database_name].get('model').get(model)
            for method in methods.split(','):
                method_obj = getattr(Model, method)
                if is_class_or_dual_method(method_obj):
                    setattr(Model, method, auto_profile_cls(method_obj))
                else:
                    setattr(Model, method, auto_profile(method_obj))
    except ImportError:
        logger.warning('profilehooks not found, auto-profiling disabled')
    except NoSectionError:
        pass
示例#4
0
from .exceptions import InvoiceChorusValidationError

CERT = (config.get('account_fr_chorus',
                   'certificate'), config.get('account_fr_chorus',
                                              'privatekey'))
BASE_URL = config.get('account_fr_chorus',
                      'url',
                      default='https://chorus-pro.gouv.fr:5443')
EDOC2SYNTAX = {
    'edocument.uncefact.invoice': 'IN_DP_E1_CII_16B',
}
EDOC2FILENAME = {
    'edocument.uncefact.invoice': 'UNCEFACT-%s.xml',
}
TIMEOUT = config.getfloat('account_fr_chorus', 'requests_timeout', default=300)
logger = logging.getLogger(__name__)


class _SyntaxMixin(object):
    __slots__ = ()

    @classmethod
    def get_syntaxes(cls):
        pool = Pool()
        syntaxes = [(None, "")]
        try:
            doc = pool.get('edocument.uncefact.invoice')
        except KeyError:
            pass
        else:
示例#5
0
from trytond.tools.gevent import is_gevent_monkey_patched

# MAB: Performance analyser tools (See [ec1462afd])
from trytond.perf_analyzer import analyze_before, analyze_after
from trytond.perf_analyzer import logger as perf_logger

__all__ = ['Database', 'DatabaseIntegrityError', 'DatabaseOperationalError']

logger = logging.getLogger(__name__)

os.environ['PGTZ'] = os.environ.get('TZ', '')
_timeout = config.getint('database', 'timeout')
_minconn = config.getint('database', 'minconn', default=1)
_maxconn = config.getint('database', 'maxconn', default=64)
_default_name = config.get('database', 'default_name', default='template1')
_slow_threshold = config.getfloat('database', 'log_time_threshold', default=-1)
_slow_logging_enabled = _slow_threshold > 0 and logger.isEnabledFor(
    logging.WARNING)


def unescape_quote(s):
    if s.startswith('"') and s.endswith('"'):
        return s.strip('"').replace('""', '"')
    return s


def replace_special_values(s, **mapping):
    for name, value in mapping.items():
        s = s.replace('$' + name, value)
    return s