Exemplo n.º 1
0
def user_exists(email):
    """Validate that a user exists."""
    try:
        profile = UserProfile.get_by_username(email)
    except NoResultFound:
        if not current_datastore.get_user(email):
            raise ValidationError('USER_DOES_NOT_EXIST')
Exemplo n.º 2
0
 def get_user(self, email=None, **kwargs):
     """Retrieve a user by the provided arguments."""
     try:
         profile = UserProfile.get_by_username(email)
         return profile.user
     except NoResultFound:
         pass
     return current_datastore.get_user(email)
Exemplo n.º 3
0
    def get_by_username(cls, username):
        """Get a user by a username.

        :param username - the user name
        :return: the user record
        """
        try:
            profile = UserProfile.get_by_username(username)
            return cls(profile.user)
        except NoResultFound:
            return None
Exemplo n.º 4
0
    def _get_user_by_data(cls, data):
        """Get the user using a dict representing a patron.

        Try to get an existing user by: user_id, email, username.
        :param cls: Class itself.
        :param data: dict representing a patron.
        :return: a patron object or None.
        """
        user = None
        if data.get('user_id'):
            user = User.query.filter_by(id=data.get('user_id')).first()
        if not user and data.get('username'):
            try:
                user = UserProfile.get_by_username(data.get('username')).user
            except NoResultFound:
                user = None
        if not user and data.get('email'):
            user = User.query.filter_by(email=data.get('email')).first()
        return user
Exemplo n.º 5
0
def import_users(infile, append, verbose, password, lazy, dont_stop_on_error,
                 debug):
    """Import users.

    :param verbose: this function will be verbose.
    :param password: the password to use for user by default.
    :param lazy: lazy reads file
    :param dont_stop_on_error: don't stop on error
    :param infile: Json user file.
    """
    click.secho('Import users:', fg='green')

    if lazy:
        # try to lazy read json file (slower, better memory management)
        data = read_json_record(infile)
    else:
        # load everything in memory (faster, bad memory management)
        data = json.load(infile)
    pids = []
    error_records = []
    for count, patron_data in enumerate(data):
        email = patron_data.get('email')
        password = patron_data.get('password', password)
        username = patron_data['username']
        if email is None:
            click.secho(
                '{count: <8} User {username} do not have email!'.format(
                    count=count, username=username),
                fg='yellow')
        if password:
            patron_data.pop('password', None)
        # do nothing if the patron alredy exists
        patron = Patron.get_patron_by_username(username)
        if patron:
            click.secho('{count: <8} Patron already exist: {username}'.format(
                count=count, username=username),
                        fg='yellow')
            continue

        if verbose:
            click.secho('{count: <8} Creating user: {username}'.format(
                count=count, username=username))
            try:
                profile = UserProfile.get_by_username(username)
                click.secho(
                    '{count: <8} User already exist: {username}'.format(
                        count=count, username=username),
                    fg='yellow')
            except NoResultFound:
                pass
        try:
            # patron creation
            patron = Patron.create(
                patron_data,
                # delete_pid=True,
                dbcommit=False,
                reindex=False,
                email_notification=False)
            user = patron.user
            user.password = hash_password(password)
            user.active = True
            db.session.merge(user)
            db.session.commit()
            confirm_user(user)
            patron.reindex()
            pids.append(patron.pid)
        except Exception as err:
            error_records.append(data)
            click.secho('{count: <8} User create error: {err}'.format(
                count=count, err=err),
                        fg='red')
            if debug:
                traceback.print_exc()
            if not dont_stop_on_error:
                sys.exit(1)
            if debug:
                traceback.print_exc()
            if not dont_stop_on_error:
                sys.exit(1)
    if append:
        click.secho(
            'Append fixtures new identifiers: {len}'.format(len=len(pids)))
        identifier = Patron.provider.identifier
        try:
            append_fixtures_new_identifiers(identifier,
                                            sorted(pids, key=lambda x: int(x)),
                                            PatronProvider.pid_type)
        except Exception as err:
            click.secho(
                "ERROR append fixtures new identifiers: {err}".format(err=err),
                fg='red')
    if error_records:
        name, ext = os.path.splitext(infile.name)
        err_file_name = '{name}_errors{ext}'.format(name=name, ext=ext)
        click.secho('Write error file: {name}'.format(name=err_file_name))
        with open(err_file_name, 'w') as error_file:
            error_file.write('[\n')
            for error_record in error_records:
                for line in json.dumps(error_record, indent=2).split('\n'):
                    error_file.write('  ' + line + '\n')
            error_file.write(']')