1 from fnmatch import fnmatch
3 class AccessControlList:
4 def __init__(self, aclText=None):
7 self.import_text(aclText)
9 def import_text(self, aclText):
10 # allow either newline or ';' to separate rules
11 aclText = aclText.replace("\n", ";")
12 for line in aclText.split(";"):
14 if line.startswith("#"):
22 if len(parts)==2 and (parts[1]=="all"):
23 # "allow all" has no pattern
24 parts = (parts[0], parts[1], "")
27 raise ACLValidationError(line)
29 (action, object, pattern) = parts
31 if action not in ["allow", "deny"]:
32 raise ACLValidationError(line)
34 if object not in ["site", "user", "all"]:
35 raise ACLValidationError(line)
37 self.rules.append( (action, object, pattern) )
41 for rule in self.rules:
42 lines.append( " ".join(rule) )
43 return ";\n".join(lines)
46 for rule in self.rules:
47 if self.match_rule(rule, user):
51 def match_rule(self, rule, user):
52 (action, object, pattern) = rule
54 if (object == "site"):
55 if fnmatch(user.site.name, pattern):
57 elif (object == "user"):
58 if fnmatch(user.email, pattern):
60 elif (object == "all"):
66 if __name__ == '__main__':
68 def __init__(self, siteName):
72 def __init__(self, email, siteName):
74 self.site = fakesite(siteName)
76 u_scott = fakeuser("scott@onlab.us", "ON.Lab")
77 u_bill = fakeuser("bill@onlab.us", "ON.Lab")
78 u_andy = fakeuser("acb@cs.princeton.edu", "Princeton")
79 u_john = fakeuser("jhh@cs.arizona.edu", "Arizona")
80 u_hacker = fakeuser("somehacker@foo.com", "Not A Real Site")
82 # check the "deny all" rule
83 acl = AccessControlList("deny all")
84 assert(acl.test(u_scott) == "deny")
86 # a blank ACL results in "deny all"
87 acl = AccessControlList("")
88 assert(acl.test(u_scott) == "deny")
90 # check the "allow all" rule
91 acl = AccessControlList("allow all")
92 assert(acl.test(u_scott) == "allow")
95 acl = AccessControlList("allow site ON.Lab")
96 assert(acl.test(u_scott) == "allow")
97 assert(acl.test(u_andy) == "deny")
99 # some complicated ACL
100 acl = AccessControlList("""allow site Princeton
101 allow user *@cs.arizona.edu
103 deny user scott@onlab.us
104 allow site ON.Lab""")
106 assert(acl.test(u_scott) == "deny")
107 assert(acl.test(u_bill) == "allow")
108 assert(acl.test(u_andy) == "allow")
109 assert(acl.test(u_john) == "allow")
110 assert(acl.test(u_hacker) == "deny")