create a splunk user by name/email

    CLI Example:

        salt myminion splunk.create_user user@example.com roles=['user'] realname="Test User" name=testuser
322254
def create_user(email, profile="splunk", **kwargs):
    '''
    
    '''

    client = _get_splunk(profile)

    email = email.lower()

    user = list_users(profile).get(email)

    if user:
        log.error("User is already present %s", email)
        return False

    property_map = {}

    for field in ALLOWED_FIELDS_FOR_MODIFICATION:
        if kwargs.get(field):
            property_map[field] = kwargs.get(field)

    try:
        # create
        for req_field in REQUIRED_FIELDS_FOR_CREATE:
            if not property_map.get(req_field):
                log.error("Missing required params %s",
                          ', '.join([six.text_type(k) for k in REQUIRED_FIELDS_FOR_CREATE]))
                return False

        newuser = client.users.create(username=property_map['name'],
                                password=_generate_password(email),
                                roles=property_map['roles'],
                                email=email,
                                realname=property_map['realname'])

        _send_email(newuser.name, newuser.email)

        response = {}
        for field in ['email', 'password', 'realname', 'roles']:
            response[field] = newuser[field]

    except Exception as e:
        log.error("Caught exception %s", e)
        return False
435588
def splunk(cmd, user='admin', passwd='changeme'):
    """"""
    return sudo('/opt/splunkforwarder/bin/splunk {c} -auth {u}:{p}'
                .format(c=cmd, u=user, p=passwd))
931611
def create(username, groups = '', opts = {})
      payload = {
        :account => {
          :username => username,
          :comment  => '',
          :groups   => groups,
          :password => password_opts.merge(opts.fetch(:password, {}))
        }
      }
      @server.commands.get(post(payload)['command']['id'])
    end
114374
def update_user(email, profile="splunk", **kwargs):
    '''
    
    '''

    client = _get_splunk(profile)

    email = email.lower()

    user = list_users(profile).get(email)

    if not user:
        log.error('Failed to retrieve user %s', email)
        return False

    property_map = {}

    for field in ALLOWED_FIELDS_FOR_MODIFICATION:
        if kwargs.get(field):
            property_map[field] = kwargs.get(field)

    # update
    kwargs = {}
    roles = [role.name for role in user.role_entities]

    for k, v in property_map.items():
        resource_value = user[k]
        if resource_value is not None:
            # you can't update the username in update api call
            if k.lower() == 'name':
                continue
            if k.lower() == 'roles':
                if isinstance(v, six.string_types):
                    v = v.split(',')
                if set(roles) != set(v):
                    kwargs['roles'] = list(set(v))
            elif resource_value != v:
                kwargs[k] = v

    if kwargs:
        user.update(**kwargs).refresh()

        fields_modified = {}
        for field in ALLOWED_FIELDS_FOR_MODIFICATION:
            fields_modified[field] = user[field]

    else:
        #succeeded, no change
        return True
1180705
static void createUserIfMissing(DbConn cnx, String login, String password, String description, String... roles)
    {
        try
        {
            int userId = cnx.runSelectSingle("user_select_id_by_key", Integer.class, login);
            cnx.runUpdate("user_update_enable_by_id", userId);
            RUser.set_roles(cnx, userId, roles);
        }
        catch (NoResultException e)
        {
            String saltS = null;
            String hash = null;
            if (null != password && !"".equals(password))
            {
                ByteSource salt = new SecureRandomNumberGenerator().nextBytes();
                hash = new Sha512Hash(password, salt, 100000).toHex();
                saltS = salt.toHex();
            }

            RUser.create(cnx, login, hash, saltS, roles);
        }
    }
1230820
def add_user(username, password):
    

    user_model = Query()
    if db.search(user_model.username == username):
        return {
            'error': 'User {0} already exists'.format(username)
        }

    salt = hashlib.sha512(str(os.urandom(64)).encode('utf-8')).hexdigest()
    password = hash_password(password, salt)
    api_key = gen_api_key(username)

    user = {
        'username': username,
        'password': password,
        'salt': salt,
        'api_key': api_key
    }
    user_id = db.insert(user)

    return {
       'result': 'success',
       'eid': user_id,
       'user_created': user
    }
386620
def add_user(name, password=None, runas=None):
    '''
    
    '''
    clear_pw = False

    if password is None:
        # Generate a random, temporary password. RabbitMQ requires one.
        clear_pw = True
        password = ''.join(random.SystemRandom().choice(
            string.ascii_uppercase + string.digits) for x in range(15))

    if runas is None and not salt.utils.platform.is_windows():
        runas = salt.utils.user.get_user()

    if salt.utils.platform.is_windows():
        # On Windows, if the password contains a special character
        # such as '|', normal execution will fail. For example:
        # cmd: rabbitmq.add_user abc "asdf|def"
        # stderr: 'def' is not recognized as an internal or external
        #         command,\r\noperable program or batch file.
        # Work around this by using a shell and a quoted command.
        python_shell = True
        cmd = '"{0}" add_user "{1}" "{2}"'.format(
            RABBITMQCTL, name, password
        )
    else:
        python_shell = False
        cmd = [RABBITMQCTL, 'add_user', name, password]

    res = __salt__['cmd.run_all'](
        cmd,
        reset_system_locale=False,
        output_loglevel='quiet',
        runas=runas,
        python_shell=python_shell)

    if clear_pw:
        # Now, Clear the random password from the account, if necessary
        try:
            clear_password(name, runas)
        except Exception:
            # Clearing the password failed. We should try to cleanup
            # and rerun and error.
            delete_user(name, runas)
            raise

    msg = 'Added'
    return _format_response(res, msg)
577666
def create_identity(self, user, sp_mapping, **extra_config):
        

        return {
            out_attr: getattr(user, user_attr)
            for user_attr, out_attr in sp_mapping.items()
            if hasattr(user, user_attr)
        }
1366110
def get_user(email, profile="splunk", **kwargs):
    '''
    
    '''

    user_map = list_users(profile)
    user_found = email.lower() in user_map.keys()

    if not kwargs.get('user_details', False) and user_found:
        # The user is in splunk group, just return
        return True
    elif kwargs.get('user_details', False) and user_found:
        user = user_map[email.lower()]

        response = {}
        for field in ['defaultApp', 'realname', 'name', 'email']:
            response[field] = user[field]

        response['roles'] = []
        for role in user.role_entities:
            response['roles'].append(role.name)

        return response

    return False
992410
def _create_or_update_user(
            self, create, name, password, read_only, **kwargs):
        
        opts = {}
        if read_only or (create and "roles" not in kwargs):
            warnings.warn("Creating a user with the read_only option "
                          "or without roles is deprecated in MongoDB "
                          ">= 2.6", DeprecationWarning)

            opts["roles"] = [self._default_role(read_only)]

        elif read_only:
            warnings.warn("The read_only option is deprecated in MongoDB "
                          ">= 2.6, use 'roles' instead", DeprecationWarning)

        if password is not None:
            # We always salt and hash client side.
            if "digestPassword" in kwargs:
                raise ConfigurationError("The digestPassword option is not "
                                         "supported via add_user. Please use "
                                         "db.command('createUser', ...) "
                                         "instead for this option.")
            opts["pwd"] = auth._password_digest(name, password)
            opts["digestPassword"] = False

        # Don't send {} as writeConcern.
        if self.write_concern.acknowledged and self.write_concern.document:
            opts["writeConcern"] = self.write_concern.document
        opts.update(kwargs)

        if create:
            command_name = "createUser"
        else:
            command_name = "updateUser"

        self.command(command_name, name, **opts)
906488
def cli(ctx, email, first_name, last_name, password, role="user", metadata={}):
    
    return ctx.gi.users.create_user(email, first_name, last_name, password, role=role, metadata=metadata)
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"))
585294
def list_users(profile="splunk"):
    '''
    
    '''

    config = __salt__['config.option'](profile)
    key = "splunk.users.{0}".format(
        config.get('host')
    )

    if key not in __context__:
        _populate_cache(profile)

    return __context__[key]
438221
def member_create(self, params, member_id):
        
        member_config = params.get('rsParams', {})
        server_id = params.pop('server_id', None)
        version = params.pop('version', self._version)
        proc_params = {'replSet': self.repl_id}
        proc_params.update(params.get('procParams', {}))
        if self.enable_ipv6:
            enable_ipv6_single(proc_params)
        # Make sure that auth isn't set the first time we start the servers.
        proc_params = self._strip_auth(proc_params)

        # Don't pass in auth_key the first time we start the servers.
        server_id = self._servers.create(
            name='mongod',
            procParams=proc_params,
            sslParams=self.sslParams,
            version=version,
            server_id=server_id
        )
        member_config.update({"_id": member_id,
                              "host": self._servers.hostname(server_id)})
        return member_config
614825
def update(name, profile="splunk", **kwargs):
    '''
    
    '''
    client = _get_splunk(profile)
    search = client.saved_searches[name]
    props = _get_splunk_search_props(search)
    updates = kwargs
    update_needed = False
    update_set = dict()
    diffs = []
    for key in sorted(kwargs):
        old_value = props.get(key, None)
        new_value = updates.get(key, None)
        if isinstance(old_value, six.string_types):
            old_value = old_value.strip()
        if isinstance(new_value, six.string_types):
            new_value = new_value.strip()
        if old_value != new_value:
            update_set[key] = new_value
            update_needed = True
            diffs.append("{0}: '{1}' => '{2}'".format(
                key, old_value, new_value
            ))
    if update_needed:
        search.update(**update_set).refresh()
        return update_set, diffs
    return False
1028864
def create_user(
            self, username, email, short_name, full_name,
            institute, password=None, **extra_fields):
        
        return self._create_user(
            username=username, email=email,
            short_name=short_name, full_name=full_name,
            institute=institute, password=password,
            is_admin=False, **extra_fields)
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")