def create_user( first_name=None, last_name=None, email=None, ein=None, is_admin=False, is_active=False, ): """Create an agency user.""" if first_name is None: raise InvalidCommand("First name is required") if last_name is None: raise InvalidCommand("Last name is required") if email is None: raise InvalidCommand("Email is required") if ein is None: raise InvalidCommand("Agency EIN is required") user = Users( guid=generate_guid(), auth_user_type=user_type_auth.AGENCY_LDAP_USER, email=email, first_name=first_name, last_name=last_name, title=None, organization=None, email_validated=True, terms_of_use_accepted=True, phone_number=None, fax_number=None, mailing_address=create_mailing_address(None, None, None, None), ) db.session.add(user) agency_user = AgencyUsers( user_guid=user.guid, auth_user_type=user.auth_user_type, agency_ein=ein, is_agency_active=is_active, is_agency_admin=is_admin, is_primary_agency=True, ) db.session.add(agency_user) db.session.commit() print(user)
def convert_staff_csvs(input=None, output=None): """ Convert data from staff.csv to new format to accomodate multi-agency users. :param input: Input file path. Must be a valid CSV. :param output: Output file path """ if input is None: raise InvalidCommand("Input CSV is required.") if output is None: raise InvalidCommand("Output CSV is required.") read_file = None if output == input: read_file = None with open(input, 'r').read() as _: read_file = csv.DictReader(_) temp_write_file = NamedTemporaryFile() with open(temp_write_file.name, 'w') as temp: for row in read_file: try: print( '"{ein}#{is_active}#{is_admin}#True","{is_super}","{first_name}","{middle_initial}","{last_name}","{email}","{email_validated}","{terms_of_use_accepted}","{phone_number}","{fax_number}"' .format(ein=row['agency_ein'], is_active=row['is_agency_active'], is_admin=row['is_agency_admin'], is_super=eval(row['is_super']), first_name=row['first_name'], middle_initial=row['middle_initial'], last_name=row['last_name'], email=row['email'], email_validated=eval( row['email_validated']), terms_of_use_accepted=eval( row['terms_of_use_accepted']), phone_number=row['phone_number'], fax_number=row['fax_number']), file=temp_write_file) except: continue
def change_password(user, password=None): try: u = model.User.query.filter( or_(model.User.user_name == user, model.User.email == user)).one() # @UndefinedVariable except NoResultFound: raise InvalidCommand('No such User') if not password: password = read_pwd() u.password = hash_pwd(password) db.session.commit() # @UndefinedVariable
def create_user(user, email, password=None, role='user'): if not password: password = read_pwd() data = dict(user_name=user, email=email, password=hash_pwd(password), active=True) errors = schema.UserSchema(exclude=('version_id', )).validate( data, db.session) if errors: raise InvalidCommand('Validation Error: %s' % errors) role = model.Role.query.filter_by(name=role).one() u = model.User(**data) u.roles.append(role) db.session.add(u) # @UndefinedVariable db.session.commit() # @UndefinedVariable
def reindex(doc_type=None): '''Reindex models''' if not doc_type: raise InvalidCommand("Please specify a DocType " "(Dataset, Organization...) with -t. If you want " "to reindex the whole index, please use " "`udata search init`.'") doc_types_names = [m.__name__.lower() for m in adapter_catalog.keys()] if doc_type and not doc_type.lower() in doc_types_names: log.error('Unknown type %s', doc_type) index_name = default_index_name() log.info('Initiliazing index "{0}"'.format(index_name)) es.initialize(index_name) for adapter in iter_adapters(): if adapter.doc_type().lower() == doc_type.lower(): index_model(index_name, adapter) else: log.info('Copying {0} objects to the new index'.format( adapter.model.__name__)) # Need upgrade to Elasticsearch-py 5.0.0 # es.reindex({ # 'source': {'index': es.index_name, 'type': adapter.doc_type()}, # 'dest': {'index': index_name} # }) # http://elasticsearch-py.readthedocs.io/en/master/api.html#elasticsearch.Elasticsearch.reindex # This method (introduced in Elasticsearch 2.3 but only in Elasticsearch-py 5.0.0) # triggers a server-side documents copy. # Instead we use this helper for meant for backward compatibility # but with poor performance as copy is client-side (scan+bulk) es_reindex(es.client, es.index_name, index_name, scan_kwargs={'doc_type': adapter.doc_type()}) set_alias(index_name)
def create_superuser(name, email, password=''): """ Creates a new superuser for Quasselflask, so that you can login. Will only work if no superuser currently exists (if there is, :param name: Username of superuser account to create. :param email: Email address of the account to create. This address will be considered automatically confirmed, but an email will be sent out confirming registration. :param password: Plain-text password of the superuser account to create. It is recommended to log in and change this password via the web interface. If not specified, will prompt at the command line. """ from quasselflask.models.models import QfUser as User db_adapter = userman.db_adapter user_class_fields = User.__dict__ user_fields = {} # Check for no superusers yet num_superusers = db.session.query(func.count( User.qfuserid)).filter_by(superuser=True).scalar() if num_superusers > 0: raise InvalidCommand( '{:d} superusers already exist. Please login as superuser and use the Web UI to create new superuser.' .format(num_superusers)) # Populate a register_form - to allow easy validation per system settings form = userman.register_form(csrf_enabled=False) form.username.data = name form.email.data = email form.password.data = form.retype_password.data = password form.validate() validation_errors = form.errors validation_errors.pop('password', None) validation_errors.pop('retype_password', None) if validation_errors: _print_form_errors(validation_errors) raise InvalidCommand() # Prompt for password (only show errors after user has entered something) first_prompt = True while not form.validate(): if not first_prompt: _print_form_errors(form.errors) else: first_prompt = False try: form.password.data = prompt_pass("Password", default=None) form.retype_password.data = prompt_pass("Retype password", default=None) except KeyboardInterrupt: raise InvalidCommand("Cancelled by KeyboardInterrupt.") _timer_start() # Create and save the user # For all form fields for field_name, field_value in form.data.items(): # Hash password field if field_name == 'password': user_fields['password'] = userman.hash_password(field_value) # Store corresponding Form fields into the User object else: if field_name in user_class_fields: user_fields[field_name] = field_value # Hardcoded user fields user_fields['active'] = True user_fields['superuser'] = True user_fields['confirmed_at'] = datetime.utcnow() user_fields['themeid'] = app.config.get('QF_DEFAULT_THEME', 0) # Add User record using named arguments 'user_fields' db_adapter.add_object(User, **user_fields) db_adapter.commit() print('Created superuser: {} <{}>'.format(user_fields['username'], user_fields['email'])) print( "Email address is assumed confirmed. Make sure it\'s correct. You can change it in the web interface." ) _timer_print()
def read_pwd(): password = prompt_pass('Password') again = prompt_pass('Repeat password') if password != again: raise InvalidCommand('Repeated password differs!') return password