0e93517fcec53092fdf227e50a051aec61412b35
[matthijs/projects/wipi.git] / conf / auth / phpbb_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 from MoinMoin import log
14 logging = log.getLogger(__name__)
15
16 class phpbb_login(BaseAuth):
17     logout_possible = True
18     login_inputs    = ['username', 'password']
19     
20     def __init__(self, name='phpbb', dbhost=None, dbuser=None, dbpass=None, dbname=None, dbport=None, hint=None):
21         """
22             Authenticate using credentials from a phpbb database
23
24             The name parameter should be unique among all authentication methods.
25
26             The hint parameter is a snippet of HTML that is displayed below the login form.
27         """
28         self.dbhost  = dbhost
29         self.dbuser  = dbuser
30         self.dbpass  = dbpass
31         self.dbname  = dbname
32         self.dbport  = dbport
33         self.name    = name
34         self.hint    = hint
35     
36     def check_login(self, request, username, password):
37         """ Checks the given username password combination. Returns the
38         corresponding emailaddress, or False if authentication failed.
39         """
40         conn = self.connect(request)
41
42         if not conn:
43             return False
44
45         # Get some data
46         cursor = conn.cursor ()
47         cursor.execute ("SELECT user_password,user_email FROM lex_users WHERE username=%s", username)
48
49         # No data? No login.
50         if (cursor.rowcount == 0):
51             conn.close()
52             return False
53        
54         # Check password
55         row = cursor.fetchone()
56         conn.close()
57
58         if (md5.new(password).hexdigest() == row[0]):
59             return row[1]
60         else:
61             return False
62
63     def connect(self, request):
64         # This code was shamelessly stolen from
65         # django.db.backends.mysql.base.cursor
66         kwargs = {
67             'charset': 'utf8',
68             'use_unicode': False,
69         }
70         if self.dbuser:
71             kwargs['user'] = self.dbuser
72         if self.dbname:
73             kwargs['db'] = self.dbname
74         if self.dbpass:
75             kwargs['passwd'] = self.dbpass
76         if self.dbhost.startswith('/'):
77             kwargs['unix_socket'] = self.dbhost
78         elif self.dbhost:
79             kwargs['host'] = self.dbhost
80         if self.dbport:
81             kwargs['port'] = int(self.dbport)
82
83         # End stolen code
84
85         try:
86             conn = MySQLdb.connect (**kwargs)
87         except:
88             import sys
89             import traceback
90             info = sys.exc_info()
91             logging.error("phpbb_login: authentication failed due to exception connecting to DB, traceback follows...")
92             logging.error(''.join(traceback.format_exception(*info)))
93             return False
94
95         return conn
96
97     def login(self, request, user_obj, **kw):
98         try:
99             username = kw.get('username')
100             password = kw.get('password')
101
102             logging.debug("phpbb_login: Trying to log in, username=%r " % (username))
103            
104             # simply continue if something else already logged in
105             # successfully
106             if user_obj and user_obj.valid:
107                 return ContinueLogin(user_obj)
108
109             # Deny empty username or passwords
110             if not username or not password:
111                 return ContinueLogin(user_obj)
112
113             email = self.check_login(request, username, password)
114             
115             # Login incorrect
116             if (not email):
117                 logging.debug("phpbb_login: authentication failed for %s" % (username))
118                 return ContinueLogin(user_obj)
119
120             logging.debug("phpbb_login: authenticated %s (email %s)" % (username, email))
121
122             u = user.User(request, auth_username=username, auth_method=self.name, auth_attribs=('name', 'password', 'email'))
123             u.email = email
124             #u.remember_me = 0 # 0 enforces cookie_lifetime config param
125             u.create_or_update(True)
126
127             return ContinueLogin(u)
128         except:
129             import sys
130             import traceback
131             info = sys.exc_info()
132             logging.error("phpbb_login: authentication failed due to unexpected exception, traceback follows...")
133             logging.error(''.join(traceback.format_exception(*info)))
134             return ContinueLogin(user_obj)
135
136     def login_hint(self, request):
137         """ Return a snippet of HTML that is displayed with the login form. """
138         return self.hint
139
140 # vim: set sw=4 expandtab sts=4:vim