create a new admin user
176853
def create_user
      @admin = Admin.new(administrator_params)
      @admin.access_level = 'admin'
      @admin.overlord = 'Y'
      
      respond_to do |format|
        if @admin.save
          Setting.save_data({setup_complete: 'Y'})
          clear_cache
          session[:setup_complete] = true
          format.html { redirect_to admin_path, notice: I18n.t("controllers.admin.setup.general.success") }
        else
          format.html { render action: "administrator" }
        end
      end

    end
488006
def create_admin(cls, email, password, **kwargs):
        
        data = {
            'email': email,
            'password': cls.hash_password(password),
            'has_agreed_to_terms': True,
            'state': State.approved,
            'role': cls.roles.administrator.value,
            'organisations': {}
        }
        data.update(**kwargs)

        user = cls(**data)
        yield user._save()

        raise Return(user)
1351439
def handle(self, *args, **options):
        """"""
        try:
            admin = User.objects.get(username='admin')
        except User.DoesNotExist:
            admin = User(
                username='admin',
                first_name='admin',
                last_name='admin',
                email='admin@localhost.localdomain',
                is_staff=True,
                is_active=True,
                is_superuser=True,
            )
        admin.set_password('admin')
        admin.save()
817344
def user(username, password, all):
    """"""
    if current_app.config['AUTH_PROVIDER'] != 'basic':
        raise click.UsageError('Not required for {} admin users'.format(current_app.config['AUTH_PROVIDER']))
    if username and username not in current_app.config['ADMIN_USERS']:
        raise click.UsageError('User {} not an admin'.format(username))
    if not username and not all:
        raise click.UsageError('Missing option "--username".')

    def create_user(admin):
        email = admin if '@' in admin else None
        user = User(
            name='Admin user',
            login=admin,
            password=generate_password_hash(password),
            roles=['admin'],
            text='Created by alertad script',
            email=email,
            email_verified=bool(email)
        )
        try:
            db.get_db()  # init db on global app context
            user = user.create()
        except Exception as e:
            click.echo('ERROR: {}'.format(e))
        else:
            click.echo('{} {}'.format(user.id, user.name))

    if all:
        for admin in current_app.config['ADMIN_USERS']:
            create_user(admin)
    else:
        create_user(username)
438011
def create_user(self, instance, name, password, database_names, host=None):
        
        return instance.create_user(name=name, password=password,
                database_names=database_names, host=host)
853435
def populate_with_defaults():
    '''
    '''
    logging.getLogger(__name__).debug("Populating with default users")
    if not User.select().where(User.name == 'admin').exists():
        admin = User.create(name='admin', password='admin')
        admins = Group.create(name='admins')
        starCap = Capability.create(domain='.+',
                                    action=(Action.CREATE |
                                            Action.READ |
                                            Action.UPDATE |
                                            Action.DELETE))
        admins.capabilities.add(starCap)
        admin.groups.add(admins)
        admin.save()
    if not User.select().where(User.name == 'anonymous').exists():
        anon = User.create(name='anonymous', password='')
        anons = Group.create(name='anonymous')
        readCap = Capability.create(domain=Capability.simToReg('/volumes/*'),
                                    action=Action.READ)
        anons.capabilities.add(readCap)
        anon.groups.add(anons)
        anon.save()
1081588
def import_admins(self):
        
        self.message('saving admins into local DB')

        saved_admins = []

        for olduser in OldUser.objects.all():
            try:
                user = User.objects.get(Q(username=olduser.username) | Q(email=olduser.email))
            except User.DoesNotExist:
                user = User()
            except User.MultipleObjectsReturned:
                continue

            user.username = olduser.username
            user.password = olduser.password
            user.first_name = olduser.first_name
            user.last_name = olduser.last_name
            user.email = olduser.email
            user.is_active = olduser.is_active
            user.is_staff = olduser.is_staff
            user.is_superuser = olduser.is_superuser
            user.date_joined = olduser.date_joined
            user.full_clean()
            user.save(sync_emailaddress=False)
            saved_admins.append(user)

            # mark email address as confirmed if feature is enabled
            if EMAIL_CONFIRMATION and EmailAddress.objects.filter(email=user.email).count() is 0:
                try:
                    email_address = EmailAddress(user=user, email=user.email, verified=True, primary=True)
                    email_address.full_clean()
                    email_address.save()
                except Exception:
                    tb = traceback.format_exc()
                    self.message('Could not save email address for user %s, got exception:\n\n%s' % (user.username, tb))

        self.message('saved %d admins into local DB' % len(saved_admins))
        self.saved_admins = saved_admins
60139
def create
      admin_set.creator = [creating_user.user_key] if creating_user
      admin_set.save.tap do |result|
        if result
          ActiveRecord::Base.transaction do
            permission_template = create_permission_template
            workflow = create_workflows_for(permission_template: permission_template)
            create_default_access_for(permission_template: permission_template, workflow: workflow) if admin_set.default_set?
          end
        end
      end
    end
1173659
def add_user(self, name, password=None, read_only=None, db=None, **kwargs):
        
        if db is None:
            return self.get_connection().admin.add_user(
                    name, password=password, read_only=read_only, **kwargs)
        return self.get_connection()[db].add_user(
                    name, password=password, read_only=read_only, **kwargs)
989096
def createuser(email, password, role=None, name=None, first_name=None):
    """"""

    if User.query.filter(User.email == email).count() > 0:
        print(f"A user with email '{email}' already exists, aborting.")
        return

    # if password is None:
    #     password = prompt_pass("Password")

    user = User(
        email=email,
        password=password,
        last_name=name,
        first_name=first_name,
        can_login=True,
    )
    db.session.add(user)

    if role in ("admin",):
        # FIXME: add other valid roles
        security = get_service("security")
        security.grant_role(user, role)

    db.session.commit()
    print(f"User {email} added")
504555
def _create_user(self, username, password, mail, method, uuid):
        """"""

        try:
            if method == 'Invited':
                config_role = self.config.group_accept_invited
            else:
                config_role = self.config.group_accept_enrolled

            roles = []
            if ',' in config_role:
                for item in config_role.split(','):
                    roles.append(item.lstrip().rstrip())
            else:
                roles = [config_role]

            newuser = objectmodels['user']({
                'name': username,
                'passhash': std_hash(password, self.salt),
                'mail': mail,
                'uuid': std_uuid(),
                'roles': roles,
                'created': std_now()
            })

            if method == 'Invited':
                newuser.needs_password_change = True

            newuser.save()
        except Exception as e:
            self.log("Problem creating new user: ", type(e), e,
                     lvl=error)
            return

        try:
            newprofile = objectmodels['profile']({
                'uuid': std_uuid(),
                'owner': newuser.uuid
            })
            self.log("New profile uuid: ", newprofile.uuid,
                     lvl=verbose)

            newprofile.save()

            packet = {
                'component': 'hfos.enrol.enrolmanager',
                'action': 'enrol',
                'data': [True, mail]
            }
            self.fireEvent(send(uuid, packet))

            # TODO: Notify crew-admins
        except Exception as e:
            self.log("Problem creating new profile: ", type(e),
                     e, lvl=error)
922515
def add_user(self, user, is_admin=False):
        
        users_count = self.users.all().count()
        if users_count == 0:
            is_admin = True
        # TODO get specific org user?
        org_user = self._org_user_model.objects.create(
            user=user, organization=self, is_admin=is_admin
        )
        if users_count == 0:
            # TODO get specific org user?
            self._org_owner_model.objects.create(
                organization=self, organization_user=org_user
            )

        # User added signal
        user_added.send(sender=self, user=user)
        return org_user
1080749
def create_user(self, name, password):
        """"""
        hashed_password = self._password_hasher(password)
        return dict(name=name, password=hashed_password)
1010675
def run(self):
        
        from zengine.models import User
        user = User(username=self.manager.args.username, superuser=self.manager.args.super)
        user.set_password(self.manager.args.password)
        user.save()
        print("New user created with ID: %s" % user.key)
1172767
private function createAdmin(): void
    {
        $this->connection->beginTransaction();
        try {
            $this->userService->createUser(
                [
                    'email' => $this->email,
                    'password' => $this->password,
                    'is_active' => BoolEnum::yes()->id(),
                    'activated_at' => Carbon::now()->toDateTimeString(),
                ],
                [
                    'first_name' => 'Super',
                    'last_name' => 'Admin',
                    // TODO set admin default photo
                ],
                [
                    $this->roleRepository->getRoleSuperAdminId(),
                    $this->roleRepository->getRoleUserId()
                ]
            );
        } catch (\Throwable $exception) {
            $this->connection->rollBack();

            report($exception);

            $this->info('error:');
            $this->error($exception->getMessage());

            exit;
        }

        $this->connection->commit();
    }
972809
protected function setupAdministrator()
    {
        $question = new ConfirmationQuestion('Would you like to create default administrator user (Recommended)? [y/n] ', true);
        if (!$this->helper->ask($this->input, $this->output, $question)) {
            return;
        }

        $this->runCommand('avoo:user:create');
    }
702632
def create_user(self, login=None, password=None, user_name=None, envs=[], query='/users/'):
        
        login = login.lower()

        data = {'login': login,
                'password': password[0],
                'name': user_name}

        juicer.utils.Log.log_debug("Create User: %s ('%s')", login, user_name)

        for env in envs:
            if envs.index(env) != 0 and juicer.utils.env_same_host(env, envs[envs.index(env) - 1]):
                juicer.utils.Log.log_info("environment `%s` shares a host with environment `%s`... skipping!",
                                          (env, envs[envs.index(env) - 1]))
                continue
            elif juicer.utils.user_exists_p(login, self.connectors[env]):
                juicer.utils.Log.log_info("user `%s` already exists in %s... skipping!",
                                          (login, env))
                continue
            else:
                _r = self.connectors[env].post(query, data)
                if _r.status_code == Constants.PULP_POST_CREATED:
                    juicer.utils.Log.log_info("created user `%s` with login `%s` in %s",
                                              (user_name, login, env))
                else:
                    _r.raise_for_status()
        return True