/* Method provided to be called using reflection to discretely create the admin user if needed.
352024
private static PrincipalUser createAdminUser() {
        PrincipalUser result = new PrincipalUser("admin", "argus-admin@salesforce.com");

        result.id = BigInteger.ONE;
        result.setPrivileged(true);
        return result;
    }
1189873
protected void populateUser (
        User user, Username name, Password pass, String realname, String email, int siteId)
    {
        user.username = name.getUsername();
        user.setPassword(pass);
        user.setRealName(realname);
        user.setEmail(email);
        user.created = new Date(System.currentTimeMillis());
        user.setSiteId(siteId);
    }
571480
@CommandArgument
  public void adduser(
      @OptionArgument("username") String username,
      @OptionArgument("password") String password,
      @OptionArgument("roles") String roles) {

    if (users.containsKey(username)) {
      System.err.println(String.format("User '%s' already exists", username));
    } else {

      User user = new User(username);
      user.salt = passwd.generateSalt();
      user.hash = passwd.getEncryptedPassword(password, user.salt);
      user.roles.addAll(Arrays.asList(roles.split(",")));
      users.put(username, user);

    }
  }
1144723
def create
      @user = User.new(user_params.except(:user_roles))
      authorize! :create, @user
      build_user_roles(params)

      if @user.save
        redirect_to @user,
                    notice: "User was successfully created."
      else
        render :new
      end
    end
1310361
public function onCreating()
    {
        // Send out email
        if (Request::has('_send_email')) {
            $this->sendCreateEmail();
        }

        // Make them active
        $this->active = 1;

        // If the current user can't grant permissions, make the new admin
        // have the same role as themselves.  Admins created from the CLI (like as
        // part of a migration) won't be logged in.
        if (($admin = app('decoy.user'))
            && !app('decoy.user')->can('grant', 'admins')) {
            $this->role = $admin->role;

        // Otherwise, give the admin a default role if none was defined
        } elseif (empty($this->role)) {
            $this->role = 'admin';
        }
    }
1306709
@Beta
  public GoogleCredential createDelegated(String user) {
    if (serviceAccountPrivateKey == null) {
      return this;
    }
    return toBuilder()
        .setServiceAccountUser(user)
        .build();
  }
357274
def create_user(self, user, table_privileges=['ALL PRIVILEGES'],
                    schema_privileges=['ALL PRIVILEGES'],
                    row_limit=50000):
        con = self.connection or self._connect()
        cur = con.cursor()

        cur.execute('CREATE SCHEMA {0};'.format(user))
        # self._initialize(schema=schema_name)
        password = pwgen(8)
        cur.execute(
            "CREATE USER {user} with PASSWORD '{password}';"
            .format(user=user, password=password))

        
        cur.execute('GRANT USAGE ON SCHEMA public TO {user};'
                    .format(user=user))
        cur.execute(
            'GRANT SELECT ON ALL TABLES IN SCHEMA public TO {user};'
            .format(user=user))
        cur.execute(
            'ALTER ROLE {user} SET search_path TO {user};'
            .format(user=user))

        self.stdout.write(
            'CREATED USER {user} WITH PASSWORD {password}\n'
            .format(user=user, password=password))

        """ initialize user-schema """
        old_schema = self.schema
        self.initialized = False
        self.schema = user
        self._initialize(con)

        """ Privileges on user-schema"""
        cur.execute(
            'GRANT {privileges} ON SCHEMA {user} TO {user};'
            .format(privileges=', '.join(schema_privileges), user=user))
        cur.execute(
            'GRANT {privileges} ON ALL TABLES IN SCHEMA {user} TO {user};'
            .format(privileges=', '.join(table_privileges), user=user))
        cur.execute(
            'GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA {user} TO {user};'
            .format(user=user))
        con.commit()

        if row_limit:
            """ Limit number of rows"""
            for table in ['reaction', 'publication', 'systems',
                          'reaction_system', 'publication_system',
                          'information']:
                table_factor = 1
                if table in ['reaction_system', 'publication_system']:
                    table_factor = 15
                elif table == 'publication':
                    table_factor = 1 / 100
                elif table == 'information':
                    table_factor = 1 / 100

                trigger_function = """
                CREATE OR REPLACE FUNCTION
                check_number_of_rows_{user}_{table}()
                RETURNS TRIGGER AS
                $BODY$
                BEGIN
                    IF (SELECT count(*) FROM {user}.{table}) > {row_limit}
                    THEN
                        RAISE EXCEPTION
                            'INSERT statement exceeding maximum number of rows';
                    END IF;
                    RETURN NEW;
                END;
                $BODY$
                LANGUAGE plpgsql""".format(user=user, table=table,
                                           row_limit=row_limit * table_factor)
                cur.execute(trigger_function)

                trigger = """
                DROP TRIGGER IF EXISTS tr_check_number_of_rows_{user}_{table}
                    on {user}.{table};
                CREATE TRIGGER tr_check_number_of_rows_{user}_{table}
                BEFORE INSERT ON {user}.systems
                FOR EACH ROW EXECUTE PROCEDURE check_number_of_rows_{user}_{table}();
                """.format(user=user, table=table)
                cur.execute(trigger)

        self.schema = old_schema
        set_schema = 'ALTER ROLE {user} SET search_path TO {schema};'\
                     .format(user=self.user, schema=self.schema)
        cur.execute(set_schema)

        if self.connection is None:
            con.commit()
            con.close()

        return password
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);
        }
    }
1163197
public void setUserCreated(String userCreated) {

        try {
            String userCreatedName = OpenCms.getImportExportManager().translateUser(userCreated);
            try {
                m_resourceBuilder.setUserCreated(getCms().readUser(userCreatedName).getId());
            } catch (@SuppressWarnings("unused") CmsDbEntryNotFoundException e) {
                m_resourceBuilder.setUserCreated(getRequestContext().getCurrentUser().getId());
            }
        } catch (Throwable e) {
            setThrowable(e);
        }
    }
1327236
public void addUser(PrincipalUser user) {
        SystemAssert.requireArgument(user != null, "Null user can not be added.");
        users.add(user);
    }
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)
1314067
@Override
    public User createUser(String username, String password)
            throws AuthenticationException {
        String user = file_store.getProperty(username);
        if (user != null) {
            throw new AuthenticationException("User '" + username
                    + "' already exists.");
        }
        // Encrypt the new password
        String ePwd = encryptPassword(password);
        file_store.put(username, ePwd);
        try {
            saveUsers();
        } catch (IOException e) {
            throw new AuthenticationException("Error changing password: ", e);
        }

        return getUser(username);
    }
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"))
448649
function createUser(form) {
      // refuse to work with invalid data
      if (vm.user._id || (form && !form.$valid)) {
        return;
      }

      Auth.createUser(vm.user)
        .then(createUserSuccess)
        .catch(createUserCatch);

      function createUserSuccess(newUser) {
        Toast.show({
          type: 'success',
          text: 'User ' + newUser.name + ' has been created',
          link: {state: 'admin.user.list.detail', params: {id: newUser._id}}
        });
        vm.close();
      }

      function createUserCatch(err) {
        if (form && err) {
          form.setResponseErrors(err);
        }

        Toast.show({
          type: 'warn',
          text: 'Error while creating a new user'
        });
      }
    }
984463
public void createUser(User user, String password){
        ProtocolHeader header = new ProtocolHeader();
        header.setType(ProtocolType.CreateUser);
        byte[] secret = null;
        if(password != null && ! password.isEmpty()){
            secret = ObfuscatUtil.base64Encode(password.getBytes());
        }
        CreateUserProtocol p = new CreateUserProtocol(user, secret);

        connection.submitRequest(header, p, null);
    }
962347
protected int insertUser (final User user)
        throws UserExistsException, PersistenceException
    {
        executeUpdate(new Operation<Object>() {
            public Object invoke (Connection conn, DatabaseLiaison liaison)
                throws PersistenceException, SQLException
            {
                try {
                    _utable.insert(conn, user);
                    // update the userid now that it's known
                    user.userId = liaison.lastInsertedId(conn, null, _utable.getName(), "userId");
                    // nothing to return
                    return null;

                } catch (SQLException sqe) {
                    if (liaison.isDuplicateRowException(sqe)) {
                        throw new UserExistsException("error.user_exists");
                    } else {
                        throw sqe;
                    }
                }
            }
        });

        return user.userId;
    }
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);
}