util.py 2.33 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# -*- coding: utf-8 -*-
# copyright 2022 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
# contact https://www.logilab.fr -- mailto:contact@logilab.fr
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation, either version 2.1 of the License, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
import re
from typing import Union

from cubicweb import ConfigurationError
from cubicweb.pyramid.core import CubicWebPyramidRequest
from cubicweb.server.repository import Repository
from pyramid.config import Configurator
from pyramid.request import Request

from cubicweb_api.constants import API_PATH_DEFAULT_PREFIX


def get_cw_request(request: Request) -> CubicWebPyramidRequest:
    return request.cw_request


def get_cw_repo(req_or_conf: Union[Request, Configurator]) -> Repository:
    return req_or_conf.registry["cubicweb.repository"]


def get_api_path_prefix(config: Configurator) -> str:
    repo = get_cw_repo(config)
    path_prefix: str = (
        repo.get_option_value("api-path-prefix") or API_PATH_DEFAULT_PREFIX
    )
42
    match = re.match("^/[a-zA-Z0-9-_@.&+!*(),/]{1,29}$", path_prefix)
43
    if match:
Arnaud Vergnet's avatar
Arnaud Vergnet committed
44
        return f"{path_prefix.rstrip('/')}/v1"
45
46
47
    else:
        if len(path_prefix) > 30:
            raise ConfigurationError(
48
49
50
51
52
53
54
55
                f"api-path-prefix '{path_prefix}' is too long. "
                f"Max size allowed is 30 characters. "
                f"Current size is {len(path_prefix)}."
            )
        if not path_prefix.startswith("/"):
            raise ConfigurationError(
                f"api-path-prefix '{path_prefix}' does not start with '/'. "
                "Prefix should start with '/' to be validated by openapi"
56
57
58
            )

        raise ConfigurationError(
59
            f"api-path-prefix '{path_prefix}' contains invalid characters. "
60
61
            "Allowed characters are: a-zA-Z0-9-_@.&+!*(),/"
        )