Replace user policies

@param  {Object}   params { id, organizationId, policies }
@param  {Function} cb
557653
function replaceUserPolicies (params, cb) {
      let promise = null
      if (typeof cb !== 'function') [promise, cb] = asyncify()

      const { id, organizationId, policies } = params
      const tasks = [
        (job, next) => {
          Joi.validate({ id, organizationId, policies }, validationRules.replaceUserPolicies, (err) => {
            if (err) return next(Boom.badRequest(err))
            next()
          })
        },
        (job, next) => {
          job.id = id
          job.organizationId = organizationId
          job.policies = utils.preparePolicies(policies)

          next()
        },
        checkUserOrg,
        clearUserPolicies
      ]

      if (policies.length > 0) {
        tasks.push((job, next) => {
          utils.checkPoliciesOrg(job.client, job.policies, job.organizationId, next)
        })
        tasks.push(insertUserPolicies)
      }

      db.withTransaction(tasks, (err, res) => {
        if (err) return cb(err)

        userOps.readUser({ id, organizationId }, cb)
      })

      return promise
    }
281903
function getUserOrganizationId (id, cb) {
      let promise = null
      if (typeof cb !== 'function') [promise, cb] = asyncify()

      const sqlQuery = SQL`
        SELECT org_id
        FROM users
        WHERE id = ${id}
      `
      db.query(sqlQuery, function (err, result) {
        if (err) return cb(Boom.badImplementation(err))
        if (result.rowCount === 0) return cb(Boom.notFound())

        return cb(null, result.rows[0].org_id)
      })

      return promise
    }
1149041
function remove(connections, params, cb) {
  var failed = validate(params).has(CONSTANTS.DATA_TARGET_ID);

  if (failed) {
    return cb(buildErrorResponse({error: new Error("An ID Parameter Is Required To Remove A Data Target"), code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS}));
  }

  if (!misc.checkId(params._id)) {
    return cb(buildErrorResponse({error: new Error("Invalid ID Paramter"), code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS}));
  }

  async.waterfall([
    function findAssociatedForms(cb) {
      checkFormsUsingDataTarget(connections, params, cb);
    },
    function verifyNoFormsAssociated(updatedDataTarget, cb) {
      //If there is more than one form using this data target, then do not delete it.

      if (updatedDataTarget.forms.length > 0) {
        return cb(buildErrorResponse({
          error: new Error("Forms Are Associated With This Data Target. Please Disassociate Forms From This Data Target Before Deleting."),
          code: ERROR_CODES.FH_FORMS_UNEXPECTED_ERROR
        }));
      }

      return cb(undefined, updatedDataTarget);
    },
    function processResponse(updatedDataTarget, cb) {
      //Removing The Data Target
      var DataTarget = models.get(connections.mongooseConnection, models.MODELNAMES.DATA_TARGET);

      DataTarget.remove({_id: updatedDataTarget._id}, function(err) {
        if (err) {
          return cb(buildErrorResponse({
            error: err,
            userDetail: "Unexpected Error When Removing A Data Target",
            code: ERROR_CODES.FH_FORMS_UNEXPECTED_ERROR
          }));
        }

        //Data Target Removed Successfully
        return cb();
      });
    }
  ], cb);

}
1168304
function replaceUserTeams (params, cb) {
      let promise = null
      if (typeof cb !== 'function') [promise, cb] = asyncify()

      const { id, organizationId, teams } = params
      const tasks = [
        (job, next) => {
          Joi.validate({ id, organizationId, teams }, validationRules.replaceUserTeams, (err) => {
            if (err) return next(Boom.badRequest(err))
            next()
          })
        },
        (job, next) => {
          job.id = id
          job.organizationId = organizationId
          job.teams = teams

          next()
        },
        checkUserOrg,
        (job, next) => {
          utils.checkTeamsOrg(job.client, job.teams, job.organizationId, next)
        },
        clearUserTeams,
        insertUserTeams
      ]

      db.withTransaction(tasks, (err, res) => {
        if (err) return cb(err)

        userOps.readUser({ id, organizationId }, cb)
      })

      return promise
    }
86459
function (userId, doc, fieldNames, modifier) {
			// only admins can update user roles via the client
			return Users.isAdmin(userId) || (doc._id === userId && fieldNames.indexOf("roles") < 0);
		}
384619
function createOwnerAccessPolicy(thingId, subject) {
  const thingOwnerPolicy = {
    id: thingId + "-" + subject + "-clrud-policy",
    effect: "allow",
    actions: [
      "dcd:actions:create",
      "dcd:actions:list",
      "dcd:actions:read",
      "dcd:actions:update",
      "dcd:actions:delete"
    ],
    subjects: [subject],
    resources: [
      "dcd:things:" + thingId,
      "dcd:things:" + thingId + ":properties",
      "dcd:things:" + thingId + ":properties:<.*>"
    ]
  };
  return policies.create(thingOwnerPolicy);
}
147854
def update_assume_role_policy(role_name, policy_document, region=None,
                              key=None, keyid=None, profile=None):
    '''
    
    '''
    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)

    if isinstance(policy_document, six.string_types):
        policy_document = salt.utils.json.loads(policy_document,
                                     object_pairs_hook=odict.OrderedDict)
    try:
        _policy_document = salt.utils.json.dumps(policy_document)
        conn.update_assume_role_policy(role_name, _policy_document)
        log.info('Successfully updated assume role policy for IAM role %s.', role_name)
        return True
    except boto.exception.BotoServerError as e:
        log.error(e)
        log.error('Failed to update assume role policy for IAM role %s.', role_name)
        return False
1216725
function setRequestId(id, cb) {
  var ns = getLoggerNamespace();
  ns.run(function() {
    ns.set('requestId', id);
    cb();
  });
}
1037928
function deleteUser (params, cb) {
      let promise = null
      if (typeof cb !== 'function') [promise, cb] = asyncify()

      const { id, organizationId } = params
      const tasks = [
        (job, next) => {
          Joi.validate({ id, organizationId }, validationRules.deleteUser, (err) => {
            if (err) return next(Boom.badRequest(err))
            next()
          })
        },
        (job, next) => {
          job.id = id
          next()
        },
        (job, next) => {
          const sqlQuery = SQL`DELETE FROM user_policies WHERE user_id = ${id}`

          job.client.query(sqlQuery, utils.boomErrorWrapper(next))
        },
        (job, next) => {
          const sqlQuery = SQL`DELETE FROM team_members WHERE user_id = ${id}`

          job.client.query(sqlQuery, utils.boomErrorWrapper(next))
        },
        (job, next) => {
          const sqlQuery = SQL`DELETE FROM users WHERE id = ${id} AND org_id = ${organizationId}`

          job.client.query(sqlQuery, (err, result) => {
            if (err) return next(Boom.badImplementation(err))
            if (result.rowCount === 0) return next(Boom.notFound(`User ${id} not found`))

            next()
          })
        }
      ]

      db.withTransaction(tasks, (err, res) => {
        if (err) return cb(err)

        cb()
      })

      return promise
    }
1364055
function createSharedPolicy (params, cb) {
      let promise = null
      if (typeof cb !== 'function') [promise, cb] = asyncify()

      Joi.validate(params, validationRules.createSharedPolicy, function (err) {
        if (err) return cb(Boom.badRequest(err))

        const { id, version, name, statements } = params

        insertSharedPolicies(db, [{
          id: id,
          version: version,
          name: name,
          statements: statements
        }], (err, result) => {
          if (utils.isUniqueViolationError(err)) return cb(Boom.conflict('policy already exists'))
          if (err) return cb(err)

          policyOps.readSharedPolicy({ id: result.rows[0].id }, cb)
        })
      })

      return promise
    }
618596
function update(name, config, cb) {
  this.remoteAccessApi.postJobConfig(name, config, this.opts.headers, cb);
}
478530
function moveTeam (params, cb) {
      let promise = null
      if (typeof cb !== 'function') [promise, cb] = asyncify()

      const { id, organizationId } = params

      db.withTransaction([
        (job, next) => {
          Joi.validate({ id, organizationId }, validationRules.moveTeam, (err) => {
            if (err) return next(Boom.badRequest(err))
            next()
          })
        },
        (job, next) => {
          job.params = params
          next()
        },
        checkBothTeamsFromSameOrg,
        moveTeamSql,
        moveTeamDescendants
      ], (err) => {
        if (err) return cb(err)
        teamOps.readTeam({ id, organizationId }, cb)
      })

      return promise
    }
407905
def update_rbac_policy(self, rbac_policy_id, body=None):
        """"""
        return self.put(self.rbac_policy_path % rbac_policy_id, body=body)
409930
function(schemaName, target, cb) {
  filter(schemaName, target, cb, { FUNCS: COMMANDS, mode: 'remove' })
}
116652
def policyChange(self, updateParams, func):
		
		for k,v in updateParams.items():
			k = k.replace('-','_')
			c = globals()[k](v)
			try:
				self.defaultPolicies[k] = getattr(c,func)(self.defaultPolicies[k])
			except Exception, e:
				raise
331536
function readPolicyVariables ({ id, organizationId, type }, cb) {
      let promise = null
      if (typeof cb !== 'function') [promise, cb] = asyncify()

      Joi.validate({ id, organizationId, type }, validationRules.readPolicyVariables, function (err) {
        if (err) return cb(Boom.badRequest(err))

        const sqlQuery = SQL`
          SELECT  *
          FROM policies
          WHERE id = ${id}
        `

        if (type === 'shared') {
          sqlQuery.append(SQL` AND org_id is NULL`)
        } else {
          sqlQuery.append(SQL` AND org_id=${organizationId}`)
        }

        db.query(sqlQuery, function (err, result) {
          if (err) return cb(Boom.badImplementation(err))
          if (result.rowCount === 0) return cb(Boom.notFound())

          let variables = []

          _.each(result.rows[0].statements.Statement, function (statement) {
            if (statement.Resource) {
              _.map(statement.Resource, function (resource) {
                // ignore context vars but list all others, should match validation.js
                let variableMatches = resource.match(/\${((?!(udaru)|(request)).*)(.+?)}/g)
                _.each(variableMatches, function (variable) {
                  variables.push(variable)
                })
              })
            }
          })

          return cb(null, variables)
        })
      })

      return promise
    }
251363
function create (params, opts, cb) {
      if (!cb) {
        cb = opts
      }
      if (!opts || typeof opts === 'function') {
        opts = {}
      }

      let promise = null
      if (typeof cb !== 'function') [promise, cb] = asyncify()

      const { createOnly } = opts

      const tasks = [
        (job, next) => {
          const id = params.id || uuid()
          params.id = id
          const { name, description, metadata, user } = params

          Joi.validate({ id, name, description, metadata, user }, validationRules.create, (err) => {
            if (err) return next(Boom.badRequest(err))
            next()
          })
        },
        (job, next) => {
          job.params = params
          job.user = params.user
          next()
        },
        insertOrganization
      ]

      if (!createOnly) {
        tasks.push(
          createDefaultPolicies,
          insertOrgAdminUser
        )
      }

      db.withTransaction(tasks, (err, res) => {
        if (err) return cb(err)

        organizationOps.readById(res.organization.id, (err, organization) => {
          if (err) return cb(Boom.badImplementation(err))

          cb(null, { organization, user: res.user })
        })
      })

      return promise
    }