/[glsr]/trunk/site/user.py
Gentoo

Contents of /trunk/site/user.py

Parent Directory Parent Directory | Revision Log Revision Log


Revision 171 - (show annotations) (download) (as text)
Sun Oct 30 19:42:41 2005 UTC (8 years, 10 months ago) by hadfield
File MIME type: text/x-python
File size: 10560 byte(s)
modified code to work with the new framework
1 # Copyright 2005 Gentoo Foundation
2 # Distributed under the terms of the GNU General Public License v2
3 #
4
5 """The DB access module for the User table.
6
7 Implements all functions necessary for obtaining or setting any user database
8 attributes.
9 """
10
11 __revision__ = "$Id$"
12 __authors__ = ["Scott Hadfield <hadfield@gentoo.org>",
13 "Ian Leitch <port001@gentoo.org>"]
14 __modulename__ = "user"
15
16 import md5
17
18 from glsr.setup import config
19 from glsr.core.db.mysql import SQLdb
20
21 GUEST = 0
22 USER = 1
23 DEVELOPER = 2
24 ADMIN = 3
25
26 def md5_passwd(passwd):
27
28 md5_obj = md5.new()
29 md5_obj.update(passwd)
30
31 return md5_obj.hexdigest()
32
33 def create_user(username = "", email = "", passwd = "", fullname = "",
34 language = "", location = "", website = "", user_type = 0):
35 """Add a new user record to the database."""
36
37 SQLdb(config.db).query(
38 "INSERT INTO %(prefix)suser " % {'prefix': config.db['prefix']} +
39 "(user_alias, user_fullname, user_passwd, user_email, user_rank," +
40 " user_type, user_joined, user_language, user_location," +
41 " user_website) VALUES (%s, %s, %s, %s, 0, %s, NOW(), %s, %s, %s)",
42 (str(username), str(fullname), str(md5_passwd(passwd)), str(email),
43 str(user_type), str(language), str(location), str(website)),
44 fetch='none')
45
46 def list_all(columns = None, constraint = None):
47 """Return selected columns from all rows in the user table.
48
49 columns should be a list containing the desired columns.
50 The constraint variable is a dictionary of (column, value) pairs that
51 requires column == value in order for that row to be returned. Note that
52 multiple constraints are joined by AND, so the constraints are fairly
53 constrained ;).
54 """
55
56 # FIXME: Sanity checks on column names and contrainst keys.
57 # Without this we could have mysql injection attacks.
58
59 if columns is None:
60 return []
61 else:
62 columns = ", ".join(columns)
63
64 where_clause = ""
65 if constraint is not None:
66 where_clause = " AND ".join(["user_%s = %%s" % key
67 for key in constraint])
68 if where_clause != "":
69 where_clause = "WHERE " + where_clause
70 else:
71 constraint = {}
72
73 results = SQLdb(config.db).query(
74 "SELECT %(columns)s FROM %(prefix)suser %(where)s" %
75 {'columns': columns, 'prefix': config.db['prefix'],
76 'where': where_clause}, constraint.values(), fetch="all")
77
78 return results
79
80 def _get_uid_by_attr(attr, value):
81 """Return the uid described by the given attribute/value pair.
82
83 attr should be a valid field in the user table.
84 """
85
86 result = SQLdb(config.db).query(
87 "SELECT user_id FROM %(prefix)suser " %
88 {'prefix': config.db['prefix']} +
89 "WHERE %(attr)s = %%s" % {'attr': attr}, str(value), fetch = 'one')
90
91 if result != None:
92 return result['user_id']
93
94 return None
95
96 def get_uid_by_alias(alias):
97 """Return the uid described by the given alias."""
98 return _get_uid_by_attr("user_alias", str(alias))
99
100 def get_uid_by_sid(sid):
101 """Return the uid described by the given sid."""
102 return _get_uid_by_attr("user_sid", str(sid))
103
104 def get_uid_by_email(email):
105 """Return the uid described by the given email."""
106 return _get_uid_by_attr("user_email", str(email))
107
108 def uid_exists(uid):
109 """Verify the existance of the specified uid."""
110
111 result = SQLdb(config.db).query(
112 "SELECT user_id FROM %suser " % config.db["prefix"] +
113 "WHERE user_id = %s", uid, fetch = "one")
114
115 if result is None:
116 return False
117 return True
118
119
120 def profile_fieldparser(request, error_method):
121
122 from glsr.core import fieldparse
123 from framework.utils import html_escape
124
125 parser = fieldparse.FieldParser(request = request,
126 error_method = error_method)
127 parser.add_field("user_id", required = True, ftype = "int")
128 #parser.add_field("username", required = True, fmin = 2, fmax = 25)
129 parser.add_field("password", required = True, fmin = 6, fmax = 32)
130 parser.add_field("password_confirm", required = True,
131 fmin = 6, fmax = 32)
132 parser.add_field("email", required = True, ffilter = html_escape)
133 parser.add_field("fullname", default = "", max_size = 40,
134 regex = r'^[\w\- ]+$', ffilter = html_escape)
135 parser.add_field("location", default = "", max_size = 100,
136 regex = r'^[\w\-\,\.0-9\:\/ ]+$',
137 ffilter = html_escape)
138 parser.add_field("language", default = "", max_size = 100,
139 regex = r'^[\w0-9\-\+\# ]+$', ffilter = html_escape)
140 parser.add_field("website", default = "", max_size = 100,
141 regex = r'^[\/:\w\-\.\~\?\#0-9]+$',
142 ffilter = html_escape)
143 parser.add_field("user_type", ffilter = html_escape)
144
145 fields = parser.parse_form()
146 return fields
147
148 def setup_params(profile_user, real_user, template):
149 """Sets up the common variables used in the profile pages."""
150
151 template.param("USERNAME", profile_user.get_alias())
152 template.param("USER_ID", profile_user.get_uid())
153 template.param("JOINED", _empty(profile_user.get_joined()))
154 template.param("TYPE", _empty(profile_user.get_type()))
155 template.param("RANK", _empty(profile_user.get_rank()))
156 template.param("LOCATION", _empty(profile_user.get_location()))
157 template.param("WEBSITE", _empty(profile_user.get_website()))
158 template.param("LANGUAGE", _empty(profile_user.get_language()))
159 template.param("LAST_IP", _empty(profile_user.get_last_ip()))
160 template.param("FULLNAME", _empty(profile_user.get_fullname()))
161 template.param("EMAIL", _empty(profile_user.get_email()))
162
163 if real_user.get_type() == ADMIN:
164 template.param("ADMIN", "1")
165 else:
166 template.param("ADMIN", "0")
167
168 def _empty(value):
169 """Simple method that converts None's to ""."""
170 if value is None:
171 return ""
172 return value
173
174 class User:
175 """Defines the get and set attributes for a User."""
176
177 def __init__(self, uid):
178
179 self._db = SQLdb(config.db)
180 self._uid = uid
181
182 def _get_attr(self, attr):
183 """Return the value of the specified attribute, or DB field."""
184
185 result = self._db.query(
186 "SELECT %(attr)s FROM %(prefix)suser " %
187 {'attr': attr, 'prefix': config.db['prefix']} +
188 "WHERE user_id = %s", str(self._uid), fetch='one')
189
190 if result != None:
191 return result[attr]
192
193 return None
194
195 def _set_attr(self, attr, value):
196 """Set attr to the specified value, where attr is a valid DB field."""
197
198 self._db.query(
199 "UPDATE %(prefix)suser " % {'prefix': config.db['prefix']} +
200 "SET %(attr)s = %%s WHERE user_id = %%s" % {'attr': attr},
201 (value, str(self._uid)), fetch='none')
202
203 def count_scripts(self):
204 """Returns the number of scripts this user has created."""
205
206 # TODO: Mabye this should only count finalized scripts?
207 results = self._db.query(
208 "SELECT COUNT(*) as count FROM %sscript " % config.db["prefix"] +
209 "WHERE script_submitter_id = %s" % self._uid,
210 fetch = "one")
211
212 return results["count"]
213
214 def get_alias(self):
215 """Return this user's alias."""
216 return self._get_attr("user_alias")
217
218 def get_email(self):
219 return self._get_attr("user_email")
220
221 def get_fullname(self):
222 return self._get_attr("user_fullname")
223
224 def get_joined(self):
225 return self._get_attr("user_joined")
226
227 def get_language(self):
228 return self._get_attr("user_language")
229
230 def get_last_ip(self):
231 """Return this user's last IP address."""
232 return self._get_attr("user_lastip")
233
234 def get_location(self):
235 return self._get_attr("user_location")
236
237 def get_passwd(self):
238 """Return this user's password."""
239 return self._get_attr("user_passwd")
240
241 def get_rank(self):
242 return self._get_attr("user_rank")
243
244 def get_session(self):
245 """Return this user's session ID."""
246 return self._get_attr("user_sid")
247
248 def get_type(self):
249 """Return the user's type"""
250 return self._get_attr("user_type")
251
252 def get_website(self):
253 return self._get_attr("user_website")
254
255 def get_uid(self):
256 return self._uid
257
258 def remove_session(self):
259 """Remove the session associated with this user."""
260 self._db.query(
261 "UPDATE %(prefix)suser " % {'prefix': config.db['prefix']} +
262 "SET user_sid = NULL WHERE user_id = %s", str(self._uid),
263 fetch='none')
264
265 def set_session(self, sid):
266 """Set this user's session to the given session ID."""
267 return self._set_attr('user_sid', str(sid))
268
269 def set_last_ip(self, ip):
270 """Set this user's session to the given IP address."""
271 return self._set_attr('user_lastip', str(ip))
272
273 def type_name(self):
274
275 user_type = self.get_type()
276 if user_type == USER:
277 retval = "user"
278 elif user_type == DEVELOPER:
279 retval = "developer"
280 elif user_type == ADMIN:
281 retval = "admin"
282 else:
283 retval = "guest"
284
285 return retval
286
287 def update(self, email = "", passwd = None, fullname = "",
288 language = "", location = "", website = "", user_type = ""):
289
290 set_str = ("user_fullname = %s, user_email = %s, user_type = %s, " +
291 "user_language = %s, user_location = %s, user_website = %s")
292
293 if passwd is None or passwd == "":
294 self._db.query(
295 "UPDATE %(prefix)suser " % {'prefix': config.db['prefix']} +
296 "SET %s WHERE user_id = %%s" % set_str,
297 (fullname, email, user_type, language, location, website,
298 self._uid), fetch='none')
299
300 else:
301 self._db.query(
302 "UPDATE %(prefix)suser " % {'prefix': config.db['prefix']} +
303 "SET %s, user_passwd = %%s WHERE user_id = %%s" % set_str,
304 (fullname, email, user_type, language, location, website,
305 str(md5_passwd(passwd)), self._uid), fetch='none')
306
307 def delete(self):
308 self._db.query(
309 "DELETE FROM %(prefix)suser " % {'prefix': config.db['prefix']} +
310 "WHERE user_id = %s", self._uid, fetch = "none")
311

Properties

Name Value
svn:keywords Id

  ViewVC Help
Powered by ViewVC 1.1.20