Code source de geonature.core.gn_permissions.schemas

import sqlalchemy as sa
from marshmallow import validate, validates
from marshmallow.exceptions import ValidationError
from marshmallow_sqlalchemy.fields import Nested

from geonature.utils.env import db, ma
from geonature.core.gn_permissions.models import (
    Permission,
    PermAction,
    PermObject,
    PermissionAvailable,
)

from pypnusershub.schemas import UserSchema
from ref_geo.schemas import AreaSchema
from apptax.taxonomie.schemas import TaxrefSchema
from utils_flask_sqla.schema import SmartRelationshipsMixin


[docs] class PermActionSchema(ma.SQLAlchemyAutoSchema):
[docs] class Meta:
[docs] model = PermAction
[docs] include_fk = True
[docs] class PermObjectSchema(ma.SQLAlchemyAutoSchema):
[docs] class Meta:
[docs] model = PermObject
[docs] include_fk = True
[docs] class PermissionSchema(SmartRelationshipsMixin, ma.SQLAlchemyAutoSchema): """ Marchmallow-sqlalchemy behavior is to search object in database, and if not found, to create a new one. As this schema is not means to create any related object, nested fields are dump only (use the FK to set the value). For m2m fields, as it is not possible to load the FK which is in another table, we let the user provide m2m models PK, but we have validation hooks which verify that related models exists and have not been created by marchmallow-sqlalchemy. """
[docs] class Meta:
[docs] model = Permission
[docs] include_fk = True
[docs] load_instance = True
[docs] sqla_session = db.session
[docs] dump_only = ("role", "action", "module", "object")
[docs] role = Nested(UserSchema)
[docs] action = Nested(PermActionSchema)
[docs] module = Nested("ModuleSchema")
[docs] object = Nested(PermObjectSchema)
[docs] scope_value = ma.auto_field(validate=validate.Range(min=0, max=3), strict=True)
[docs] areas_filter = Nested(AreaSchema, many=True)
[docs] taxons_filter = Nested(TaxrefSchema, many=True)
@validates("areas_filter")
[docs] def validate_areas_filter(self, data, **kwargs): errors = {} for i, area in enumerate(data): if not area or not sa.inspect(area).persistent: errors[i] = "Area does not exist" if errors: raise ValidationError(errors, field_name="areas_filter") return data
@validates("taxons_filter")
[docs] def validate_taxons_filter(self, data, **kwargs): errors = {} for i, taxon in enumerate(data): if not taxon or not sa.inspect(taxon).persistent: errors[i] = "Taxon does not exist" if errors: raise ValidationError(errors, field_name="taxons_filter") return data
[docs] class PermissionAvailableSchema(SmartRelationshipsMixin, ma.SQLAlchemyAutoSchema):
[docs] class Meta:
[docs] model = PermissionAvailable
[docs] include_fk = True
[docs] load_instance = True
[docs] sqla_session = db.session
[docs] action = Nested(PermActionSchema)
[docs] module = Nested("ModuleSchema")
[docs] object = Nested(PermObjectSchema)