首先文件auth.py
import _hashlib
class User:
'''Create a new user object. The password will be
encrypted before storing'''
def __init__(self, username, password):
self.username = username
self.password = self._encrypt_pw(password)
# 这还是一个注意点
self.is_logged_in = False
def _encrypt_pw(self, password):
hash_string = (self.username + password)
hash_string = hash_string.encode("utf-8")
return _hashlib.openssl_sha256(hash_string).hexdigest()
def check_password(self, password):
encryted = self._encrypt_pw(password)
return encryted == self.password
class AuthException(Exception):
def __init__(self, username, user=None):
super().__init__(username, user)
self.username = username
self.user = user
class UsernameAlreadyExists(AuthException):
pass
class PasswordTooShort(AuthException):
pass
class InvalidUsername(AuthException):
pass
class InvalidPassword(AuthException):
pass
class NotLoggedInError(AuthException):
pass
class NotPermittedError(AuthException):
pass
class PermissionError(Exception):
pass
class Authenticator:
'''这里有一个用户的字典,并将合格的用户存储到字典中'''
def __init__(self):
self.users = {}
def add_user(self, username, password):
if username in self.users:
raise UsernameAlreadyExists(username)
if len(password) < 6:
raise PasswordTooShort(username)
self.users[username] = User(username, password)
# 将一个符合的用户以及用户名加入到users中
def login(self, username, password):
try:
user = self.users[username]
except KeyError:
# if username not in self.users
# 这个就是一个使用异常进行决策的例子
raise InvalidUsername(username)
if not user.check_password(password):
raise InvalidPassword(username, user)
user.is_logged_in = True
return True
def is_logged_in(self, username):
# 用于检查用户是否登录了
# 其实也检查了是否存在这个用户的问题
if username in self.users:
return self.users[username].is_logged_in
return False
# 接下来是添加为用户添加权限的类
class Authorizor:
def __init__(self, authenticator):
self.authenticator = authenticator
self.permissions = {}
# 键值对的方式是:键——perm_name; 值——拥有这个权限的用户组成的元组
def add_permission(self, perm_name):
'''创建一个可以为用户添加的权限名称'''
try:
perm_set = self.permissions[perm_name]
except KeyError:
self.permissions[perm_name] = set()
else:
raise PermissionError("Permission Exists")
def permit_user(self, perm_name, username):
'''将perm_name这个权限给username'''
try:
perm_set = self.permissions[perm_name]
except KeyError:
raise PermissionError("Permissions does not exist")
else:
if username not in self.authenticator.users:
raise InvalidUsername(username)
perm_set.add(username)
def check_permission(self, perm_name, username):
if not self.authenticator.is_logged_in(username):
raise NotLoggedInError(username)
try:
perm_set = self.permissions[perm_name]
except KeyError:
raise PermissionError("Permission does not exist")
else:
if username not in perm_set:
raise NotPermittedError(username)
else: return True
# authenticator = Authenticator()
# authenticator.add_user("joe", "joepassword")
# # 创建一个实例,并且添加一个用户
# authorizor = Authorizor(authenticator)
# authorizor.add_permission("paint")
# # 创建一个实例,并且添加一个新权限
# # authorizor.check_permission("paint", "joe")
# # 这里会显示joe并没有登录
# log = authenticator.is_logged_in("joe")
# # 检查一下joe用户是否登录了
# if not log:
# authenticator.login("joe", "joepassword")
# # authorizor.check_permission("paint", "joe")
# authorizor.permit_user("paint", "joe")
# authorizor.check_permission("paint", "joe")
# 上面几行用于测试程序是否可以有用,接下来使用一些例子来说明真正的作用
authenticator = Authenticator()
authorizor = Authorizor(authenticator)
接下来是一个使用程序的借口文件:auth_API.py
import auth
# 创建一个测试用户并设置权限
auth.authenticator.add_user("joe", "joepassword")
auth.authorizor.add_permission("test program")
auth.authorizor.add_permission("change program")
auth.authorizor.permit_user("test program", "joe")
class Editor:
def __init__(self):
self.username = None
self.menu_map = {
"login": self.login,
"test": self.test,
"change": self.change,
"quit": self.quit
}
def login(self):
logged_in = False
while not logged_in:
username = input("input:")
password = input("password:")
try:
logged_in = auth.authenticator.login(username, password)
except auth.InvalidUsername:
print("Sorry, that username does not exist")
except auth.InvalidPassword:
print("Sorry, incorrect password")
else:
self.username = username
def is_permitted(self, permission):
try:
auth.authorizor.check_permission(permission, self.username)
except auth.NotLoggedInError as e:
print("{} is not logged in".format(e.username))
return False
except auth.NotPermittedError as e:
print("{} cannot {}".format(e.username, permission))
return False
else:
return True
def test(self):
if self.is_permitted("test program"):
print("Testing program now...")
def change(self):
if self.is_permitted("change program"):
print("Changing program now...")
def quit(self):
raise SystemExit()
def menu(self):
try:
answer = ""
while True:
print("""
Please enter a command:
\tlogin\tLogin
\ttest\tTest the program
\tchange\tChange the program
\tquie\tQuit
""")
answer = input("enter a command: ").lower()
try:
func = self.menu_map[answer]
except KeyError:
print("{} is not a valid option".format(answer))
else:
func()
finally:
print("Thank you for testing the auth module")
Editor().menu()