portal.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. # -*- test-case-name: twisted.cred.test.test_cred -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. The point of integration of application and authentication.
  6. """
  7. from typing import Callable, Dict, Iterable, List, Tuple, Type, Union
  8. from zope.interface import Interface, providedBy
  9. from twisted.cred import error
  10. from twisted.cred.checkers import ICredentialsChecker
  11. from twisted.cred.credentials import ICredentials
  12. from twisted.internet import defer
  13. from twisted.internet.defer import Deferred, maybeDeferred
  14. from twisted.python import failure, reflect
  15. # To say 'we need an Interface object', we have to say Type[Interface];
  16. # although zope.interface has no type/instance distinctions within the
  17. # implementation of Interface itself (subclassing it actually instantiates it),
  18. # since mypy-zope treats Interface objects *as* types, this is how you have to
  19. # treat it.
  20. _InterfaceItself = Type[Interface]
  21. # This is the result shape for both IRealm.requestAvatar and Portal.login,
  22. # although the former is optionally allowed to return synchronously and the
  23. # latter must be Deferred.
  24. _requestResult = Tuple[_InterfaceItself, object, Callable[[], None]]
  25. class IRealm(Interface):
  26. """
  27. The realm connects application-specific objects to the
  28. authentication system.
  29. """
  30. def requestAvatar(
  31. avatarId: Union[bytes, Tuple[()]], mind: object, *interfaces: _InterfaceItself
  32. ) -> Union[Deferred[_requestResult], _requestResult]:
  33. """
  34. Return avatar which provides one of the given interfaces.
  35. @param avatarId: a string that identifies an avatar, as returned by
  36. L{ICredentialsChecker.requestAvatarId<twisted.cred.checkers.ICredentialsChecker.requestAvatarId>}
  37. (via a Deferred). Alternatively, it may be
  38. C{twisted.cred.checkers.ANONYMOUS}.
  39. @param mind: usually None. See the description of mind in
  40. L{Portal.login}.
  41. @param interfaces: the interface(s) the returned avatar should
  42. implement, e.g. C{IMailAccount}. See the description of
  43. L{Portal.login}.
  44. @returns: a deferred which will fire a tuple of (interface,
  45. avatarAspect, logout), or the tuple itself. The interface will be
  46. one of the interfaces passed in the 'interfaces' argument. The
  47. 'avatarAspect' will implement that interface. The 'logout' object
  48. is a callable which will detach the mind from the avatar.
  49. """
  50. class Portal:
  51. """
  52. A mediator between clients and a realm.
  53. A portal is associated with one Realm and zero or more credentials checkers.
  54. When a login is attempted, the portal finds the appropriate credentials
  55. checker for the credentials given, invokes it, and if the credentials are
  56. valid, retrieves the appropriate avatar from the Realm.
  57. This class is not intended to be subclassed. Customization should be done
  58. in the realm object and in the credentials checker objects.
  59. """
  60. checkers: Dict[Type[Interface], ICredentialsChecker]
  61. def __init__(
  62. self, realm: IRealm, checkers: Iterable[ICredentialsChecker] = ()
  63. ) -> None:
  64. """
  65. Create a Portal to a L{IRealm}.
  66. """
  67. self.realm = realm
  68. self.checkers = {}
  69. for checker in checkers:
  70. self.registerChecker(checker)
  71. def listCredentialsInterfaces(self) -> List[Type[Interface]]:
  72. """
  73. Return list of credentials interfaces that can be used to login.
  74. """
  75. return list(self.checkers.keys())
  76. def registerChecker(
  77. self, checker: ICredentialsChecker, *credentialInterfaces: Type[Interface]
  78. ) -> None:
  79. if not credentialInterfaces:
  80. credentialInterfaces = checker.credentialInterfaces
  81. for credentialInterface in credentialInterfaces:
  82. self.checkers[credentialInterface] = checker
  83. def login(
  84. self, credentials: ICredentials, mind: object, *interfaces: Type[Interface]
  85. ) -> Deferred[_requestResult]:
  86. """
  87. @param credentials: an implementor of
  88. L{twisted.cred.credentials.ICredentials}
  89. @param mind: an object which implements a client-side interface for
  90. your particular realm. In many cases, this may be None, so if the
  91. word 'mind' confuses you, just ignore it.
  92. @param interfaces: list of interfaces for the perspective that the mind
  93. wishes to attach to. Usually, this will be only one interface, for
  94. example IMailAccount. For highly dynamic protocols, however, this
  95. may be a list like (IMailAccount, IUserChooser, IServiceInfo). To
  96. expand: if we are speaking to the system over IMAP, any information
  97. that will be relayed to the user MUST be returned as an
  98. IMailAccount implementor; IMAP clients would not be able to
  99. understand anything else. Any information about unusual status
  100. would have to be relayed as a single mail message in an
  101. otherwise-empty mailbox. However, in a web-based mail system, or a
  102. PB-based client, the ``mind'' object inside the web server
  103. (implemented with a dynamic page-viewing mechanism such as a
  104. Twisted Web Resource) or on the user's client program may be
  105. intelligent enough to respond to several ``server''-side
  106. interfaces.
  107. @return: A deferred which will fire a tuple of (interface,
  108. avatarAspect, logout). The interface will be one of the interfaces
  109. passed in the 'interfaces' argument. The 'avatarAspect' will
  110. implement that interface. The 'logout' object is a callable which
  111. will detach the mind from the avatar. It must be called when the
  112. user has conceptually disconnected from the service. Although in
  113. some cases this will not be in connectionLost (such as in a
  114. web-based session), it will always be at the end of a user's
  115. interactive session.
  116. """
  117. for i in self.checkers:
  118. if i.providedBy(credentials):
  119. return maybeDeferred(
  120. self.checkers[i].requestAvatarId, credentials
  121. ).addCallback(self.realm.requestAvatar, mind, *interfaces)
  122. ifac = providedBy(credentials)
  123. return defer.fail(
  124. failure.Failure(
  125. error.UnhandledCredentials(
  126. "No checker for %s" % ", ".join(map(reflect.qual, ifac))
  127. )
  128. )
  129. )