Example #1
0
class Event(Base):
    __tablename__ = "event"
    __table_args__ = {"schema": schema}
    __colanderalchemy_config__ = {"title": _("Event"), "plural": _("Events")}
    id = Column(
        Integer,
        primary_key=True,
        info={"colanderalchemy": {"title": _("Identifier"), "widget": HiddenWidget()}},
    )
    issue_id = Column(
        Integer,
        ForeignKey("{}.issue.id".format(schema)),
        nullable=False,
        info={"colanderalchemy": {"title": _("Type"), "widget": HiddenWidget()}},
    )
    status = Column(
        Enum(*tuple(STATUSES.keys()), native_enum=False, name="status"),
        nullable=False,
        info={
            "colanderalchemy": {
                "title": _("Status"),
                "widget": SelectWidget(
                    values=list(STATUSES.items()), item_css_class="item-status"
                ),
            }
        },
    )
    date = Column(
        DateTime(timezone=True),
        nullable=False,
        server_default=func.now(),
        info={"colanderalchemy": {"title": _("Date"), "widget": HiddenWidget()}},
    )
    comment = Column(
        Text, info={"colanderalchemy": {"title": _("Comment"), "missing": ""}}
    )

    private = Column(
        Boolean,
        info={
            "colanderalchemy": {
                "title": _("Private"),
                "widget": CheckboxWidget(item_css_class="item-private"),
            }
        },
    )
    author = Column(
        Enum(*tuple(USER_AUTHORS.keys()), native_enum=False, name="author"),
        nullable=False,
        default="new",
        info={"colanderalchemy": {"title": _("Author"), "widget": HiddenWidget()}},
    )
Example #2
0
class BooleanNode(SchemaNode):
    """
    Colander node representing a boolean value with a checkbox widget.
    """
    schema_type = Boolean
    widget = CheckboxWidget()

    def __init__(self,
                 *args,
                 title: str = "?",
                 label: str = "",
                 default: bool = False,
                 **kwargs) -> None:
        self.title = title  # above the checkbox
        self.label = label or title  # to the right of the checkbox
        self.default = default
        self.missing = default
        super().__init__(*args, **kwargs)
Example #3
0
class BaseUserForm(colander.MappingSchema):
    account_id = colander.SchemaNode(
        colander.String(encoding='utf-8'))
    password = colander.SchemaNode(
        colander.String(encoding='utf-8'), widget=PasswordWidget())
    confirm_password = colander.SchemaNode(
        colander.String(encoding='utf-8'), widget=PasswordWidget())
    is_active = colander.SchemaNode(
        colander.Boolean(), title="Active",
        description="Make this user active/inactive",
        widget=CheckboxWidget())
    group_names = UserGroups(widget=CheckboxChoiceWidget(
        values=[('su', 'Admin')]))

    def validator(self, node, cstruct):
        if cstruct['password'] != cstruct['confirm_password']:
            exc = colander.Invalid(
                self, 'Password and confirmation password must match')
            exc['confirm_password'] = '******'
            raise exc
Example #4
0
class CreateAdminGroupSchema(CSRFSchema):
    def __init__(self, *args):
        super(CreateAdminGroupSchema, self).__init__(
            validator=group_creator_validator, *args
        )

    group_type = colander.SchemaNode(
        colander.String(),
        title=_("Group Type"),
        widget=SelectWidget(values=(("", _("Select")),) + VALID_GROUP_TYPES),
        validator=group_type_validator,
    )

    name = colander.SchemaNode(
        colander.String(),
        title=_("Group Name"),
        validator=validators.Length(
            min=GROUP_NAME_MIN_LENGTH, max=GROUP_NAME_MAX_LENGTH
        ),
        widget=TextInputWidget(max_length=GROUP_NAME_MAX_LENGTH),
    )

    organization = colander.SchemaNode(
        colander.String(),
        title=_("Organization"),
        description=_("Organization which this group belongs to"),
        widget=group_organization_select_widget,
    )

    creator = colander.SchemaNode(
        colander.String(),
        title=_("Creator"),
        description=_("Username for this group's creator"),
        hint=_(
            'This user will be set as the "creator" of the group. Note that'
            " the user must be on the same authority as the group authority"
        ),
    )

    description = colander.SchemaNode(
        colander.String(),
        title=_("Description"),
        description=_("Optional group description"),
        validator=colander.Length(max=GROUP_DESCRIPTION_MAX_LENGTH),
        widget=TextAreaWidget(rows=3, max_length=GROUP_DESCRIPTION_MAX_LENGTH),
        missing=None,
    )

    # Although the default value of the enforce_scope property is True,
    # we need to allow the unchecking of the checkbox that represents it,
    # which means that empty values should be treated as False.
    enforce_scope = colander.SchemaNode(
        colander.Boolean(),
        hint=_(
            "Only allow annotations for documents within this group's defined scopes"
        ),
        widget=CheckboxWidget(css_class="form-checkbox--inline"),
        missing=False,
    )

    scopes = colander.SequenceSchema(
        colander.Sequence(),
        colander.SchemaNode(
            colander.String(), name="scope", validator=url_with_origin_validator
        ),
        title=_("Scopes"),
        hint=_(
            "Define where this group appears. A document's URL must start with one or more"
            " of the entered scope strings (e.g. 'http://www.example.com')"
        ),
        widget=SequenceWidget(add_subitem_text_template=_("Add scope"), min_len=1),
        validator=colander.Length(
            min=1, min_err=_("At least one scope must be specified")
        ),
    )

    members = colander.SequenceSchema(
        colander.Sequence(),
        colander.SchemaNode(
            colander.String(), name="member", validator=member_exists_validator
        ),
        title=_("Members"),
        hint=_("Add more members by their username to this group"),
        widget=SequenceWidget(add_subitem_text_template=_("Add member")),
        missing=None,
    )
Example #5
0
class LayerWMS(DimensionLayer):
    __tablename__ = "layer_wms"
    __table_args__ = {"schema": _schema}
    __colanderalchemy_config__ = {
        "title": _("WMS Layer"),
        "plural": _("WMS Layers")
    }

    __c2cgeoform_config__ = {"duplicate": True}

    __mapper_args__ = {"polymorphic_identity": "l_wms"}

    id = Column(
        Integer,
        ForeignKey(_schema + ".layer.id", ondelete="CASCADE"),
        primary_key=True,
        info={"colanderalchemy": {
            "missing": None,
            "widget": HiddenWidget()
        }},
    )
    ogc_server_id = Column(
        Integer,
        ForeignKey(_schema + ".ogc_server.id"),
        nullable=False,
        info={
            "colanderalchemy": {
                "title":
                _("OGC server"),
                "column":
                2,
                "widget":
                RelationSelect2Widget(OGCServer,
                                      "id",
                                      "name",
                                      order_by="name",
                                      default_value=("", _("- Select -"))),
            }
        },
    )
    layer = Column(
        Unicode,
        nullable=False,
        info={"colanderalchemy": {
            "title": _("WMS layer name"),
            "column": 2
        }})
    style = Column(
        Unicode, info={"colanderalchemy": {
            "title": _("Style"),
            "column": 2
        }})
    valid = Column(
        Boolean,
        info={
            "colanderalchemy": {
                "title": _("Valid"),
                "column": 2,
                "widget": CheckboxWidget(readonly=True)
            }
        },
    )
    invalid_reason = Column(
        Unicode,
        info={
            "colanderalchemy": {
                "title": _("Reason why I am not valid"),
                "column": 2,
                "widget": TextInputWidget(readonly=True),
            }
        },
    )
    time_mode = Column(
        Enum("disabled", "value", "range", native_enum=False),
        default="disabled",
        nullable=False,
        info={
            "colanderalchemy": {
                "title":
                _("Time mode"),
                "column":
                2,
                "widget":
                SelectWidget(values=(("disabled", _("Disabled")), ("value",
                                                                   _("Value")),
                                     ("range", _("Range")))),
            }
        },
    )
    time_widget = Column(
        Enum("slider", "datepicker", native_enum=False),
        default="slider",
        nullable=False,
        info={
            "colanderalchemy": {
                "title":
                _("Time widget"),
                "column":
                2,
                "widget":
                SelectWidget(values=(("slider", _("Slider")),
                                     ("datepicker", _("Datepicker")))),
            }
        },
    )

    # relationship with OGCServer
    ogc_server = relationship(
        "OGCServer",
        info={"colanderalchemy": {
            "title": _("OGC server"),
            "exclude": True
        }})

    def __init__(
        self,
        name: str = "",
        layer: str = "",
        public: bool = True,
        time_mode: str = "disabled",
        time_widget: str = "slider",
    ) -> None:
        DimensionLayer.__init__(self, name=name, public=public)
        self.layer = layer
        self.time_mode = time_mode
        self.time_widget = time_widget

    @staticmethod
    def get_default(dbsession: Session) -> Optional[DimensionLayer]:
        return cast(
            Optional[DimensionLayer],
            dbsession.query(LayerWMS).filter(
                LayerWMS.name == "wms-defaults").one_or_none(),
        )
Example #6
0
def FancyCheckboxInput(label):
    w = CheckboxWidget(template='fancycheckbox',
                       css_class='custom-control-input',
                       label=label)
    return w
Example #7
0
class User(Base):
    __tablename__ = "user"
    __table_args__ = {"schema": _schema + "_static"}
    __acl__ = [
        (Allow, AUTHORIZED_ROLE, ALL_PERMISSIONS),
    ]
    item_type = Column("type",
                       String(10),
                       nullable=False,
                       info={'colanderalchemy': {
                           'widget': HiddenWidget()
                       }})
    __mapper_args__ = {
        "polymorphic_on": item_type,
        "polymorphic_identity": "user",
    }

    id = Column(Integer,
                primary_key=True,
                info={'colanderalchemy': {
                    'widget': HiddenWidget()
                }})
    username = Column(
        Unicode,
        unique=True,
        nullable=False,
    )
    _password = Column("password",
                       Unicode,
                       nullable=False,
                       info={'colanderalchemy': {
                           'widget': HiddenWidget()
                       }})
    temp_password = Column(
        "temp_password",
        Unicode,
        nullable=True,
    )
    email = Column(Unicode,
                   nullable=False,
                   info={'colanderalchemy': {
                       'title': _('email')
                   }})
    is_password_changed = Column(
        Boolean,
        default=False,
        info={'colanderalchemy': {
            'widget': CheckboxWidget(readonly=True)
        }})
    role_name = Column(String,
                       info={
                           'colanderalchemy': {
                               'widget':
                               deform_ext.RelationSelect2Widget(
                                   Role,
                                   'name',
                                   'name',
                                   order_by='name',
                                   default_value=('', _('- Select -')))
                           }
                       })
    _cached_role_name = None
    _cached_role = None

    @property
    def role(self):
        if self._cached_role_name == self.role_name:
            return self._cached_role

        if self.role_name is None or self.role_name == "":  # pragma: no cover
            self._cached_role_name = self.role_name
            self._cached_role = None
            return None

        result = self._sa_instance_state.session.query(Role).filter(
            Role.name == self.role_name).all()
        if len(result) == 0:  # pragma: no cover
            self._cached_role = None
        else:
            self._cached_role = result[0]

        self._cached_role_name = self.role_name
        return self._cached_role

    def __init__(self,
                 username="",
                 password="",
                 email="",
                 is_password_changed=False,
                 functionalities=None,
                 role=None):
        if functionalities is None:
            functionalities = []
        self.username = username
        self.password = password
        self.email = email
        self.is_password_changed = is_password_changed
        self.functionalities = functionalities
        if role is not None:
            self.role_name = role.name

    def _get_password(self):
        """returns password"""
        return self._password  # pragma: no cover

    def _set_password(self, password):
        """encrypts password on the fly."""
        self._password = self.__encrypt_password(password)

    def set_temp_password(self, password):
        """encrypts password on the fly."""
        self.temp_password = self.__encrypt_password(password)

    @staticmethod
    def __encrypt_password(password):
        """Hash the given password with SHA1."""
        return sha1(password.encode("utf8")).hexdigest()

    def validate_password(self, passwd):
        """Check the password against existing credentials.
        this method _MUST_ return a boolean.

        @param passwd: the password that was provided by the user to
        try and authenticate. This is the clear text version that we will
        need to match against the (possibly) encrypted one in the database.
        @type password: string
        """
        if self._password == self.__encrypt_password(passwd):
            return True
        if \
                self.temp_password is not None and \
                self.temp_password != "" and \
                self.temp_password == self.__encrypt_password(passwd):
            self._password = self.temp_password
            self.temp_password = None
            self.is_password_changed = True
            return True
        return False

    password = property(_get_password, _set_password)

    def __unicode__(self):
        return self.username or ""  # pragma: no cover
Example #8
0
class SoftwareProjectSchema(DocumentSchema):

    choices = (
        ('', '- Select -'),
        ('use_entered', 'Used entered description (can be blank)'),
        ('use_pypi_summary', 'Use summary in PyPI data'),
        ('use_pypi_description', 'Use description in PyPI data'),
        ('use_github_description', 'Use description in GitHub data'),
        ('use_bitbucket_description', 'Use description in Bitbucket data'))
    desc_handling_choice = colander.SchemaNode(
        colander.String(),
        default='use_entered',
        missing='use_entered',
        title=_(u'Description Handling'),
        widget=SelectWidget(values=choices))

    pypi_url = colander.SchemaNode(
        colander.String(),
        title=_(u'PyPI URL'),
        description=_(u'Enter unless doing a manual entry.'),
        missing=_(''),)

    choices = (
        ('', '- Select -'),
        ('use_entered', 'Use entered date'),
        ('use_pypi_date', 'Use date in PyPI data'),
        ('use_github_date', 'Use date in GitHub data'),
        ('use_bitbucket_date', 'Use date in Bitbucket data'),
        ('use_now', 'Use current date and time'))
    date_handling_choice = colander.SchemaNode(
        colander.String(),
        default='use_pypi_date',
        title=_(u'Date Handling'),
        widget=SelectWidget(values=choices))
    date = colander.SchemaNode(
        colander.DateTime(),
        title=_(u'Date'),
        description=_(u'Enter date only if date handling = use_entered.'),
        validator=colander.Range(
            min=datetime.datetime(2012, 1, 1, 0, 0,
                                  tzinfo=colander.iso8601.Utc()),
            min_err=_('${val} is too early; min date now is ${min}')),
        widget=DateTimeInputWidget(),
        missing=deferred_date_missing,)

    home_page_url = colander.SchemaNode(
        colander.String(),
        title=_(u'Home Page URL'),
        description=_(u'Leave blank usually, and the URL will be fetched.'),
        missing=_(''),)
    overwrite_home_page_url = colander.SchemaNode(
        colander.Boolean(),
        description='Overwrite home page from PyPI',
        default=True,
        missing=True,
        widget=CheckboxWidget(),
        title='')

    docs_url = colander.SchemaNode(
        colander.String(),
        title=_(u'Docs URL'),
        description=_(u'Leave blank usually, and the URL will be fetched.'),
        missing=_(''),)
    overwrite_docs_url = colander.SchemaNode(
        colander.Boolean(),
        description='Overwrite docs URL from PyPI',
        default=True,
        missing=True,
        widget=CheckboxWidget(),
        title='')

    package_url = colander.SchemaNode(
        colander.String(),
        title=_(u'Download URL'),
        description=_(u'Leave blank usually, and the URL will be fetched.'),
        missing=_(''),)
    overwrite_package_url = colander.SchemaNode(
        colander.Boolean(),
        description='Overwrite package URL from PyPI',
        default=True,
        missing=True,
        widget=CheckboxWidget(),
        title='')

    bugtrack_url = colander.SchemaNode(
        colander.String(),
        title=_(u'Bugtracker URL'),
        description=_(u'Leave blank usually, and the URL will be fetched.'),
        missing=_(''),)
    overwrite_bugtrack_url = colander.SchemaNode(
        colander.Boolean(),
        description='Overwrite bugtracker URL from PyPI',
        default=True,
        missing=True,
        widget=CheckboxWidget(),
        title='')

    github_owner = colander.SchemaNode(
        colander.String(),
        title=_(u'GitHub Owner'),
        description=_(u'Name of the owner on GitHub for the project repo.'),
        missing=_(''),)

    github_repo = colander.SchemaNode(
        colander.String(),
        title=_(u'GitHub Repo'),
        description=_(u'Name of the repo on GitHub for the project.'),
        missing=_(''),)

    bitbucket_owner = colander.SchemaNode(
        colander.String(),
        title=_(u'Bitbucket Owner'),
        description=_(u'Name of the owner on Bitbucket for the project repo.'),
        missing=_(''),)

    bitbucket_repo = colander.SchemaNode(
        colander.String(),
        title=_(u'Bitbucket Repo'),
        description=_(u'Name of the repo on Bitbucket for the project.'),
        missing=_(''),)