cred_memory.py 2.3 KB

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