Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def list(self, hostname=None):
now = time.time()
timeout = config.getint('session', 'timeout')
res = self.__class__._list_cache.get(hostname)
timestamp = self.__class__._list_cache_timestamp.get(hostname, now)
if res and abs(timestamp - now) < timeout:
return res
connection = self.get_connection()
try:
cursor = connection.cursor()
cursor.execute('SELECT datname FROM pg_database '
'WHERE datistemplate = false ORDER BY datname')
res = []
for db_name, in cursor:
try:
with connect(**self._connection_params(db_name)
) as conn:
if self._test(conn, hostname=hostname):
def get_login(cls, login, parameters):
'''
Return user id if password matches
'''
LoginAttempt = Pool().get('res.user.login.attempt')
count_ip = LoginAttempt.count_ip()
if count_ip > config.getint(
'session', 'max_attempt_ip_network', default=300):
# Do not add attempt as the goal is to prevent flooding
raise RateLimitException()
count = LoginAttempt.count(login)
if count > config.getint('session', 'max_attempt', default=5):
LoginAttempt.add(login)
raise RateLimitException()
Transaction().atexit(time.sleep, random.randint(0, 2 ** count - 1))
for methods in config.get(
'session', 'authentications', default='password').split(','):
user_ids = set()
for method in methods.split('+'):
try:
func = getattr(cls, '_login_%s' % method)
except AttributeError:
logger.info('Missing login method: %s', method)
break
user_ids.add(func(login, parameters))
if len(user_ids) != 1 or not all(user_ids):
break
if len(user_ids) == 1 and all(user_ids):
from trytond.tools.domain_inversion import (
domain_inversion, parse as domain_parse)
from trytond.pyson import PYSONEncoder, PYSONDecoder, PYSON
from trytond.const import OPERATORS
from trytond.config import config
from trytond.i18n import gettext, lazy_gettext
from trytond.transaction import Transaction
from trytond.pool import Pool
from trytond.cache import LRUDict, LRUDictTransaction, freeze
from trytond.rpc import RPC
from .modelview import ModelView
from .descriptors import dualmethod
__all__ = ['ModelStorage', 'EvalEnvironment']
_cache_record = config.getint('cache', 'record')
_cache_field = config.getint('cache', 'field')
class AccessError(UserError):
pass
class ImportDataError(UserError):
pass
class ValidationError(UserError):
pass
class DomainValidationError(ValidationError):
pass
# This file is part of Tryton. The COPYRIGHT file at the top level of
# this repository contains the full copyright notices and license terms.
import logging
import time
from collections import defaultdict
from threading import local
from sql import Flavor
from trytond.config import config
_cache_model = config.getint('cache', 'model')
logger = logging.getLogger(__name__)
class _AttributeManager(object):
'''
Manage Attribute of transaction
'''
def __init__(self, **kwargs):
self.kwargs = kwargs
def __enter__(self):
return Transaction()
def __exit__(self, type, value, traceback):
for name, value in self.kwargs.items():
def run(cls, db_name):
logger.info('cron started for "%s"', db_name)
now = datetime.datetime.now()
retry = config.getint('database', 'retry')
with Transaction().start(db_name, 0) as transaction:
transaction.database.lock(transaction.connection, cls._table)
crons = cls.search(['OR',
('next_call', '<=', now),
('next_call', '=', None),
])
for cron in crons:
logger.info("Run cron %s", cron.id)
for count in range(retry, -1, -1):
if count != retry:
time.sleep(0.02 * (retry - count))
try:
cron.run_once()
cron.next_call = cron.compute_next_call(now)
cron.save()
from sql import Flavor, Cast, For
from sql.functions import Function
from sql.operators import BinaryOperator
from trytond.backend.database import DatabaseInterface, SQLType
from trytond.config import config, parse_uri
from trytond.tools.gevent import is_gevent_monkey_patched
__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')
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
NotImplemented as NotImplementedException, BadRequest)
from trytond import backend
from trytond.wsgi import app
from trytond.transaction import Transaction
from trytond.protocols.jsonrpc import JSONEncoder, JSONDecoder
from trytond.config import config
from trytond.tools import resolve
logger = logging.getLogger(__name__)
_db_timeout = config.getint('database', 'timeout')
_cache_timeout = config.getint('bus', 'cache_timeout')
_select_timeout = config.getint('bus', 'select_timeout')
_long_polling_timeout = config.getint('bus', 'long_polling_timeout')
_allow_subscribe = config.getboolean('bus', 'allow_subscribe')
_url_host = config.get('bus', 'url_host')
_web_cache_timeout = config.getint('web', 'cache_timeout')
class _MessageQueue:
Message = collections.namedtuple('Message', 'channel content timestamp')
def __init__(self, timeout):
super().__init__()
self._lock = threading.Lock()
self._timeout = timeout
self._messages = []
def append(self, channel, element):
if rpc.fresh_session and session:
context = {'_request': request.context}
if not security.check_timeout(
pool.database_name, user, session, context=context):
abort(http.client.UNAUTHORIZED)
log_message = '%s.%s(*%s, **%s) from %s@%s/%s'
username = request.authorization.username
if isinstance(username, bytes):
username = username.decode('utf-8')
log_args = (
obj, method, args, kwargs, username, request.remote_addr, request.path)
logger.info(log_message, *log_args)
retry = config.getint('database', 'retry')
for count in range(retry, -1, -1):
if count != retry:
time.sleep(0.02 * (retry - count))
with Transaction().start(pool.database_name, user,
readonly=rpc.readonly) as transaction:
try:
c_args, c_kwargs, transaction.context, transaction.timestamp \
= rpc.convert(obj, *args, **kwargs)
transaction.context['_request'] = request.context
meth = getattr(obj, method)
if (rpc.instantiate is None
or not is_instance_method(obj, method)):
result = rpc.result(meth(*c_args, **c_kwargs))
else:
assert rpc.instantiate == 0
inst = c_args.pop(0)
def check(cls, user, key, domain=None):
"""
Check user key against max_age and delete old one.
Return True if key is still valid, False if the key is expired and None
if the key does not exist.
"""
now = datetime.datetime.now()
timeout = datetime.timedelta(
seconds=config.getint('session', 'max_age'))
sessions = cls.search([
('create_uid', '=', user),
domain or [],
])
find = None
to_delete = []
for session in sessions:
if abs(session.create_date - now) < timeout:
if session.key == key:
find = True
else:
if find is None and session.key == key:
find = False
to_delete.append(session)
cls.delete(to_delete)
return find