def get_user_by_phone(self, db_session: Session, phone): user = get_object(User, db_session, User.phone == phone) if not user: # self.defender.check_ip_exceed() raise HTTPError(*AUTHENTICATION_ERROR) if not user.is_active: raise HTTPError(*USER_IS_NOT_ACTIVE) return user
def get_user_by_id(self, db_session: Session, pk): user = get_object(User, db_session, User.id == pk) dumped_user = user_serializer.dump(user) if not user: raise HTTPError(*TOKEN_EXPIRED) if not user.is_active: raise HTTPError(*USER_IS_NOT_ACTIVE) return dumped_user
def filter(self): try: result = (self.model.mongoquery( self.query).query(**self.mongo_filter_query).end()) return result except Exception as e: raise HTTPError(403, e.args)
def is_object_exist_409(model, session, *args, **kwargs): """ Use is_object_exist_409 if object exist raise Http409. """ model_object = session.query(model).filter(*args, **kwargs).first() if model_object: raise HTTPError(409, body=model().__class__.__name__ + " Already exist") return None
def delete_user(pk, db_session): identity = get_user_identity(db_session) if identity.check_permission("delete_user", User): user = get_object_or_404(User, db_session, User.id == pk) db_session.delete(user) db_session.commit() raise HTTPResponse(status=204, body="Successfully deleted !") raise HTTPError(status=403, body="Access denied")
def change_password(db_session, data): validate_data(change_password_serializer, data) req_user_json = bottle.request.get_user() current_user = db_session.query(User).get(req_user_json['id']) if current_user.check_password(data['old_password']): current_user.set_password(data['password']) return HTTPResponse(*PASSWORD_CHANGED) raise HTTPError(*OLD_PASSWORD_NOT_VALID)
def get_object_or_404(model, session, *args, **kwargs): """ Use get() to return an object, or raise a Http404 exception if the object does not exist. """ model_object = session.query(model).filter(*args, **kwargs).first() if model_object: return model_object raise HTTPError(404, body="Not Found!")
def is_ip_in_blacklist(self): self.ip = request.environ.get('HTTP_X_FORWARDED_FOR') redis = RedisCache() is_blacklisted = redis.get(self.ip) if is_blacklisted: if strtobool(is_blacklisted.decode('utf-8')): raise HTTPError(*IP_BANNED_ERROR) return True return False
def get_users(db_session): try: page_number = bottle.request.GET.get('page') or 1 page_size = bottle.request.GET.get('count') or 10 users = db_session.query(User) return Paginate(users, int(page_number), int(page_size), users_serializer) except Exception as e: raise HTTPError(status=404, body="Something wrong")
def get_object_or_404(model, session, *args, **kwargs): """ Use get() to return an object, or raise a Http404 exception if the object does not exist. """ model_object = session.query(model).filter(*args, **kwargs).first() session.commit() if model_object: return model_object raise HTTPError(404, body=model().__class__.__name__ + "_Not_Found")
def get_nested_list_data(model, data, db_session): if not data: return [] _list_object = [] if hasattr(model(), "id"): for _object in data: actor_obj = get_object_or_404(model, db_session, model.id == _object.get("id")) _list_object.append(actor_obj) return _list_object HTTPError(400, "Model_should_has_id")
def authenticate_user(self, username, password): # self.defender.is_ip_in_blacklist() validate_data(login_serializer, data={"phone": username, "password": password}) user_obj = self.get_user_by_phone(phone=username) if user_obj is not None: if username == user_obj.phone and user_obj.check_password(password): user = user_serializer.dump(user_obj) return user # self.defender.check_ip_exceed() raise HTTPError(*AUTHENTICATION_ERROR)
def phone_activation(data, db_session): try: SMSSchema().load(data) except ValidationError as err: return err.messages cache = RedisCache() phone = data.get('phone') is_object_exist_409(User, db_session, User.phone == phone) if cache.get_cache_multiple_value(phone, 'activation_code'): raise HTTPError(403, ' Phone already has valid activation code') activation_code = generate_otp_code() if send_message(cell_number=phone, activation_code=activation_code): cache.set_cache_multiple_value(key=phone, value=activation_code, custom_value_name='activation_code', ttl=valid_registering_interval) else: raise HTTPError(403, ' Message.Didnt send') result = {'msg': ' Message.MESSAGE_SENT' + phone} return result
def create_user(db_session, data): try: user_serializer.load(data) except Exception as e: raise HTTPError(404, e.args) identity = get_user_identity(db_session) if identity.check_permission("add_user", User): is_object_exist_409(User, db_session, User.phone == data['phone']) person = data['person'] person_obj = get_or_create(Person, db_session, name=person['name']) person_obj.name = person['name'] person_obj.last_name = person['last_name'] person_obj.bio = person['bio'] db_session.add(person_obj) user = get_or_create(User, db_session, phone=data['phone']) user.phone = data['phone'] user.set_roles(data['roles']) user.set_password(data['password']) user.person = person_obj db_session.add(user) db_session.commit() result = user_serializer.dump(db_session.query(User).get(user.id)) return result raise HTTPError(403, "Access denied")
def phone_validation(data, db_session): cache = RedisCache() cell_number = data.get('phone') is_object_exist_409(User, db_session, User.phone == cell_number) activation_code = cache.get_cache_multiple_value(cell_number, 'activation_code') if activation_code is None or activation_code != data.get( 'activation_code'): raise HTTPError(404, body='Validation code is not valid') signup_token = str(uuid4()) cache.set_cache_multiple_value(cell_number, signup_token, 'signup_token', valid_activating_interval) data = {'phone': cell_number, 'signup_token': signup_token} return data
def validate_permission(rule: str, db_session: Session, model): identity = get_user_identity(db_session, model) if identity.check_permission(rule, model): return True raise HTTPError(status=403, body="Access_denied")
def validate_permissions(rules: [], db_session: Session, model): identity = get_user_identity(db_session, model) for rule in rules: if not identity.check_permission(rule, model): raise HTTPError(status=403, body="Access_denied") return True
def validate_response_count(count): if int(count) > 30: raise HTTPError(404, "count of page is too big") return int(count)
def validate_data(serializer: Schema, data: Dict): validation_errors = serializer.validate(data) if validation_errors: raise HTTPError(403, validation_errors) return True
def check_image_extension(ext): if ext not in ('.png', '.jpg', '.jpeg', '.jpe'): raise HTTPError(403, "image_type_forbidden")
def get_user(self, user_id): user = self.get_user_by_id(pk=user_id) if user_id == user['id']: return {k: user[k] for k in user.keys() if k != 'password'} raise HTTPError(*AUTHENTICATION_ERROR)
def check_image_extension(ext): if ext not in (".png", ".jpg", ".jpeg", ".jpe"): raise HTTPError(403, "image_type_forbidden")