users_collection.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. from .user import user
  2. from .user import user_builder
  3. from .user import user_factory
  4. from .exception import in_collection_exception
  5. class users_collection:
  6. """
  7. This is responsible for managing users in the system. It could login new
  8. users, or load them by ApiKey.
  9. """
  10. def __init__(self):
  11. """
  12. This create new collection.
  13. """
  14. self.__by_apikey = dict()
  15. self.__by_nick = dict()
  16. def add(self, target: user) -> None:
  17. """
  18. This add new user to the collection. When ApiKey or login already
  19. exists in the collection, then error had been raised.
  20. Parameters:
  21. target (user): New user to add
  22. """
  23. if target.apikey in self.__by_apikey:
  24. error = "User with ApiKey \"" + target.apikey + "\" "
  25. error = error + "already in collection."
  26. raise in_collection_exception(error)
  27. if target.nick in self.__by_nick:
  28. error = "User with nick \"" + target.nick + "\" "
  29. error = error + "already in collection."
  30. raise in_collection_exception(error)
  31. self.__by_apikey[target.apikey] = target
  32. self.__by_nick[target.nick] = target
  33. def login(self, nick: str, password: str) -> user | None:
  34. """
  35. This try to login user by nick and password. When nick or password
  36. had been wrong, then None had been returned. When nick and password
  37. are correct, then return that user.
  38. Parameters:
  39. nick (str): Nick of the user
  40. password (str): Password of the user
  41. Returns:
  42. (user): User with that nick and password, if exists
  43. (None): When user with that nick and password not exists
  44. """
  45. if not nick in self.__by_nick:
  46. return None
  47. target = self.__by_nick[nick]
  48. if target.password != password:
  49. return None
  50. return target
  51. def get(self, apikey: str) -> user | None:
  52. """
  53. This try to load user by ApiKey. When user with that ApiKey exists
  54. then return it. When not, return None.
  55. Parameters:
  56. apikey (str): ApiKey of the user to load
  57. Returns:
  58. (user): User with that ApiKey
  59. (None): When user with that ApiKey not exists
  60. """
  61. if not apikey in self.__by_apikey:
  62. return None
  63. return self.__by_apikey[apikey]