Learning by doing: Reading books and trying to understand the (code) examples
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

79 lines
2.2 KiB

  1. import auth
  2. # setup a test user & permission
  3. auth.authenticator.add_user("joe", "joepassword")
  4. auth.authorizor.add_permission("test program")
  5. auth.authorizor.add_permission("change program")
  6. auth.authorizor.permit_user("test program", "joe")
  7. class Editor:
  8. def __init__(self):
  9. self.username = None
  10. self.menu_map = {
  11. "login": self.login,
  12. "test": self.test,
  13. "change": self.change,
  14. "quit": self.quit
  15. }
  16. def login(self):
  17. logged_in = False
  18. while not logged_in:
  19. username = input("username: ")
  20. password = input("password: ")
  21. try:
  22. logged_in = auth.authenticator.login(username, password)
  23. except auth.InvalidUsername:
  24. print("Sorry, that username doesn't exist")
  25. except auth.InvalidPassword:
  26. print("Sorry, incorrect password")
  27. else:
  28. self.username = username
  29. def is_permitted(self, permission):
  30. try:
  31. auth.authorizor.check_permission(permission, self.username)
  32. except auth.NotLoggedInError as e:
  33. print("{} is not logged in".format(e.username))
  34. except auth.NotPermittedError as e:
  35. print("{} cannot {}".format(e.username, permission))
  36. else:
  37. return True
  38. def test(self):
  39. if self.is_permitted("test program"):
  40. print("Testing program now...")
  41. def change(self):
  42. if self.is_permitted("change program"):
  43. print("Changing program now...")
  44. def quit(self):
  45. raise SystemExit()
  46. def menu(self):
  47. try:
  48. answer = ""
  49. while True:
  50. print("""
  51. Please enter a command:
  52. \tlogin\tLogin
  53. \ttest\tTest the program
  54. \tchange\tChange the program
  55. \tquit\tQuit
  56. """)
  57. answer = input("enter a command: ").lower()
  58. try:
  59. func = self.menu_map[answer]
  60. except KeyError:
  61. print("{} isn't a valid option".format(answer))
  62. else:
  63. func()
  64. finally:
  65. print("Thank you for testing the auth module")
  66. Editor().menu()