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