Code

14dbcda0da9338193fbd2b128dbf0881be899778
[roundup.git] / roundup / password.py
1 #
2 # Copyright (c) 2001 Bizar Software Pty Ltd (http://www.bizarsoftware.com.au/)
3 # This module is free software, and you may redistribute it and/or modify
4 # under the same terms as Python, so long as this copyright message and
5 # disclaimer are retained in their original form.
6 #
7 # IN NO EVENT SHALL BIZAR SOFTWARE PTY LTD BE LIABLE TO ANY PARTY FOR
8 # DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING
9 # OUT OF THE USE OF THIS CODE, EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE
10 # POSSIBILITY OF SUCH DAMAGE.
11 #
12 # BIZAR SOFTWARE PTY LTD SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
13 # BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
14 # FOR A PARTICULAR PURPOSE.  THE CODE PROVIDED HEREUNDER IS ON AN "AS IS"
15 # BASIS, AND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCE,
16 # SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
17
18 # $Id: password.py,v 1.12 2004-03-22 07:45:39 richard Exp $
20 """Password handling (encoding, decoding).
21 """
22 __docformat__ = 'restructuredtext'
24 import sha, re, string, random
25 try:
26     import crypt
27 except:
28     crypt = None
29     pass
31 class PasswordValueError(ValueError):
32     ''' The password value is not valid '''
33     pass
35 def encodePassword(plaintext, scheme, other=None):
36     '''Encrypt the plaintext password.
37     '''
38     if plaintext is None:
39         plaintext = ""
40     if scheme == 'SHA':
41         s = sha.sha(plaintext).hexdigest()
42     elif scheme == 'crypt' and crypt is not None:
43         if other is not None:
44             salt = other[:2]
45         else:
46             saltchars = './0123456789'+string.letters
47             salt = random.choice(saltchars) + random.choice(saltchars)
48         s = crypt.crypt(plaintext, salt)
49     elif scheme == 'plaintext':
50         s = plaintext
51     else:
52         raise PasswordValueError, 'unknown encryption scheme %r'%scheme
53     return s
55 def generatePassword(length=8):
56     chars = string.letters+string.digits
57     return ''.join([random.choice(chars) for x in range(length)])
59 class Password:
60     '''The class encapsulates a Password property type value in the database. 
62     The encoding of the password is one if None, 'SHA' or 'plaintext'. The
63     encodePassword function is used to actually encode the password from
64     plaintext. The None encoding is used in legacy databases where no
65     encoding scheme is identified.
67     The scheme is stored with the encoded data in the database:
68         {scheme}data
70     Example usage:
71     >>> p = Password('sekrit')
72     >>> p == 'sekrit'
73     1
74     >>> p != 'not sekrit'
75     1
76     >>> 'sekrit' == p
77     1
78     >>> 'not sekrit' != p
79     1
80     '''
82     default_scheme = 'SHA'        # new encryptions use this scheme
83     pwre = re.compile(r'{(\w+)}(.+)')
85     def __init__(self, plaintext=None, scheme=None, encrypted=None):
86         '''Call setPassword if plaintext is not None.'''
87         if scheme is None:
88             scheme = self.default_scheme
89         if plaintext is not None:
90             self.password = encodePassword(plaintext, self.default_scheme)
91             self.scheme = self.default_scheme
92         elif encrypted is not None:
93             self.unpack(encrypted)
94         else:
95             self.password = None
96             self.scheme = self.default_scheme
98     def unpack(self, encrypted):
99         '''Set the password info from the scheme:<encryted info> string
100            (the inverse of __str__)
101         '''
102         m = self.pwre.match(encrypted)
103         if m:
104             self.scheme = m.group(1)
105             self.password = m.group(2)
106         else:
107             # currently plaintext - encrypt
108             self.password = encodePassword(encrypted, self.default_scheme)
109             self.scheme = self.default_scheme
111     def setPassword(self, plaintext, scheme=None):
112         '''Sets encrypts plaintext.'''
113         if scheme is None:
114             scheme = self.default_scheme
115         self.password = encodePassword(plaintext, scheme)
117     def __cmp__(self, other):
118         '''Compare this password against another password.'''
119         # check to see if we're comparing instances
120         if isinstance(other, Password):
121             if self.scheme != other.scheme:
122                 return cmp(self.scheme, other.scheme)
123             return cmp(self.password, other.password)
125         # assume password is plaintext
126         if self.password is None:
127             raise ValueError, 'Password not set'
128         return cmp(self.password, encodePassword(other, self.scheme,
129             self.password))
131     def __str__(self):
132         '''Stringify the encrypted password for database storage.'''
133         if self.password is None:
134             raise ValueError, 'Password not set'
135         return '{%s}%s'%(self.scheme, self.password)
137 def test():
138     # SHA
139     p = Password('sekrit')
140     assert p == 'sekrit'
141     assert p != 'not sekrit'
142     assert 'sekrit' == p
143     assert 'not sekrit' != p
145     # crypt
146     p = Password('sekrit', 'crypt')
147     assert p == 'sekrit'
148     assert p != 'not sekrit'
149     assert 'sekrit' == p
150     assert 'not sekrit' != p
152 if __name__ == '__main__':
153     test()
155 # vim: set filetype=python ts=4 sw=4 et si