示例#1
0
 def validate(self, clean=True):
     if not self.title or not self.payload:
         raise ValidationError("title and payload must be present!")
     elif Utility.check_empty_string(
             self.title) or Utility.check_empty_string(
                 self.payload.strip()):
         raise ValidationError(
             "Response title and payload cannot be empty or blank spaces")
示例#2
0
 def validate(self, clean=True):
     if (Utility.check_empty_string(self.email)
             or Utility.check_empty_string(self.first_name)
             or Utility.check_empty_string(self.last_name)
             or Utility.check_empty_string(self.password)):
         raise ValidationError(
             "Email, FirstName, LastName and password cannot be empty or blank space"
         )
     elif isinstance(email(self.email), ValidationFailure):
         raise ValidationError("Please enter valid email address")
示例#3
0
 def validate(self, clean=True):
     if Utility.check_empty_string(self.name) or Utility.check_empty_string(
             self.pattern):
         raise ValidationError(
             "Regex name and pattern cannot be empty or blank spaces")
     else:
         try:
             re.compile(self.pattern)
         except AppException as e:
             raise AppException("invalid regular expression " +
                                self.pattern)
示例#4
0
    def check(cls, values):
        from kairon.utils import Utility

        if Utility.check_empty_string(values.get('key')):
            raise ValueError("key cannot be empty")

        if values.get('parameter_type'
                      ) == ParameterChoice.slot and Utility.check_empty_string(
                          values.get('value')):
            raise ValueError("Provide name of the slot as value")
        return values
示例#5
0
 def validate(self, clean=True):
     if (Utility.check_empty_string(self.type)
             or Utility.check_empty_string(self.url)
             or Utility.check_empty_string(self.db)):
         raise ValidationError(
             "Type, Url and DB cannot be blank or empty spaces")
     else:
         if self.type == "mongo":
             try:
                 parse_uri(self.url)
             except InvalidURI:
                 raise AppException("Invalid tracker url!")
示例#6
0
    def add_user(
        email: str,
        password: str,
        first_name: str,
        last_name: str,
        account: int,
        bot: str,
        user: str,
        is_integration_user=False,
        role="trainer",
    ):
        """
        adds new user to the account

        :param email: user login id
        :param password: user password
        :param first_name: user firstname
        :param last_name:  user lastname
        :param account: account id
        :param bot: bot id
        :param user: user id
        :param is_integration_user: is this
        :param role: user role
        :return: user details
        """
        if (Utility.check_empty_string(email)
                or Utility.check_empty_string(last_name)
                or Utility.check_empty_string(first_name)
                or Utility.check_empty_string(password)):
            raise AppException(
                "Email, FirstName, LastName and password cannot be empty or blank spaces"
            )

        Utility.is_exist(
            User,
            exp_message=
            "User already exists! try with different email address.",
            email__iexact=email.strip(),
            status=True,
        )
        return (User(
            email=email.strip(),
            password=Utility.get_password_hash(password.strip()),
            first_name=first_name.strip(),
            last_name=last_name.strip(),
            account=account,
            bot=bot.strip(),
            user=user.strip(),
            is_integration_user=is_integration_user,
            role=role.strip(),
        ).save().to_mongo().to_dict())
示例#7
0
    def validate(self, clean=True):
        if Utility.check_empty_string(self.name):
            raise ValidationError(
                "Action name cannot be empty or blank spaces")

        if self.name.startswith('utter_'):
            raise ValidationError("Action name cannot start with utter_")
示例#8
0
 def validate(self, clean=True):
     if Utility.check_empty_string(self.name):
         raise ValidationError("Form name cannot be empty or blank spaces")
     try:
         _validate_slot_mappings({self.name: self.mapping})
     except Exception as e:
         raise ValidationError(e)
示例#9
0
 def validate(self, clean=True):
     if self.entities:
         for ent in self.entities:
             ent.validate()
             extracted_ent = self.text[ent.start:ent.end]
             if extracted_ent != ent.value:
                 raise ValidationError(
                     "Invalid entity: " + ent.entity + ", value: " +
                     ent.value +
                     " does not match with the position in the text " +
                     extracted_ent)
     elif Utility.check_empty_string(
             self.text) or Utility.check_empty_string(self.intent):
         raise ValidationError(
             "Training Example name and text cannot be empty or blank spaces"
         )
示例#10
0
 def validate(self, clean=True):
     Utility.validate_document_list(self.events)
     if Utility.check_empty_string(self.block_name):
         raise ValidationError(
             "Story path name cannot be empty or blank spaces")
     elif not self.events:
         raise ValidationError("Stories cannot be empty")
示例#11
0
    def add_account(name: str, user: str):
        """
        adds a new account

        :param name: account name
        :param user: user id
        :return: account id
        """
        if Utility.check_empty_string(name):
            raise AppException("Account Name cannot be empty or blank spaces")
        Utility.is_exist(
            Account,
            exp_message="Account name already exists!",
            name__iexact=name,
            status=True,
        )
        license = {
            "bots": 2,
            "intents": 10,
            "examples": 50,
            "training": 3,
            "augmentation": 5
        }
        return Account(name=name.strip(), user=user,
                       license=license).save().to_mongo().to_dict()
示例#12
0
 def validate_value(cls, v, values, **kwargs):
     from kairon.utils import Utility
     if len(v) <= 0:
         raise ValueError("value field cannot be empty")
     for ele in v:
         if Utility.check_empty_string(ele):
             raise ValueError("value cannot be an empty string")
     return v
示例#13
0
 def update_bot(name: Text, bot: Text):
     if Utility.check_empty_string(name):
         raise AppException('Name cannot be empty')
     try:
         bot_info = Bot.objects(id=bot, status=True).get()
         bot_info.name = name
         bot_info.save()
     except DoesNotExist:
         raise AppException('Bot not found')
示例#14
0
文件: bot.py 项目: kamalcharan/kairon
async def add_simple_story(request_data: SimpleStoryRequest,
                           current_user: User = Depends(
                               auth.get_current_user)):
    """
    Adds a story (conversational flow) with just one intent and an http action against it.
    """
    if Utility.check_empty_string(
            request_data.action) or Utility.check_empty_string(
                request_data.intent):
        raise AppException("Action and intent cannot be empty")
    return {
        "message": "Story added successfully",
        "data": {
            "_id":
            mongo_processor.prepare_and_add_story(story=request_data.action,
                                                  intent=request_data.intent,
                                                  bot=current_user.get_bot(),
                                                  user=current_user.get_user())
        },
    }
示例#15
0
 def validate(self, clean=True):
     if Utility.check_empty_string(self.name):
         raise ValidationError(
             "Response name cannot be empty or blank spaces")
     elif not self.text and not self.custom:
         raise ValidationError(
             "Either Text or Custom response must be present!")
     else:
         if self.text:
             self.text.validate()
         elif self.custom:
             self.custom.validate()
示例#16
0
 def validate(self, clean=True):
     if Utility.check_empty_string(self.name) or Utility.check_empty_string(
             self.type):
         raise ValueError(
             "Slot name and type cannot be empty or blank spaces")
     error = ""
     if self.type == FloatSlot.type_name:
         if not self.min_value and not self.max_value:
             self.min_value = 0.0
             self.max_value = 1.0
         if self.min_value < self.max_value:
             error = "FloatSlot must have min_value < max_value"
         if not isinstance(self.initial_value, int):
             if error:
                 error += "\n"
             error = "FloatSlot initial_value must be numeric value"
             ValidationError(error)
     elif self.type == CategoricalSlot.type_name:
         if not self.values:
             raise ValidationError(
                 "CategoricalSlot must have list of categories in values field"
             )
示例#17
0
    def add_bot(name: str,
                account: int,
                user: str,
                is_new_account: bool = False):
        """
        add a bot to account

        :param name: bot name
        :param account: account id
        :param user: user id
        :param is_new_account: True if it is a new account
        :return: bot id
        """
        if Utility.check_empty_string(name):
            raise AppException("Bot Name cannot be empty or blank spaces")

        if Utility.check_empty_string(user):
            raise AppException("user cannot be empty or blank spaces")

        Utility.is_exist(
            Bot,
            exp_message="Bot already exists!",
            name__iexact=name,
            account=account,
            status=True,
        )
        bot = Bot(name=name, account=account,
                  user=user).save().to_mongo().to_dict()
        bot_id = bot['_id'].__str__()
        if not is_new_account:
            AccountProcessor.add_bot_for_user(bot_id, user)
        BotSettings(bot=bot_id, user=user).save()
        processor = MongoProcessor()
        config = processor.load_config(bot_id)
        processor.add_or_overwrite_config(config, bot_id, user)
        processor.add_default_fallback_data(bot_id, user, True, True)
        return bot
示例#18
0
    def add_account(name: str, user: str):
        """
        adds a new account

        :param name: account name
        :param user: user id
        :return: account id
        """
        if Utility.check_empty_string(name):
            raise AppException("Account Name cannot be empty or blank spaces")
        Utility.is_exist(
            Account,
            exp_message="Account name already exists!",
            name__iexact=name,
            status=True,
        )
        return Account(name=name.strip(),
                       user=user).save().to_mongo().to_dict()
示例#19
0
    async def overwrite_password(token: str, password: str):
        """
        Changes the user's password

        :param token: unique token from the password reset page
        :param password: new password entered by the user
        :return: mail id, mail subject and mail body
        """
        if Utility.check_empty_string(password):
            raise AppException("password cannot be empty or blank")
        email = Utility.verify_token(token)
        user = User.objects().get(email=email)
        user.password = Utility.get_password_hash(password.strip())
        user.user = email
        user.timestamp = datetime.utcnow
        user.save()
        subject = Utility.email_conf['email']['templates'][
            'password_changed_subject']
        body = Utility.email_conf['email']['templates'][
            'password_changed_body']
        return email, subject, body
示例#20
0
    def add_bot(name: str, account: int, user: str):
        """
        add a bot to account

        :param name: bot name
        :param account: account id
        :param user: user id
        :return: bot id
        """
        if Utility.check_empty_string(name):
            raise AppException("Bot Name cannot be empty or blank spaces")

        Utility.is_exist(
            Bot,
            exp_message="Bot already exists!",
            name__iexact=name,
            account=account,
            status=True,
        )
        return Bot(name=name, account=account,
                   user=user).save().to_mongo().to_dict()
示例#21
0
    async def get_current_user(self,
                               request: Request,
                               token: str = Depends(Utility.oauth2_scheme)):
        """
        validates jwt token

        :param token: jwt token, default extracted by fastapi
        :param request: http request object
        :return: dict of user details
        """
        credentials_exception = HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Could not validate credentials",
            headers={"WWW-Authenticate": "Bearer"},
        )
        try:
            payload = decode(token,
                             self.SECRET_KEY,
                             algorithms=[self.ALGORITHM])
            username: str = payload.get("sub")
            if username is None:
                raise credentials_exception
            token_data = TokenData(username=username)
        except PyJWTError:
            raise credentials_exception
        user = AccountProcessor.get_user_details(token_data.username)
        if user is None:
            raise credentials_exception

        user_model = User(**user)
        if user["is_integration_user"]:
            alias_user = request.headers.get("X-USER")
            if Utility.check_empty_string(alias_user):
                raise HTTPException(
                    status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
                    detail="Alias user missing for integration",
                    headers={"WWW-Authenticate": "Bearer"},
                )
            user_model.alias_user = alias_user
        return user_model
示例#22
0
文件: auth.py 项目: siddbane10/kairon
 async def get_current_user_and_bot(self,
                                    request: Request,
                                    token: str = Depends(
                                        Utility.oauth2_scheme)):
     user = await self.get_current_user(request, token)
     bot_id = request.path_params.get('bot')
     if Utility.check_empty_string(bot_id):
         raise HTTPException(
             status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
             detail='Bot is required',
         )
     if bot_id not in user.bot:
         raise HTTPException(
             status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
             detail='Access denied for bot',
         )
     bot = AccountProcessor.get_bot(bot_id)
     if not bot["status"]:
         raise HTTPException(
             status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
             detail="Inactive Bot Please contact system admin!",
         )
     user.bot = bot_id
     return user
示例#23
0
    def validate_action_name(cls, v, values, **kwargs):
        from kairon.utils import Utility

        if Utility.check_empty_string(v):
            raise ValueError("action_name is required")
        return v
示例#24
0
 def validate(self, clean=True):
     if Utility.check_empty_string(self.block_name):
         raise ValidationError("rule name cannot be empty or blank spaces")
     elif not self.events:
         raise ValidationError("events cannot be empty")
     Utility.validate_flow_events(self.events, "RULE", self.block_name)
示例#25
0
 def validate_synonym(cls, f, values, **kwargs):
     from kairon.utils import Utility
     if Utility.check_empty_string(f):
         raise ValueError("synonym cannot be empty")
     return f
示例#26
0
 def validate(self, clean=True):
     if not Utility.check_empty_string(self.value) and self.type != 'slot':
         raise ValidationError("Value is allowed only for slot")
示例#27
0
 def validate(self, clean=True):
     if Utility.check_empty_string(self.text):
         raise ValidationError(
             "Response text cannot be empty or blank spaces")
     Utility.validate_document_list(self.buttons)
示例#28
0
 def validate(self, clean=True):
     if Utility.check_empty_string(self.name):
         raise ValidationError(
             "Account Name cannot be empty or blank spaces")
示例#29
0
 def validate(self, clean=True):
     if Utility.check_empty_string(self.email):
         raise ValidationError("Email cannot be empty or blank spaces")
     elif isinstance(email(self.email), ValidationFailure):
         raise ValidationError("Invalid email address")
示例#30
0
 def validate(self, clean=True):
     if Utility.check_empty_string(
             self.synonym) or Utility.check_empty_string(self.value):
         raise ValidationError(
             "Synonym name and value cannot be empty or blank spaces")