cred_memory.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. # -*- test-case-name: twisted.test.test_strcred -*-
  2. #
  3. # Copyright (c) Twisted Matrix Laboratories.
  4. # See LICENSE for details.
  5. """
  6. Cred plugin for an in-memory user database.
  7. """
  8. from zope.interface import implementer
  9. from twisted import plugin
  10. from twisted.cred.checkers import InMemoryUsernamePasswordDatabaseDontUse
  11. from twisted.cred.credentials import IUsernameHashedPassword, IUsernamePassword
  12. from twisted.cred.strcred import ICheckerFactory
  13. inMemoryCheckerFactoryHelp = """
  14. A checker that uses an in-memory user database.
  15. This is only of use in one-off test programs or examples which
  16. don't want to focus too much on how credentials are verified. You
  17. really don't want to use this for anything else. It is a toy.
  18. """
  19. @implementer(ICheckerFactory, plugin.IPlugin)
  20. class InMemoryCheckerFactory:
  21. """
  22. A factory for in-memory credentials checkers.
  23. This is only of use in one-off test programs or examples which don't
  24. want to focus too much on how credentials are verified.
  25. You really don't want to use this for anything else. It is, at best, a
  26. toy. If you need a simple credentials checker for a real application,
  27. see L{cred_file.FileCheckerFactory}.
  28. """
  29. authType = "memory"
  30. authHelp = inMemoryCheckerFactoryHelp
  31. argStringFormat = "A colon-separated list (name:password:...)"
  32. credentialInterfaces = (IUsernamePassword, IUsernameHashedPassword)
  33. def generateChecker(self, argstring):
  34. """
  35. This checker factory expects to get a list of
  36. username:password pairs, with each pair also separated by a
  37. colon. For example, the string 'alice:f:bob:g' would generate
  38. two users, one named 'alice' and one named 'bob'.
  39. """
  40. checker = InMemoryUsernamePasswordDatabaseDontUse()
  41. if argstring:
  42. pieces = argstring.split(":")
  43. if len(pieces) % 2:
  44. from twisted.cred.strcred import InvalidAuthArgumentString
  45. raise InvalidAuthArgumentString("argstring must be in format U:P:...")
  46. for i in range(0, len(pieces), 2):
  47. username, password = pieces[i], pieces[i + 1]
  48. checker.addUser(username, password)
  49. return checker
  50. theInMemoryCheckerFactory = InMemoryCheckerFactory()