Files
tryton/trytond/protocols/wrappers.py
T

257 lines
8.2 KiB
Python
Raw Normal View History

2016-03-15 16:57:26 +01:00
# 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 base64
import gzip
2016-09-27 11:56:19 +02:00
import logging
2019-02-04 22:23:12 +01:00
import time
2016-09-27 11:56:19 +02:00
from functools import wraps
2021-12-11 17:58:45 +01:00
from io import BytesIO
try:
from http import HTTPStatus
except ImportError:
from http import client as HTTPStatus
2016-03-15 16:57:26 +01:00
from werkzeug.datastructures import Authorization
2021-12-11 17:58:45 +01:00
from werkzeug.exceptions import HTTPException, abort
from werkzeug.wrappers import Request as _Request
from werkzeug.wrappers import Response
2016-03-15 16:57:26 +01:00
2021-12-11 17:58:45 +01:00
from trytond import backend, security
from trytond.config import config
2022-06-09 09:29:33 +02:00
from trytond.exceptions import RateLimitException, UserError, UserWarning
2016-09-27 11:56:19 +02:00
from trytond.pool import Pool
2020-06-17 00:33:30 +02:00
from trytond.tools import cached_property
2016-09-27 11:56:19 +02:00
from trytond.transaction import Transaction
logger = logging.getLogger(__name__)
2016-03-15 16:57:26 +01:00
class Request(_Request):
view_args = None
2021-03-27 19:42:53 +01:00
def __repr__(self):
args = []
try:
if self.url is None or isinstance(self.url, str):
url = self.url
else:
url = self.url.decode(self.url_charset)
auth = self.authorization
if auth:
args.append("%s@%s" % (
auth.get('userid', auth.username), self.remote_addr))
else:
args.append(self.remote_addr)
2021-03-27 19:42:53 +01:00
args.append("'%s'" % url)
args.append("[%s]" % self.method)
args.append("%s" % (self.rpc_method or ''))
except Exception:
args.append("(invalid WSGI environ)")
return "<%s %s>" % (
self.__class__.__name__, " ".join(filter(None, args)))
2016-03-15 16:57:26 +01:00
@property
def decoded_data(self):
if self.content_encoding == 'gzip':
zipfile = gzip.GzipFile(fileobj=BytesIO(self.data), mode='rb')
return zipfile.read()
else:
return self.data
@property
def parsed_data(self):
return self.data
@property
2016-09-27 11:56:19 +02:00
def rpc_method(self):
2016-03-15 16:57:26 +01:00
return
@property
2016-09-27 11:56:19 +02:00
def rpc_params(self):
2016-03-15 16:57:26 +01:00
return
@cached_property
def authorization(self):
authorization = super(Request, self).authorization
if authorization is None:
header = self.environ.get('HTTP_AUTHORIZATION')
return parse_authorization_header(header)
return authorization
@cached_property
def user_id(self):
2021-03-27 19:42:53 +01:00
if not self.view_args:
return None
2017-09-03 11:32:17 +02:00
database_name = self.view_args.get('database_name')
if not database_name:
return None
2016-03-15 16:57:26 +01:00
auth = self.authorization
if not auth:
2017-09-03 11:32:17 +02:00
return None
2018-03-07 00:34:09 +01:00
context = {'_request': self.context}
2016-03-15 16:57:26 +01:00
if auth.type == 'session':
user_id = security.check(
database_name, auth.get('userid'), auth.get('session'),
2018-03-07 00:34:09 +01:00
context=context)
2016-03-15 16:57:26 +01:00
else:
try:
user_id = security.login(
database_name, auth.username, auth, cache=False,
context=context)
except RateLimitException:
abort(HTTPStatus.TOO_MANY_REQUESTS)
2016-03-15 16:57:26 +01:00
return user_id
@cached_property
def context(self):
return {
'remote_addr': self.remote_addr,
'http_host': self.environ.get('HTTP_HOST'),
'scheme': self.scheme,
'is_secure': self.is_secure,
}
2016-03-15 16:57:26 +01:00
def parse_authorization_header(value):
if not value:
return
2021-05-28 09:10:15 +02:00
if not isinstance(value, bytes):
value = value.encode('latin1')
2016-03-15 16:57:26 +01:00
try:
auth_type, auth_info = value.split(None, 1)
auth_type = auth_type.lower()
except ValueError:
return
if auth_type == b'session':
try:
username, userid, session = base64.b64decode(auth_info).split(
b':', 3)
userid = int(userid)
except Exception:
return
return Authorization('session', {
2021-05-28 09:10:15 +02:00
'username': username.decode("latin1"),
2016-03-15 16:57:26 +01:00
'userid': userid,
2021-05-28 09:10:15 +02:00
'session': session.decode("latin1"),
2016-03-15 16:57:26 +01:00
})
2016-09-27 11:56:19 +02:00
2017-09-03 11:32:17 +02:00
def set_max_request_size(size):
def decorator(func):
func.max_request_size = size
return func
return decorator
2021-03-07 10:01:20 +01:00
def allow_null_origin(func):
func.allow_null_origin = True
return func
2016-09-27 11:56:19 +02:00
def with_pool(func):
@wraps(func)
def wrapper(request, database_name, *args, **kwargs):
database_list = Pool.database_list()
pool = Pool(database_name)
if database_name not in database_list:
with Transaction().start(database_name, 0, readonly=True):
2016-09-27 11:56:19 +02:00
pool.init()
2022-06-09 09:29:33 +02:00
try:
return func(request, pool, *args, **kwargs)
except HTTPException:
logger.debug('%s', request, exc_info=True)
raise
except (UserError, UserWarning) as e:
logger.debug('%s', request, exc_info=True)
if request.rpc_method:
raise
else:
abort(HTTPStatus.BAD_REQUEST, e)
2022-06-09 09:29:33 +02:00
except Exception as e:
logger.error('%s', request, exc_info=True)
if request.rpc_method:
raise
else:
abort(HTTPStatus.INTERNAL_SERVER_ERROR, e)
2016-09-27 11:56:19 +02:00
return wrapper
2019-03-30 16:04:45 +01:00
def with_transaction(readonly=None, user=0, context=None):
from trytond.worker import run_task
2016-09-27 11:56:19 +02:00
def decorator(func):
@wraps(func)
def wrapper(request, pool, *args, **kwargs):
2019-03-30 16:04:45 +01:00
nonlocal user, context
2016-09-27 11:56:19 +02:00
readonly_ = readonly # can not modify non local
if readonly_ is None:
if request.method in {'POST', 'PUT', 'DELETE', 'PATCH'}:
readonly_ = False
else:
readonly_ = True
2019-03-30 16:04:45 +01:00
if context is None:
context = {}
else:
context = context.copy()
context['_request'] = request.context
if user == 'request':
user = request.user_id
2019-02-04 22:23:12 +01:00
retry = config.getint('database', 'retry')
for count in range(retry, -1, -1):
if count != retry:
time.sleep(0.02 * (retry - count))
2016-09-27 11:56:19 +02:00
with Transaction().start(
2019-03-30 16:04:45 +01:00
pool.database_name, user, readonly=readonly_,
context=context) as transaction:
2016-09-27 11:56:19 +02:00
try:
result = func(request, pool, *args, **kwargs)
2019-12-06 17:33:47 +01:00
except backend.DatabaseOperationalError:
2016-09-27 11:56:19 +02:00
if count and not readonly_:
transaction.rollback()
continue
raise
# Need to commit to unlock SQLite database
transaction.commit()
while transaction.tasks:
task_id = transaction.tasks.pop()
run_task(pool, task_id)
return result
2016-09-27 11:56:19 +02:00
return wrapper
return decorator
def user_application(name, json=True):
2021-12-11 17:58:45 +01:00
from .jsonrpc import JSONEncoder
from .jsonrpc import json as json_
2016-09-27 11:56:19 +02:00
def decorator(func):
@wraps(func)
def wrapper(request, *args, **kwargs):
pool = Pool()
UserApplication = pool.get('res.user.application')
2021-05-28 09:10:15 +02:00
authorization = request.headers['Authorization']
2016-09-27 11:56:19 +02:00
try:
auth_type, auth_info = authorization.split(None, 1)
auth_type = auth_type.lower()
except ValueError:
abort(HTTPStatus.UNAUTHORIZED)
2021-05-28 09:10:15 +02:00
if auth_type != 'bearer':
abort(HTTPStatus.FORBIDDEN)
2016-09-27 11:56:19 +02:00
2021-05-28 09:10:15 +02:00
application = UserApplication.check(auth_info, name)
2016-09-27 11:56:19 +02:00
if not application:
abort(HTTPStatus.FORBIDDEN)
2016-09-27 11:56:19 +02:00
transaction = Transaction()
# TODO language
with transaction.set_user(application.user.id), \
transaction.set_context(_check_access=True):
2022-06-09 09:29:33 +02:00
response = func(request, *args, **kwargs)
2016-09-27 11:56:19 +02:00
if not isinstance(response, Response) and json:
response = Response(json_.dumps(response, cls=JSONEncoder),
content_type='application/json')
return response
return wrapper
return decorator