Add a key/account to an account's permission
185444
def allow(ctx, foreign_account, permission, weight, threshold, account):
    
    if not foreign_account:
        from peerplaysbase.account import PasswordKey

        pwd = click.prompt(
            "Password for Key Derivation", hide_input=True, confirmation_prompt=True
        )
        foreign_account = format(
            PasswordKey(account, pwd, permission).get_public(), "PPY"
        )
    pprint(
        ctx.peerplays.allow(
            foreign_account,
            weight=weight,
            account=account,
            permission=permission,
            threshold=threshold,
        )
    )
169981
def run(self, value, errors, request):
        """"""
        thing = super(AccessibleDBThing, self).run(value, errors, request)
        if errors:
            return None
        if not thing.can_access(request.user):
            message = 'Insufficient permissions for {0}'.format(self.param)
            raise HTTPForbidden(message)
        return thing
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')
1241752
def add_permission(self, role, name):
        
        if self.has_permission(role, name):
            return True
        targetGroup = AuthGroup.objects(role=role, creator=self.client).first()
        if not targetGroup:
            return False
        # Create or update
        permission = AuthPermission.objects(name=name).update(
                add_to_set__groups=[targetGroup], creator=self.client, upsert=True
        )
        return True
380741
def update_permission(obj, data):
    """"""
    full_permissions = get_all_perms(obj)

    def apply_perm(perm_func, perms, entity):
        """Apply permissions using given ``perm_func``.

        ``perm_func`` is intended to be ``assign_perms`` or
        ``remove_perms`` shortcut function from ``django-guardian``, but
        can be any function that accepts permission codename,
        user/group and object parameters (in this order).

        If given permission does not exist, ``exceptions.ParseError`` is
        raised.

        "ALL" passed as ``perms`` parameter, will call ``perm_function``
        with ``full_permissions`` list.

        :param func perm_func: Permissions function to be applied
        :param list params: list of params to be allpied
        :param entity: user or group to be passed to ``perm_func``
        :type entity: `~django.contrib.auth.models.User` or
            `~django.contrib.auth.models.Group`

        """
        if perms == 'ALL':
            perms = full_permissions
        for perm in perms:
            perm_codename = get_full_perm(perm, obj)
            if perm_codename not in full_permissions:
                raise exceptions.ParseError("Unknown permission: {}".format(perm))
            perm_func(perm_codename, entity, obj)

    def set_permissions(entity_type, perm_type):
        """Set object permissions."""
        perm_func = assign_perm if perm_type == 'add' else remove_perm
        fetch_fn = fetch_user if entity_type == 'users' else fetch_group

        for entity_id in data.get(entity_type, {}).get(perm_type, []):
            entity = fetch_fn(entity_id)
            if entity:
                perms = data[entity_type][perm_type][entity_id]
                apply_perm(perm_func, perms, entity)

    def set_public_permissions(perm_type):
        """Set public permissions."""
        perm_func = assign_perm if perm_type == 'add' else remove_perm
        user = AnonymousUser()
        perms = data.get('public', {}).get(perm_type, [])
        apply_perm(perm_func, perms, user)

    with transaction.atomic():
        set_permissions('users', 'add')
        set_permissions('users', 'remove')
        set_permissions('groups', 'add')
        set_permissions('groups', 'remove')
        set_public_permissions('add')
        set_public_permissions('remove')
392909
def _add_ssh_key(ret):
    '''
    
    '''
    priv = None
    if __opts__.get('ssh_use_home_key') and os.path.isfile(os.path.expanduser('~/.ssh/id_rsa')):
        priv = os.path.expanduser('~/.ssh/id_rsa')
    else:
        priv = __opts__.get(
            'ssh_priv',
            os.path.abspath(os.path.join(
                __opts__['pki_dir'],
                'ssh',
                'salt-ssh.rsa'
            ))
        )
    if priv and os.path.isfile(priv):
        ret['priv'] = priv
387346
def run_putgist(filename, user, **kwargs):
    """"""
    assume_yes = kwargs.get("yes_to_all")
    private = kwargs.get("private")
    getgist = GetGist(
        user=user,
        filename=filename,
        assume_yes=assume_yes,
        create_private=private,
        allow_none=True,
    )
    getgist.put()
1274417
def authorized_keys(mode='r'):
    
    path = '/var/home/.ssh/authorized_keys'
    if not os.path.exists(path):
        os.makedirs(os.path.dirname(path))
        open(path, 'w').close()
    with open(path, mode) as ak:
        yield ak
186439
def add(name,
        uid=None,
        gid=None,
        groups=None,
        home=None,
        shell=None,
        fullname=None,
        createhome=True,
        **kwargs):
    '''
    
    '''
    if info(name):
        raise CommandExecutionError('User \'{0}\' already exists'.format(name))

    if salt.utils.stringutils.contains_whitespace(name):
        raise SaltInvocationError('Username cannot contain whitespace')

    if uid is None:
        uid = _first_avail_uid()
    if gid is None:
        gid = 20  # gid 20 == 'staff', the default group
    if home is None:
        home = '/Users/{0}'.format(name)
    if shell is None:
        shell = '/bin/bash'
    if fullname is None:
        fullname = ''

    if not isinstance(uid, int):
        raise SaltInvocationError('uid must be an integer')
    if not isinstance(gid, int):
        raise SaltInvocationError('gid must be an integer')

    name_path = '/Users/{0}'.format(name)
    _dscl([name_path, 'UniqueID', uid])
    _dscl([name_path, 'PrimaryGroupID', gid])
    _dscl([name_path, 'UserShell', shell])
    _dscl([name_path, 'NFSHomeDirectory', home])
    _dscl([name_path, 'RealName', fullname])

    # Make sure home directory exists
    if createhome:
        __salt__['file.mkdir'](home, user=uid, group=gid)

    # dscl buffers changes, sleep before setting group membership
    time.sleep(1)
    if groups:
        chgroups(name, groups)
    return True
667011
function revokePermission (commandOptions, { accountId, grantablePermissionName }) {
  return command(
    commandOptions,
    txHelper.addCommand(
      txHelper.emptyTransaction(),
      'revokePermission',
      {
        accountId,
        grantablePermissionName
      }
    )
  )
}
1163564
def setup_auth(**keys):
    ''''''
    auth = tweepy.OAuthHandler(consumer_key=keys['consumer_key'], consumer_secret=keys['consumer_secret'])
    auth.set_access_token(
        key=keys.get('token', keys.get('key', keys.get('oauth_token'))),
        secret=keys.get('secret', keys.get('oauth_secret'))
    )
    return auth
1262839
def SetCredentials(api_key,api_passwd):
	""""""
	global V1_API_KEY
	global V1_API_PASSWD
	global _V1_ENABLED
	_V1_ENABLED = True
	V1_API_KEY = api_key
	V1_API_PASSWD = api_passwd
549758
function setAccountQuorum (commandOptions, { accountId, quorum }) {
  return command(
    commandOptions,
    txHelper.addCommand(
      txHelper.emptyTransaction(),
      'setAccountQuorum',
      {
        accountId,
        quorum
      }
    )
  )
}
777273
def import_key(
        ctx, slot, management_key, pin, private_key,
        pin_policy, touch_policy, password):
    
    dev = ctx.obj['dev']
    controller = ctx.obj['controller']
    _ensure_authenticated(ctx, controller, pin, management_key)

    data = private_key.read()

    while True:
        if password is not None:
            password = password.encode()
        try:
            private_key = parse_private_key(data, password)
        except (ValueError, TypeError):
            if password is None:
                password = click.prompt(
                    'Enter password to decrypt key',
                    default='', hide_input=True,
                    show_default=False,
                    err=True)
                continue
            else:
                password = None
                click.echo('Wrong password.')
            continue
        break

    if pin_policy:
        pin_policy = PIN_POLICY.from_string(pin_policy)
    if touch_policy:
        touch_policy = TOUCH_POLICY.from_string(touch_policy)

    _check_pin_policy(ctx, dev, controller, pin_policy)
    _check_touch_policy(ctx, controller, touch_policy)
    _check_key_size(ctx, controller, private_key)

    controller.import_key(
            slot,
            private_key,
            pin_policy,
            touch_policy)
1039078
def UpdateUser(self, user, ssh_keys):
    
    if not bool(USER_REGEX.match(user)):
      self.logger.warning('Invalid user account name %s.', user)
      return False
    if not self._GetUser(user):
      # User does not exist. Attempt to create the user and add them to the
      # appropriate user groups.
      if not (self._AddUser(user)
              and self._UpdateUserGroups(user, self.groups)):
        return False
    # Add the user to the google sudoers group.
    if not self._UpdateSudoer(user, sudoer=True):
      return False

    # Don't try to manage account SSH keys with a shell set to disable
    # logins. This helps avoid problems caused by operator and root sharing
    # a home directory in CentOS and RHEL.
    pw_entry = self._GetUser(user)
    if pw_entry and os.path.basename(pw_entry.pw_shell) == 'nologin':
      message = 'Not updating user %s. User set `nologin` as login shell.'
      self.logger.debug(message, user)
      return True

    try:
      self._UpdateAuthorizedKeys(user, ssh_keys)
    except (IOError, OSError) as e:
      message = 'Could not update the authorized keys file for user %s. %s.'
      self.logger.warning(message, user, str(e))
      return False
    else:
      return True
465935
def cli(ctx, key, metadata=""):
    
    return ctx.gi.cannedkeys.add_key(key, metadata=metadata)
410540
def add_permission(self, name):
        
        perm = self.find_permission(name)
        if perm is None:
            try:
                perm = self.permission_model()
                perm.name = name
                self.get_session.add(perm)
                self.get_session.commit()
                return perm
            except Exception as e:
                log.error(c.LOGMSG_ERR_SEC_ADD_PERMISSION.format(str(e)))
                self.get_session.rollback()
        return perm