Exemple #1
0
class ProfileForm(wtf.Form):
    nickname = wtf.TextField('nickname',
                             validators=[wtf.Required(message=u'请填写昵称')])
    slug = wtf.TextField(
        'slug',
        validators=[
            wtf.Regexp(regex=r'^([a-zA-Z][a-zA-Z0-9_-]{4,23})?$',
                       message=u'长度应为5~24位,仅能包含数字、英文字母及下划线(_)和减号(-),并且需要以字母开头')
        ])
    phone = wtf.TextField(
        'phone',
        validators=[wtf.Regexp(regex=r'^(1\d{10})?$', message=u'请输入有效的手机号码')])
    phone_status = wtf.RadioField('phone_status',
                                  choices=[('0', u'不公开'), ('1', u'公开'),
                                           ('2', u'仅向会员公开')],
                                  default='0')
    # photo = db.Column(db.String(255), nullable=True) # 存一张照片,既然有线下的聚会的,总得认得人才行
    motoo = wtf.TextAreaField(
        'motoo',
        validators=[wtf.Length(min=0, max=255, message=u'座右铭最多为255个字符')])
    introduction = wtf.TextAreaField(
        'introduction',
        validators=[wtf.Length(min=0, max=3000, message=u'个人介绍最多为3000个字')])

    def __init__(self, *args, **kargs):
        wtf.Form.__init__(self, *args, **kargs)
        self.user = None
Exemple #2
0
class MetaDataForm(wtf.Form):
    meta_d = wtf.TextAreaField(
        label=u'"Пошуковий" опис',
        description=u"Пошукові системи відображають цю інформацію при виводі результатів пошуку",
        validators=[wtf.required()]
    )
    meta_k = wtf.TextAreaField(
        label=u"Ключові слова",
        description=u"Перелік ключових слів, які будуть застосовуватися на кожній сторінці сайту",
        validators=[wtf.required()]
    )
Exemple #3
0
class UserGroupForm(wtf.Form):
    name = wtf.TextField('URL name', validators=[wtf.Required()])
    title = wtf.TextField('Title', validators=[wtf.Required()])
    users = wtf.TextAreaField(
        'Users',
        validators=[wtf.Required()],
        description="Usernames or email addresses, one per line")
Exemple #4
0
class ContactUpdateForm(wtf.Form):
    name = wtf.StringField('Name', [wtf.validators.required()])
    email = wtf.StringField(
        'Email', [wtf.validators.optional(),
                  wtf.validators.email()])
    phone = wtf.StringField('Phone', [wtf.validators.optional()])
    address = wtf.TextAreaField('Address', [wtf.validators.optional()])
Exemple #5
0
class ConfigUpdateForm(wtf.Form):
    analytics_id = wtf.StringField('Tracking ID', filters=[util.strip_filter])
    announcement_html = wtf.TextAreaField('Announcement HTML',
                                          filters=[util.strip_filter])
    announcement_type = wtf.SelectField(
        'Announcement Type',
        choices=[(t, t.title())
                 for t in model.Config.announcement_type._choices])
    brand_name = wtf.StringField('Brand Name', [wtf.validators.required()],
                                 filters=[util.strip_filter])
    facebook_app_id = wtf.StringField('Facebook App ID',
                                      filters=[util.strip_filter])
    facebook_app_secret = wtf.StringField('Facebook App Secret',
                                          filters=[util.strip_filter])
    feedback_email = wtf.StringField(
        'Feedback Email', [wtf.validators.optional(),
                           wtf.validators.email()],
        filters=[util.email_filter])
    flask_secret_key = wtf.StringField('Secret Key',
                                       [wtf.validators.optional()],
                                       filters=[util.strip_filter])
    notify_on_new_user = wtf.BooleanField(
        'Send an email notification when a user signs up')
    twitter_consumer_key = wtf.StringField('Twitter Consumer Key',
                                           filters=[util.strip_filter])
    twitter_consumer_secret = wtf.StringField('Twitter Consumer Secret',
                                              filters=[util.strip_filter])
Exemple #6
0
class ResourceActionForm(Form):
    """
    Edit an action associated with a resource
    """
    name = wtf.TextField(
        'Action name',
        validators=[wtf.Required()],
        description="Name of the action as a single word in lower case. "
        "This is provided by applications as part of the scope in the form "
        "'resource/action' when requesting access to a user's resources. "
        "Read actions are implicit when applications request just 'resource' "
        "in the scope and do not need to be specified as an explicit action.")
    title = wtf.TextField(
        'Title',
        validators=[wtf.Required()],
        description='Action title that is displayed to users')
    description = wtf.TextAreaField(
        'Description',
        description='An optional description of what the action is')

    def validate_name(self, field):
        if not valid_username(field.data):
            raise wtf.ValidationError("Name contains invalid characters.")

        existing = ResourceAction.query.filter_by(
            name=field.data, resource=self.edit_resource).first()
        if existing and existing.id != self.edit_id:
            raise wtf.ValidationError(
                "An action with that name already exists for this resource")
Exemple #7
0
class InventoryItemForm(wtf.Form):
    """Represents the admin inventory item form"""
    group = wtf.SelectField()
    name = wtf.TextField(validators=[wtf.required()])
    identifier = wtf.TextField()
    status = wtf.SelectField(choices=INVENTORY_STATUS, coerce=int)
    comment = wtf.TextAreaField()

    def __init__(self, formdata=None, obj=None, prefix='', **kwargs):
        super(InventoryItemForm, self).__init__(request.form, obj, prefix,
                                                **kwargs)
        self.csrf_enabled = False
        self.group.choices = [(str(grp.id), grp.name)
                              for grp in InventoryGroup.objects]
        # select the group
        if request.args.get('id') and not self.is_submitted():
            item = InventoryItem.objects(id=request.args.get('id')).get()
            self.group.data = str(item.group.id)

    def validate(self, extra_validators=None):
        success = True
        # run validation for fields
        for field in (self.name, self.status):
            if not field.validate(self.data):
                success = False
                self.errors[field.name] = field.errors
        return success

    def process(self, formdata=None, obj=None, **kwargs):
        super(InventoryItemForm, self).process(formdata, obj, **kwargs)
        if self.is_submitted():
            # convert to admin model friendly types
            self.status.data = int(self.status.data)
Exemple #8
0
class ContentForm(Form):
    previous_id = wtf.HiddenField(u"Previous revision")
    title = wtf.TextField(u"Title", validators=[wtf.Required()])
    name = wtf.TextField(u"URL name", validators=[wtf.Optional(), valid_name])
    description = wtf.TextAreaField(u"Summary",
                                    description=u"Summary of this page")
    content = RichTextField(u"Page content",
                            linkify=False,
                            buttons1=richtext_buttons1,
                            valid_elements=richtext_valid_elements,
                            sanitize_tags=richtext_sanitize_tags,
                            sanitize_attributes=richtext_sanitize_attributes)
    template = wtf.TextField(
        "Template",
        validators=[wtf.Required()],
        default='page.html',
        description=u"Template with which this page will be rendered.")
    properties = DictField(u"Properties")

    def validate_previous_id(self, field):
        if not field.data:
            field.data = None
        else:
            try:
                field.data = int(field.data)
            except ValueError:
                raise wtf.ValidationError("Unknown previous revision")

    def validate_name(self, field):
        # TODO
        pass
Exemple #9
0
class CommentForm(wtf.Form):

    parent = QuerySelectField('Reply to', allow_blank=True)
    body = wtf.TextAreaField('Comment', validators=[wtf.Required()])
    submit = wtf.SubmitField('Submit')

    def fill_comments(self, post):
        self.parent.query = post.comments
Exemple #10
0
class CommentForm(wtf.Form):
    reply_to_id = wtf.HiddenField('Parent',
                                  default="",
                                  id="comment_reply_to_id")
    edit_id = wtf.HiddenField('Edit', default="", id="comment_edit_id")
    message = wtf.TextAreaField('Add comment',
                                id="comment_message",
                                validators=[wtf.Required()])
Exemple #11
0
class MapForm(Form):
    name = wtf.TextField(u"URL name", validators=[wtf.Required(), valid_name])
    title = wtf.TextField(u"Title", validators=[wtf.Required()])
    list = wtf.TextAreaField(
        'Map markers',
        validators=[wtf.Required()],
        description=u'Enter each row as a JSON object with name, title, url, '
        u'latitude, longitude, zoomlevel and marker. '
        u'The URL, zoomlevel and marker can be null, others cannot.')
    properties = DictField(u"Properties")
class ElectionForm(wtf.Form):
    summary = wtf.TextField(
        'Summary', [wtf.validators.Required(),
                    wtf.validators.Length(max=150)])
    alias = wtf.TextField('Alias', [
        wtf.validators.Required(),
        wtf.validators.Length(max=100),
        wtf.validators.Regexp('[a-z0-9_-]+',
                              message=('Alias may only contain lower case '
                                       'letters, numbers, hyphens and '
                                       'underscores.')),
    ])
    description = wtf.TextAreaField('Description', [wtf.validators.Required()])
    url = wtf.TextField('URL', [
        wtf.validators.Required(),
        wtf.validators.URL(),
        wtf.validators.Length(max=250)
    ])
    start_date = wtf.DateField('Start date', [wtf.validators.Required()])
    end_date = wtf.DateField('End date', [wtf.validators.Required()])
    number_elected = wtf.IntegerField(
        'Number elected',
        [wtf.validators.Required(),
         wtf.validators.NumberRange(min=1)],
        default=1)
    candidates_are_fasusers = wtf.BooleanField('Candidates are FAS users?')
    frontpage = wtf.BooleanField('Show on front page?')
    embargoed = wtf.BooleanField('Embargo results?', default=True)

    def __init__(form, election_id=None, *args, **kwargs):
        super(ElectionForm, form).__init__(*args, **kwargs)
        form._election_id = election_id

    def validate_summary(form, field):
        check = Election.query.filter_by(summary=form.summary.data).all()
        if check:
            if not (form._election_id and form._election_id == check[0].id):
                raise wtf.ValidationError('There is already another election '
                                          'with this summary.')

    def validate_alias(form, field):
        if form.alias.data == 'new':
            raise wtf.ValidationError(
                flask.Markup('The alias cannot be '
                             '<code>new</code>.'))
        check = Election.query.filter_by(alias=form.alias.data).all()
        if check:
            if not (form._election_id and form._election_id == check[0].id):
                raise wtf.ValidationError('There is already another election '
                                          'with this alias.')

    def validate_end_date(form, field):
        if form.end_date.data <= form.start_date.data:
            raise wtf.ValidationError('End date must be later than '
                                      'start date.')
Exemple #13
0
class ProposalForm(wtf.Form):
    email = wtf.html5.EmailField('Your email address', validators=[wtf.Required()],
        description="An email address we can contact you at. "\
            "Not displayed anywhere")
    phone = wtf.TextField('Phone number', validators=[wtf.Required()],
        description="A phone number we can call you at to discuss your proposal, if required. "
            "Will not be displayed")
    speaking = wtf.RadioField("Are you speaking?", coerce=int,
        choices=[(1, u"I will be speaking"),
                 (0, u"I’m proposing a topic for someone to speak on")])
    title = wtf.TextField('Title', validators=[wtf.Required()],
        description="The title of your session")
    section = wtf.QuerySelectField('Section', get_label='title', validators=[wtf.Required()],
        widget=wtf.ListWidget(prefix_label=False), option_widget=wtf.RadioInput())
    objective = wtf.TextAreaField('Objective', validators=[wtf.Required()],
        description="What is the expected benefit for someone attending this?")
    session_type = wtf.RadioField('Session type', validators=[wtf.Required()], choices=[
        ('Lecture', 'Lecture'),
        ('Demo', 'Demo'),
        ('Tutorial', 'Tutorial'),
        ('Workshop', 'Workshop'),
        ('Discussion', 'Discussion'),
        ('Panel', 'Panel'),
        ])
    technical_level = wtf.RadioField('Technical level', validators=[wtf.Required()], choices=[
        ('Beginner', 'Beginner'),
        ('Intermediate', 'Intermediate'),
        ('Advanced', 'Advanced'),
        ])
    description = wtf.TextAreaField('Description', validators=[wtf.Required()],
        description="A detailed description of the session")
    requirements = wtf.TextAreaField('Requirements',
        description="For workshops, what must participants bring to the session?")
    slides = wtf.html5.URLField('Slides', validators=[wtf.Optional(), wtf.URL()],
        description="Link to your slides. These can be just an outline initially. "\
            "If you provide a Slideshare link, we'll embed slides in the page")
    links = wtf.TextAreaField('Links',
        description="Other links, one per line. Provide links to your profile and "\
            "slides and videos from your previous sessions; anything that'll help "\
            "folks decide if they want to attend your session")
    bio = wtf.TextAreaField('Speaker bio', validators=[wtf.Required()],
        description="Tell us why you are the best person to be taking this session")
Exemple #14
0
class ListForm(Form):
    name = wtf.TextField(u"URL name", validators=[wtf.Required(), valid_name])
    title = wtf.TextField(u"Title", validators=[wtf.Required()])
    list = wtf.TextAreaField(
        'Items',
        validators=[wtf.Required()],
        description=
        u'Enter each row as a JSON array with ["name", title", "url", "folder/node"]. '
        u'For nodes in the root folder, use "/node". To not include a node, use "".'
    )
    properties = DictField(u"Properties")
Exemple #15
0
class FeedbackForm(wtf.Form):
  subject = wtf.StringField('Subject',
      [wtf.validators.required()], filters=[util.strip_filter],
    )
  message = wtf.TextAreaField('Message',
      [wtf.validators.required()], filters=[util.strip_filter],
    )
  email = wtf.StringField('Email (optional)',
      [wtf.validators.optional(), wtf.validators.email()],
      filters=[util.email_filter],
    )
Exemple #16
0
class CommentForm(wtf.Form):
    """
    Comment form
    """
    reply_to_id = wtf.HiddenField("Parent",
                                  default='',
                                  id='comment_reply_to_id')
    edit_id = wtf.HiddenField("Edit", default='', id='comment_edit_id')
    message = wtf.TextAreaField("Add comment",
                                id='comment_message',
                                validators=[wtf.Required()])
Exemple #17
0
class PostForm(wtf.Form):

    title = wtf.TextField('Title',
                          validators=[wtf.Required()],
                          description='This will be shown on the list.')
    body = wtf.TextAreaField('Body',
                             validators=[wtf.Required()],
                             description='Markdown format enabled.')
    sticky = wtf.BooleanField('Sticky',
                              description='Show this post always on top.')
    submit = wtf.SubmitField('Submit')
Exemple #18
0
class ActivityForm(RedirectForm):
    title = wtf.TextField(u'活动标题', validators=[ \
            wtf.Required(message=u'请为活动填写一个标题')])
    content = wtf.TextAreaField(u'活动简介', validators=[ \
            wtf.Length(min=10, max=5000, message=u'简介至少10个字')])
    start_time = wtf.TextField(u'开始时间', validators=[ \
            wtf.Required(message=u'需要指定开始时间')])
    end_time = wtf.TextField(u'结束时间', validators=[ \
            wtf.Required(message=u'需要指定结束时间')])
    address = wtf.TextField(u'活动地点')
    latitude = wtf.HiddenField()
    longitude = wtf.HiddenField()
Exemple #19
0
class DataForm(Form):
    name = wtf.TextField(u"URL name", validators=[wtf.Required(), valid_name])
    title = wtf.TextField(u"Title", validators=[wtf.Required()])
    data = wtf.TextAreaField(u"Data",
                             validators=[wtf.Required()],
                             description=u"Enter JSON data")
    properties = DictField(u"Properties")

    def validate_data(self, field):
        # Check for exceptions when loading data
        parsed = simplejson.loads(field.data, use_decimal=True)
        if not isinstance(parsed, dict):
            raise wtf.ValidationError(
                u'This is not a valid JSON object. Use {"key": value, ...}')
Exemple #20
0
class ProfileNewForm(ProfileFormBase, Form):
    fullname = wtf.TextField('Full name', validators=[wtf.Required()])
    email = wtf.html5.EmailField('Email address',
                                 validators=[wtf.Required(),
                                             wtf.Email()])
    username = wtf.TextField('Username (optional)')
    description = wtf.TextAreaField('Bio')

    def validate_email(self, field):
        existing = UserEmail.query.filter_by(email=field.data).first()
        self.existing_email = existing  # Save for later
        if existing is not None and existing.user != self.edit_obj:
            raise wtf.ValidationError(
                "This email address has been claimed by another user.")
Exemple #21
0
class EventForm(Form):
    """Form to create or edit an event."""

    name = wtf.TextField('Name',
                         validators=[
                             wtf.Required(),
                             wtf.Length(max=200),
                         ])
    starts_at = wtf.DateTimeField('When', format='%Y-%m-%d %H:%M')
    venue = wtf.TextField('Where', validators=[
        wtf.Length(max=200),
    ])
    description = wtf.TextAreaField('What')
    contacts_invited_ids_str = wtf.HiddenField()
Exemple #22
0
class OrganizationForm(Form):
    title = wtf.TextField('Organization name', validators=[wtf.Required()])
    name = wtf.TextField('URL name', validators=[wtf.Required()])
    description = wtf.TextAreaField('Description')

    def validate_name(self, field):
        if not valid_username(field.data):
            raise wtf.ValidationError("Invalid characters in name")
        if field.data in RESERVED_USERNAMES:
            raise wtf.ValidationError("That name is reserved")
        existing = User.query.filter_by(username=field.data).first()
        if existing is not None:
            raise wtf.ValidationError("That name is taken")
        existing = Organization.query.filter_by(name=field.data).first()
        if existing is not None and existing.id != self.edit_id:
            raise wtf.ValidationError("That name is taken")
Exemple #23
0
class ProposalSpaceForm(wtf.Form):
    name = wtf.TextField('URL name', validators=[wtf.Required()])
    title = wtf.TextField('Title', validators=[wtf.Required()])
    datelocation = wtf.TextField('Date and Location', validators=[wtf.Required()])
    date = wtf.DateField('Date (for sorting)', validators=[wtf.Required()])
    tagline = wtf.TextField('Tagline', validators=[wtf.Required()])
    description = wtf.TextAreaField('Description', validators=[wtf.Required()])
    status = wtf.SelectField('Status', coerce=int, choices=[
        (0, 'Draft'),
        (1, 'Open'),
        (2, 'Voting'),
        (3, 'Jury selection'),
        (4, 'Feedback'),
        (5, 'Closed'),
        (6, 'Rejected'),
        ])
Exemple #24
0
class NewPaste(wtf.Form):
    text = wtf.TextField('uid') # honeypot field
    paste = wtf.TextAreaField('text', validators=[wtf.Required()])
    title = wtf.TextField('title', validators=[wtf.Optional()])
    password = wtf.PasswordField('password', validators=[wtf.Optional()])
    unlisted = wtf.BooleanField('Unlisted')
    submit = wtf.SubmitField('Paste')
    language = wtf.SelectField(
        'language',
        choices=[
            ('', ''),
            ('text', 'Text'),
            ('c', 'C'),
            ('csharp', 'C#'),
            ('cpp', 'C++'),
            ('css', 'CSS'),
            ('erlang', 'Erlang'),
            ('go', 'GO'),
            ('html', 'HTML'),
            ('java', 'Java'),
            ('javascript', 'Javascript'),
            ('json', 'JSON'),
            ('objectivec', 'Objective-C'),
            ('perl', 'Perl'),
            ('python', 'Python (2.X)'),
            ('python3', 'Python (3.X)'),
            ('pycon', 'Python Console'),
            ('pytb', 'Python 2 Traceback'),
            ('py3tb', 'Python 3 Traceback'),
            ('ruby', 'Ruby'),
            ('sql', 'SQL'),
            ('vbnet', 'VB.NET'),
        ]
    )

    def validate_uid(form, field):
        """
        This ensures the hidden honeypot field is left blank,
        only automated spambots should attempt to fill it in
        """
        if field.data != '':
            raise wtf.validators.ValidationError()
Exemple #25
0
class ResourceForm(Form):
    """
    Edit a resource provided by an application
    """
    name = wtf.TextField(
        'Resource name',
        validators=[wtf.Required()],
        description="Name of the resource as a single word in lower case. "
        "This is provided by applications as part of the scope "
        "when requesting access to a user's resources.")
    title = wtf.TextField(
        'Title',
        validators=[wtf.Required()],
        description='Resource title that is displayed to users')
    description = wtf.TextAreaField(
        'Description',
        description='An optional description of what the resource is')
    siteresource = wtf.BooleanField(
        'Site resource',
        description=
        'Enable if this resource is generic to the site and not owned by specific users'
    )
    trusted = wtf.BooleanField(
        'Trusted applications only',
        description=
        'Enable if access to the resource should be restricted to trusted '
        'applications. You may want to do this for sensitive information like billing data'
    )

    def validate_name(self, field):
        if not valid_username(field.data):
            raise wtf.ValidationError("Name contains invalid characters.")

        if field.data in registry:
            raise wtf.ValidationError("This name is reserved for internal use")

        existing = Resource.query.filter_by(name=field.data).first()
        if existing and existing.id != self.edit_id:
            raise wtf.ValidationError(
                "A resource with that name already exists")
Exemple #26
0
class ProfileForm(Form):
    fullname = wtf.TextField('Full name', validators=[wtf.Required()])
    email = wtf.html5.EmailField('Email address',
                                 validators=[wtf.Required(),
                                             wtf.Email()])
    username = wtf.TextField('Username', validators=[wtf.Required()])
    description = wtf.TextAreaField('Bio')
    timezone = wtf.SelectField('Timezone',
                               validators=[wtf.Required()],
                               choices=timezones)

    def __init__(self, *args, **kwargs):
        super(ProfileForm, self).__init__(*args, **kwargs)
        self.existing_email = None

    def validate_username(self, field):
        ## Usernames are now mandatory. This should be commented out:
        # if not field.data:
        #     field.data = None
        #     return
        if not valid_username(field.data):
            raise wtf.ValidationError("Invalid characters in username")
        if field.data in RESERVED_USERNAMES:
            raise wtf.ValidationError("That name is reserved")
        existing = User.query.filter_by(username=field.data).first()
        if existing is not None and existing.id != self.edit_id:
            raise wtf.ValidationError("That username is taken")
        existing = Organization.query.filter_by(name=field.data).first()
        if existing is not None:
            raise wtf.ValidationError("That username is taken")

    def validate_email(self, field):
        existing = UserEmail.query.filter_by(email=field.data).first()
        if existing is not None and existing.user != self.edit_obj:
            raise wtf.ValidationError(
                "This email address has been claimed by another user.")
Exemple #27
0
class EditForm(form.BaseForm):
    content = wtf.TextAreaField(lazy_gettext('Content'),
                                [wtf.validators.required()])
Exemple #28
0
class NewAlbumForm(wtf.Form):
    title = wtf.TextField(validators=[wtf.required()])
    description = wtf.TextAreaField()
Exemple #29
0
class RegisterClientForm(Form):
    """
    Register a new OAuth client application
    """
    title = wtf.TextField('Application title',
                          validators=[wtf.Required()],
                          description="The name of your application")
    description = wtf.TextAreaField(
        'Description',
        validators=[wtf.Required()],
        description="A description to help users recognize your application")
    client_owner = wtf.RadioField(
        'Owner',
        validators=[wtf.Required()],
        description=
        "User or organization that owns this application. Changing the owner "
        "will revoke all currently assigned permissions for this app")
    website = wtf.html5.URLField(
        'Application website',
        validators=[wtf.Required(), wtf.URL()],
        description="Website where users may access this application")
    redirect_uri = wtf.html5.URLField('Redirect URI',
                                      validators=[wtf.Optional(),
                                                  wtf.URL()],
                                      description="OAuth2 Redirect URI")
    notification_uri = wtf.html5.URLField(
        'Notification URI',
        validators=[wtf.Optional(), wtf.URL()],
        description=
        "Lastuser resource provider Notification URI. When another application requests access to "
        "resources provided by this app, Lastuser will post a notice to this URI with a copy of the access "
        "token that was provided to the other application. Other notices may be posted too "
        "(not yet implemented)")
    iframe_uri = wtf.html5.URLField(
        'IFrame URI',
        validators=[wtf.Optional(), wtf.URL()],
        description=
        "Front-end notifications URL. This is loaded in a hidden iframe to notify the app that the "
        "user updated their profile in some way (not yet implemented)")
    resource_uri = wtf.html5.URLField(
        'Resource URI',
        validators=[wtf.Optional(), wtf.URL()],
        description=
        "URI at which this application provides resources as per the Lastuser Resource API "
        "(not yet implemented)")
    allow_any_login = wtf.BooleanField(
        'Allow anyone to login',
        default=True,
        description=
        "If your application requires access to be restricted to specific users, uncheck this, "
        "and only users who have been assigned a permission to the app will be able to login"
    )
    team_access = wtf.BooleanField(
        'Requires access to teams',
        default=False,
        description=
        "If your application is capable of assigning access permissions to teams, check this. "
        "Organization owners will then able to grant access to teams in their organizations"
    )

    def validate_client_owner(self, field):
        if field.data == g.user.userid:
            self.user = g.user
            self.org = None
        else:
            orgs = [
                org for org in g.user.organizations_owned()
                if org.userid == field.data
            ]
            if len(orgs) != 1:
                raise wtf.ValidationError("Invalid owner")
            self.user = None
            self.org = orgs[0]
Exemple #30
0
class PermissionForm(Form):
    """
    Create or edit a permission
    """
    name = wtf.TextField(
        'Permission name',
        validators=[wtf.Required()],
        description='Name of the permission as a single word in lower case. '
        'This is passed to the application when a user logs in. '
        'Changing the name will not automatically update it everywhere. '
        'You must reassign the permission to users who had it with the old name'
    )
    title = wtf.TextField(
        'Title',
        validators=[wtf.Required()],
        description='Permission title that is displayed to users')
    description = wtf.TextAreaField(
        'Description',
        description='An optional description of what the permission is for')
    context = wtf.RadioField(
        'Context',
        validators=[wtf.Required()],
        description='Context where this permission is available')

    def validate(self):
        rv = super(PermissionForm, self).validate()
        if not rv:
            return False

        if not valid_username(self.name.data):
            raise wtf.ValidationError("Name contains invalid characters")

        existing = Permission.query.filter_by(name=self.name.data,
                                              allusers=True).first()
        if existing and existing.id != self.edit_id:
            self.name.errors.append(
                "A global permission with that name already exists")
            return False

        if self.context.data == g.user.userid:
            existing = Permission.query.filter_by(name=self.name.data,
                                                  user=g.user).first()
        else:
            org = Organization.query.filter_by(
                userid=self.context.data).first()
            if org:
                existing = Permission.query.filter_by(name=self.name.data,
                                                      org=org).first()
            else:
                existing = None
        if existing and existing.id != self.edit_id:
            self.name.errors.append(
                "You have another permission with the same name")
            return False

        return True

    def validate_context(self, field):
        if field.data == g.user.userid:
            self.user = g.user
            self.org = None
        else:
            orgs = [
                org for org in g.user.organizations_owned()
                if org.userid == field.data
            ]
            if len(orgs) != 1:
                raise wtf.ValidationError("Invalid context")
            self.user = None
            self.org = orgs[0]