Code

Use abspath() from os.path, it's been there since 1.5.2.
[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.9 2003-04-10 05:12:41 richard Exp $
20 __doc__ = """
21 Password handling (encoding, decoding).
22 """
24 import sha, re, string, random
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 plaintext is None:
35         plaintext = ""
36     if scheme == 'SHA':
37         s = sha.sha(plaintext).hexdigest()
38     elif scheme == 'crypt' and crypt is not None:
39         if other is not None:
40             salt = other[:2]
41         else:
42             saltchars = './0123456789'+string.letters
43             salt = random.choice(saltchars) + random.choice(saltchars)
44         s = crypt.crypt(plaintext, salt)
45     elif scheme == 'plaintext':
46         s = plaintext
47     else:
48         raise ValueError, 'Unknown encryption scheme "%s"'%scheme
49     return s
51 def generatePassword(length=8):
52     chars = string.letters+string.digits
53     return ''.join([random.choice(chars) for x in range(length)])
55 class Password:
56     '''The class encapsulates a Password property type value in the database. 
58     The encoding of the password is one if None, 'SHA' or 'plaintext'. The
59     encodePassword function is used to actually encode the password from
60     plaintext. The None encoding is used in legacy databases where no
61     encoding scheme is identified.
63     The scheme is stored with the encoded data in the database:
64         {scheme}data
66     Example usage:
67     >>> p = Password('sekrit')
68     >>> p == 'sekrit'
69     1
70     >>> p != 'not sekrit'
71     1
72     >>> 'sekrit' == p
73     1
74     >>> 'not sekrit' != p
75     1
76     '''
78     default_scheme = 'SHA'        # new encryptions use this scheme
79     pwre = re.compile(r'{(\w+)}(.+)')
81     def __init__(self, plaintext=None, scheme=None):
82         '''Call setPassword if plaintext is not None.'''
83         if scheme is None:
84             scheme = self.default_scheme
85         if plaintext is not None:
86             self.password = encodePassword(plaintext, self.default_scheme)
87             self.scheme = self.default_scheme
88         else:
89             self.password = None
90             self.scheme = self.default_scheme
92     def unpack(self, encrypted):
93         '''Set the password info from the scheme:<encryted info> string
94            (the inverse of __str__)
95         '''
96         m = self.pwre.match(encrypted)
97         if m:
98             self.scheme = m.group(1)
99             self.password = m.group(2)
100         else:
101             # currently plaintext - encrypt
102             self.password = encodePassword(encrypted, self.default_scheme)
103             self.scheme = self.default_scheme
105     def setPassword(self, plaintext, scheme=None):
106         '''Sets encrypts plaintext.'''
107         if scheme is None:
108             scheme = self.default_scheme
109         self.password = encodePassword(plaintext, scheme)
111     def __cmp__(self, other):
112         '''Compare this password against another password.'''
113         # check to see if we're comparing instances
114         if isinstance(other, Password):
115             if self.scheme != other.scheme:
116                 return cmp(self.scheme, other.scheme)
117             return cmp(self.password, other.password)
119         # assume password is plaintext
120         if self.password is None:
121             raise ValueError, 'Password not set'
122         return cmp(self.password, encodePassword(other, self.scheme,
123             self.password))
125     def __str__(self):
126         '''Stringify the encrypted password for database storage.'''
127         if self.password is None:
128             raise ValueError, 'Password not set'
129         return '{%s}%s'%(self.scheme, self.password)
131 def test():
132     # SHA
133     p = Password('sekrit')
134     assert p == 'sekrit'
135     assert p != 'not sekrit'
136     assert 'sekrit' == p
137     assert 'not sekrit' != p
139     # crypt
140     p = Password('sekrit', 'crypt')
141     assert p == 'sekrit'
142     assert p != 'not sekrit'
143     assert 'sekrit' == p
144     assert 'not sekrit' != p
146 if __name__ == '__main__':
147     test()
149 # vim: set filetype=python ts=4 sw=4 et si