=============================================================================
 Create or update the CIM record in authorize.net for the given user.
433902
def customer_profile(user)
      resp = Caboose::StdClass.new('success' => true)    
      options = { :profile => { :merchant_customer_id => user.id, :email => user.email }}
      
      if user.authnet_customer_profile_id.nil? || user.authnet_customer_profile_id.strip.length == 0 # No customer profile, so create it 
        response = self.gateway.create_customer_profile(options)
        if response.success?
          user.authnet_customer_profile_id = response.params['customer_profile_id']
          user.save
        elsif response.message.starts_with?("A duplicate record with ID ")
          user.authnet_customer_profile_id = response.message.gsub("A duplicate record with ID ", '').gsub(" already exists.", '')
          user.save
        else
          resp.success = false
          resp.error = "A fatal error occured, the web administrator has been notified. Please try again later."        
        end        	
      else # Update the profile
        options[:profile][:customer_profile_id] = user.authnet_customer_profile_id      
        response = self.gateway.update_customer_profile(options)    
        if !response.success?
          resp.success = false
          resp.error = "A fatal error occured, the web administrator has been notified. Please try again later."        
        end
      end
      return resp 
    end
991197
function authorize(newDoc, oldDoc, userContext, securityInfo, docDefinition) {
    if (utils.isValueNullOrUndefined(userContext)) {
      throw unauthorizedResult();
    }

    var authorizedRoles = resolveRequiredAuthorizations(newDoc, oldDoc, docDefinition.authorizedRoles);
    var authorizedUsers = resolveRequiredAuthorizations(newDoc, oldDoc, docDefinition.authorizedUsers);
    var grantAllMembersWriteAccess = utils.resolveDocumentConstraint(docDefinition.grantAllMembersWriteAccess);

    if (grantAllMembersWriteAccess) {
      // The document definition allows any authenticated DB member to write documents of this type
      return authorizationSuccessResult(authorizedRoles, authorizedUsers);
    } else if (isAdminUser(userContext, securityInfo)) {
      // Database admins have unrestricted access
      return authorizationSuccessResult(authorizedRoles, authorizedUsers);
    } else if (!authorizedRoles && !authorizedUsers) {
      // The document type does not define any authorized roles or users
      throw forbiddenResult();
    }

    var roleMatch = hasAuthorizedRole(authorizedRoles, userContext.roles);
    var usernameMatch = hasAuthorizedUsername(authorizedUsers, userContext.name);
    if (!roleMatch && !usernameMatch) {
      // None of the required authorizations were satisfied
      throw forbiddenResult();
    } else {
      return authorizationSuccessResult(authorizedRoles, authorizedUsers);
    }
  }
1208093
public static function updateInternal($id, $record, $params = [])
    {
        if (empty($record)) {
            throw new BadRequestException('There are no fields in the record to create . ');
        }

        if (empty($id)) {
            //Todo:perform logging below
            //Log::error( 'Update request with no id supplied: ' . print_r( $record, true ) );
            throw new BadRequestException('Identifying field "id" can not be empty for update request . ');
        }

        $userId = SessionUtility::getCurrentUserId();
        $record['user_id'] = $userId;
        // Making sure name is not changed during update as it not be unique.
        $record['name'] = $id;
        $model = static::whereUserId($userId)->whereName($id)->first();

        if (!$model instanceof Model) {
            throw new NotFoundException("Record with identifier '$id' not found.");
        }

        $pk = $model->primaryKey;
        //	Remove the PK from the record since this is an update
        unset($record[$pk]);

        try {
            $model->update($record);

            return static::buildResult($model, $params);
        } catch (\Exception $ex) {
            throw new InternalServerErrorException('Failed to update resource: ' . $ex->getMessage());
        }
    }
790714
def post(method, hmc, uri, uri_parms, body, logon_required,
             wait_for_completion):
        """"""
        assert wait_for_completion is True  # synchronous operation
        user_role_oid = uri_parms[0]
        user_role_uri = '/api/user-roles/' + user_role_oid
        try:
            user_role = hmc.lookup_by_uri(user_role_uri)
        except KeyError:
            raise InvalidResourceError(method, uri)
        check_required_fields(method, uri, body,
                              ['permitted-object', 'permitted-object-type'])
        # Reject if User Role is system-defined:
        if user_role.properties['type'] == 'system-defined':
            raise BadRequestError(
                method, uri, reason=314, message="Cannot add permission to "
                "system-defined user role: {}".format(user_role_uri))
        # Apply defaults, so our internally stored copy has all fields:
        permission = copy.deepcopy(body)
        if 'include-members' not in permission:
            permission['include-members'] = False
        if 'view-only-mode' not in permission:
            permission['view-only-mode'] = True
        # Add the permission to its store (the faked User Role object):
        if user_role.properties.get('permissions', None) is None:
            user_role.properties['permissions'] = []
        user_role.properties['permissions'].append(permission)
176256
public PanelUser create(Panel panel, User user, PanelUserRole role, PanelUserJoinType joinType, PanelStamp stamp, User creator) {
    Date now = new Date();
    
    PanelUser panelUser = new PanelUser();
    panelUser.setPanel(panel);
    panelUser.setUser(user);
    panelUser.setRole(role);
    panelUser.setJoinType(joinType);
    panelUser.setStamp(stamp);
    panelUser.setCreated(now);
    panelUser.setCreator(creator);
    panelUser.setLastModified(now);
    panelUser.setLastModifier(creator);
    panelUser.setArchived(Boolean.FALSE);
    
    return persist(panelUser);
  }
1274263
function update(store: RecordSourceProxy, payload: HandleFieldPayload): void {
  const record = store.get(payload.dataID);
  if (!record) {
    return;
  }

  const {
    EDGES,
    END_CURSOR,
    HAS_NEXT_PAGE,
    HAS_PREV_PAGE,
    PAGE_INFO,
    PAGE_INFO_TYPE,
    START_CURSOR,
  } = RelayConnectionInterface.get();

  const serverConnection = record.getLinkedRecord(payload.fieldKey);
  const serverPageInfo =
    serverConnection && serverConnection.getLinkedRecord(PAGE_INFO);
  if (!serverConnection) {
    record.setValue(null, payload.handleKey);
    return;
  }
  const clientConnection = record.getLinkedRecord(payload.handleKey);
  let clientPageInfo =
    clientConnection && clientConnection.getLinkedRecord(PAGE_INFO);
  if (!clientConnection) {
    // Initial fetch with data: copy fields from the server record
    const connection = store.create(
      generateClientID(record.getDataID(), payload.handleKey),
      serverConnection.getType(),
    );
    connection.setValue(0, NEXT_EDGE_INDEX);
    connection.copyFieldsFrom(serverConnection);
    let serverEdges = serverConnection.getLinkedRecords(EDGES);
    if (serverEdges) {
      serverEdges = serverEdges.map(edge =>
        buildConnectionEdge(store, connection, edge),
      );
      connection.setLinkedRecords(serverEdges, EDGES);
    }
    record.setLinkedRecord(connection, payload.handleKey);

    clientPageInfo = store.create(
      generateClientID(connection.getDataID(), PAGE_INFO),
      PAGE_INFO_TYPE,
    );
    clientPageInfo.setValue(false, HAS_NEXT_PAGE);
    clientPageInfo.setValue(false, HAS_PREV_PAGE);
    clientPageInfo.setValue(null, END_CURSOR);
    clientPageInfo.setValue(null, START_CURSOR);
    if (serverPageInfo) {
      clientPageInfo.copyFieldsFrom(serverPageInfo);
    }
    connection.setLinkedRecord(clientPageInfo, PAGE_INFO);
  } else {
    const connection = clientConnection;
    // Subsequent fetches:
    // - updated fields on the connection
    // - merge prev/next edges, de-duplicating by node id
    // - synthesize page info fields
    let serverEdges = serverConnection.getLinkedRecords(EDGES);
    if (serverEdges) {
      serverEdges = serverEdges.map(edge =>
        buildConnectionEdge(store, connection, edge),
      );
    }
    const prevEdges = connection.getLinkedRecords(EDGES);
    const prevPageInfo = connection.getLinkedRecord(PAGE_INFO);
    connection.copyFieldsFrom(serverConnection);
    // Reset EDGES and PAGE_INFO fields
    if (prevEdges) {
      connection.setLinkedRecords(prevEdges, EDGES);
    }
    if (prevPageInfo) {
      connection.setLinkedRecord(prevPageInfo, PAGE_INFO);
    }

    let nextEdges = [];
    const args = payload.args;
    if (prevEdges && serverEdges) {
      if (args.after != null) {
        // Forward pagination from the end of the connection: append edges
        if (
          clientPageInfo &&
          args.after === clientPageInfo.getValue(END_CURSOR)
        ) {
          const nodeIDs = new Set();
          mergeEdges(prevEdges, nextEdges, nodeIDs);
          mergeEdges(serverEdges, nextEdges, nodeIDs);
        } else {
          warning(
            false,
            'RelayConnectionHandler: Unexpected after cursor `%s`, edges must ' +
              'be fetched from the end of the list (`%s`).',
            args.after,
            clientPageInfo && clientPageInfo.getValue(END_CURSOR),
          );
          return;
        }
      } else if (args.before != null) {
        // Backward pagination from the start of the connection: prepend edges
        if (
          clientPageInfo &&
          args.before === clientPageInfo.getValue(START_CURSOR)
        ) {
          const nodeIDs = new Set();
          mergeEdges(serverEdges, nextEdges, nodeIDs);
          mergeEdges(prevEdges, nextEdges, nodeIDs);
        } else {
          warning(
            false,
            'RelayConnectionHandler: Unexpected before cursor `%s`, edges must ' +
              'be fetched from the beginning of the list (`%s`).',
            args.before,
            clientPageInfo && clientPageInfo.getValue(START_CURSOR),
          );
          return;
        }
      } else {
        // The connection was refetched from the beginning/end: replace edges
        nextEdges = serverEdges;
      }
    } else if (serverEdges) {
      nextEdges = serverEdges;
    } else {
      nextEdges = prevEdges;
    }
    // Update edges only if they were updated, the null check is
    // for Flow (prevEdges could be null).
    if (nextEdges != null && nextEdges !== prevEdges) {
      connection.setLinkedRecords(nextEdges, EDGES);
    }
    // Page info should be updated even if no new edge were returned.
    if (clientPageInfo && serverPageInfo) {
      if (args.after == null && args.before == null) {
        // The connection was refetched from the beginning/end: replace
        // page_info
        clientPageInfo.copyFieldsFrom(serverPageInfo);
      } else if (args.before != null || (args.after == null && args.last)) {
        clientPageInfo.setValue(
          !!serverPageInfo.getValue(HAS_PREV_PAGE),
          HAS_PREV_PAGE,
        );
        const startCursor = serverPageInfo.getValue(START_CURSOR);
        if (typeof startCursor === 'string') {
          clientPageInfo.setValue(startCursor, START_CURSOR);
        }
      } else if (args.after != null || (args.before == null && args.first)) {
        clientPageInfo.setValue(
          !!serverPageInfo.getValue(HAS_NEXT_PAGE),
          HAS_NEXT_PAGE,
        );
        const endCursor = serverPageInfo.getValue(END_CURSOR);
        if (typeof endCursor === 'string') {
          clientPageInfo.setValue(endCursor, END_CURSOR);
        }
      }
    }
  }
}
356801
def _add_iam_policy_binding(service_account, roles):
    """"""
    project_id = service_account["projectId"]
    email = service_account["email"]
    member_id = "serviceAccount:" + email

    policy = crm.projects().getIamPolicy(resource=project_id).execute()

    already_configured = True

    for role in roles:
        role_exists = False
        for binding in policy["bindings"]:
            if binding["role"] == role:
                if member_id not in binding["members"]:
                    binding["members"].append(member_id)
                    already_configured = False
                role_exists = True

        if not role_exists:
            already_configured = False
            policy["bindings"].append({
                "members": [member_id],
                "role": role,
            })

    if already_configured:
        # In some managed environments, an admin needs to grant the
        # roles, so only call setIamPolicy if needed.
        return

    result = crm.projects().setIamPolicy(
        resource=project_id, body={
            "policy": policy,
        }).execute()

    return result
583939
def create_admin(ctx):
    """"""

    try:
        admin = _create_user(ctx)
        admin.roles.append('admin')

        admin.save()
        log("Done")
    except KeyError:
        log('User already exists', lvl=warn)
290639
function(data, options) {
                console.log('iamInterface.user.update', data);
                corbel.validate.value('id', this.id);
                var args = corbel.utils.extend(options || {}, {
                    url: this._buildUriWithDomain(this.uri, this.id),
                    method: corbel.request.method.PUT,
                    data: data
                });
                return this.request(args);
            }
857582
function updateUser (params, cb) {
      let promise = null
      if (typeof cb !== 'function') [promise, cb] = asyncify()

      const { id, organizationId, name, metadata } = params

      Joi.validate({ id, organizationId, name, metadata }, validationRules.updateUser, function (err) {
        if (err) return cb(Boom.badRequest(err))

        const sqlQuery = SQL`
          UPDATE users
          SET name = ${name},
          metadata = ${metadata}
          WHERE id = ${id}
          AND org_id = ${organizationId}
        `
        db.query(sqlQuery, (err, result) => {
          if (utils.isUniqueViolationError(err)) return cb(Boom.conflict(err.detail))
          if (err) return cb(Boom.badImplementation(err))
          if (result.rowCount === 0) return cb(Boom.notFound(`User ${id} not found`))

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

      return promise
    }
1214263
public static void actionCreate(PageContext pc, Resource directory, String serverPassword, boolean createPath, int mode, Object acl, String storage, int nameConflict)
	    throws PageException {

	SecurityManager securityManager = pc.getConfig().getSecurityManager();
	securityManager.checkFileLocation(pc.getConfig(), directory, serverPassword);

	if (directory.exists()) {
	    if (directory.isDirectory()) {
		if (nameConflict == NAMECONFLICT_SKIP) return;

		throw new ApplicationException("directory [" + directory.toString() + "] already exist");
	    }
	    else if (directory.isFile()) throw new ApplicationException("can't create directory [" + directory.toString() + "], it exist a file with same name");
	}
	// if(!directory.mkdirs()) throw new ApplicationException("can't create directory
	// ["+directory.toString()+"]");
	try {
	    directory.createDirectory(createPath);
	}
	catch (IOException ioe) {
	    throw Caster.toPageException(ioe);
	}

	// set S3 stuff
	setS3Attrs(pc, directory, acl, storage);

	// Set Mode
	if (mode != -1) {
	    try {
		directory.setMode(mode);
		// FileUtil.setMode(directory,mode);
	    }
	    catch (IOException e) {
		throw Caster.toPageException(e);
	    }
	}
    }
1140013
def update(gandi, resource, name, algorithm, ssl_enable, ssl_disable):
    """"""
    result = gandi.webacc.update(resource, name, algorithm, ssl_enable,
                                 ssl_disable)
    return result
160612
def _create_record(self, rtype, name, content):
        """"""
        return self._change_record_sets('CREATE', rtype, name, content)
64275
function createUser(name, pass, cb) {
  // Check name
  if(!isValidName(name)) return cb(new Error('Invalid name "'+name+'"'))
  // Check pass
  if(!isValidPass(pass)) return cb(new Error('Invalid pass: "'+pass+'"'))
  // gen salt
  var salt = crypto.randomBytes(16).toString('hex')
  // gen sha1
  var hash = crypto.createHash('sha1')
  hash.update(pass)
  hash.update(salt)
  var password_sha = hash.digest('hex')
  
  var new_doc =
      { _id: user_namespace+':'+name
      , name: name
      , roles: []
      , type: 'user'
      , password_sha: password_sha
      , salt: salt
      }
    ;
  
  nano().use(user_dbname).insert(new_doc, function(err, doc, h) {
    if(err) return cb(err)
    
    // Every user gets its own database
    createDatabase(name, function(err) {
      if(err) return cb(err)
      
      // Sets the _security
      setDatabaseSecurity(name, function(err) {
        if(err) return cb(err)
        cb(null, doc.id, doc.rev)
      })
    })
  })
}
492418
def create(self, name):
        """"""
        with contextlib.closing(self.database.cursor()) as cursor:
            cursor.execute('INSERT INTO users(name) VALUES (?)', (name,))
            return cursor.lastrowid
38643
def _create_record(self, rtype, name, content):
        """"""
        # check if record already exists
        existing_records = self._list_records(rtype, name, content)
        if len(existing_records) >= 1:
            return True

        record = {
            "record_type": rtype,
            "name": self._relative_name(name),
            "content": content,
        }
        if self._get_lexicon_option("ttl"):
            record["ttl"] = self._get_lexicon_option("ttl")
        if self._get_lexicon_option("priority"):
            record["prio"] = self._get_lexicon_option("priority")

        payload = self._post(
            "/v1/domains/{0}/records".format(self.domain),
            {"record": record},
        )

        status = "id" in payload.get("record", {})
        LOGGER.debug("create_record: %s", status)
        return status
1213858
function createUser(ctx, next) {
            client.post({
                path: '/v1/users/'
            }, {
                username: opts.username,
                email: opts.email,
                password: opts.password
            }, function _afterCreateUser(err, req, res, body) {
                if (err && !res) {  // e.g. connect error
                    return next(err);
                }
                ctx.createStatusCode = res.statusCode;
                ctx.createErr = err;
                ctx.createBody = body;
                next();
            });
        }