def async_wrapper(self, *args, **kwargs): current_user = yield self.current_user if not current_user: raise ServerError(ServerError.AUTH_REQUIRED) elif current_user.role not in role: raise ServerError(ServerError.ROLE_FORBIDDEN) yield method(self, *args, **kwargs)
def upload(self): self.check_request() request_files = self.request.files['files'] if len(request_files) < 1: raise ServerError(ServerError.BAD_REQUEST) result = [] for file_request in request_files: file_ext = FileHelper.file_ext(file_request['filename']) if len(self.allowed_extensions ) > 0 and file_ext not in self.allowed_extensions: raise ServerError(ServerError.BAD_REQUEST, data="incorrect_file_extension") save_path_tree, file_name = save_file(file_request, self.file_save_path) result.append({ "id": '%s/%s' % (save_path_tree, file_name), "path": '%s/%s/%s' % (self.static_server_address, save_path_tree, file_name) }) self.make_result(result)
def get_str_array_argument(self, name, **kwargs): arguments = self.get_argument(name, **self._clear_kwargs(kwargs)) try: if arguments != kwargs.get('default'): arguments = [self.STR_TYPE(x) for x in arguments.split(',')] else: return arguments except Exception: raise ServerError(ServerError.INVALID_PARAMETER, description='Argument %s is not str' % name, field=name, field_problem=ServerError.FIELD_INVALID_FORMAT) if kwargs.get('empty', None) is not None: empty = bool(kwargs.get('empty', None)) for argument in arguments: if len(argument) == 0 and empty is False: raise ServerError(ServerError.INVALID_PARAMETER, description='Argument %s have empty elements' % name, field=name, field_problem=ServerError.FIELD_EMPTY) if kwargs.get('allowed_values', None) is not None: allowed_values = kwargs.get('allowed_values', None) for argument in arguments: if argument not in allowed_values: raise ServerError(ServerError.INVALID_PARAMETER, description='Value %s is not allowed' % argument, field=name, field_problem=ServerError.FIELD_NOT_ALLOWED) return arguments
def check(): if kwargs.get('length_min', None) is not None: length_min = int(kwargs.get('length_min')) if len(argument) < length_min: raise ServerError(ServerError.INVALID_PARAMETER, description='Length of argument %s must be greater than %s' % (name, length_min), field=name, field_problem=ServerError.FIELD_LESS_MIN) if kwargs.get('length_max', None) is not None: length_max = int(kwargs.get('length_max')) if len(argument) > length_max: raise ServerError(ServerError.INVALID_PARAMETER, description='Length of argument %s must be less than than %s' % ( name, length_max), field=name, field_problem=ServerError.FIELD_MORE_MAX) # Аналог length_min == 1 if kwargs.get('empty', None) is not None: empty = bool(kwargs.get('empty', None)) if len(argument) == 0 and empty is False: raise ServerError(ServerError.INVALID_PARAMETER, description='Argument %s cannot be empty' % name, field=name, field_problem=ServerError.FIELD_EMPTY) if kwargs.get('allowed_values', None) is not None: allowed_values = kwargs.get('allowed_values', None) if argument not in allowed_values: raise ServerError(ServerError.INVALID_PARAMETER, description='Value %s is not allowed' % argument, field=name, field_problem=ServerError.FIELD_NOT_ALLOWED)
def get_int_array_argument(self, name, **kwargs): arguments = self.get_argument(name, **self._clear_kwargs(kwargs)) try: if arguments != kwargs.get('default'): if arguments == '': return [] arguments = [int(x) for x in arguments.split(',')] else: return arguments except Exception: raise ServerError(ServerError.INVALID_PARAMETER, description='Argument %s is not int' % name, field=name) if kwargs.get('min', None) is not None: min_value = int(kwargs.get('min')) for argument in arguments: if argument < min_value: raise ServerError(ServerError.INVALID_PARAMETER, description='Argument %s must be greater than %s' % (name, min_value), field=name, field_problem=ServerError.FIELD_LESS_MIN) if kwargs.get('max', None) is not None: max_value = int(kwargs.get('max', self.INT_MAX)) for argument in arguments: if argument > max_value: raise ServerError(ServerError.INVALID_PARAMETER, description='Argument %s must be less than than %s' % (name, max_value), field=name, field_problem=ServerError.FIELD_MORE_MAX) return arguments
def get_float_argument(self, name, **kwargs): argument = self.get_argument(name, **self._clear_kwargs(kwargs)) try: if argument != kwargs.get('default'): argument = argument.replace(',', '.') argument = float(argument) else: return argument except Exception: raise ServerError(ServerError.INVALID_PARAMETER, description='Argument %s is not number' % name, field=name, field_problem=ServerError.FIELD_INVALID_FORMAT) if kwargs.get('min', None) is not None: min_value = float(kwargs.get('min')) if argument < min_value: raise ServerError(ServerError.INVALID_PARAMETER, description='Argument %s must be greater than %s' % (name, min_value), field=name, field_problem=ServerError.FIELD_LESS_MIN) if kwargs.get('max', None) is not None: max_value = float(kwargs.get('max')) if argument > max_value: raise ServerError(ServerError.INVALID_PARAMETER, description='Argument %s must be less than than %s' % (name, max_value), field=name, field_problem=ServerError.FIELD_MORE_MAX) return argument
def wrapper(self, *args, **kwargs): if not self.current_user or not self.current_user.permissions: raise ServerError(ServerError.AUTH_REQUIRED) else: for item in permissions: if item not in self.current_user.permissions or not self.current_user.permissions[ item]: raise ServerError(ServerError.ROLE_FORBIDDEN) return method(self, *args, **kwargs)
def post(self, *args, **kwargs): action_title = args[0] if len(args) > 0 else '' if not (action_title in self.post_methods.keys()): action_title = self.default_post_method if action_title in self.post_methods.keys(): return self.post_methods.get(action_title)() if action_title in self.get_methods: raise ServerError(ServerError.NOT_IMPLEMENTED) else: raise ServerError(ServerError.NOT_FOUND)
def respond(self): request_id = self.get_mongo_id_argument('request_id') exchange_id = self.get_mongo_id_argument('exchange_id') external_id = self.get_int_argument('external_id') request = get_object_or_none(Request, id=request_id) if request is None: raise ServerError(ServerError.NOT_FOUND) exchange = get_object_or_none(Exchange, id=exchange_id) if exchange is None: raise ServerError(ServerError.NOT_FOUND) AwaExchangeBot._confirm(request=request, exchange=exchange, external_id=external_id)
def verify(verified_entity, verification_key): """ Метод должен райзить ошибки :param verified_entity: сущность :param verification_key: ключ :return: """ verification = get_object_or_none(Verification, verified_entity=verified_entity) if verification is None: raise ServerError(VerificationHandler.STATUS_VERIFICATION_NOT_FOUND) if not verification.verify(verification_key): raise ServerError(VerificationHandler.STATUS_INVALID_VERIFICATION_KEY) verification.verified = True verification.save()
def check_repeat(admin, email): if admin is None or (admin.email != email): email_busy = BaseAdmin.objects(email=email).count() if email_busy > 0: raise ServerError(ServerError.INVALID_PARAMETER, field='email', field_problem=ServerError.FIELD_REPEAT)
def get_mongo_id_argument(self, name, **kwargs): argument = self.get_str_argument(name, **kwargs) if argument != kwargs.get('default'): if len(argument) != 24 or len(re.findall('[^A-Ha-h0-9]', argument)) > 0: raise ServerError(ServerError.INVALID_PARAMETER, description='Argument %s is not mongo id' % name, field=name, field_problem=ServerError.FIELD_INVALID_FORMAT) return argument
def set_fail(self): id = self.get_mongo_id_argument('id') request = get_object_or_none(self.MODEL_CLS, id=id) if request is None: raise ServerError(ServerError.NOT_FOUND) else: send_fails([request]) self.send_success_response()
def get_date_argument(self, name, date_format, **kwargs): argument = self.get_argument(name, **self._clear_kwargs(kwargs)) try: if argument != kwargs.get('default'): argument = datetime.strptime(argument, date_format) except Exception: raise ServerError(ServerError.INVALID_PARAMETER, description='Argument %s have invalid format. Valid format: %s' % (name, date_format), field=name, field_problem=ServerError.FIELD_INVALID_FORMAT) if kwargs.get('min', ArgumentsMixin.MIN_DATE) is not None and not kwargs.get('ignore_min', False): min_value = kwargs.get('min', ArgumentsMixin.MIN_DATE) if isinstance(min_value, datetime) and argument < min_value: raise ServerError(ServerError.INVALID_PARAMETER, description='Argument %s must be greater than %s' % ( name, min_value.strftime('%Y-%m-%d %H:%M:%S')), field=name, field_problem=ServerError.FIELD_LESS_MIN) return argument
def update_date_commission_withdrawal(self): id = self.get_mongo_id_argument('id') request = get_object_or_none(Request, id=id) if request is None: raise ServerError(ServerError.NOT_FOUND) value = self.get_date_argument('value', '%d.%m.%Y') request.update(date_commission_withdrawal=value) self.send_success_response()
def update_exchange_confirm(self): id = self.get_mongo_id_argument('id') request = get_object_or_none(Request, id=id) if request is None: raise ServerError(ServerError.NOT_FOUND) value = self.get_bool_argument('value') request.update(exchange_confirm=value) self.send_success_response()
def get_email_argument(self, name, **kwargs): argument = self.get_str_argument(name, **kwargs) if argument != kwargs.get('default'): if not (argument == '' and kwargs.get('empty', False)): if not ArgumentsMixin.EMAIL_REGEX.match(argument): raise ServerError(ServerError.INVALID_PARAMETER, description='Argument %s have bad email format' % name, field=name, field_problem=ServerError.FIELD_NOT_EMAIL) return argument
def index(self): template = path.join(options.static_root, 'index.html') if path.isfile(template) is False: raise ServerError('not_found') with open(template, 'r') as file: result = file.read() self.set_header('Content-type', 'text/html') self.write(result, nocontenttype=True)
def get_json_argument(self, name, **kwargs): argument = self.get_argument(name, **self._clear_kwargs(kwargs)) try: if argument != kwargs.get('default'): argument = json.loads(argument) except Exception: raise ServerError(ServerError.INVALID_PARAMETER, description='Argument %s is invalid json' % name, field=name, field_problem=ServerError.FIELD_INVALID_FORMAT) return argument
def validate_model(self, prefix=None): if prefix is not None: prefix += '.' else: prefix = '' try: self.validate() except ValidationError as e: field = e.errors.keys().pop() raise ServerError(ServerError.INVALID_PARAMETER, field=prefix + str(field), field_problem=ServerError.FIELD_INVALID_FORMAT)
def post(self, id): bots = self.settings.get('bots', []) ok = False for bot in bots: if bot.access_key == id: ok = True data = utils.json_loads(self.request.body) bot._on_hook(**data) break if ok: self.send_success_response() else: raise ServerError('not_found')
def auth(self): email = self.get_argument('email') password = self.get_argument('password') admin = None for auth_cls in self.auth_classes: role = [auth_cls.role] admin = get_object_or_none(auth_cls, email=email) if admin is not None: break if admin is None: raise ServerError(ServerError.INVALID_CREDENTIALS) if self.current_user and self.current_user.role in role: raise ServerError(ServerError.AUTH_NOT_REQUIRED) if not PasswordHelper.verify_hash(password, admin.password): raise ServerError(ServerError.INVALID_CREDENTIALS) self.session_set('user_id', admin.get_id()) self.session_set('is_auth', True) self.send_success_response()
def get_int_argument(self, name, **kwargs): argument = self.get_argument(name, **self._clear_kwargs(kwargs)) try: if argument != kwargs.get('default'): if argument == '' and 'default' in kwargs: argument = kwargs.get('default') else: argument = int(argument) else: return argument except Exception: raise ServerError(ServerError.INVALID_PARAMETER, description='Argument %s is not int' % name, field=name, field_problem=ServerError.FIELD_INVALID_FORMAT) if kwargs.get('min', None) is not None: min_value = int(kwargs.get('min')) if argument < min_value: raise ServerError(ServerError.INVALID_PARAMETER, description='Argument %s must be greater than %s' % (name, min_value), field=name, field_problem=ServerError.FIELD_LESS_MIN) if kwargs.get('max', None) is not None: max_value = int(kwargs.get('max', self.INT_MAX)) if argument > max_value: raise ServerError(ServerError.INVALID_PARAMETER, description='Argument %s must be less than than %s' % (name, max_value), field=name, field_problem=ServerError.FIELD_MORE_MAX) if kwargs.get('allowed_values', None) is not None: allowed_values = kwargs.get('allowed_values', None) if argument not in allowed_values: raise ServerError(ServerError.INVALID_PARAMETER, description='Value %s is not allowed' % argument, field=name, field_problem=ServerError.FIELD_NOT_ALLOWED) return argument
def get_bool_argument(self, name, **kwargs): argument = self.get_str_argument(name, **kwargs) try: if argument != kwargs.get('default'): if argument.lower() == 'true': argument = True else: argument = False else: return argument except Exception: raise ServerError(ServerError.INVALID_PARAMETER, description='Argument %s is not bool' % name, field=name, field_problem=ServerError.FIELD_INVALID_FORMAT) return argument
def start(self): bots = self.settings.get('bots', []) mode = self.settings.get('mode', BaseBot.MODE_HOOK) for bot in bots: if mode == BaseBot.MODE_HOOK: requests.post(bot.get_method_url('setWebhook'), {'url': bot.get_webhook_url()}) elif mode == BaseBot.MODE_GET_UPDATES: PeriodicCallback(get_updates(bot), options.update_interval).start() else: raise ServerError(ServerError.INTERNAL_SERVER_ERROR, description='Bad server mode') self.listen(options.port, options.host) IOLoop.instance().start()
def get_object(self): id = self.get_str_argument('id', default=None) if id is None: limit = self.get_int_argument('limit', default=20) offset = self.get_int_argument('offset', default=0) objects = self.queryset.skip(offset).limit(limit) objects = [object.to_dict() for object in objects] count = self.MODEL_CLS.objects.count() else: single_object = get_object_or_none(self.MODEL_CLS, id=id) if single_object is None: raise ServerError(ServerError.NOT_FOUND) else: count = 1 objects = [single_object.to_dict()] response = {"items": objects, "count": count} self.send_success_response(data=response)
def to_dict(self, name='', *args, **kwargs): depth = kwargs.get('depth', 0) kwargs.update({'depth': depth + 1}) if depth == 0: fields = kwargs.get('fields', None) else: fields = kwargs.get(name + '_fields', None) next_fields = {} if isinstance(fields, dict): for k, mode in fields.items(): field = k.split('.', 1) if len(field) > 1: entity_title = field[0] fields_chain = field[1] kwargs_key = entity_title + '_fields' if mode == ToDictMixin.MODE_INCLUDE: fields[field[0]] = mode if next_fields.get(kwargs_key) is None: next_fields[kwargs_key] = {} next_fields[kwargs_key][fields_chain] = mode kwargs.update(next_fields) dict_object = self.to_dict_impl(**kwargs) if isinstance(fields, dict): mode = None for v in fields.values(): if v != mode and mode is not None: raise ServerError(ServerError.MIX_FIELDS_FILTER) mode = v % 2 # MODE_EXCLUDE or MODE_INCLUDE for field in dict_object.keys(): if mode == ToDictMixin.MODE_INCLUDE: if field not in fields.keys(): dict_object.pop(field, False) elif mode == ToDictMixin.MODE_EXCLUDE: if field in fields.keys(): dict_object.pop(field, False) return dict_object
async def add_passenger(self): buy_id = self.get_str_argument('buy_id') passengers = json_loads(self.get_argument('passengers')) passengers_names = [] if not isinstance(passengers, list): raise ServerError(ServerError.BAD_REQUEST) user = await self._get_user(buy_id) cv = user['cv'] if not cv.get('passengers'): cv['passengers'] = list() for passenger in passengers: cv['passengers'].append(passenger) passengers_names.append('{name} {surname}'.format( name=passenger.get('name'), surname=passenger.get('surname'), )) user['cv'] = cv await self._save_user(buy_id, user) self.send_success_response() self.finish() if len(passengers_names) > 0: bot = self.bot(user) await bot.send( '{users} {verb} на рейс\n\n' 'Для просмотра всех пассажиров введите {all}\n' 'Для заказа билетов напишите {yes}\n' 'Для отмены покупки напишите {cancel}'.format( all='Все' if bot.is_vk else '/all', yes='Да' if bot.is_vk else '/ok', cancel='Отмена' if bot.is_vk else '/cancel', users=', '.join(passengers_names), verb='зарегистрировался' if len(passengers_names) == 1 else 'зарегистрировались', ))
def start(self, loop_start=True): host = self.settings.get('host', '127.0.0.1') port = self.settings.get('port', 8000) bots = self.settings.get('bots', []) mode = self.settings.get('mode', BaseBot.MODE_HOOK) update_interval = self.settings.get('update_interval', 1000) for bot in bots: if mode == BaseBot.MODE_HOOK: requests.post(bot.get_method_url('setWebhook'), {'url': bot.get_webhook_url()}) elif mode == BaseBot.MODE_GET_UPDATES: PeriodicCallback(get_updates(bot), update_interval).start() else: raise ServerError(ServerError.INTERNAL_SERVER_ERROR, description='Bad server mode') logger.info('Start Roboman') logger.info('Bots: %s' % (', '.join([bot.__name__ for bot in bots]))) self.listen(port, host) if loop_start: IOLoop.instance().start()
def wrapper(self, *args, **kwargs): if self.current_user and self.current_user.role in role: if self.current_user.is_active is not True: raise ServerError(ServerError.ACCOUNT_INACTIVE) return method(self, *args, **kwargs)