/* Method provided to be called using reflection to discretely create the admin user if needed.
777844
private static PrincipalUser createDefaultUser() {
        PrincipalUser result = new PrincipalUser("default", "default@default.com");

        result.id = BigInteger.valueOf(2);
        result.setPrivileged(false);
        return result;
    }
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)
1151655
def create(self, validated_data):
        ''''''
        validated_data['username'] = validated_data['email']
        admin = validated_data.pop('is_superuser', None)

        if admin is True:
            user = User.objects.create_superuser(**validated_data)
        else:
            user = User.objects.create_user(**validated_data)

        return user
1141710
@RequirePOST
    @Restricted(NoExternalUse.class)
    public HttpResponse doCreateAdminUser(StaplerRequest req, StaplerResponse rsp) throws IOException {
        Jenkins j = Jenkins.getInstance();

        j.checkPermission(Jenkins.ADMINISTER);

        // This will be set up by default. if not, something changed, ok to fail
        HudsonPrivateSecurityRealm securityRealm = (HudsonPrivateSecurityRealm) j.getSecurityRealm();

        User admin = securityRealm.getUser(SetupWizard.initialSetupAdminUserName);
        try {
            if (admin != null) {
                admin.delete(); // assume the new user may well be 'admin'
            }

            User newUser = securityRealm.createAccountFromSetupWizard(req);
            if (admin != null) {
                admin = null;
            }

            // Success! Delete the temporary password file:
            try {
                getInitialAdminPasswordFile().delete();
            } catch (InterruptedException e) {
                throw new IOException(e);
            }

            InstallUtil.proceedToNextStateFrom(InstallState.CREATE_ADMIN_USER);

            // ... and then login
            Authentication auth = new UsernamePasswordAuthenticationToken(newUser.getId(), req.getParameter("password1"));
            auth = securityRealm.getSecurityComponents().manager.authenticate(auth);
            SecurityContextHolder.getContext().setAuthentication(auth);
            
            HttpSession session = req.getSession(false);
            if (session != null) {
                // avoid session fixation
                session.invalidate();
            }
            HttpSession newSession = req.getSession(true);

            UserSeedProperty userSeed = newUser.getProperty(UserSeedProperty.class);
            String sessionSeed = userSeed.getSeed();
            // include the new seed
            newSession.setAttribute(UserSeedProperty.USER_SESSION_SEED, sessionSeed);
            
            CrumbIssuer crumbIssuer = Jenkins.getInstance().getCrumbIssuer();
            JSONObject data = new JSONObject();
            if (crumbIssuer != null) {
                data.accumulate("crumbRequestField", crumbIssuer.getCrumbRequestField()).accumulate("crumb", crumbIssuer.getCrumb(req));
            }
            return HttpResponses.okJSON(data);
        } catch (AccountCreationFailedException e) {
            /*
            Return Unprocessable Entity from WebDAV. While this is not technically in the HTTP/1.1 standard, browsers
            seem to accept this. 400 Bad Request is technically inappropriate because that implies invalid *syntax*,
            not incorrect data. The client only cares about it being >200 anyways.
             */
            rsp.setStatus(422);
            return HttpResponses.forwardToView(securityRealm, "/jenkins/install/SetupWizard/setupWizardFirstUser.jelly");
        } finally {
            if (admin != null) {
                admin.save(); // recreate this initial user if something failed
            }
        }
    }
1317192
def create_admin(app, appbuilder, username, firstname, lastname, email, password):
    
    auth_type = {
        c.AUTH_DB: "Database Authentications",
        c.AUTH_OID: "OpenID Authentication",
        c.AUTH_LDAP: "LDAP Authentication",
        c.AUTH_REMOTE_USER: "WebServer REMOTE_USER Authentication",
        c.AUTH_OAUTH: "OAuth Authentication",
    }
    _appbuilder = import_application(app, appbuilder)
    click.echo(
        click.style(
            "Recognized {0}.".format(
                auth_type.get(_appbuilder.sm.auth_type, "No Auth method")
            ),
            fg="green",
        )
    )
    role_admin = _appbuilder.sm.find_role(_appbuilder.sm.auth_role_admin)
    user = _appbuilder.sm.add_user(
        username, firstname, lastname, email, role_admin, password
    )
    if user:
        click.echo(click.style("Admin User {0} created.".format(username), fg="green"))
    else:
        click.echo(click.style("No user created an error occured", fg="red"))
760181
def create_user(email, password, active, confirmed_at, send_email):
    
    if confirmed_at == 'now':
        confirmed_at = security.datetime_factory()
    user = user_manager.create(email=email, password=password, active=active,
                               confirmed_at=confirmed_at)
    if click.confirm(f'Are you sure you want to create {user!r}?'):
        security_service.register_user(user, allow_login=False, send_email=send_email)
        user_manager.save(user, commit=True)
        click.echo(f'Successfully created {user!r}')
    else:
        click.echo('Cancelled.')
1372672
private void createNewUser() throws CmsException {

        //Password was checked by validator before
        String ou = m_ou.getValue();
        if (!ou.endsWith("/")) {
            ou += "/";
        }
        CmsUser user = m_cms.createUser(ou + m_loginname.getValue(), m_pw.getPassword1(), "", null);
        updateUser(user);
        m_cms.writeUser(user);
        if (!CmsStringUtil.isEmptyOrWhitespaceOnly(m_group.getValue())) {
            m_cms.addUserToGroup(user.getName(), m_group.getValue());
        }
        OpenCms.getRoleManager().addUserToRole(m_cms, (CmsRole)m_role.getValue(), user.getName());
        m_user = user;

    }
801745
def create
      session[:impersonator_redirect_path] = params[:redirect_path].presence
      @user = MnoEnterprise::User.find(params[:user_id])
      if @user.present?
        if @user.admin_role.present?
          flash[:notice] = 'User is a staff member'
        else
          impersonate(@user)
        end
      else
        flash[:notice] = "User doesn't exist"
      end

      path = mnoe_home_path
      path = add_param_to_fragment(path, 'dhbRefId', params[:dhbRefId]) if params[:dhbRefId].present?

      redirect_to path
    end
1167637
private function createUsersTable()
    {
        Schema::create('users', function ($table) {
            foreach ($this->fields as $field => $value) {
                $query = $table->$value['type']($field);

                if (isset($value['extra'])) {
                    $query->$value['extra']();
                }
            }

            $table->foreign('role_id')->references('id')->on('roles');
            $table->timestamps();
            $table->softDeletes();
        });
    }
286378
private function createUsers()
    {
        if($this->option('users')
            || $this->option('users_per_role')
            || $this->option('all')
        ) {

            $this->comment('Creating dummy users...');
            $output = (new \UserSeeder())
                ->setCommand($this)
                ->run(
                    $this->getDefaultOption('users'),
                    $this->getDefaultOption('users_per_role'),
                    $this->getDefaultOption('role_id')
                );
            $this->info($output);
        }
        return $this;
    }
6126
def get_or_create_user(self, username, password):
        '''
        
        '''

        # Get the groups for this user
        info = self.get_ad_info(username, password)
        self.debug("INFO found: {}".format(info))

        # Find the user
        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            user = User(username=username)

        # Update user
        user.first_name = info.get('first_name', '')
        user.last_name = info.get('last_name', '')
        user.email = info.get('email', '')

        # Check if the user is in the Administrators groups
        is_admin = False
        for domain in info['groups']:
            if 'Domain Admins' in info['groups'][domain]:
                is_admin = True
                break

        # Set the user permissions
        user.is_staff = is_admin
        user.is_superuser = is_admin

        # Refresh the password
        user.set_password(password)

        # Validate the selected user and gotten information
        user = self.validate(user, info)
        if user:
            self.debug("User got validated!")

            # Autosave the user until this point
            user.save()

            # Synchronize user
            self.synchronize(user, info)
        else:
            self.debug("User didn't pass validation!")

        # Finally return user
        return user
1325124
private function createSuperAdmin(): void
    {
        $this->getEmail();

        $this->info('');
        $this->comment('Creating default super-admin user...');
        $this->info('');

        $this->checkIfAdminExists();

        $this->getPassword();

        $this->createAdmin();

        $this->comment('Super admin account successfully created!');
        $this->comment('Your email: ');
        $this->error($this->email);

        $this->info('');
    }
740535
def create_user(self, name, password, is_super=False):
        
        statement = ddl.CreateUser(
            name=name, password=password, is_super=is_super
        )
        self._execute(statement)
569048
private static function _createAdminUser()
        {

            $oUser     = new User();
            $factory   = self::$_container->get('security.encoder_factory');
            $encoder   = $factory->getEncoder($oUser);
            $sSalt     = $oUser->getSalt();
            $sPassword = $encoder->encodePassword(self::$_data['adminPassword'], $sSalt);


            $oStatement = self::$_connection->prepare('INSERT INTO `user` (`id`, `username`, `password`, `salt`, `firstname`, `lastname`, `email`, `phone`, `memo`, `activated`, `last_login`, `notification_change`, `notification_error`) VALUES (null, :adminUser, :adminPassword , :adminPasswordSalt, \'admin\', \'admin\', :adminEmail, \'\', \'\', 1, \'0000-00-00 00:00:00\', 1, 1);');
            $oResult    = $oStatement->execute(array(
                                                   ":adminUser"         => self::$_data['adminUser'],
                                                   ":adminPassword"     => $sPassword,
                                                   ":adminPasswordSalt" => $sSalt,
                                                   ":adminEmail"        => self::$_data['adminEmail'],
                                               ));

            if ($oResult !== true) {
                throw new Exception("Error while creating admin user");
            }

            $iUserId = self::$_connection->lastInsertId();

            $oStatement = self::$_connection->prepare('INSERT INTO  `user_role` (`user_id` ,`role_id`)VALUES (:user_id,  :user_role_id);');
            $oResult    = $oStatement->execute(array(
                                                   ":user_id"      => $iUserId,
                                                   ":user_role_id" => 6,
                                               ));

            if ($oResult !== true) {
                throw new Exception("Error while creating admin user");
            }

        }
575176
@Override
    public User createUser(User user) throws UnauthorizedException, NameConflictException {
        try {
            return userDao.createUser(user);
        } catch (DuplicateKeyException e) {
            throw new NameConflictException("User name is already in use", e);
        }
    }
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
1059244
function createAdminUser(app, result, callback) {
  // Create the admin user.
  var User = app.type('user');
  var userData = {
    username: result.adminName,
    password: result.adminPass,
    email: result.adminEmail,
    roles: ['administrator']
  };
  User.validateAndSave(userData, callback);
}