Beispiel #1
0
    def set_validators(self):
        config = self.db.config
        T = self.db.T
        request = self.db.request
        self.entity.nickname.requires = [
            IS_SLUG(), IS_NOT_IN_DB(self.db, self.entity.nickname)
        ]
        self.entity.twitter.requires = IS_EMPTY_OR(
            IS_NOT_IN_DB(self.db, self.entity.twitter))
        self.entity.facebook.requires = IS_EMPTY_OR(
            IS_NOT_IN_DB(self.db, self.entity.facebook))

        self.entity.extra_links.requires = IS_EMPTY_OR(
            IS_LIST_OF(
                IS_URL(allowed_schemes=['https', 'http'],
                       prepend_scheme='http')))

        self.entity.photo_source.requires = IS_IN_SET(
            config.get_list('auth', 'photo_source'))
        self.entity.gender.requires = IS_EMPTY_OR(
            IS_IN_SET(config.get_list('auth', 'gender')))
        self.entity.privacy.requires = IS_IN_SET(
            config.get_list('auth', 'privacy'))
        #date format not allowed on gae
        if not request.env.web2py_runtime_gae:
            self.entity.birthdate.requires = IS_EMPTY_OR(
                IS_DATE(format=str(T('%Y-%m-%d'))))

        self.entity.website.requires = IS_EMPTY_OR(IS_URL())
Beispiel #2
0
 def __init__(
         self,
         dbset,
         field,
         error_message='value already in database or empty',
         allowed_override=None,
         ignore_common_filters=False):
     if allowed_override is None:
         allowed_override = []
     IS_NOT_IN_DB.__init__(
         self,
         dbset,
         field,
         error_message,
         allowed_override,
         ignore_common_filters
     )
Beispiel #3
0
 def _define_alt_login_table(self):
     """
     Define the OpenID login table.
     Note: type is what I used for our project. We're going to support 'fackbook' and
           'plurk' alternate login methods. Otherwise it's always 'openid' and you
           may not need it. This should be easy to changed.
           (Just remove the field of "type" and remove the
            "and db.alt_logins.type == type_" in _find_matched_openid function)
     """
     db = self.db
     table = db.define_table(
         self.table_alt_logins_name,
         Field('username', length=512, default=''),
         Field('type', length=128, default='openid', readable=False),
         Field('user', self.table_user, readable=False),
     )
     table.username.requires = IS_NOT_IN_DB(db, table.username)
     self.table_alt_logins = table
Beispiel #4
0
    def set_properties(self):
        ckeditor = CKEditor()
        self.fields = [
            Field("title", unique=True),
            Field("description", "text"),
            Field("page_content", "text"),
            Field("picture", "upload"),
            Field("thumbnail", "upload"),
            Field("tags", "list:string"),
            Field("slug"),
            Field("page_scope", "list:string", default=["public", "sitemap"]),
            Field("visibility"),
            Field("text_language", default="pt-br"),
            Field("redirect_url"),
        ]

        self.widgets = {
            "tags": StringListWidget.widget,
            "page_content": ckeditor.widget
        }

        self.comments = {
          "page_scope": "public, sitemap, members"
        }

        self.computations = {
            "slug": lambda r: IS_SLUG()(r.title)[0],
            "thumbnail": lambda r: THUMB2(r.picture, 200, 200)
        }

        self.validators = {
            "title": [IS_NOT_EMPTY(), IS_NOT_IN_DB(self.db, "internal_page.title")],
            "description": IS_NOT_EMPTY(),
            "picture": IS_EMPTY_OR(IS_IMAGE()),
            "tags": COMMA_SEPARATED_LIST(),
            "text_language": IS_IN_SET(["en", "pt-br", "es"])
        }
Beispiel #5
0
    def register(self, log=DEFAULT, **kwargs):
        """
        Register a user.
        """

        table_user = self.table_user()
        settings = self.settings

        if self.is_logged_in():
            raise AssertionError('User trying to register is logged in')

        if log is DEFAULT:
            log = self.messages['register_log']

        if self.settings.login_userfield:
            userfield = self.settings.login_userfield
        elif 'username' in table_user.fields:
            userfield = 'username'
        else:
            userfield = 'email'

        # Ensure the username field is unique.
        unique_validator = IS_NOT_IN_DB(self.db, table_user[userfield])
        userfield_validator = table_user[userfield].requires
        if userfield_validator is None:
            userfield_validator = unique_validator
        elif isinstance(userfield_validator, (list, tuple)):
            if not any([
                    isinstance(validator, IS_NOT_IN_DB)
                    for validator in userfield_validator
            ]):
                if isinstance(userfield_validator, list):
                    userfield_validator.append(unique_validator)
                else:
                    userfield_validator += (unique_validator, )
        elif not isinstance(userfield_validator, IS_NOT_IN_DB):
            userfield_validator = [userfield_validator, unique_validator]
        table_user[userfield].requires = userfield_validator

        passfield = settings.password_field

        try:  # Make sure we have our original minimum length
            table_user[passfield].requires[
                -1].min_length = settings.password_min_length
        except:
            pass

        key = web2py_uuid()
        if settings.registration_requires_approval:
            key = 'pending-' + key

        table_user.registration_key.default = key

        result = table_user.validate_and_insert(**kwargs)
        if result.errors:
            return {
                'errors': result.errors.as_dict(),
                'message': None,
                'user': None
            }

        user = table_user[result.id]

        message = self.messages.registration_successful

        if settings.create_user_groups:
            d = user.as_dict()
            description = self.messages.group_description % d
            group_id = self.add_group(settings.create_user_groups % d,
                                      description)
            self.add_membership(group_id, result.id)

        if self.settings.everybody_group_id:
            self.add_membership(self.settings.everybody_group_id, result)

        if settings.registration_requires_verification:
            d = {
                k: user[k]
                for k in table_user.fields if table_user[k].readable
            }
            d['key'] = key
            if settings.login_after_registration and not settings.registration_requires_approval:
                self.login_user(user)
            return {'errors': None, 'message': None, 'user': d}

        if settings.registration_requires_approval:
            user.update_record(registration_key='pending')
            message = self.messages.registration_pending
        elif settings.login_after_registration:
            user.update_record(registration_key='')
            self.login_user(user)
            message = self.messages.logged_in

        self.log_event(log, user)

        return {
            'errors': None,
            'message': message,
            'user':
            {k: user[k]
             for k in table_user.fields if table_user[k].readable}
        }
Beispiel #6
0
    def define_tables(self,
                      username=None,
                      signature=None,
                      migrate=None,
                      fake_migrate=None):
        """
        To be called unless tables are defined manually

        Examples:
            Use as::

                # defines all needed tables and table files
                # 'myprefix_auth_user.table', ...
                auth.define_tables(migrate='myprefix_')

                # defines all needed tables without migration/table files
                auth.define_tables(migrate=False)

        """

        db = self.db
        if migrate is None:
            migrate = db._migrate
        if fake_migrate is None:
            fake_migrate = db._fake_migrate

        settings = self.settings
        if username is None:
            username = settings.use_username
        else:
            settings.use_username = username

        if not self.signature:
            self.define_signature()
        if signature is True:
            signature_list = [self.signature]
        elif not signature:
            signature_list = []
        elif isinstance(signature, Table):
            signature_list = [signature]
        else:
            signature_list = signature
        self._table_signature_list = signature_list  # Should it defined in __init__ first??

        is_not_empty = IS_NOT_EMPTY(error_message=self.messages.is_empty)
        is_crypted = CRYPT(key=settings.hmac_key,
                           min_length=settings.password_min_length)
        is_unique_email = [
            IS_EMAIL(error_message=self.messages.invalid_email),
            IS_NOT_IN_DB(db,
                         '%s.email' % settings.table_user_name,
                         error_message=self.messages.email_taken)
        ]
        if not settings.email_case_sensitive:
            is_unique_email.insert(1, IS_LOWER())
        if settings.table_user_name not in db.tables:
            passfield = settings.password_field
            extra_fields = settings.extra_fields.get(settings.table_user_name,
                                                     []) + signature_list
            # cas_provider Will always be None here but we compare it anyway so subclasses can use our define_tables
            if username or settings.cas_provider:
                is_unique_username = \
                    [IS_MATCH('[\w\.\-]+', strict=True,
                              error_message=self.messages.invalid_username),
                     IS_NOT_IN_DB(db, '%s.username' % settings.table_user_name,
                                  error_message=self.messages.username_taken)]
                if not settings.username_case_sensitive:
                    is_unique_username.insert(1, IS_LOWER())
                db.define_table(
                    settings.table_user_name,
                    Field('first_name',
                          length=128,
                          default='',
                          label=self.messages.label_first_name,
                          requires=is_not_empty),
                    Field('last_name',
                          length=128,
                          default='',
                          label=self.messages.label_last_name,
                          requires=is_not_empty),
                    Field('email',
                          length=512,
                          default='',
                          label=self.messages.label_email,
                          requires=is_unique_email),
                    Field('username',
                          length=128,
                          default='',
                          label=self.messages.label_username,
                          requires=is_unique_username),
                    Field(passfield,
                          'password',
                          length=512,
                          readable=False,
                          label=self.messages.label_password,
                          requires=[is_crypted]),
                    Field('registration_key',
                          length=512,
                          writable=False,
                          readable=False,
                          default='',
                          label=self.messages.label_registration_key),
                    Field('reset_password_key',
                          length=512,
                          writable=False,
                          readable=False,
                          default='',
                          label=self.messages.label_reset_password_key),
                    Field('registration_id',
                          length=512,
                          writable=False,
                          readable=False,
                          default='',
                          label=self.messages.label_registration_id),
                    *extra_fields,
                    **dict(migrate=self._get_migrate(settings.table_user_name,
                                                     migrate),
                           fake_migrate=fake_migrate,
                           format='%(username)s'))
            else:
                db.define_table(
                    settings.table_user_name,
                    Field('first_name',
                          length=128,
                          default='',
                          label=self.messages.label_first_name,
                          requires=is_not_empty),
                    Field('last_name',
                          length=128,
                          default='',
                          label=self.messages.label_last_name,
                          requires=is_not_empty),
                    Field('email',
                          length=512,
                          default='',
                          label=self.messages.label_email,
                          requires=is_unique_email),
                    Field(passfield,
                          'password',
                          length=512,
                          readable=False,
                          label=self.messages.label_password,
                          requires=[is_crypted]),
                    Field('registration_key',
                          length=512,
                          writable=False,
                          readable=False,
                          default='',
                          label=self.messages.label_registration_key),
                    Field('reset_password_key',
                          length=512,
                          writable=False,
                          readable=False,
                          default='',
                          label=self.messages.label_reset_password_key),
                    Field('registration_id',
                          length=512,
                          writable=False,
                          readable=False,
                          default='',
                          label=self.messages.label_registration_id),
                    *extra_fields,
                    **dict(migrate=self._get_migrate(settings.table_user_name,
                                                     migrate),
                           fake_migrate=fake_migrate,
                           format='%(first_name)s %(last_name)s (%(id)s)'))
        reference_table_user = '******' % settings.table_user_name
        if settings.table_group_name not in db.tables:
            extra_fields = settings.extra_fields.get(settings.table_group_name,
                                                     []) + signature_list
            db.define_table(
                settings.table_group_name,
                Field('role',
                      length=512,
                      default='',
                      label=self.messages.label_role,
                      requires=IS_NOT_IN_DB(
                          db, '%s.role' % settings.table_group_name)),
                Field('description',
                      'text',
                      label=self.messages.label_description), *extra_fields,
                **dict(migrate=self._get_migrate(settings.table_group_name,
                                                 migrate),
                       fake_migrate=fake_migrate,
                       format='%(role)s (%(id)s)'))
        reference_table_group = 'reference %s' % settings.table_group_name
        if settings.table_membership_name not in db.tables:
            extra_fields = settings.extra_fields.get(
                settings.table_membership_name, []) + signature_list
            db.define_table(
                settings.table_membership_name,
                Field('user_id',
                      reference_table_user,
                      label=self.messages.label_user_id),
                Field('group_id',
                      reference_table_group,
                      label=self.messages.label_group_id), *extra_fields,
                **dict(migrate=self._get_migrate(
                    settings.table_membership_name, migrate),
                       fake_migrate=fake_migrate))
        if settings.table_permission_name not in db.tables:
            extra_fields = settings.extra_fields.get(
                settings.table_permission_name, []) + signature_list
            db.define_table(
                settings.table_permission_name,
                Field('group_id',
                      reference_table_group,
                      label=self.messages.label_group_id),
                Field('name',
                      default='default',
                      length=512,
                      label=self.messages.label_name,
                      requires=is_not_empty),
                Field('table_name',
                      length=512,
                      label=self.messages.label_table_name),
                Field('record_id',
                      'integer',
                      default=0,
                      label=self.messages.label_record_id,
                      requires=IS_INT_IN_RANGE(0, 10**9)), *extra_fields,
                **dict(migrate=self._get_migrate(
                    settings.table_permission_name, migrate),
                       fake_migrate=fake_migrate))
        if settings.table_event_name not in db.tables:
            db.define_table(
                settings.table_event_name,
                Field('time_stamp',
                      'datetime',
                      default=current.request.now,
                      label=self.messages.label_time_stamp),
                Field('client_ip',
                      default=current.request.client,
                      label=self.messages.label_client_ip),
                Field('user_id',
                      reference_table_user,
                      default=None,
                      label=self.messages.label_user_id),
                Field('origin',
                      default='auth',
                      length=512,
                      label=self.messages.label_origin,
                      requires=is_not_empty),
                Field('description',
                      'text',
                      default='',
                      label=self.messages.label_description,
                      requires=is_not_empty),
                *settings.extra_fields.get(settings.table_event_name, []),
                **dict(migrate=self._get_migrate(settings.table_event_name,
                                                 migrate),
                       fake_migrate=fake_migrate))

        return self
    def __new__(cls, **kwargs):

        instance = super(PERSON_FORM, cls).__new__(cls)

        instance.person = kwargs.get('person')  # PERSON type
        instance.readonly = kwargs.get('readonly') or False
        instance.readonly_fields = kwargs.get('readonly_fields') or []
        my_logger.debug(message='instance.person:%s' % instance.person)
        my_logger.debug(message='instance.person.creator:%s' %
                        instance.person.creator)

        if instance.person is not None:
            current.db.person.first_name.default = instance.person.first_name
            if 'first_name' in instance.readonly_fields:
                current.db.person.first_name.writable = False
            current.db.person.last_name.default = instance.person.last_name
            if 'last_name' in instance.readonly_fields:
                current.db.person.last_name.writable = False
            current.db.person.email.default = instance.person.email
            if 'email' in instance.readonly_fields:
                current.db.person.email.writable = False
            current.db.person.contact.default = instance.person.contact
            if 'contact' in instance.readonly_fields:
                current.db.person.contact.writable = False

            current.db.person.email.requires = [
                IS_NOT_EMPTY(),
                IS_EMAIL(),
                IS_NOT_IN_DB(
                    current.db(current.db.person.id != instance.person.id),
                    current.db.person.email)
            ]

            # creator is a computed field and then not shown by web2py
            # we need to add it manually
            instance.form = SQLFORM.factory(Field('creator',
                                                  'string',
                                                  writable=not 'creator' in instance.readonly_fields,
                                                  label=cc.get_string("PERSON_CREATOR_LABEL"),
                                                  default=instance.person.creator.email \
                                                            if instance.person.creator is not None \
                                                            else ''),  # creator should exists - backward compatibility

                                            current.db.person,

                                    Field('is_all_entity',
                                          'boolean',
                                          label=cc.get_string("PERSON_IS_ALL_ENTITY_LABEL"),
                                          comment=cc.get_string("PERSON_IS_ALL_ENTITY_COMMENT"),
                                          represent=lambda r: current.T(str(instance.person.is_all_entity())),
                                          # disabled if the user is not admin
                                          readable=current.auth.has_membership('all_entity') or \
                                                    current.auth.has_membership('admin_entity') or \
                                                    current.auth.has_permission('admin'),  # admin_ENTITY: backward compatibility
                                          writable=(current.auth.has_membership('all_entity') or \
                                          current.auth.has_membership('admin_entity') or \
                                          current.auth.has_permission('admin')) and \
                                          not 'custom_entity' in instance.readonly_fields,
                                          # for an update request, pre populating the widget if the user is in all entities
                                          default=instance.person.is_all_entity(),
                                          ),

                                       Field('custom_entity',
                                            'list:reference entity',
                                            comment=cc.get_string("PERSON_ENTITY_COMMENT"),
                                            label=cc.get_string("PERSON_ENTITY_LABEL"),
                                            required=True,
                                            notnull=True,
                                            writable=not 'custom_entity' in instance.readonly_fields,
                                            # for an update request, pre populating the widget given the user entities
                                            default=[_entity.id for _entity in instance.person.entities] \
                                                      if instance.person.entities is not None \
                                                      else [],
                                            requires=[IS_IN_DB_AND_USER_ENTITY(current.db(current.db.entity.id > 0),
                                                                               current.db.entity.id,
                                                                               current.db.entity._format, multiple=True),
                                                       IS_ONE_SELECTED(db=current.db, table=current.db.entity, table_set=~current.db.entity.role.like('user_%'))],
                                            represent=lambda r: XML(' <br/>'.join(['%s' % (e.name) \
                                                                    for e in instance.person.entities])) \
                                            if (not instance.person.is_all_entity() and instance.person.entities is not None) else 'X',

                                            widget=lambda field, value: SQLFORM.widgets.multiple.widget(field, value, _class='required')),

                                        Field('is_admin',
                                              'boolean',
                                              label=cc.get_string("PERSON_IS_ADMIN_LABEL"),
                                              comment=cc.get_string("PERSON_IS_ADMIN_COMMENT"),
                                              represent=lambda r: current.T(str(instance.person.is_admin())),
                                              # disabled if the user is not admin
                                              readable=current.auth.has_permission('admin'),
                                              writable=current.auth.has_permission('admin') and not 'is_admin' in instance.readonly_fields,
                                              # for an update request, pre populating the widget if the user is admin
                                              default=instance.person.is_admin(),
                                              ),

                                        Field('custom_permission',
                                              'string',  # this does not matter given that we define our own permission widget
                                              label=cc.get_string("PERSON_ENTITY_PERMISSION_LABEL"),
                                              required=True,
                                              notnull=True,
                                              writable=not 'custom_permission' in instance.readonly_fields,
                                              # for an update request, pre populating the widget given the user permissions
                                              default=[_permission.name for _permission in instance.person.permissions],
                                              comment=cc.get_string("PERSON_ENTITY_PERMISSION_COMMENT"),
                                              requires=IS_CHIMITHEQUE_PERMISSION(),
                                              represent=lambda r: PermissionWidget.represent(r),
                                              widget=lambda field, value: PermissionWidget.widget(field,
                                                                                                value,
                                                                                                _class='required',
                                                                                                auth_user_permissions=[_permission.name for _permission in PERSON_MAPPER().find_permissions(current.auth.user.id)] \
                                                                                                                      if not current.auth.has_permission('admin') \
                                                                                                                      else None)),

                                       readonly=instance.readonly,
                                       comments=not instance.readonly,
                                       next=URL(current.request.application, 'user', 'list'),
                                       submit_button=cc.get_string("SUBMIT")
                                       )
        else:

            instance.form = SQLFORM.factory(
                Field('None', 'string', writable=False, readable=False))

        return instance
Beispiel #8
0
from gluon.storage import Storage

# create DAL connection (and create DB if not exists)
db = DAL('sqlite://guitest.sqlite', folder=None)

# define a table 'person' (create/aster as necessary)
person = db.define_table(
    'person',
    Field('name', 'string', length=100),
    Field('sex', 'string', length=1),
    Field('active', 'boolean', comment="check!"),
    Field('bio', 'text', comment="resume (CV)"),
)

# set sample validator (do not allow empty nor duplicate names)
db.person.name.requires = [IS_NOT_EMPTY(), IS_NOT_IN_DB(db, 'person.name')]

db.person.sex.requires = IS_IN_SET({'M': 'Male', 'F': 'Female'})

# create the wxPython GUI application instance:
app = wx.App(False)

# create a testing frame (wx "window"):
f = wx.Frame(None, title="web2py/gui2py sample app")

# create the web2py FORM based on person table
form = SQLFORM(db.person)

# create the HTML "browser" window:
html = wx.html.HtmlWindow(f, style=wx.html.HW_DEFAULT_STYLE | wx.TAB_TRAVERSAL)
# convert the web2py FORM to XML and display it