Common code to change a user's GECOS information
552528
def _update_gecos(name, key, value):
    '''
    
    '''
    if not isinstance(value, six.string_types):
        value = six.text_type(value)
    pre_info = _get_gecos(name)
    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', '-c', _build_gecos(gecos_data), name]
    __salt__['cmd.run'](cmd, python_shell=False)
    post_info = info(name)
    return _get_gecos(name).get(key) == value
776664
def _get_gecos(name):
    '''
    
    '''
    gecos_field = pwd.getpwnam(name).pw_gecos.split(',', 3)
    if not gecos_field:
        return {}
    else:
        # Assign empty strings for any unspecified trailing GECOS fields
        while len(gecos_field) < 4:
            gecos_field.append('')
        return {'fullname': six.text_type(gecos_field[0]),
                'roomnumber': six.text_type(gecos_field[1]),
                'workphone': six.text_type(gecos_field[2]),
                'homephone': six.text_type(gecos_field[3])}
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
911366
def Modify(self, user_type=None, password=None):
    """"""

    args = user_management_pb2.ApiModifyGrrUserArgs(
        username=self.username, user_type=user_type)

    if user_type is not None:
      args.user_type = user_type

    if password is not None:
      args.password = password

    data = self._context.SendRequest("ModifyGrrUser", args)
    return GrrUser(data=data, context=self._context)
408478
def _UpdateSudoer(self, user, sudoer=False):
    
    if sudoer:
      self.logger.info('Adding user %s to the Google sudoers group.', user)
      command = self.gpasswd_add_cmd.format(
          user=user, group=self.google_sudoers_group)
    else:
      self.logger.info('Removing user %s from the Google sudoers group.', user)
      command = self.gpasswd_remove_cmd.format(
          user=user, group=self.google_sudoers_group)

    try:
      subprocess.check_call(command.split(' '))
    except subprocess.CalledProcessError as e:
      self.logger.warning('Could not update user %s. %s.', user, str(e))
      return False
    else:
      self.logger.debug('Removed user %s from the Google sudoers group.', user)
      return True
373771
def change_nick(self, new_nick):
        """"""

        if self.logged_in:
            raise RuntimeError("User must be logged out")
        self.__verify_username(new_nick)

        self.conn.make_call("command", self.nick, "nick", new_nick)
        self.nick = new_nick
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
461019
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)
        )
    _dscl(
        ['/Users/{0}'.format(name), 'RecordName', name, new_name],
        ctype='change'
    )
    # dscl buffers changes, sleep 1 second before checking if new value
    # matches desired value
    time.sleep(1)
    return info(new_name).get('RecordName') == new_name
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)
138972
def change_status(self, bucket, key, status, cond):
        
        resource = entry(bucket, key)
        if cond and isinstance(cond, dict):
            condstr = ""
            for k, v in cond.items():
                condstr += "{0}={1}&".format(k, v)
            condstr = urlsafe_base64_encode(condstr[:-1])
            return self.__rs_do('chstatus', resource, 'status/{0}'.format(status), 'cond', condstr)
        return self.__rs_do('chstatus', resource, 'status/{0}'.format(status))
931188
def _copy_old_configs(self, user, default):
        
        DEPRECATED_SUMMERNOTE_CONFIGS = (
            'width',
            'height',
            'lang',
            'toolbar',
        )
        for key in DEPRECATED_SUMMERNOTE_CONFIGS:
            if user.get(key):
                self.config['summernote'][key] = user.get(key)
            if not self.config['summernote'].get(key):
                self.config['summernote'][key] = default['summernote'].get(key)
723788
def cli(ctx, id_number, new_value):
    
    return ctx.gi.status.update_status(id_number, new_value)
1121991
def modify(self, **params):
        """"""
        data = self.api_client.update_current_user(**params)
        self.update(data)
        return data
1355981
def changememokey(ctx, key, account):
    
    pprint(ctx.blockchain.update_memo_key(key, account=account))
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
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
551162
def cli(env, identifier, enable, permission, from_user):
    """"""
    mgr = SoftLayer.UserManager(env.client)
    user_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'username')
    result = False
    if from_user:
        from_user_id = helpers.resolve_id(mgr.resolve_ids, from_user, 'username')
        result = mgr.permissions_from_user(user_id, from_user_id)
    elif enable:
        result = mgr.add_permissions(user_id, permission)
    else:
        result = mgr.remove_permissions(user_id, permission)

    if result:
        click.secho("Permissions updated successfully: %s" % ", ".join(permission), fg='green')
    else:
        click.secho("Failed to update permissions: %s" % ", ".join(permission), fg='red')