From 78e27a063356827c3e1d6e4aefcf4976bafa833f Mon Sep 17 00:00:00 2001 From: tmeissner Date: Sat, 13 Sep 2014 20:42:37 +0200 Subject: [PATCH] added Editor class --- python_3_oop/chapter04/editor.py | 73 +++++++++++++++++++++++++++++++- 1 file changed, 72 insertions(+), 1 deletion(-) diff --git a/python_3_oop/chapter04/editor.py b/python_3_oop/chapter04/editor.py index 17ae123..a6bc126 100644 --- a/python_3_oop/chapter04/editor.py +++ b/python_3_oop/chapter04/editor.py @@ -5,4 +5,75 @@ 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") \ No newline at end of file +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("username: ") + password = input("password: ") + try: + logged_in = auth.authenticator.login(username, password) + except auth.InvalidUsername: + print("Sorry, that username doesn't 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)) + except auth.NotPermittedError as e: + print("{} cannot {}".format(e.username, permission)) + 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 +\tquit\tQuit +""") + answer = input("enter a command: ").lower() + try: + func = self.menu_map[answer] + except KeyError: + print("{} isn't a valid option".format(answer)) + else: + func() + finally: + print("Thank you for testing the auth module") + + +Editor().menu()