Common code to change a user's GECOS information
331678
def _update_gecos(name, key, value, root=None):
    '''
    
    '''
    if value is None:
        value = ''
    elif not isinstance(value, six.string_types):
        value = six.text_type(value)
    else:
        value = salt.utils.stringutils.to_unicode(value)
    pre_info = _get_gecos(name, root=root)
    if not pre_info:
        return False
    if value == pre_info[key]:
        return True
    gecos_data = copy.deepcopy(pre_info)
    gecos_data[key] = value

    cmd = ['usermod']
    if root is not None and __grains__['kernel'] != 'AIX':
        cmd.extend(('-R', root))
    cmd.extend(('-c', _build_gecos(gecos_data), name))

    __salt__['cmd.run'](cmd, python_shell=False)
    return _get_gecos(name, root=root).get(key) == value
872807
def alter(self, operation, timeout=None, metadata=None, credentials=None):
        """"""
        new_metadata = self.add_login_metadata(metadata)

        try:
            return self.any_client().alter(operation, timeout=timeout,
                                           metadata=new_metadata,
                                           credentials=credentials)
        except Exception as error:
            if util.is_jwt_expired(error):
                self.retry_login()
                new_metadata = self.add_login_metadata(metadata)
                return self.any_client().alter(operation, timeout=timeout,
                                               metadata=new_metadata,
                                               credentials=credentials)
            else:
                raise error
1337158
def cli(env, identifier):
    """"""

    mgr = SoftLayer.UserManager(env.client)
    user_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'username')
    object_mask = "mask[id, permissions, isMasterUserFlag, roles]"

    user = mgr.get_user(user_id, object_mask)
    all_permissions = mgr.get_all_permissions()
    user_permissions = perms_to_dict(user['permissions'])

    if user['isMasterUserFlag']:
        click.secho('This account is the Master User and has all permissions enabled', fg='green')

    env.fout(roles_table(user))
    env.fout(permission_table(user_permissions, all_permissions))
306370
def info(name):
    '''
    
    '''
    ret = {}
    try:
        data = pwd.getpwnam(name)
        ret['gid'] = data.pw_gid
        ret['groups'] = list_groups(name)
        ret['home'] = data.pw_dir
        ret['name'] = data.pw_name
        ret['passwd'] = data.pw_passwd
        ret['shell'] = data.pw_shell
        ret['uid'] = data.pw_uid
        # Put GECOS info into a list
        gecos_field = data.pw_gecos.split(',', 3)
        # Assign empty strings for any unspecified GECOS fields
        while len(gecos_field) < 4:
            gecos_field.append('')
        ret['fullname'] = gecos_field[0]
        ret['roomnumber'] = gecos_field[1]
        ret['workphone'] = gecos_field[2]
        ret['homephone'] = gecos_field[3]
    except KeyError:
        return {}
    return ret
1306276
def upgradeUserInfo1to2(oldUserInfo):
    
    newUserInfo = oldUserInfo.upgradeVersion(
        UserInfo.typeName, 1, 2,
        realName=oldUserInfo.firstName + u" " + oldUserInfo.lastName)
    return newUserInfo
963164
def rename(name, new_name):
    '''
    
    '''
    current_info = info(name)
    if not current_info:
        raise CommandExecutionError('User \'{0}\' does not exist'.format(name))
    new_info = info(new_name)
    if new_info:
        raise CommandExecutionError(
            'User \'{0}\' already exists'.format(new_name)
        )
    cmd = ['usermod', '-l', new_name, name]
    __salt__['cmd.run'](cmd, python_shell=False)
    return info(new_name).get('name') == new_name
973117
def cli(ctx, email, first_name, last_name, password, metadata={}):
    
    return ctx.gi.users.update_user(email, first_name, last_name, password, metadata=metadata)
1333988
def cli(env, group_id, name, description):
    """"""
    mgr = SoftLayer.NetworkManager(env.client)
    data = {}
    if name:
        data['name'] = name
    if description:
        data['description'] = description

    if not mgr.edit_securitygroup(group_id, **data):
        raise exceptions.CLIAbort("Failed to edit security group")
510477
def p_changeinfo(self):
        '''
        
        '''

        post_data, def_dic = self.fetch_post_data()

        usercheck = MUser.check_user(self.userinfo.uid, post_data['rawpass'])
        if usercheck == 1:
            MUser.update_info(self.userinfo.uid, post_data['user_email'], extinfo=def_dic)
            output = {'changeinfo ': usercheck}
        else:
            output = {'changeinfo ': 0}
        return json.dump(output, self)
1025086
def add_credential(self, credtype, domain, username, password, groupid=None, pillaged_from=None):
        
        domain = domain.split('.')[0].upper()
        user_rowid = None
        cur = self.conn.cursor()

        if groupid and not self.is_group_valid(groupid):
            cur.close()
            return

        if pillaged_from and not self.is_computer_valid(pillaged_from):
            cur.close()
            return

        cur.execute("SELECT * FROM users WHERE LOWER(domain)=LOWER(?) AND LOWER(username)=LOWER(?) AND LOWER(credtype)=LOWER(?)", [domain, username, credtype])
        results = cur.fetchall()

        if not len(results):
            cur.execute("INSERT INTO users (domain, username, password, credtype, pillaged_from_computerid) VALUES (?,?,?,?,?)", [domain, username, password, credtype, pillaged_from])
            user_rowid = cur.lastrowid
            if groupid:
                cur.execute("INSERT INTO group_relations (userid, groupid) VALUES (?,?)", [user_rowid, groupid])
        else:
            for user in results:
                if not user[3] and not user[4] and not user[5]:
                    cur.execute('UPDATE users SET password=?, credtype=?, pillaged_from_computerid=? WHERE id=?', [password, credtype, pillaged_from, user[0]])
                    user_rowid = cur.lastrowid
                    if groupid and not len(self.get_group_relations(user_rowid, groupid)):
                        cur.execute("INSERT INTO group_relations (userid, groupid) VALUES (?,?)", [user_rowid, groupid])

        cur.close()

        logging.debug('add_credential(credtype={}, domain={}, username={}, password={}, groupid={}, pillaged_from={}) => {}'.format(credtype, domain, username, password,
                                                                                                                                    groupid, pillaged_from, user_rowid))

        return user_rowid
1358504
def SetConfiguredUsers(self, users):
    
    prefix = self.logger.name + '-'
    with tempfile.NamedTemporaryFile(
        mode='w', prefix=prefix, delete=True) as updated_users:
      updated_users_file = updated_users.name
      for user in users:
        updated_users.write(user + '\n')
      updated_users.flush()
      if not os.path.exists(self.google_users_dir):
        os.makedirs(self.google_users_dir)
      shutil.copy(updated_users_file, self.google_users_file)

    file_utils.SetPermissions(self.google_users_file, mode=0o600, uid=0, gid=0)
440953
def auth_edit(name, **kwargs):
    
    ctx = Context(**kwargs)
    ctx.timeout = None
    ctx.execute_action('auth:group:edit', **{
        'storage': ctx.repo.create_secure_service('storage'),
        'name': name,
    })
262810
def chgid(name, gid):
    '''
    
    '''
    pre_info = info(name)
    if not pre_info:
        raise CommandExecutionError(
            'User \'{0}\' does not exist'.format(name)
        )
    if gid == pre_info['gid']:
        return True
    cmd = ['usermod', '-g', gid, name]
    __salt__['cmd.run'](cmd, python_shell=False)
    return info(name).get('gid') == gid
969223
def alter(data, system):
    """"""
    device = data[0]
    action = data[1]
    if data[2] == '*':
        data[2] = '.*'
    regex = re.compile(data[2])
    prop = data[3]
    value = float(data[4])
    if action == 'MUL':
        for item in range(system.__dict__[device].n):
            if regex.search(system.__dict__[device].name[item]):
                system.__dict__[device].__dict__[prop][item] *= value
    elif action == 'REP':
        for item in range(system.__dict__[device].n):
            if regex.search(system.__dict__[device].name[item]):
                system.__dict__[device].__dict__[prop][item] = value
    elif action == 'DIV':
        if not value:
            return
        for item in range(system.__dict__[device].n):
            if regex.search(system.__dict__[device].name[item]):
                system.__dict__[device].__dict__[prop][item] /= value
    elif action == 'SUM':
        for item in range(system.__dict__[device].n):
            if regex.search(system.__dict__[device].name[item]):
                system.__dict__[device].__dict__[prop][item] += value
    elif action == 'SUB':
        for item in range(system.__dict__[device].n):
            if regex.search(system.__dict__[device].name[item]):
                system.__dict__[device].__dict__[prop][item] -= value
    elif action == 'POW':
        for item in range(system.__dict__[device].n):
            if regex.search(system.__dict__[device].name[item]):
                system.__dict__[device].__dict__[prop][item] **= value
    else:
        print('ALTER action <%s> is not defined', action)
1033215
function(userId, properties, callback) {
      if (!userId) return callback(new Error(utils.i18n.identities.id));
      utils.debug('Identity edit: ' + userId);

      request.patch({
        path: '/users/' + userId + '/identity',
        body: Object.keys(properties).map(function(propertyName) {
          return {
            operation: 'set',
            property: propertyName,
            value: properties[propertyName]
          };
        })
      }, callback || utils.nop);
    }
275657
def edit(user_name, repo_name, key_id, params={})
      _update_user_repo_params(user_name, repo_name)
      _validate_user_repo_params(user, repo) unless user? && repo?
      _validate_presence_of key_id

      normalize! params
      filter! VALID_KEY_PARAM_NAMES, params

      put_request("/1.0/repositories/#{user}/#{repo.downcase}/deploy-keys/#{key_id}", params)
    end
1314357
def _legacy_add_user(self, name, password, read_only, **kwargs):
        
        # Use a Collection with the default codec_options.
        system_users = self._collection_default_options('system.users')
        user = system_users.find_one({"user": name}) or {"user": name}
        if password is not None:
            user["pwd"] = auth._password_digest(name, password)
        if read_only is not None:
            user["readOnly"] = read_only
        user.update(kwargs)

        # We don't care what the _id is, only that it has one
        # for the replace_one call below.
        user.setdefault("_id", ObjectId())
        try:
            system_users.replace_one({"_id": user["_id"]}, user, True)
        except OperationFailure as exc:
            # First admin user add fails gle in MongoDB >= 2.1.2
            # See SERVER-4225 for more information.
            if 'login' in str(exc):
                pass
            # First admin user add fails gle from mongos 2.0.x
            # and 2.2.x.
            elif (exc.details and
                  'getlasterror' in exc.details.get('note', '')):
                pass
            else:
                raise