Пример #1
0
def save_password(password, port):
    """
    Used by main() to save the password in the parameters_port.py file.
    """

    password_file = abspath('parameters_%i.py' % port)
    if password == '<random>':
        # make up a new password
        chars = string.letters + string.digits
        password = ''.join([random.choice(chars) for i in range(8)])
        cpassword = CRYPT()(password)[0]
        print '******************* IMPORTANT!!! ************************'
        print 'your admin password is "%s"' % password
        print '*********************************************************'
    elif password == '<recycle>':
        # reuse the current password if any
        if exists(password_file):
            return
        else:
            password = ''
    elif password.startswith('<pam_user:'******'w')
    if password:
        fp.write('password="******"\n' % cpassword)
    else:
        fp.write('password=None\n')
    fp.close()
Пример #2
0
def crea_usuario():
    from gluon.validators import CRYPT
    from gluon.tools import Auth
    db = current.db
    auth = Auth(db)

    db.Sede.insert(name="Sede de pruebas")
    id_almacen = db.Almacen.insert(name="AlmacenTest 1")
    db.Almacen.insert(name="AlmacenTest 2")
    db.Estanteria.insert(name="Estanteria Test", almacen=id_almacen)

    my_crypt = CRYPT(key=auth.settings.hmac_key)
    crypted_passwd = my_crypt('password_malo')[0]
    db.commit()
    db.auth_user.insert(email='*****@*****.**',
                        first_name='Administrator',
                        password=crypted_passwd)
    auth.add_group('admins', 'Administradores de la aplicación')
    auth.add_membership(1, 1)
    auth.add_permission(1, 'admins', db.auth_user)

    db.Beneficiario.insert(name="Beneficiario 1",
                           tipobeneficiario="ASOCIACIONES")
    db.Colaborador.insert(name="Donante 1", Donante=True)
    db.commit()
Пример #3
0
def create_users():
    from gluon.validators import CRYPT
    from gluon.tools import Auth
    db = current.db
    auth = Auth(db)

    my_crypt = CRYPT(key=auth.settings.hmac_key)
    crypted_passwd = my_crypt('password')[0]
    db.commit()
    db.auth_user.insert(email='*****@*****.**',
                        first_name='Administrator',
                        password=crypted_passwd)
    auth.add_group('admins', 'Application Administrators')
    auth.add_membership(1, 1)
    auth.add_permission(1, 'admins', db.auth_user)

    db.commit()
Пример #4
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
Пример #5
0
    def change_password(self, log=DEFAULT, **kwargs):
        """
        Lets the user change password

        Keyword Args:
            old_password (string) - User's current password
            new_password (string) - User's new password
            new_password2 (string) - Verify the new password
        """
        settings = self.settings
        messages = self.messages

        if not self.is_logged_in():
            raise AssertionError('User is not logged in')

        db = self.db
        table_user = self.table_user()
        s = db(table_user.id == self.user.id)

        request = current.request
        session = current.session
        passfield = settings.password_field

        requires = table_user[passfield].requires
        if not isinstance(requires, (list, tuple)):
            requires = [requires]
        requires = [t for t in requires if isinstance(t, CRYPT)]
        if requires:
            requires[0] = CRYPT(
                **requires[0].__dict__)  # Copy the existing CRYPT attributes
            requires[
                0].min_length = 0  # But do not enforce minimum length for the old password

        old_password = kwargs.get('old_password', '')
        new_password = kwargs.get('new_password', '')
        new_password2 = kwargs.get('new_password2', '')

        validator_old = requires
        validator_pass2 = IS_EQUAL_TO(
            new_password, error_message=messages.mismatched_password)

        old_password, error_old = self.__validate(old_password, validator_old)
        new_password2, error_new2 = self.__validate(new_password2,
                                                    validator_pass2)

        errors = {}
        if error_old:
            errors['old_password'] = error_old
        if error_new2:
            errors['new_password2'] = error_new2
        if errors:
            return {'errors': errors, 'message': None}

        current_user = s.select(limitby=(0, 1),
                                orderby_on_limitby=False).first()
        if not old_password == current_user[passfield]:
            return {
                'errors': {
                    'old_password': messages.invalid_password
                },
                'message': None
            }
        else:
            d = {passfield: new_password}
            resp = s.validate_and_update(**d)
            if resp.errors:
                return {
                    'errors': {
                        'new_password': resp.errors[passfield]
                    },
                    'message': None
                }
            if log is DEFAULT:
                log = messages['change_password_log']
            self.log_event(log, self.user)
            return {'errors': None, 'message': messages.password_changed}
Пример #6
0
    def change_password(self, log=DEFAULT, **kwargs):
        """
        Lets the user change password

        Keyword Args:
            old_password (string) - User's current password
            new_password (string) - User's new password
            new_password2 (string) - Verify the new password
        """
        settings = self.settings
        messages = self.messages

        if not self.is_logged_in():
            raise AssertionError('User is not logged in')

        db = self.db
        table_user = self.table_user()
        s = db(table_user.id == self.user.id)

        request = current.request
        session = current.session
        passfield = settings.password_field

        requires = table_user[passfield].requires
        if not isinstance(requires, (list, tuple)):
            requires = [requires]
        requires = list(filter(lambda t: isinstance(t, CRYPT), requires))
        if requires:
            requires[0] = CRYPT(**requires[0].__dict__) # Copy the existing CRYPT attributes
            requires[0].min_length = 0 # But do not enforce minimum length for the old password

        old_password = kwargs.get('old_password', '')
        new_password = kwargs.get('new_password', '')
        new_password2 = kwargs.get('new_password2', '')

        validator_old = requires
        validator_pass2 = IS_EQUAL_TO(new_password, error_message=messages.mismatched_password)

        old_password, error_old = self.__validate(old_password, validator_old)
        new_password2, error_new2 = self.__validate(new_password2, validator_pass2)

        errors = {}
        if error_old:
            errors['old_password'] = error_old
        if error_new2:
            errors['new_password2'] = error_new2
        if errors:
            return {'errors': errors, 'message': None}

        current_user = s.select(limitby=(0, 1), orderby_on_limitby=False).first()
        if not old_password == current_user[passfield]:
            return {'errors': {'old_password': messages.invalid_password}, 'message': None}
        else:
            d = {passfield: new_password}
            resp = s.validate_and_update(**d)
            if resp.errors:
                return {'errors': {'new_password': resp.errors[passfield]}, 'message': None}
            if log is DEFAULT:
                log = messages['change_password_log']
            self.log_event(log, self.user)
            return {'errors': None, 'message': messages.password_changed}
Пример #7
0
    def init_app(self, app):
        super().init_app(app)

        # Create the web2py encrypter.
        self.crypt = CRYPT(key=app.config['WEB2PY_PRIVATE_KEY'], salt=app.config['WEB2PY_SALT'])