# Path: doorman/models.py
# class Rule(SurrogatePK, Model):
# 
#     name = Column(db.String, nullable=False)
#     alerters = Column(ARRAY(db.String), nullable=False)
#     description = Column(db.String, nullable=True)
#     conditions = Column(JSONB)
#     updated_at = Column(db.DateTime, nullable=False, default=dt.datetime.utcnow)
# 
#     def __init__(self, name, alerters, description=None, conditions=None, updated_at=None):
#         self.name = name
#         self.description = description
#         self.alerters = alerters
#         self.conditions = conditions
#         self.updated_at = updated_at
# 
#     @property
#     def template(self):
#         return string.Template("{name}\r\n\r\n{description}".format(
#             name=self.name, description=self.description or '')
#         )
# 
# Path: doorman/utils.py
# def validate_osquery_query(query):
#     # Check if this thread has an instance of the SQLite database
#     db = getattr(osquery_mock_db, 'db', None)
#     if db is None:
#         db = create_mock_db()
#         osquery_mock_db.db = db
# 
#     try:
#         db.execute(query)
#     except sqlite3.Error:
#         current_app.logger.exception("Invalid query: %s", query)
#         return False
# 
#     return True


import json
from flask import current_app
from flask_wtf import FlaskForm as Form
from flask_wtf.file import FileField, FileRequired
from wtforms.fields import (
    BooleanField,
    DateTimeField,
    Field,
    IntegerField,
    SelectField,
    SelectMultipleField,
    StringField,
    TextAreaField
)
from wtforms.validators import DataRequired, Optional, ValidationError
from wtforms.widgets import HiddenInput
from doorman.models import Rule
from doorman.utils import validate_osquery_query
        from doorman.models import Pack
        from doorman.models import Query
        from doorman.models import Node, Tag
        from doorman.models import Rule
    def __init__(self, *args, **kwargs):
        super(FilePathUpdateForm, self).__init__(*args, **kwargs)
        # self.set_choices()
        file_path = kwargs.pop('obj', None)
        if file_path:
            self.target_paths.process_data('\n'.join(file_path.get_paths()))
            self.tags.process_data('\n'.join(t.value for t in file_path.tags))


class RuleForm(Form):

    name = StringField('Rule Name', validators=[DataRequired()])
    alerters = SelectMultipleField('Alerters', default=None, choices=[
    ])
    description = TextAreaField('Description', validators=[Optional()])
    conditions = HiddenJSONField('Conditions')

    def set_choices(self):
        alerter_ids = list(current_app.config.get('DOORMAN_ALERTER_PLUGINS', {}).keys())
        self.alerters.choices = [(a, a.title()) for a in alerter_ids]


class CreateRuleForm(RuleForm):

    def validate(self):

        initial_validation = super(CreateRuleForm, self).validate()
        if not initial_validation:
            return False


# Path: doorman/models.py
# class Rule(SurrogatePK, Model):
# 
#     name = Column(db.String, nullable=False)
#     alerters = Column(ARRAY(db.String), nullable=False)
#     description = Column(db.String, nullable=True)
#     conditions = Column(JSONB)
#     updated_at = Column(db.DateTime, nullable=False, default=dt.datetime.utcnow)
# 
#     def __init__(self, name, alerters, description=None, conditions=None, updated_at=None):
#         self.name = name
#         self.description = description
#         self.alerters = alerters
#         self.conditions = conditions
#         self.updated_at = updated_at
# 
#     @property
#     def template(self):
#         return string.Template("{name}\r\n\r\n{description}".format(
#             name=self.name, description=self.description or '')
#         )
# 
# Path: doorman/utils.py
# def validate_osquery_query(query):
#     # Check if this thread has an instance of the SQLite database
#     db = getattr(osquery_mock_db, 'db', None)
#     if db is None:
#         db = create_mock_db()
#         osquery_mock_db.db = db
# 
#     try:
#         db.execute(query)
#     except sqlite3.Error:
#         current_app.logger.exception("Invalid query: %s", query)
#         return False
# 
#     return True


# Path: doorman/manage/forms.py
import json
from flask import current_app
from flask_wtf import FlaskForm as Form
from flask_wtf.file import FileField, FileRequired
from wtforms.fields import (
    BooleanField,
    DateTimeField,
    Field,
    IntegerField,
    SelectField,
    SelectMultipleField,
    StringField,
    TextAreaField
)
from wtforms.validators import DataRequired, Optional, ValidationError
from wtforms.widgets import HiddenInput
from doorman.models import Rule
from doorman.utils import validate_osquery_query
        from doorman.models import Pack
        from doorman.models import Query
        from doorman.models import Node, Tag
        from doorman.models import Rule

    def __init__(self, *args, **kwargs):
        super(FilePathUpdateForm, self).__init__(*args, **kwargs)
        # self.set_choices()
        file_path = kwargs.pop('obj', None)
        if file_path:
            self.target_paths.process_data('\n'.join(file_path.get_paths()))
            self.tags.process_data('\n'.join(t.value for t in file_path.tags))


class RuleForm(Form):

    name = StringField('Rule Name', validators=[DataRequired()])
    alerters = SelectMultipleField('Alerters', default=None, choices=[
    ])
    description = TextAreaField('Description', validators=[Optional()])
    conditions = HiddenJSONField('Conditions')

    def set_choices(self):
        alerter_ids = list(current_app.config.get('DOORMAN_ALERTER_PLUGINS', {}).keys())
        self.alerters.choices = [(a, a.title()) for a in alerter_ids]


class CreateRuleForm(RuleForm):

    def validate(self):

        initial_validation = super(CreateRuleForm, self).validate()
        if not initial_validation:
            return False


        query = Rule.query.filter(Rule.name == self.name.data).first()