cancanisatinypermissioncontrollerbaseonrubycancanlibrary.Oncedefineduserability,caneasilycheckuser'spermission.
Installpipinstallcancan
BasicUsageinheritfromcancan.Ability
useaddmethodtoadduserAbility
defadd(self,action=None,subject=None,**conditions)`"""Addabilityareallowedusingtwoarguments.Thefirstoneistheactionyou'resettingthepermissionfor,thesecondoneistheclassofobjectyou'resettingiton.thethirdoneisthesubject'sattributesmustbematchesorafunctiontobetest.self.add('update',Article)self.add('update',Article,user_id=1)self.add('update',Article,user_id=1,title='hello')self.add('update',Article,function=test_title)"""importcancanclassUser(object):def__init__(self,id,name,role):self.id=idself.name=nameself.role=roleclassArticle(object):def__init__(self,title,user_id):self.title=titleself.user_id=user_idclassAbility(cancan.Ability):def__init__(self,user):ifuser.role=='admin':self.add('manage','all')else:self.add('read',Article)self.add('create',Article)self.add('update',Article,user_id=user.id)self.add('create','bbb')admin=User(1,'neven','admin')ability=Ability(admin)#adminability.can('read',Article)#Trueability.can('create',Article)#Trueability.can('delete',Article)#Trueability.can('aaa',Article)#Trueability.can('create','bbb')#Trueability.can('create','ccc')#Trueuser=User(2,'joe','user')ability2=Ability(user)#userability2.can('read',Article)#Trueability2.can('create',Article)#Trueability2.can('delete',Article)#Falseability2.can('aaa',Article)#Falseability2.can('create','bbb')#Trueability2.can('create','ccc')#Falsearticle=Article('hello',2)#adminability.can('update',article)#True#userability2.can('update',article)#Trueability2.can('update',Article)#True(classdontcheckconditions)Advancedimportcancandeftest_title_gt_100(article):returnlen(article.title)>100defanoter_test(article,id,len_title):returnarticle.user_id<idandlen(article.title)>len_articleclassAbility(cancan.Ability):def__init__(self,user):self.alias_action('create','read','update',to='cru')ifuser.role=='admin':self.add('manage','all')self.addnot('destroy','gem')elifuser.role=='editor':self.add('cru',Article)self.add(['read','create'],'gem')self.add('update',Article,function=test_title_gt_100)self.add('delete',Article,function=another_test,func_args=(10,),func_kwargs={"len_title":4})else:self.add('create',Article)self.add('update',Article,user_id=user.id)self.add('create','bbb')editor=User(3,'kali','editor')ability3=Ability(editor)#editorability3.can('create',Article)#Trueability3.can('update',Article)#Trueability3.can('cru',Article)#Trueability3.can('read','gem')#Trueability3.can('create','gem')#Truearticle=Article('world',1)ability3.can('update',article)#Falseability3.can('delete',article)#Truearticle=Article('world'*100,1)ability3.can('delete',article)#TrueExampleseeexample.py
IntegrateDjangoseedjango_example
评论