Update mysql_login to moin 1.8.
[matthijs/projects/wipi.git] / conf / auth / mysql_login.py
1 # -*- coding: iso-8859-1 -*-
2 """
3     MoinMoin - auth plugin doing a check against MySQL db
4
5     @copyright: 2008 Matthijs Kooijman
6     @license: GNU GPL, see COPYING for details.
7 """
8
9 import MySQLdb
10 import md5
11 from MoinMoin import user
12 from MoinMoin.auth import BaseAuth, ContinueLogin
13
14 class mysql_login(BaseAuth):
15     logout_possible = True
16     login_inputs    = ['username', 'password']
17     
18     def __init__(self, name='mysql', dbhost=None, dbuser=None, dbpass=None, dbname=None, dbport=None, verbose=False):
19         """
20             Authenticate using credentials from a mysql database
21         """
22         self.verbose = verbose
23         self.dbhost  = dbhost
24         self.dbuser  = dbuser
25         self.dbpass  = dbpass
26         self.dbname  = dbname
27         self.dbport  = dbport
28         self.name    = name
29     
30     def check_login(self, request, username, password):
31         """ Checks the given username password combination. Returns the
32         corresponding emailaddress, or False if authentication failed.
33         """
34         conn = self.connect(request)
35
36         if not conn:
37             return False
38
39         # Get some data
40         cursor = conn.cursor ()
41         cursor.execute ("SELECT user_password,user_email FROM lex_users WHERE username=%s", username)
42
43         # No data? No login.
44         if (cursor.rowcount == 0):
45             conn.close()
46             return False
47        
48         # Check password
49         row = cursor.fetchone()
50         conn.close()
51
52         if (md5.new(password).hexdigest() == row[0]):
53             return row[1]
54         else:
55             return False
56
57     def connect(self, request):
58         # This code was shamelessly stolen from
59         # django.db.backends.mysql.base.cursor
60         kwargs = {
61             'charset': 'utf8',
62             'use_unicode': False,
63         }
64         if self.dbuser:
65             kwargs['user'] = self.dbuser
66         if self.dbname:
67             kwargs['db'] = self.dbname
68         if self.dbpass:
69             kwargs['passwd'] = self.dbpass
70         if self.dbhost.startswith('/'):
71             kwargs['unix_socket'] = self.dbhost
72         elif self.dbhost:
73             kwargs['host'] = self.dbhost
74         if self.dbport:
75             kwargs['port'] = int(self.dbport)
76
77         # End stolen code
78
79         try:
80             conn = MySQLdb.connect (**kwargs)
81         except:
82             import sys
83             import traceback
84             info = sys.exc_info()
85             request.log("mysql_login: authentication failed due to exception connecting to DB, traceback follows...")
86             request.log(''.join(traceback.format_exception(*info)))
87             return False
88
89         return conn
90
91     def login(self, request, user_obj, **kw):
92         try:
93             username = kw.get('username')
94             password = kw.get('password')
95
96             if self.verbose: request.log("mysql_login: Trying to log in, username=%r " % (username))
97            
98             # simply continue if something else already logged in
99             # successfully
100             if user_obj and user_obj.valid:
101                 return ContinueLogin(user_obj)
102
103             # Deny empty username or passwords
104             if not username or not password:
105                 return ContinueLogin(user_obj)
106
107             email = self.check_login(request, username, password)
108             
109             # Login incorrect
110             if (not email):
111                 if self.verbose: request.log("mysql_login: authentication failed for %s" % (username))
112                 return ContinueLogin(user_obj)
113
114             if self.verbose: request.log("mysql_login: authenticated %s (email %s)" % (username, email))
115
116             u = user.User(request, auth_username=username, auth_method=self.name, auth_attribs=('password', 'email', ))
117             u.email = email
118             #u.remember_me = 0 # 0 enforces cookie_lifetime config param
119             u.create_or_update(True)
120
121             return ContinueLogin(u)
122         except:
123             import sys
124             import traceback
125             info = sys.exc_info()
126             request.log("mysql_login: authentication failed due to unexpected exception, traceback follows...")
127             request.log(''.join(traceback.format_exception(*info)))
128             return ContinueLogin(user_obj)
129
130 # vim: set sw=4 expandtab sts=4:vim