Source

ziggurat_foundations / ziggurat_foundations / models.py

Full commit
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
import sqlalchemy as sa
import hashlib
import urllib
import random
import string
import webhelpers

from cryptacular.bcrypt import BCRYPTPasswordManager
from cryptacular.core import DelegatingPasswordManager
from ziggurat_foundations.utils import PlaceholderPasswordChecker
from sqlalchemy.ext.declarative import declared_attr
from pyramid.security import Allow, ALL_PERMISSIONS


DBSession = None


def get_db_session(session=None, obj=None):
    """ attempts to return sqlalchemy session that could have been
        created/passed in one of few ways"""
    # try to read the session from instance
    if obj:
        return sa.orm.session.object_session(obj)
    #try passed session
    elif session:
        return session
    #try global pylons-like session then
    elif DBSession:
        return DBSession
    raise Exception('No Session found')

class BaseModel(object):
    """ base class for  all other models to inherit """
    
    @classmethod
    def _get_keys(cls):
        """ return column names for this model """ 
        return sa.orm.class_mapper(cls).c.keys()
    
    def get_dict(self):
        """ return dict with keys and values corresponding to this model data """
        d = {}
        for k in self._get_keys():
            d[k] = getattr(self, k)
        return d
    
    def get_appstruct(self):
        """ return dict with keys and values corresponding to this model data """
        l = []
        for k in self._get_keys():
            l.append((k, getattr(self, k),))
        return l
    
    def populate_obj(self, appstruct):
        """ populate model with data from dict """
        for k in self._get_keys():
            if k in appstruct:
                setattr(self, k, appstruct[k])
                
                
    def get_db_session(self, session=None):
        return get_db_session(session, self)
            
                
class UserMapperExtension(sa.orm.interfaces.MapperExtension):
    
    def after_update(self, mapper, connection, instance):
        instance.by_user_name(instance.user_name, invalidate=True,
                        db_session=get_db_session(None, instance))
        
    def after_delete(self, mapper, connection, instance):
        instance.by_user_name(instance.user_name, invalidate=True,
                        db_session=get_db_session(None, instance))
                
class UserMixin(BaseModel):
    """base mixin for user object"""
    
    __mapper_args__ = {'extension': UserMapperExtension()}
    __table_args__ = {
                      'mysql_engine':'InnoDB',
                      'mysql_charset':'utf8'
                      }
    
    @declared_attr
    def __tablename__(cls):
        return 'users'
    
    @declared_attr
    def id(cls):
        return sa.Column(sa.Integer, primary_key=True)
    
    @declared_attr
    def user_name(cls):
        return sa.Column(sa.Unicode(30), unique=True)
    
    @declared_attr
    def user_password(cls):
        return sa.Column(sa.String(40))
    
    @declared_attr
    def email(cls):
        return sa.Column(sa.Unicode(100), nullable=False, unique=True)
    
    @declared_attr
    def status(cls):
        return sa.Column(sa.SmallInteger(), nullable=False)
    
    @declared_attr
    def security_code(cls):
        return sa.Column(sa.String(40), default='default')
    
    @declared_attr
    def last_login_date(cls):
        return sa.Column(sa.TIMESTAMP(timezone=True),
                                default=sa.sql.func.now(),
                                server_default=sa.func.now()
                                )
    
    passwordmanager = DelegatingPasswordManager(
            preferred=BCRYPTPasswordManager(),
            fallbacks=(PlaceholderPasswordChecker(),)
            )
    
    def __repr__(self):
        return '<User: %s>' % self.user_name
    
    @declared_attr
    def groups_dynamic(cls):
        """ returns dynamic relationship for groups - filter can be used """
        return sa.orm.relationship('Group', secondary='users_groups',
                        lazy='dynamic',
                        passive_deletes=True,
                        passive_updates=True
                        )
    
    @declared_attr
    def user_permissions(cls):
        """ returns all direct non-resource permissions for this user"""
        return sa.orm.relationship('UserPermission',
                        cascade="all, delete-orphan",
                        passive_deletes=True,
                        passive_updates=True
                        )

    @declared_attr
    def resource_permissions(cls):
        """returns all direct resource permissions for this user"""
        return sa.orm.relationship('UserResourcePermission',
                        cascade="all, delete-orphan",
                        passive_deletes=True,
                        passive_updates=True
                        )
    
    @declared_attr
    def resources(cls):
        return sa.orm.relationship('Resource',
                        cascade="all",
                        passive_deletes=True,
                        passive_updates=True,
                        backref='owner'
                        )
    
    @property
    def permissions(self):
        """ returns all non-resource permissions based on what groups user
            belongs and directly set ones for this user"""
        db_session = get_db_session(None, self)
        q = db_session.query((u'group:' + self.GroupPermission.group_name).label('owner_name'),
                             self.GroupPermission.perm_name.label('perm_name'))
        q = q.filter(self.GroupPermission.group_name == self.UserGroup.group_name)
        q = q.filter(self.User.user_name == self.UserGroup.user_name)
        q = q.filter(self.User.user_name == self.user_name)
        
        q2 = db_session.query(self.UserPermission.user_name.label('owner_name'),
                              self.UserPermission.perm_name.label('perm_name'))
        q2 = q2.filter(self.UserPermission.user_name == self.user_name)
        q = q.union(q2)
        return [(row.owner_name, row.perm_name) for row in q]
        
        
    
    def resources_with_perms(self, perms, resource_ids=None, cache='default',
                             invalidate=False, db_session=None):
        """ returns all resources that user has perms for,
            note that at least one perm needs to be met,
            resource_ids restricts the search tospecific resources"""
        # owned entities have ALL permissions so we return those resources too
        # even without explict perms set
        # TODO: implement admin superrule perm - maybe return all apps
        db_session = get_db_session(db_session, self)
        q = db_session.query(self.Resource).distinct()
        group_names = [gr.group_name for gr in self.groups]
        #if user has some groups lets try to join based on their permissions
        if group_names:
            join_conditions = (
                self.GroupResourcePermission.group_name.in_(group_names),
                self.Resource.resource_id == self.GroupResourcePermission.resource_id,
                self.GroupResourcePermission.perm_name.in_(perms),
                          )
            q = q.outerjoin(
                            (self.GroupResourcePermission,
                             sa.and_(*join_conditions),)
                            )
            #ensure outerjoin permissions are correct - dont add empty rows from join
            #conditions are - join ON possible group permissions OR owning group/user
            q = q.filter(sa.or_(
                                self.Resource.owner_user_name == self.user_name,
                                self.Resource.owner_group_name.in_(group_names),
                                self.GroupResourcePermission.perm_name != None                                
                                ,))
        else:
            #filter just by username
            q = q.filter(self.Resource.owner_user_name == self.user_name)
        # lets try by custom user permissions for resource
        q2 = db_session.query(self.Resource).distinct()
        q2 = q2.filter(self.UserResourcePermission.user_name == self.user_name)
        q2 = q2.filter(self.Resource.resource_id == self.UserResourcePermission.resource_id)
        q2 = q2.filter(self.UserResourcePermission.perm_name.in_(perms))
        q = q.union(q2)
        if resource_ids:
            q = q.filter(self.Resource.resource_id.in_(resource_ids))
        q = q.order_by(self.Resource.resource_name)
        if invalidate:
            return True
        return q
    
    def gravatar_url(self, default='mm'):
        """ returns user gravatar url """
        # construct the url
        hash = hashlib.md5(self.email.encode('utf8').lower()).hexdigest()
        gravatar_url = "https://secure.gravatar.com/avatar/%s?%s" % (
                                                hash,
                                                urllib.urlencode({'d':default})
                                                                      )
        return gravatar_url
    
    
    def set_password(self, raw_password):
        """ sets new password """
        self.user_password = self.passwordmanager.encode(raw_password)
        self.regenerate_security_code()

    def check_password(self, raw_password):
        """ checks string with users password hash"""
        return self.passwordmanager.check(self.user_password, raw_password,
                                          setter=self.set_password)



    @classmethod
    def generate_random_pass(cls, chars=7):
        """ generates random string of fixed length"""
        return cls.generate_random_string(chars)

    def regenerate_security_code(self):
        """ generates new security code"""
        self.security_code = self.generate_random_string(32)
        

    @staticmethod
    def generate_random_string(chars=7):
        return u''.join(random.sample(string.ascii_letters + string.digits, chars))

    
    @classmethod
    def by_user_name(cls, user_name, cache='default',
                    invalidate=False, db_session=None):
        """ fetch user by user name """
        db_session = get_db_session(db_session)
        q = db_session.query(cls)
        q = q.filter(sa.func.lower(cls.user_name) == user_name.lower())
        q = q.options(sa.orm.eagerload('groups'))
        if invalidate:
            return True
        return q.first()
    
    @classmethod
    def by_user_name_and_security_code(cls, user_name, security_code,
                                       db_session=None):
        """ fetch user objects by user name and security code"""
        db_session = get_db_session(db_session)
        q = db_session.query(cls)
        q = q.filter(sa.func.lower(cls.user_name) == user_name.lower())
        q = q.filter(cls.security_code == security_code)
        return q.first()
    
    
    @classmethod
    def by_user_names(cls, user_names, cache='default',
                    invalidate=False, db_session=None):
        """ fetch user objects by user names """
        user_names = [name.lower() for name in user_names]
        db_session = get_db_session(db_session)
        q = db_session.query(cls)
        q = q.filter(sa.func.lower(cls.user_name).in_(user_names))
        #q = q.options(sa.orm.eagerload(cls.groups))
        if invalidate:
            return True
        return q
    
    @classmethod
    def user_names_like(cls, user_name, cache='default',
                    invalidate=False, db_session=None):
        """
        fetch users with similar names
        
        For now rely on LIKE in db - shouldnt be issue ever
        in future we can plug in fulltext search like solr or whoosh
        """
        db_session = get_db_session(db_session)
        q = db_session.query(cls)
        q = q.filter(sa.func.lower(cls.user_name).like(user_name.lower()))
        q = q.order_by(cls.user_name)
        #q = q.options(sa.orm.eagerload('groups'))
        if invalidate:
            return True
        return q

    @classmethod
    def by_email(cls, email, cache='default',
                    invalidate=False, db_session=None):
        """ fetch user objects by email """
        db_session = get_db_session(db_session)
        q = db_session.query(cls).filter(cls.email == email)
        q = q.options(sa.orm.eagerload('groups'))
        if invalidate:
            return True
        return q.first()
    
    @classmethod
    def by_email_and_username(cls, email, user_name, cache='default',
                    invalidate=False, db_session=None):
        """ fetch user objects by email and username """
        db_session = get_db_session(db_session)
        q = db_session.query(cls).filter(cls.email == email)
        q = q.filter(sa.func.lower(cls.user_name) == user_name.lower())
        q = q.options(sa.orm.eagerload('groups'))
        if invalidate:
            return True
        return q.first()

class GroupMixin(BaseModel):
    """ base mixin for group object"""
    
    __table_args__ = {
                      'mysql_engine':'InnoDB',
                      'mysql_charset':'utf8'
                      }
    
    @declared_attr
    def __tablename__(cls):
        return 'groups'
    
    # lists app wide permissions we might want to assign to groups
    __possible_permissions__ = ('root_administration',
                                'administration',
                                'backend_admin_panel',
                                'manage_apps',)
    
    @declared_attr
    def id(cls):
        return sa.Column(sa.Integer, primary_key=True)
    
    @declared_attr
    def group_name(cls):
        return sa.Column(sa.Unicode(50), unique=True)
    
    @declared_attr
    def description(cls):
        return sa.Column(sa.Text())
    
    @declared_attr
    def member_count(cls):
        return sa.Column(sa.Integer, nullable=False, default=0)
    
    @declared_attr
    def users(cls):
        """ relationship for users belonging to this group"""
        return sa.orm.relationship('User',
                        secondary='users_groups',
                        order_by='User.user_name',
                        passive_deletes=True,
                        passive_updates=True,
                        backref='groups'
                        )
    
    # dynamic property - useful
    @declared_attr
    def users_dynamic(cls):
        """ dynamiec relationship for users belonging to this group
            one can use filter """
        return sa.orm.relationship('User',
                        secondary='users_groups',
                        order_by='User.user_name',
                        lazy="dynamic"
                        )
    
    @declared_attr
    def permissions(cls):
        """ non-resource permissions assigned to this group"""
        return sa.orm.relationship('GroupPermission',
                        backref='groups',
                        cascade="all, delete-orphan",
                        passive_deletes=True,
                        passive_updates=True
                        )

    @declared_attr
    def resource_permissions(cls):
        """ permissions to specific resources this group has"""
        return sa.orm.relationship('GroupResourcePermission',
                        backref='groups',
                        cascade="all, delete-orphan",
                        passive_deletes=True,
                        passive_updates=True
                        )
    
    def __repr__(self):
        return '<Group: %s>' % self.group_name
    
    @classmethod
    def all(cls, db_session=None):
        """ return all groups"""
        q = get_db_session(db_session).query(cls)
        return q
    
    @classmethod
    def by_group_name(cls, group_name, db_session=None):
        """ fetch group by name"""
        db_session = get_db_session(db_session)
        q = db_session.query(cls).filter(cls.group_name == group_name)
        return q.first()

    @sa.orm.validates('permissions')
    def validate_permission(self, key, permission):
        """ validates if group can get assigned with permission"""
        assert permission.perm_name in self.__possible_permissions__
        return permission


    def get_user_paginator(self, page=1, item_count=None, items_per_page=50,
                           user_names=None, GET_params={}):
        """ returns paginator over users belonging to the group"""
        GET_params.pop('page', None)
        q = self.users_dynamic
        if user_names:
            q = q.filter(self.UserGroup.user_name.in_(user_names))
        return webhelpers.paginate.Page(q, page=page,
                                     item_count=item_count,
                                     items_per_page=items_per_page,
                                     **GET_params
                                     )
        
    
    
class GroupPermissionMixin(BaseModel):
    """ group permission mixin """
    
    __table_args__ = {
                      'mysql_engine':'InnoDB',
                      'mysql_charset':'utf8'
                      }
    
    @declared_attr
    def __tablename__(cls):
        return 'groups_permissions'
    
    @declared_attr
    def group_name(cls):
        return sa.Column(sa.Unicode(50),
                        sa.ForeignKey('groups.group_name', onupdate='CASCADE',
                                      ondelete='CASCADE'), primary_key=True)
    
    @declared_attr
    def perm_name(cls):
        return sa.Column(sa.Unicode(30), primary_key=True)
    
    def __repr__(self):
        return '<GroupPermission: %s>' % self.perm_name
    
    @classmethod
    def by_group_and_perm(cls, group_name, perm_name, db_session=None):
        """" return all instances by group and permission names """
        db_session = get_db_session(db_session)
        q = db_session.query(cls).filter(cls.group_name == group_name)
        q = q.filter(cls.perm_name == perm_name)
        return q.first()
        
class UserPermissionMixin(BaseModel):
    
    __table_args__ = {
                      'mysql_engine':'InnoDB',
                      'mysql_charset':'utf8'
                      }
    
    @declared_attr
    def __tablename__(cls):
        return 'users_permissions'
    
    @declared_attr
    def user_name(cls):
        return sa.Column(sa.Unicode(50),
                         sa.ForeignKey('users.user_name', onupdate='CASCADE',
                                       ondelete='CASCADE'), primary_key=True)
    @declared_attr
    def perm_name(cls):
        return sa.Column(sa.Unicode(30), primary_key=True)
    
    def __repr__(self):
        return '<UserPermission: %s>' % self.perm_name
    
    @classmethod
    def by_user_and_perm(cls, user_name, perm_name, db_session=None):
        """ return all instances by user and permission name"""
        db_session = get_db_session(db_session)
        q = db_session.query(cls).filter(cls.user_name == user_name)
        q = q.filter(cls.perm_name == perm_name)
        return q.first()

class UserGroupMixin(BaseModel):
    
    __table_args__ = {
                      'mysql_engine':'InnoDB',
                      'mysql_charset':'utf8'
                      }
    
    @declared_attr
    def __tablename__(cls):
        return 'users_groups'
    
    @declared_attr
    def group_name(cls):
        return sa.Column(sa.Unicode(50),
                         sa.ForeignKey('groups.group_name', onupdate='CASCADE',
                                       ondelete='CASCADE'), primary_key=True)

    @declared_attr
    def user_name(cls):
        return sa.Column(sa.Unicode(30),
                        sa.ForeignKey('users.user_name', onupdate='CASCADE',
                                      ondelete='CASCADE'), primary_key=True)

    def __repr__(self):
        return '<UserGroup: %s, %s>' % (self.group_name, self.user_name,)

class GroupResourcePermissionMixin(BaseModel):
    
    __table_args__ = {
                      'mysql_engine':'InnoDB',
                      'mysql_charset':'utf8'
                      }
    
    @declared_attr
    def __tablename__(cls):
        return 'groups_resources_permissions'
    
    @declared_attr
    def group_name(cls):
        return sa.Column(sa.Unicode(50), sa.ForeignKey('groups.group_name',
                                                     onupdate='CASCADE',
                                                     ondelete='CASCADE'),
                                                     primary_key=True)
        
    @declared_attr
    def resource_id(cls):
        return sa.Column(sa.BigInteger(), sa.ForeignKey('resources.resource_id',
                                                     onupdate='CASCADE',
                                                     ondelete='CASCADE'),
                                                     primary_key=True,
                                                     autoincrement=False)
    @declared_attr
    def perm_name(cls):
        return sa.Column(sa.Unicode(50), primary_key=True)

    def __repr__(self):
        return '<GroupResourcePermission: %s, %s, %s>' % (self.group_name,
                                                      self.perm_name,
                                                      self.resource_id,)

class UserResourcePermissionMixin(BaseModel):
    
    __table_args__ = {
                      'mysql_engine':'InnoDB',
                      'mysql_charset':'utf8'
                      }
    
    @declared_attr
    def __tablename__(cls):
        return 'users_resources_permissions'
    
    @declared_attr
    def user_name(cls):
        return sa.Column(sa.Unicode(50), sa.ForeignKey('users.user_name',
                                                     onupdate='CASCADE',
                                                     ondelete='CASCADE'),
                                                     primary_key=True)
    @declared_attr
    def resource_id(cls):
        return sa.Column(sa.BigInteger(), sa.ForeignKey('resources.resource_id',
                                                     onupdate='CASCADE',
                                                     ondelete='CASCADE'),
                                                     primary_key=True,
                                                     autoincrement=False)
    @declared_attr
    def perm_name(cls):
        return sa.Column(sa.Unicode(50), primary_key=True)

    def __repr__(self):
        return '<userResourcePermission: %s, %s, %s>' % (self.user_name,
                                                      self.perm_name,
                                                      self.resource_id,)
            
    @classmethod
    def by_resource_user_and_perm(cls, user_name, perm_name, resource_id,
                                  db_session=None):
        """ return all instances by user name, perm name and resource id """
        db_session = get_db_session(db_session)
        q = db_session.query(cls).filter(cls.user_name == user_name)
        q = q.filter(cls.resource_id == resource_id)
        q = q.filter(cls.perm_name == perm_name)
        return q.first()
    
#    @classmethod
#    def allowed_permissions(cls, key):
#        """ ensures we can only use permission that can be assigned 
#            to this resource type"""
#        if key in cls.__possible_permissions__:
#            return key
#        raise KeyError

class ResourceMapperExtension(sa.orm.interfaces.MapperExtension):
    
    def after_update(self, mapper, connection, instance):
        instance.by_resource_id(instance.resource_id, invalidate=True,
                                db_session=get_db_session(None, instance))
        
    def after_delete(self, mapper, connection, instance):
        instance.by_resource_id(instance.resource_id, invalidate=True,
                                db_session=get_db_session(None, instance))

class ResourceMixin(BaseModel):    
    
    __possible_permissions__ = ()
    
    @declared_attr
    def __tablename__(cls):
        return 'resources'
    
    @declared_attr
    def resource_id(cls):
        return sa.Column(sa.BigInteger(), primary_key=True, nullable=False)
    
    @declared_attr
    def resource_name(cls):
        return sa.Column(sa.Unicode(100), nullable=False)
    
    @declared_attr
    def resource_type(cls):
        return sa.Column(sa.Unicode(30), nullable=False)
    
    @declared_attr
    def owner_group_name(cls):
        return sa.Column(sa.Unicode(50),
                       sa.ForeignKey('groups.group_name', onupdate='CASCADE',
                                     ondelete='SET NULL'))
    
    @declared_attr
    def owner_user_name(cls):
        return sa.Column(sa.Unicode(30),
                       sa.ForeignKey('users.user_name', onupdate='CASCADE',
                                     ondelete='SET NULL'))
    
    @declared_attr
    def group_permissions(cls):
        """ returns all group permissions for this resource"""
        return sa.orm.relationship('GroupResourcePermission',
                                  cascade="all, delete-orphan",
                                  passive_deletes=True,
                                  passive_updates=True
                                  )

    @declared_attr
    def user_permissions(cls):
        """ returns all user permissions for this resource"""
        return sa.orm.relationship('UserResourcePermission',
                                  cascade="all, delete-orphan",
                                  passive_deletes=True,
                                  passive_updates=True
                                  )
    
    @declared_attr
    def groups(cls):
        """ returns all groups that have permissions for this resource"""
        return sa.orm.relationship('Group',
                                 secondary='groups_resources_permissions',
                                 passive_deletes=True,
                                 passive_updates=True
                                  )
    
    @declared_attr
    def users(cls):
        """ returns all users that have permissions for this resource"""
        return sa.orm.relationship('User',
                                 secondary='users_resources_permissions',
                                 passive_deletes=True,
                                 passive_updates=True
                                  )
    
    __mapper_args__ = {'polymorphic_on': resource_type,
                       'extension': ResourceMapperExtension()
                       }
    __table_args__ = {
                      'mysql_engine':'InnoDB',
                      'mysql_charset':'utf8'
                      }
    
    def __repr__(self):
        return '<Resource: %s, %s, id: %s>' % (self.resource_type,
                                               self.resource_name,
                                               self.resource_id,
                                               )
        
    @property
    def __acl__(self):
        acls = [(Allow, 'group:Administrators', ALL_PERMISSIONS,), ]
        
        if self.owner_user_name:
            acls.extend([(Allow, self.owner_user_name, ALL_PERMISSIONS,), ])
            
        if self.owner_group_name:
            acls.extend([(Allow, "group:%s" % self.owner_group_name, ALL_PERMISSIONS,), ])
        return acls
    
    def perms_for_user(self, user, cache='default',
                       invalidate=False, db_session=None):
        """ returns all permissions that given user has for this resource
            from groups and directly set ones too"""
        db_session = get_db_session(db_session, self)
        q = db_session.query(u'group:' + self.GroupResourcePermission.group_name,
                             self.GroupResourcePermission.perm_name)
        q = q.filter(self.GroupResourcePermission.group_name.in_(
                                        [gr.group_name for gr in user.groups]
                                        )
                     )
        q = q.filter(self.GroupResourcePermission.resource_id == self.resource_id)
        
        q2 = db_session.query(self.UserResourcePermission.user_name,
                              self.UserResourcePermission.perm_name)
        q2 = q2.filter(self.UserResourcePermission.user_name == user.user_name)
        q2 = q2.filter(self.UserResourcePermission.resource_id == self.resource_id)
        q = q.union(q2)
        if invalidate:
            return True
        perms = [(row[0], row.perm_name,) for row in q]
        #include all perms if user is the owner of this resource
        if self.owner_user_name == user.user_name:
            perms.append((self.owner_user_name, ALL_PERMISSIONS,))
        return perms
    
    
    def direct_perms_for_user(self, user, cache='default',
                       invalidate=False, db_session=None):
        """ returns permissions that given user has for this resource
            without ones inherited from groups that user belongs to"""
        db_session = get_db_session(db_session, self)
        q = db_session.query(self.UserResourcePermission.user_name,
                             self.UserResourcePermission.perm_name)
        q = q.filter(self.UserResourcePermission.user_name == user.user_name)
        q = q.filter(self.UserResourcePermission.resource_id == self.resource_id)
        if invalidate:
            return True
        perms = [(row[0], row.perm_name,) for row in q]
        #include all perms if user is the owner of this resource
        if self.owner_user_name == user.user_name:
            perms.append((self.owner_user_name, ALL_PERMISSIONS,))
        return perms

    def group_perms_for_user(self, user, cache='default',
                       invalidate=False, db_session=None):
        """ returns permissions that given user has for this resource
            that are inherited from groups """        
        db_session = get_db_session(db_session, self)
        q = db_session.query(u'group:' + self.GroupResourcePermission.group_name,
                             self.GroupResourcePermission.perm_name)
        q = q.filter(self.GroupResourcePermission.group_name.in_(
                                    [gr.group_name for gr in user.groups]
                                    )
                     )
        q = q.filter(self.GroupResourcePermission.resource_id == self.resource_id)
        if invalidate:
            return True
        perms = [(row[0], row.perm_name,) for row in q]
#        if self.owner_group_name:
#            perms.append(('group:' + self.owner_group_name, ALL_PERMISSIONS,))
        return perms
    
    
    def users_for_perm(self, perm_name, cache='default',
                       invalidate=False, db_session=None):
        """ return tuple (user,perm_name) that have given permission for the resource """
        db_session = get_db_session(db_session, self)
        q = db_session.query(self.User, self.GroupResourcePermission.perm_name)
        q = q.filter(self.User.user_name == self.UserGroup.user_name)
        q = q.filter(self.UserGroup.group_name == self.GroupResourcePermission.group_name)
        if perm_name != '__any_permission__':
            q = q.filter(self.GroupResourcePermission.perm_name == perm_name)
        q = q.filter(self.GroupResourcePermission.resource_id == self.resource_id)        
        q2 = db_session.query(self.User, self.UserResourcePermission.perm_name)
        q2 = q2.filter(self.User.user_name == self.UserResourcePermission.user_name)
        if perm_name != '__any_permission__':
            q2 = q2.filter(self.UserResourcePermission.perm_name == perm_name)
        q2 = q2.filter(self.UserResourcePermission.resource_id == self.resource_id)
        q = q.union(q2)
        if invalidate:
            return True
        users = [(row.User, row.perm_name,) for row in q]
        if self.owner_user_name:
            users.append((self.User.by_user_name(self.owner_user_name), ALL_PERMISSIONS,))
        return users
        
    @classmethod
    def by_resource_id(cls, resource_id, cache='default',
                       invalidate=False, db_session=None):
        """ fetch the resouce by id """
        db_session = get_db_session(db_session)
        q = db_session.query(cls).filter(cls.resource_id == int(resource_id))
        if invalidate:
            return True
        return q.first()
    
    @classmethod
    def all(cls, db_session=None):
        """ fetch all permissions"""
        q = get_db_session(db_session).query(cls)
        return q
    
    @classmethod
    def perm_by_group_and_perm_name(cls, res_id, group_name, perm_name,
                                    db_session=None):
        """ fetch permissions by group and permission name"""
        db_session = get_db_session(db_session)
        q = db_session.query(cls.GroupResourcePermission)
        q = q.filter(cls.GroupResourcePermission.group_name == group_name)
        q = q.filter(cls.GroupResourcePermission.perm_name == perm_name)
        q = q.filter(cls.GroupResourcePermission.resource_id == res_id)
        return q.first()
    
    @sa.orm.validates('user_permissions', 'group_permissions')
    def validate_permission(self, key, permission):
        """ validate if resouce can have specific permission """
        assert permission.perm_name in self.__possible_permissions__
        return permission