Generates a basic object with RBAC properties
179363
def base_object(name,
                no_perms=False,
                has_owner=True,
                hide_owner=True,
                has_uuid=True,
                roles_write=None,
                roles_read=None,
                roles_list=None,
                roles_create=None,
                all_roles=None):
    """"""
    base_schema = {
        'id': '#' + name,
        'type': 'object',
        'name': name,
        'properties': {}
    }

    if not no_perms:
        if all_roles:
            roles_create = ['admin', all_roles]
            roles_write = ['admin', all_roles]
            roles_read = ['admin', all_roles]
            roles_list = ['admin', all_roles]
        else:
            if roles_write is None:
                roles_write = ['admin']
            if roles_read is None:
                roles_read = ['admin']
            if roles_list is None:
                roles_list = ['admin']
            if roles_create is None:
                roles_create = ['admin']

        if isinstance(roles_create, str):
            roles_create = [roles_create]
        if isinstance(roles_write, str):
            roles_write = [roles_write]
        if isinstance(roles_read, str):
            roles_read = [roles_read]
        if isinstance(roles_list, str):
            roles_list = [roles_list]

        if has_owner:
            roles_write.append('owner')
            roles_read.append('owner')
            roles_list.append('owner')

        base_schema['roles_create'] = roles_create
        base_schema['properties'].update({
            'perms': {
                'id': '#perms',
                'type': 'object',
                'name': 'perms',
                'properties': {
                    'write': {
                        'type': 'array',
                        'default': roles_write,
                        'items': {
                            'type': 'string',
                        }
                    },
                    'read': {
                        'type': 'array',
                        'default': roles_read,
                        'items': {
                            'type': 'string',
                        }
                    },
                    'list': {
                        'type': 'array',
                        'default': roles_list,
                        'items': {
                            'type': 'string',
                        }
                    }
                },
                'default': {},
                'x-schema-form': {
                    'condition': "false"
                }
            },
            'name': {
                'type': 'string',
                'description': 'Name of ' + name
            }
        })

        if has_owner:
            # TODO: Schema should allow specification of non-local owners as
            #  well as special accounts like admin or even system perhaps
            # base_schema['required'] = base_schema.get('required', [])
            # base_schema['required'].append('owner')
            base_schema['properties'].update({
                'owner': uuid_object(title='Unique Owner ID', display=hide_owner)
            })
    else:
        base_schema['no_perms'] = True

    # TODO: Using this causes all sorts of (obvious) problems with the object
    # manager
    if has_uuid:
        base_schema['properties'].update({
            'uuid': uuid_object(title='Unique ' + name + ' ID', display=False)
        })
        base_schema['required'] = ["uuid"]

    return base_schema
275548
def generate_getter(value):
    """"""
    @property
    @wraps(is_)
    def getter(self):
        return self.is_(value)

    return getter
1192085
function () {
            /*  determine parameters  */
            var params = $cs.params("value", arguments, {
                name:        { pos: 0, req: true,      valid: "string"   },
                value:       { pos: 1, def: undefined, valid: "any"      },
                force:       { pos: 2, def: false,     valid: "boolean"  },
                injected:    {         def: false,     valid: "boolean"  },
                op:          {         def: [],        valid: "(string|[string?]|[string,number,number])" },
                returnowner: {         def: false,     valid: "boolean"  }
            });

            /*  determine operation  */
            if (typeof params.op === "string")
                params.op = [ params.op ];
            if (params.op.length === 0)
                params.op = (_cs.isdefined(params.value) ? [ "set" ] : [ "get" ]);
            else if (!params.op[0].match(/^(?:get|set|splice|delete|push|pop|shift|unshift)$/))
                throw _cs.exception("value", "invalid operation \"" + params.op[0] + "\"");
            if (   params.op[0] === "splice"
                && (   params.op.length !== 3
                    || typeof params.op[1] !== "number"
                    || typeof params.op[2] !== "number"))
                throw _cs.exception("value", "invalid arguments for operation \"splice\"");

            /*  parse the value name into selection path segments  */
            var path = _cs.select_parse(params.name);

            /*  create new canonical name out of the parsed path segments  */
            var pathName = path.join(".");

            /*  determine component owning model with requested value  */
            var owner = null;
            var model = null;
            var comp  = this;
            while (comp !== null) {
                owner = comp.property({ name: "ComponentJS:model", returnowner: true });
                if (!_cs.isdefined(owner))
                    throw _cs.exception("value", "no model found containing value \"" + path[0] + "\"");
                model = owner.property("ComponentJS:model");
                if (_cs.isdefined(model.spec[path[0]]))
                    break;
                comp = owner.parent();
            }
            if (comp === null)
                throw _cs.exception("value", "no model found containing value \"" + path[0] + "\"");

            /*  get new model value  */
            var value_new = params.value;

            /*  translate special-case array operations to splice operation  */
            var obj;
            switch (params.op[0]) {
                case "unshift":
                    params.op = [ "splice", 0, 0 ];
                    break;
                case "shift":
                    params.op = [ "splice", 0, 1 ];
                    value_new = undefined;
                    break;
                case "push":
                    obj = $cs.select(model.data, path);
                    params.op = [ "splice", obj.length, 0 ];
                    break;
                case "pop":
                    obj = $cs.select(model.data, path);
                    params.op = [ "splice", obj.length - 1, 1 ];
                    value_new = undefined;
                    break;
            }

            /*  get old model value  */
            var ev;
            var result;
            var value_old = $cs.select(model.data, path);
            if (params.op[0] === "splice") {
                /*  splice operation is on collection itself,
                    so pick the target collection element!  */
                if (params.op[2] > 0)
                    value_old = $cs.select(value_old, "" + params.op[1]);
                else
                    value_old = undefined;
            }
            else if (params.op[0] === "get") {
                if (owner.property({ name: "ComponentJS:model:subscribers:get", def: 0, bubbling: false }) > 0) {
                    /*  send event to observers for value get and allow observers
                        to reject value get operation and/or change old value to get  */
                    ev = owner.publish({
                        name:      "ComponentJS:model:" + pathName + ":" + params.op[0],
                        args:      [ value_old, value_old, params.op, pathName ],
                        capturing: false,
                        spreading: false,
                        bubbling:  false,
                        async:     false
                    });
                    if (ev.processing()) {
                        /*  allow value to be overridden by event result  */
                        result = ev.result();
                        if (typeof result !== "undefined")
                            value_old = result;
                    }
                }
            }

            /*  optionally set/delete/splice new model value  */
            if (   (   params.op[0] === "set"
                    && (params.force || value_old !== value_new))
                || params.op[0] === "delete"
                || params.op[0] === "splice"                     ) {

                /*  check validity of new value  */
                if (   params.op[0] === "set"
                    || (   params.op[0] === "splice"
                        && value_new !== undefined  )) {
                    var subPath = (
                          params.op[0] === "splice"
                        ? path.slice(1).concat([ "0" ])
                        : path.slice(1)
                    );
                    if (!_cs.validate_at(value_new, model.spec[path[0]].valid, subPath))
                        throw _cs.exception("value", "model field \"" + params.name + "\" receives " +
                            "new value " + _cs.json(value_new) + ", which does not validate " +
                            "against \"" + model.spec[path[0]].valid + "\"" +
                            (subPath.length > 0 ? " at sub-path \"" + subPath.join(".") + "\"" : ""));
                }

                /*  send event to observers for value set/delete/splice operation
                    and allow observers to reject operation and/or change new value to set  */
                var cont = true;
                if (owner.property({ name: "ComponentJS:model:subscribers:" + params.op[0], def: 0, bubbling: false }) > 0) {
                    ev = owner.publish({
                        name:      "ComponentJS:model:" + pathName + ":" + params.op[0],
                        args:      [ value_new, value_old, params.op, pathName ],
                        capturing: false,
                        spreading: false,
                        bubbling:  false,
                        async:     false
                    });
                    if (!ev.processing()) {
                        if (params.injected)
                            throw _cs.exception("value", "model field \"" + params.name + "\" receives (again) " +
                                "value " + _cs.json(value_new) + ", which is rejected by observers, " +
                                "but the value was indicated to be already injected by third-parties " +
                                "(so it technically no longer can be rejected)");
                        cont = false;
                    }
                    else {
                        /*  allow value to be overridden  */
                        result = ev.result();
                        if (typeof result !== "undefined")
                            value_new = result;
                    }
                }
                if (cont && !model.spec[path[0]].autoreset) {
                    /*  perform destructive operation on model  */
                    if (params.op[0] === "set") {
                        /*  set value in model  */
                        $cs.select(model.data, path, value_new);
                    }
                    else if (params.op[0] === "splice") {
                        /*  splice value into model  */
                        obj = $cs.select(model.data, path);
                        if (!(obj instanceof Array))
                            throw new _cs.exception("value", "cannot splice: target object is not of Array type");
                        if (typeof value_new !== "undefined")
                            obj.splice(params.op[1], params.op[2], value_new);
                        else
                            obj.splice(params.op[1], params.op[2]);
                    }
                    else if (params.op[0] === "delete") {
                        /*  delete value from model  */
                        if (path.length < 2)
                            throw new _cs.exception("value", "cannot delete model root or top-level model entry");
                        obj = $cs.select(model.data, path.slice(0, path.length - 1));
                        var pathSegment = path[path.length - 1];
                        if (obj instanceof Array)
                            obj.splice(parseInt(pathSegment, 10), 1);
                        else if (typeof obj === "object")
                            delete obj[pathSegment];
                        else
                            throw new _cs.exception("value", "cannot delete: target object is neither Array nor Object type");
                    }

                    /*  synchronize model with underlying store  */
                    if (model.spec[path[0]].store) {
                        var store = owner.store("model");
                        store[path[0]] = model.data[path[0]];
                        owner.store("model", store);
                    }

                    /*  send event to observers after value finally changed  */
                    if (owner.property({ name: "ComponentJS:model:subscribers:changed", def: 0, bubbling: false }) > 0) {
                        owner.publish({
                            name:      "ComponentJS:model:" + pathName + ":changed",
                            args:      [ value_new, value_old, params.op, pathName ],
                            noresult:  true,
                            capturing: false,
                            spreading: false,
                            bubbling:  false,
                            async:     true
                        });
                    }
                }
            }

            /*  return old model value  */
            return (params.returnowner ? owner : value_old);
        }
816598
def apply_basic_auth(params)
      headers = params.fetch(:headers, {})
      headers = basic_auth_header.merge(headers)
      params.merge(:headers => headers)
    end
65463
function(apiKey, templateId, pieceTitle,
        category, fromAddress, toAddress, ccAddress, bccAddresses, subject,
        textBody, htmlBody, contentType, mergeContext) {}
315035
def create (raw_properties = []):
    
    assert (is_iterable_typed(raw_properties, property.Property)
            or is_iterable_typed(raw_properties, basestring))
    # FIXME: propagate to callers.
    if len(raw_properties) > 0 and isinstance(raw_properties[0], property.Property):
        x = raw_properties
    else:
        x = [property.create_from_string(ps) for ps in raw_properties]

    # These two lines of code are optimized to the current state
    # of the Property class. Since this function acts as the caching
    # frontend to the PropertySet class modifying these two lines
    # could have a severe performance penalty. Be careful.
    # It would be faster to sort by p.id, but some projects may rely
    # on the fact that the properties are ordered alphabetically. So,
    # we maintain alphabetical sorting so as to maintain backward compatibility.
    x = sorted(set(x), key=lambda p: (p.feature.name, p.value, p.condition))
    key = tuple(p.id for p in x)

    if key not in __cache:
        __cache [key] = PropertySet(x)

    return __cache [key]
579915
def from_dict(cls, data):
        
        auth_info = AuthenticationInformation.from_dict(
            data.get("auth_info", {})
        )
        instance = cls(
            auth_info=auth_info,
            requester=data.get("requester"),
            requester_name=data.get("requester_name"),
            subject_id=data.get("subject_id"),
            subject_type=data.get("subject_type"),
            attributes=data.get("attributes"),
            user_id=data.get("user_id"),
            user_id_hash_type=data.get("hash_type"),
            name_id=data.get("name_id"),
            approved_attributes=data.get("approved_attributes"),
        )
        return instance
459376
def generate(self):
        """"""
        payload = {
            'algorithm': 'HMAC-SHA256'
        }

        if self.data:
            payload['app_data'] = self.data

        if self.page:
            payload['page'] = {}

            if self.page.id:
                payload['page']['id'] = self.page.id

            if self.page.is_liked:
                payload['page']['liked'] = self.page.is_liked

            if self.page.is_admin:
                payload['page']['admin'] = self.page.is_admin

        if self.user:
            payload['user'] = {}

            if self.user.country:
                payload['user']['country'] = self.user.country

            if self.user.locale:
                payload['user']['locale'] = self.user.locale

            if self.user.age:
                payload['user']['age'] = {
                    'min': self.user.age[0],
                    'max': self.user.age[-1]
                }

            if self.user.oauth_token:

                if self.user.oauth_token.token:
                    payload['oauth_token'] = self.user.oauth_token.token

                if self.user.oauth_token.expires_at is None:
                    payload['expires_in'] = 0
                else:
                    payload['expires_in'] = int(time.mktime(self.user.oauth_token.expires_at.timetuple()))

                if self.user.oauth_token.issued_at:
                    payload['issued_at'] = int(time.mktime(self.user.oauth_token.issued_at.timetuple()))

        if self.user.id:
            payload['user_id'] = self.user.id

        encoded_payload = base64.urlsafe_b64encode(
            json.dumps(payload, separators=(',', ':')).encode('utf-8')
        )

        encoded_signature = base64.urlsafe_b64encode(hmac.new(
            self.application_secret_key.encode('utf-8'),
            encoded_payload,
            hashlib.sha256
        ).digest())

        return '%(signature)s.%(payload)s' % {
            'signature': encoded_signature,
            'payload': encoded_payload
        }
410880
def to_native(self, obj):
        """"""
        ret = super(UserSerializer, self).to_native(obj)
        del ret['password']
        return ret
25832
def generate(cls):
        
        return cls(libnacl.randombytes(PrivateKey.SIZE), encoder=encoding.RawEncoder)
108297
def create(cls, object_version, key, value):
        """"""
        assert len(key) < 256
        assert len(value) < 256
        with db.session.begin_nested():
            obj = cls(version_id=as_object_version_id(object_version),
                      key=key,
                      value=value)
            db.session.add(obj)
        return obj
523229
def auth_basic(check, realm="private", text="Access denied"):
    '''  '''
    def decorator(func):
      def wrapper(*a, **ka):
        user, password = request.auth or (None, None)
        if user is None or not check(user, password):
          response.headers['WWW-Authenticate'] = 'Basic realm="%s"' % realm
          return HTTPError(401, text)
        return func(*a, **ka)
      return wrapper
    return decorator
705818
function instantiate(schema, options) {
  options = options || {};

  /**
   * Visits each sub-object using recursion.
   * If it reaches a primitive, instantiate it.
   * @param obj - The object that represents the schema.
   * @param name - The name of the current object.
   * @param data - The instance data that represents the current object.
   */
  function visit(obj, name, data) {
    if (!obj) {
      return;
    }

    var i;
    var type = getObjectType(obj);

    // We want non-primitives objects (primitive === object w/o properties).
    if (type === 'object' && obj.properties) {
      data[name] = data[name] || { };

      // Visit each property.
      for (var property in obj.properties) {
        if (obj.properties.hasOwnProperty(property)) {
          if (shouldVisit(property, obj, options)) {
            visit(obj.properties[property], property, data[name]);
          }
        }
      }
    } else if (obj.allOf) {
      for (i = 0; i < obj.allOf.length; i++) {
        visit(obj.allOf[i], name, data);
      }
    } else if (obj.$ref) {
      obj = findDefinition(schema, obj.$ref);
      visit(obj, name, data);
    } else if (type === 'array') {
      data[name] = [];
      var len = 0;
      if (obj.minItems || obj.minItems > 0) {
        len = obj.minItems;
      }

      // Instantiate 'len' items.
      for (i = 0; i < len; i++) {
        visit(obj.items, i, data[name]);
      }
    } else if (isEnum(obj)) {
      data[name] = instantiateEnum(obj);
    } else if (isPrimitive(obj)) {
      data[name] = instantiatePrimitive(obj);
    }
  }

  var data = {};
  visit(schema, 'kek', data);
  return data['kek'];
}
831377
def _basic_field_data(field, obj):
    """"""
    value = field.value_from_object(obj)
    return {Field.TYPE: FieldType.VAL, Field.VALUE: value}
1001568
def create_authentication_from_json(values):
        """"""
        key_id = values.get('publicKey')
        authentication_type = values.get('type')
        if not key_id:
            raise ValueError(
                f'Invalid authentication definition, "publicKey" is missing: {values}')

        authentication = {'type': authentication_type, 'publicKey': key_id}

        return authentication
177543
def _generate_union_properties(self, fields):
        """"""
        for field in fields:
            # void types do not need properties to store additional state
            # information
            if not is_void_type(field.data_type):
                doc = self.process_doc(
                    field.doc, self._docf) if field.doc else undocumented
                warning_str = (
                    ' @note Ensure the `is{}` method returns true before accessing, '
                    'otherwise a runtime exception will be raised.')
                doc += warning_str.format(fmt_camel_upper(field.name))
                self.emit_wrapped_text(
                    self.process_doc(doc, self._docf), prefix=comment_prefix)
                self.emit(fmt_property(field=field))
                self.emit()
995451
def generate_id(self, obj):
        """"""
        object_type = type(obj).__name__.lower()
        return '{}_{}'.format(object_type, self.get_object_id(obj))