Code

fix typo
[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.7 2002-09-26 13:38:35 gmcm Exp $
20 __doc__ = """
21 Password handling (encoding, decoding).
22 """
24 import sha, re, string
25 try:
26     import crypt
27 except:
28     crypt = None
29     pass
31 def encodePassword(plaintext, scheme, other=None):
32     '''Encrypt the plaintext password.
33     '''
34     if scheme == 'SHA':
35         s = sha.sha(plaintext).hexdigest()
36     elif scheme == 'crypt' and crypt is not None:
37         if other is not None:
38             salt = other[:2]
39         else:
40             saltchars = './0123456789'+string.letters
41             salt = random.choice(saltchars) + random.choice(saltchars)
42         s = crypt.crypt(plaintext, salt)
43     elif scheme == 'plaintext':
44         s = plaintext
45     else:
46         raise ValueError, 'Unknown encryption scheme "%s"'%scheme
47     return s
49 class Password:
50     '''The class encapsulates a Password property type value in the database. 
52     The encoding of the password is one if None, 'SHA' or 'plaintext'. The
53     encodePassword function is used to actually encode the password from
54     plaintext. The None encoding is used in legacy databases where no
55     encoding scheme is identified.
57     The scheme is stored with the encoded data in the database:
58         {scheme}data
60     Example usage:
61     >>> p = Password('sekrit')
62     >>> p == 'sekrit'
63     1
64     >>> p != 'not sekrit'
65     1
66     >>> 'sekrit' == p
67     1
68     >>> 'not sekrit' != p
69     1
70     '''
72     default_scheme = 'SHA'        # new encryptions use this scheme
73     pwre = re.compile(r'{(\w+)}(.+)')
75     def __init__(self, plaintext=None, scheme=None):
76         '''Call setPassword if plaintext is not None.'''
77         if scheme is None:
78             scheme = self.default_scheme
79         if plaintext is not None:
80             self.password = encodePassword(plaintext, self.default_scheme)
81             self.scheme = self.default_scheme
82         else:
83             self.password = None
84             self.scheme = self.default_scheme
86     def unpack(self, encrypted):
87         '''Set the password info from the scheme:<encryted info> string
88            (the inverse of __str__)
89         '''
90         m = self.pwre.match(encrypted)
91         if m:
92             self.scheme = m.group(1)
93             self.password = m.group(2)
94         else:
95             # currently plaintext - encrypt
96             self.password = encodePassword(encrypted, self.default_scheme)
97             self.scheme = self.default_scheme
99     def setPassword(self, plaintext, scheme=None):
100         '''Sets encrypts plaintext.'''
101         if scheme is None:
102             scheme = self.default_scheme
103         self.password = encodePassword(plaintext, scheme)
105     def __cmp__(self, other):
106         '''Compare this password against another password.'''
107         # check to see if we're comparing instances
108         if isinstance(other, Password):
109             if self.scheme != other.scheme:
110                 return cmp(self.scheme, other.scheme)
111             return cmp(self.password, other.password)
113         # assume password is plaintext
114         if self.password is None:
115             raise ValueError, 'Password not set'
116         return cmp(self.password, encodePassword(other, self.scheme,
117             self.password))
119     def __str__(self):
120         '''Stringify the encrypted password for database storage.'''
121         if self.password is None:
122             raise ValueError, 'Password not set'
123         return '{%s}%s'%(self.scheme, self.password)
125 def test():
126     # SHA
127     p = Password('sekrit')
128     assert p == 'sekrit'
129     assert p != 'not sekrit'
130     assert 'sekrit' == p
131     assert 'not sekrit' != p
133     # crypt
134     p = Password('sekrit', 'crypt')
135     assert p == 'sekrit'
136     assert p != 'not sekrit'
137     assert 'sekrit' == p
138     assert 'not sekrit' != p
140 if __name__ == '__main__':
141     test()
143 # vim: set filetype=python ts=4 sw=4 et si