def root():
    if request.method == 'POST':
        try:
            name = request.json['name']
            if not isinstance(name, str) or not 0 < len(name) < 26:
                raise HttpException("Name attribute must be a string between 1 and 25 characters", 400)
        except (TypeError, KeyError):
            raise HttpException("Must be JSON object with a name attribute!", 400)
    else:
        name = 'World!'

    return jsonify(Hello=name), 200
    def request_started_handler(self, sender, **extra):
        def _get_cache_key():
            time_chunk = int(datetime.utcnow().timestamp()) // self.__rate_seconds
            key = "{}-{}-{}".format(request.path, request.method, time_chunk)
            return key

        cache_key = _get_cache_key()
        if self.__cache.inc(cache_key) > self.__rate_count:
            raise HttpException("Rate limit exceeded", 429)
Пример #3
0
    def get(cls, url):
        """
        HTTP GET请求

        Args:
            url (str): 请求的url
        Return:
            str: Http Response的内容
        """
        try:
            headers = {
                'user-agent':
                'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36'
            }
            response = requests.get(url, headers=headers, timeout=30)
        except requests.RequestException:
            raise HttpException('HTTP Exception: %s', url)
        else:
            return response.content
Пример #4
0
    def request_started_handler(self, sender, **extra):
        token = get_token_from_request(request)
        if not token:
            raise HttpException("No EX-JWT authorization token provided", 401)

        try:
            self._request_jwt_claims = JWS().verify_compact(token, self._keys)
        except JWKESTException:
            raise HttpException("Invalid token", 401)

        errors = list()
        now = int(datetime.utcnow().timestamp())
        if self._request_jwt_claims.get('iss') != "valid-client":
            errors.append("missing or invalid issuer")
        if self._request_jwt_claims.get('aud') != "api-server":
            errors.append("missing or invalid audience")
        if not 'jti' in self._request_jwt_claims:
            errors.append("missing token ID")
        elif not self._cache.add(self._request_jwt_claims['jti'], 1, 3600):
            errors.append("duplicate token ID")
        if 'nbf' not in self._request_jwt_claims:
            errors.append("missing not before")
        elif not isinstance(self._request_jwt_claims['nbf'], int):
            errors.append("invalid not before type")
        elif self._request_jwt_claims['nbf'] + self._leeway < now:
            errors.append("invalid not before")
        if 'exp' not in self._request_jwt_claims:
            errors.append("missing expires")
        elif not isinstance(self._request_jwt_claims['exp'], int):
            errors.append("invalid expires type")
        elif self._request_jwt_claims['exp'] - self._leeway > now:
            errors.append("invalid expires")

        if 'request' not in self._request_jwt_claims:
            errors.append("request claim missing")

        if 'path' not in self._request_jwt_claims['request']:
            errors.append("request[path] claim missing")
        elif self._request_jwt_claims['request']['path'] != request.path:
            errors.append("invalid request[path] claim")

        if 'method' not in self._request_jwt_claims['request']:
            errors.append("request[method] claim missing")
        elif self._request_jwt_claims['request']['method'] != request.method:
            errors.append("invalid request[method] claim")

        if request.content_length is not None and request.content_length > 0:
            if 'body_hash_alg' not in self._request_jwt_claims['request']:
                errors.append("request[body_hash_alg] claim missing")
            elif self._request_jwt_claims['request'][
                    'body_hash_alg'] not in self._hash_algs:
                errors.append(
                    "request[body_hash_alg] must be one of: {}".format(
                        ", ".join(self._hash_algs.keys())))
            elif 'body_hash' not in self._request_jwt_claims['request']:
                errors.append("request[body_hash_alg] claim missing")

            hasher = hashlib.new(self._hash_algs[
                self._request_jwt_claims['request']['body_hash_alg']])
            hasher.update(request.data)
            actual = hasher.hexdigest()
            if actual != self._request_jwt_claims['request']['body_hash']:
                errors.append("invalid body hash")

        if len(errors) > 0:
            raise HttpException("Invalid token: {}".format(", ".join(errors)),
                                401)
Пример #5
0
 def request_started_handler(self, sender, **extra):
     token = get_token_from_request(request)
     if token is None:
         raise HttpException("Authorization Required!", 401)
     if not self.__cache.add(sha512(token.encode('utf-8')), 1):
         raise HttpException("Invalid Request: Replay Detected", 400)
 def request_started_handler(self, sender, **extra):
     token = request.headers.get('Authorization', None)
     if token is None:
         raise HttpException("Authorization Required!", 401)
     if not self.__cache.add(sha512(token.encode('utf-8')).digest(), 1):
         raise HttpException("Invalid Request: Replay Detected", 400)
Пример #7
0
 async def cancel(self) -> None:
     r = await self.session.post(self.url+'/job', data=json.dumps({"command": "cancel"}))
     if not r.status == 204:
         raise HttpException(r.status)
Пример #8
0
 async def print(self, file: str) -> None:
     r = await self.session.post(self.url+'/files/local/'+file, data=json.dumps({"command": "select", "print": True}))
     if not r.status == 204:
         raise HttpException(r.status)
Пример #9
0
 async def post_command(self, command: str) -> None:
     r = await self.session.post(self.url+'/printer/command', data=json.dumps({"commands": [command]}))
     if not r.status == 204:
         raise HttpException(r.status)
Пример #10
0
 async def get_job(self) -> dict:
     r = await self.session.get(self.url+'/job')
     if not r.status == 200:
         raise HttpException(r.status)
     status = await r.json()
     return status
Пример #11
0
 async def connect(self) -> None:
     r = await self.session.post(self.url+'/connection', data=json.dumps({"command": "connect"}))
     if not r.status == 200:
         raise HttpException(r.status)