Ejemplo n.º 1
0
    def config(self, request):
        if request.method == 'OPTIONS':
            request.app.fire('on_preflight', request, methods=('GET', 'PATCH'))
            return request.response

        user = self.model.get_instance(request).obj
        resource = 'applications:%s:config' % user.application_id.hex
        with self.model.session(request) as session:
            session.add(user)
            if request.method == 'GET':
                Resource(resource, 'read')(request)
                result = user.application.config or {}
            else:
                form_class = get_form_class(request, 'application-config')
                Resource(resource, 'update')(request)
                data, files = request.data_and_files()
                form = form_class(request, data=data, files=files)

                if form.is_valid(exclude_missing=True):
                    application = user.application
                    result = application.config
                    if result is None:
                        result = {}
                        application.config = result
                    session.add(application)
                    for key, value in form.cleaned_data.items():
                        if not value:
                            result.pop(key, None)
                        else:
                            result[key] = value
                    flag_modified(application, 'config')
                else:
                    result = form.tojson()
        return self.json_response(request, result)
Ejemplo n.º 2
0
    def run(self, options):
        auth_backend = self.app.auth_backend
        request = self.app.wsgi_request(urlargs={}, app_handler=True)
        request.cache.auth_backend = auth_backend

        form_class = get_form_class(request, 'create-application')
        if not form_class:
            raise CommandError('Cannot create application')

        model = self.app.models['applications']
        ID = request.config['MASTER_APPLICATION_ID']
        if not ID:
            raise CommandError(
                'MASTER_APPLICATION_ID not available in config.\n'
                'Create a UUID with the create_uuid command'
            )
        try:
            app_domain = model.get_instance(request, id=ID)
        except Http404:
            form = form_class(request, data=dict(
                id=ID,
                name=slugify(request.config['APP_NAME']),
            ), model='applications')
            if form.is_valid():
                app_domain = model.create_model(
                    request,
                    data=form.cleaned_data
                )
            else:
                raise CommandError(form.message())
            self.write('Successfully created admin application')
        data = model.tojson(request, app_domain)
        jwt = model.jwt(request, app_domain)
        self.write(json.dumps(data, indent=4))
        return jwt
Ejemplo n.º 3
0
    def config(self, request):
        if request.method == 'OPTIONS':
            request.app.fire('on_preflight', request, methods=('GET', 'PATCH'))
            return request.response

        user = self.model.get_instance(request).obj
        resource = 'applications:%s:config' % user.application_id.hex
        with self.model.session(request) as session:
            session.add(user)
            if request.method == 'GET':
                Resource(resource, 'read')(request)
                result = user.application.config or {}
            else:
                form_class = get_form_class(request, 'application-config')
                Resource(resource, 'update')(request)
                data, files = request.data_and_files()
                form = form_class(request, data=data, files=files)

                if form.is_valid(exclude_missing=True):
                    application = user.application
                    result = application.config
                    if result is None:
                        result = {}
                        application.config = result
                    session.add(application)
                    for key, value in form.cleaned_data.items():
                        if not value:
                            result.pop(key, None)
                        else:
                            result[key] = value
                    flag_modified(application, 'config')
                else:
                    result = form.tojson()
        return self.json_response(request, result)
Ejemplo n.º 4
0
    def ws_model_create(self, wsrequest):
        """Create a new model

        From the client::

            client.rpc('model_create', {'field1': 'foo', ...})

        :param request:
        :return: object with metadata information
        """
        model = get_model(wsrequest)
        request = wsrequest.wsgi_request
        form_class = get_form_class(request, model.form)
        if not form_class:
            raise rpc.InvalidRequest('cannot create model %s' % model.name)

        fields = wsrequest.check_permission(model.name, 'create',
                                            model.fields())
        # fields = model.column_fields(fields, 'name')
        instance = model.instance(fields=fields)

        form = form_class(request, data=wsrequest.params)
        if form.is_valid():
            with model.session(request) as session:
                instance = model.create_model(request,
                                              instance,
                                              form.cleaned_data,
                                              session=session)
                return model.tojson(request, instance)
        else:
            raise rpc.InvalidParams(data=form.tojson())
Ejemplo n.º 5
0
    def run(self, options):
        auth_backend = self.app.auth_backend
        request = self.app.wsgi_request(urlargs={}, app_handler=True)
        request.cache.auth_backend = auth_backend

        form_class = get_form_class(request, 'create-application')
        if not form_class:
            raise CommandError('Cannot create application')

        model = self.app.models['applications']
        ID = request.config['MASTER_APPLICATION_ID']
        if not ID:
            raise CommandError(
                'MASTER_APPLICATION_ID not available in config.\n'
                'Create a UUID with the create_uuid command')
        try:
            app_domain = model.get_instance(request, id=ID)
        except Http404:
            form = form_class(request,
                              data=dict(
                                  id=ID,
                                  name=slugify(request.config['APP_NAME']),
                              ),
                              model='applications')
            if form.is_valid():
                app_domain = model.create_model(request,
                                                data=form.cleaned_data)
            else:
                raise CommandError(form.message())
            self.write('Successfully created admin application')
        data = model.tojson(request, app_domain)
        jwt = model.jwt(request, app_domain)
        self.write(json.dumps(data, indent=4))
        return jwt
Ejemplo n.º 6
0
    def ws_model_create(self, wsrequest):
        """Create a new model

        From the client::

            client.rpc('model_create', {'field1': 'foo', ...})

        :param request:
        :return: object with metadata information
        """
        model = get_model(wsrequest)
        request = wsrequest.wsgi_request
        form_class = get_form_class(request, model.form)
        if not form_class:
            raise rpc.InvalidRequest('cannot create model %s' % model.name)

        fields = wsrequest.check_permission(
            model.name, 'create', model.fields())
        # fields = model.column_fields(fields, 'name')
        instance = model.instance(fields=fields)

        form = form_class(request, data=wsrequest.params)
        if form.is_valid():
            with model.session(request) as session:
                instance = model.create_model(request,
                                              instance,
                                              form.cleaned_data,
                                              session=session)
                return model.tojson(request, instance)
        else:
            raise rpc.InvalidParams(data=form.tojson())
Ejemplo n.º 7
0
    def method_parameters(self, verb, method, parameters, model):
        form = get_form_class(self.app, getattr(method, 'form', None))
        if not form:
            if verb == 'post':
                form = get_form_class(self.app, model.form)
            elif verb == 'patch':
                form = get_form_class(self.app, model.updateform)

        if form:
            parameters = (parameters or [])[:]
            for name, field in form.base_fields.items():
                parameters.append(
                    obj((("name",
                          name), ("description", field.help_text or field.label
                                  or name), ("type", field_type(field)),
                         ("required", field.required), ("in", "formData"))))
        return parameters
Ejemplo n.º 8
0
def auth_form(request, form):
    form = get_form_class(request, form)
    if not form:
        raise Http404

    request.set_response_content_type(['application/json'])

    return form(request, data=request.body_data())
Ejemplo n.º 9
0
def auth_form(request, form):
    form = get_form_class(request, form)
    if not form:
        raise Http404

    request.set_response_content_type(['application/json'])

    return form(request, data=request.body_data())
Ejemplo n.º 10
0
    def method_parameters(self, verb, method, parameters, model):
        form = get_form_class(self.app, getattr(method, 'form', None))
        if not form:
            if verb == 'post':
                form = get_form_class(self.app, model.form)
            elif verb == 'patch':
                form = get_form_class(self.app, model.updateform)

        if form:
            parameters = (parameters or [])[:]
            for name, field in form.base_fields.items():
                parameters.append(obj((
                    ("name", name),
                    ("description", field.help_text or field.label or name),
                    ("type", field_type(field)),
                    ("required", field.required),
                    ("in", "formData")
                )))
        return parameters
Ejemplo n.º 11
0
def _auth_form(request, form):
    form = get_form_class(request, form)
    if not form:
        raise Http404

    request.set_response_content_type(['application/json'])
    user = request.cache.user
    if user.is_authenticated():
        raise MethodNotAllowed

    return form(request, data=request.body_data())
Ejemplo n.º 12
0
def _auth_form(request, form):
    form = get_form_class(request, form)
    if not form:
        raise Http404

    request.set_response_content_type(['application/json'])
    user = request.cache.user
    if user.is_authenticated():
        raise MethodNotAllowed

    return form(request, data=request.body_data())
Ejemplo n.º 13
0
def get_owned_model(request, identifier):
    app = request.app
    owned = owner_model_targets(app).get(identifier)
    if not owned:
        raise Http404

    form_class = get_form_class(request, owned.form)

    if form_class:
        target = app.models.get(identifier)
        if target:
            return OwnedTarget(target, form_class, owned.filters, owned.cast)

    raise Http404
Ejemplo n.º 14
0
def get_owned_model(request, identifier):
    app = request.app
    owned = owner_model_targets(app).get(identifier)
    if not owned:
        raise Http404

    form_class = get_form_class(request, owned.form)

    if form_class:
        target = app.models.get(identifier)
        if target:
            return OwnedTarget(target, form_class, owned.filters, owned.cast)

    raise Http404
Ejemplo n.º 15
0
 def patch(self, request):
     """Update authenticated user and/or user profile
     """
     user = self.model.get_instance(request)
     model = self.model
     form_class = get_form_class(request, model.updateform)
     if not form_class:
         raise MethodNotAllowed
     form = form_class(request, data=request.body_data())
     if form.is_valid(exclude_missing=True):
         user = model.update_model(request, user, form.cleaned_data)
         data = model.tojson(request, user)
     else:
         data = form.tojson()
     return self.json_response(request, data)
Ejemplo n.º 16
0
 def patch(self, request):
     """Update authenticated user and/or user profile
     """
     user = self.model.get_instance(request)
     model = self.model
     form_class = get_form_class(request, model.updateform)
     if not form_class:
         raise MethodNotAllowed
     form = form_class(request, data=request.body_data())
     if form.is_valid(exclude_missing=True):
         user = model.update_model(request, user, form.cleaned_data)
         data = model.tojson(request, user)
     else:
         data = form.tojson()
     return self.json_response(request, data)
Ejemplo n.º 17
0
    def post(self, request):
        '''Create a new model
        '''
        model = self.get_model(request)
        form_class = get_form_class(request, model.form)
        if not form_class:
            raise MethodNotAllowed

        check_permission = Resource.rest(request,
                                         'create',
                                         model.fields(),
                                         list=True)
        fields = check_permission(request)

        instance = model.instance(fields=fields)
        data, files = request.data_and_files()
        form = form_class(request, data=data, files=files, model=model)
        if form.is_valid():
            with model.session(request) as session:
                try:
                    instance = model.create_model(request,
                                                  instance,
                                                  form.cleaned_data,
                                                  session=session)
                except ValidationError as exc:
                    form.add_error_message(str(exc) or CREATE_MODEL_ERROR_MSG)
                    data = form.tojson()
                except Exception as exc:
                    request.logger.exception(CREATE_MODEL_ERROR_MSG)
                    form.add_error_message(CREATE_MODEL_ERROR_MSG)
                    data = form.tojson()
                else:
                    data = model.tojson(request, instance)
                    request.response.status_code = 201
        else:
            data = form.tojson()

        return self.json_response(request, data)
Ejemplo n.º 18
0
    def post(self, request):
        '''Create a new model
        '''
        model = self.get_model(request)
        form_class = get_form_class(request, model.form)
        if not form_class:
            raise MethodNotAllowed

        check_permission = Resource.rest(request, 'create',
                                         model.fields(), list=True)
        fields = check_permission(request)

        instance = model.instance(fields=fields)
        data, files = request.data_and_files()
        form = form_class(request, data=data, files=files, model=model)
        if form.is_valid():
            with model.session(request) as session:
                try:
                    instance = model.create_model(request,
                                                  instance,
                                                  form.cleaned_data,
                                                  session=session)
                except ValidationError as exc:
                    form.add_error_message(str(exc) or CREATE_MODEL_ERROR_MSG)
                    data = form.tojson()
                except Exception as exc:
                    request.logger.exception(CREATE_MODEL_ERROR_MSG)
                    form.add_error_message(CREATE_MODEL_ERROR_MSG)
                    data = form.tojson()
                else:
                    data = model.tojson(request, instance)
                    request.response.status_code = 201
        else:
            data = form.tojson()

        return self.json_response(request, data)
Ejemplo n.º 19
0
    def read_update_delete(self, request):
        model = self.get_model(request)

        if request.method == 'OPTIONS':
            request.app.fire('on_preflight',
                             request,
                             methods=model.instance_verbs())
            return request.response

        with model.session(request) as session:
            if request.method in GET_HEAD:
                instance = self.get_instance(
                    request,
                    session=session,
                    check_permission=Resource.rest(request, 'read',
                                                   model.fields())
                )
                data = model.tojson(request, instance)

            elif request.method in POST_PUT_PATCH:
                exclude_missing = False
                if request.method == 'PATCH':
                    exclude_missing = True
                    form_class = get_form_class(request, model.updateform)
                elif request.method == 'POST':
                    form_class = get_form_class(request, model.postform)
                else:
                    form_class = get_form_class(request, model.putform)

                if not form_class:
                    raise MethodNotAllowed

                instance = self.get_instance(
                    request,
                    session=session,
                    check_permission=Resource.rest(request, 'update',
                                                   model.fields())
                )
                data, files = request.data_and_files()
                form = form_class(request, data=data, files=files,
                                  previous_state=instance, model=model)

                if form.is_valid(exclude_missing=exclude_missing):
                    try:
                        instance = model.update_model(request,
                                                      instance,
                                                      form.cleaned_data,
                                                      session=session)
                    except Exception:
                        request.logger.exception('Could not update model')
                        form.add_error_message('Could not update model')
                        data = form.tojson()
                    else:
                        if isinstance(instance, dict):
                            data = instance
                        elif instance:
                            data = model.tojson(request, instance)
                        else:
                            request.response.status_code = 204
                            return request.response
                else:
                    data = form.tojson()

            elif request.method == 'DELETE':
                instance = self.get_instance(
                    request,
                    session=session,
                    check_permission=Resource.rest(request, 'delete',
                                                   model.fields())
                )
                model.delete_model(request, instance, session=session)
                request.response.status_code = 204
                return request.response

            else:
                raise MethodNotAllowed

            return self.json_response(request, data)
Ejemplo n.º 20
0
    def read_update_delete(self, request):
        model = self.get_model(request)

        if request.method == 'OPTIONS':
            request.app.fire('on_preflight',
                             request,
                             methods=model.instance_verbs())
            return request.response

        with model.session(request) as session:
            if request.method in GET_HEAD:
                instance = self.get_instance(request,
                                             session=session,
                                             check_permission=Resource.rest(
                                                 request, 'read',
                                                 model.fields()))
                data = model.tojson(request, instance)

            elif request.method in POST_PUT_PATCH:
                exclude_missing = False
                if request.method == 'PATCH':
                    exclude_missing = True
                    form_class = get_form_class(request, model.updateform)
                elif request.method == 'POST':
                    form_class = get_form_class(request, model.postform)
                else:
                    form_class = get_form_class(request, model.putform)

                if not form_class:
                    raise MethodNotAllowed

                instance = self.get_instance(request,
                                             session=session,
                                             check_permission=Resource.rest(
                                                 request, 'update',
                                                 model.fields()))
                data, files = request.data_and_files()
                form = form_class(request,
                                  data=data,
                                  files=files,
                                  previous_state=instance,
                                  model=model)

                if form.is_valid(exclude_missing=exclude_missing):
                    try:
                        instance = model.update_model(request,
                                                      instance,
                                                      form.cleaned_data,
                                                      session=session)
                    except Exception:
                        request.logger.exception('Could not update model')
                        form.add_error_message('Could not update model')
                        data = form.tojson()
                    else:
                        if isinstance(instance, dict):
                            data = instance
                        elif instance:
                            data = model.tojson(request, instance)
                        else:
                            request.response.status_code = 204
                            return request.response
                else:
                    data = form.tojson()

            elif request.method == 'DELETE':
                instance = self.get_instance(request,
                                             session=session,
                                             check_permission=Resource.rest(
                                                 request, 'delete',
                                                 model.fields()))
                model.delete_model(request, instance, session=session)
                request.response.status_code = 204
                return request.response

            else:
                raise MethodNotAllowed

            return self.json_response(request, data)