<s> from aleph . core import db <EOL> from aleph . model . common import SoftDeleteModel , IdModel <EOL> class Permission ( db . Model , IdModel , SoftDeleteModel ) : <EOL> """<STR_LIT>""" <EOL> __tablename__ = '<STR_LIT>' <EOL> COLLECTION = '<STR_LIT>' <EOL> SOURCE = '<STR_LIT:source>' <EOL> RESOURCE_TYPES = [ COLLECTION , SOURCE ] <EOL> id = db . Column ( db . Integer , primary_key = True ) <EOL> role_id = db . Column ( db . Integer , db . ForeignKey ( '<STR_LIT>' ) , index = True ) <EOL> read = db . Column ( db . Boolean , default = False ) <EOL> write = db . Column ( db . Boolean , default = False ) <EOL> resource_id = db . Column ( db . Integer , nullable = False ) <EOL> resource_type = db . Column ( db . Enum ( * RESOURCE_TYPES , name = '<STR_LIT>' ) , <EOL> nullable = False ) <EOL> @ classmethod <EOL> def grant_foreign ( cls , resource , foreign_id , read , write ) : <EOL> from aleph . model import Source , Collection , Role <EOL> role = Role . by_foreign_id ( foreign_id ) <EOL> if role is None : <EOL> return <EOL> if isinstance ( resource , Source ) : <EOL> cls . grant_resource ( cls . SOURCE , resource . id , role , read , write ) <EOL> if isinstance ( resource , Collection ) : <EOL> cls . grant_resource ( cls . COLLECTION , resource . id , role , read , write ) <EOL> @ classmethod <EOL> def grant_resource ( cls , resource_type , resource_id , role , read , write ) : <EOL> q = cls . all ( ) <EOL> q = q . filter ( Permission . role_id == role . id ) <EOL> q = q . filter ( Permission . resource_type == resource_type ) <EOL> q = q . filter ( Permission . resource_id == resource_id ) <EOL> permission = q . first ( ) <EOL> if permission is None : <EOL> permission = Permission ( ) <EOL> permission . role_id = role . id <EOL> permission . resource_type = resource_type <EOL> permission . resource_id = resource_id <EOL> permission . read = read <EOL> permission . write = write <EOL> db . session . add ( permission ) <EOL> return permission <EOL> def to_dict ( self ) : <EOL> return { <EOL> '<STR_LIT>' : self . role_id , <EOL> '<STR_LIT>' : self . read , <EOL> '<STR_LIT>' : self . write , <EOL> '<STR_LIT>' : self . resource_id , <EOL> '<STR_LIT>' : self . resource_type <EOL> } </s>
