summaryrefslogtreecommitdiffstats
path: root/index.py
blob: 8d4fe29e10a5c6c70bf54e04b79de0039b6a2887 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
# setup django environment, so we can use their template engine
from django.core.management import setup_environ
from account import settings
setup_environ(settings)

from django.template import Context
from django.template.loader import render_to_string

# mod_python session handling and redirects
from mod_python import Session
from mod_python.util import redirect

# import mysql bindings
import MySQLdb

# trac.ini parsing
import trac.config

# import other common stuff
from random import choice
import base64, cracklib, sha, string, os


# render mail template and send it using local sendmail binary
def sendmail(to_addr, template, c):
	c['from_addr'] = "dev@spline.de"
	c['to_addr'] = to_addr

	msg = render_to_string(template + "_mail.txt", c)

	# open sendmail process for writing
	p = os.popen("/usr/sbin/sendmail -t", 'w')
	p.write(msg)

	# close will return exit status
	# TODO: log error to some file
	if p.close():
		return False

	return True


# cleanup database connection after every request
def closedb(req):
	req.cursor.close()
	req.dbc.close()


# start a new session and context and register the session dictionary in our
# global template context
def session_start(req, anonymous):
	try:
		req.dbc = MySQLdb.connect(host="localhost", user="apache", passwd="password", db="trac")
	except:
		redirect(req, "db_error")

	req.cursor = req.dbc.cursor()
	req.register_cleanup(closedb, req)

	s = Session.Session(req)

	if not 'login' in s:
		s['login'] = None

	s.save()

	req.c = Context()
	req.c['session'] = s

	# None means everyone can acccess this URL
	# True/False means only anonymous/authenticated users can access this URL
	if anonymous != None:
		if (anonymous and s['login']) or (not anonymous and not s['login']):
			redirect(req, "index")

	return (req.c, s, req.cursor)


# generate a htpasswd compatible sha1 digest in base64 encoding
# see: http://httpd.apache.org/docs/2.2/misc/password_encryptions.html
def generate_sha_base64(password):
	return "{SHA}" + base64.encodestring(sha.new(password).digest()).rstrip('\n')


# this function calls /var/www/localhost/scripts/bin/generate_users to create
# project specific htpasswd files
def generate_users_file(cursor):
	cursor.execute("SELECT project_name FROM project WHERE project_name != 'ALL'")
	projects = cursor.fetchall()

	for project in projects:
		cursor.execute("SELECT DISTINCT login, password FROM project_members WHERE password IS NOT NULL AND (project_name = %s OR project_name = 'ALL')", (project[0],))
		users = cursor.fetchall()
		htpasswd = open("/var/www/localhost/users/" + project[0], "w")

		for user in users:
			htpasswd.write("%s:%s\n" % (user[0], user[1]))

		htpasswd.close()

# generate a new random password, save it to the database and send it to the user
# WARNING: this function will do an implicit commit/rollback to the database!
def set_random_password(req, user_id, length):
	req.c['new_password'] = ''.join([choice(string.letters) for i in range(length)])

	pw_hash = generate_sha_base64(req.c['new_password'])
	req.cursor.execute("UPDATE user SET password = %s WHERE id = %s", (pw_hash, user_id))

	req.cursor.execute("SELECT email FROM user WHERE id = %s", (user_id,))
	result = req.cursor.fetchone()
	email = result[0]

	req.cursor.execute("SELECT login FROM user WHERE id = %s AND password NOT NULL", (user_id,))
	result = req.cursor.fetchone()

	if not result:
		template = 'registration'
	else:
		req.c['login'] = result[0]
		template = 'password'

	if not sendmail(email, template, req.c):
		req.dbc.rollback()
		return "failed to send temporary password. sorry."

	# otherwise commit to database and confirm
	req.dbc.commit()
	generate_users_file(req.cursor)
	return None


# Ditch nonsense email addresses.
# taken from http://commandline.org.uk/python/2008/may/3/email-syntax-check/

GENERIC_DOMAINS = "aero", "asia", "biz", "cat", "com", "coop", \
    "edu", "gov", "info", "int", "jobs", "mil", "mobi", "museum", \
    "name", "net", "org", "pro", "tel", "travel"

def invalid(emailaddress, domains = GENERIC_DOMAINS):
    """Checks for a syntactically invalid email address."""

    # Email address must be 7 characters in total.
    if len(emailaddress) < 7:
        return True # Address too short.

    # Split up email address into parts.
    try:
        localpart, domainname = emailaddress.rsplit('@', 1)
        host, toplevel = domainname.rsplit('.', 1)
    except ValueError:
        return True # Address does not have enough parts.

    # Check for Country code or Generic Domain.
    if len(toplevel) != 2 and toplevel not in domains:
        return True # Not a domain name.

    for i in '-_.%+.':
        localpart = localpart.replace(i, "")
    for i in '-_.':
        host = host.replace(i, "")

    if localpart.isalnum() and host.isalnum():
        return False # Email address is fine.
    else:
        return True # Email address has funny characters.


def validate_and_register(req, login, email):
	# check for invalid entries

	# empty login
	if login == "":
		return "please enter a username";

	# no fu-berlin.de address
	if not email.endswith('.fu-berlin.de'):
		return "you did not give a &nbsp;*.fu-berlin.de address"

	# regex checker for valid email
	if invalid(email):
		return "please enter a valid email address";

	req.cursor.execute("SELECT login FROM user WHERE login = %s", (login, ))
	if req.cursor.fetchone():
		return "username already taken, please choose another one"

	req.cursor.execute("SELECT login FROM user WHERE email = %s", (email, ))
	if req.cursor.fetchone():
		return 'you already have an account! <a href="password">forgot your password?</a>'

	# entries are valid - generate activation code and prepare insert statements
	hash = ''.join([choice(string.letters) for i in range(10)])
	req.cursor.execute("INSERT INTO user (login, email, date_added) VALUES (%s, %s, NOW())", (login, email))
	req.cursor.execute("INSERT INTO activation (hash, user_id) VALUES (%s, LAST_INSERT_ID())", (hash, ))

	# send confirmation email to applicant
	req.c['activation_link'] = "https://dev.spline.de/account/activate?hash=" + hash

	# in case of an error, rollback
	if not sendmail(email, 'activation', req.c):
		req.dbc.rollback()
		return "failed to send confirmation link."

	# otherwise commit to database
	req.dbc.commit()
	return None


###############################
#   URL handlers start here   #
###############################

# req = request
def index(req):
	(c, s, cursor) = session_start(req, None)
	return render_to_string("index.html", c)


def activate(req, **formdata):
	(c, s, cursor) = session_start(req, True)

	# check whether a (correct) hashcode is given in the url
	if "hash" in formdata:
		cursor.execute("SELECT user_id FROM activation WHERE hash = %s", (formdata['hash'],))
		result = cursor.fetchone()

		if not result:
			c['error_msg'] = "invalid activation code"
		else:
			user_id = result[0]
			cursor.execute("DELETE FROM activation WHERE user_id = %s", (user_id,))
			cursor.execute("UPDATE user SET activated = 1 WHERE id = %s", (user_id,))

			# send email containing a temporary password
			c['error_msg'] = set_random_password(req, user_id, 8)

			if not c['error_msg']:
				c['info_msg'] = "your account has been activated. you will receive an email with a temporary password."

	# no hash value given
	else:
		redirect(req, "index")

	return render_to_string("index.html", c)


def login(req, **formdata):
	(c, s, cursor) = session_start(req, True)

	if req.method == "POST":
		pw_hash = generate_sha_base64(formdata['password'])
		cursor.execute("SELECT * FROM user WHERE login = %s AND password = %s", (formdata['login'], pw_hash))

		if not cursor.fetchone():
			c['error_msg'] = "Login failed. Sorry."
			return render_to_string("index.html", c)
		else:
			s['login'] = formdata['login']
			s.save()

	redirect(req, 'index')


def logout(req):
	(c, s, cursor) = session_start(req, False)
	s['login'] = None
	s.save()
	redirect(req, 'index')


def register(req, **formdata):
	(c, s, cursor) = session_start(req, True)

	if req.method == "POST":
		c['error_msg'] = validate_and_register(req, formdata['login'], formdata['email'])
		if not c['error_msg']:
			c['info_msg'] = "we have sent an email to " + formdata['email'] + " with your confirmation link"
			return render_to_string("index.html", c)

	return render_to_string("register.html", c)


def password(req, **formdata):
	(c, s, cursor) = session_start(req, True)

	if req.method == 'POST':
		cursor.execute("SELECT id FROM user WHERE email = %s", (formdata['email'],))
		result = cursor.fetchone()

		if not result:
			c['error_msg'] = "unknown email address"
		else:
			c['error_msg'] = set_random_password(req, result[0], 8)

		if not c['error_msg']:
			c['info_msg'] = "a new temporary password has been sent to your email address"
			return render_to_string("index.html", c)

	return render_to_string("password.html", c)


def profile(req, **formdata):
	(c, s, cursor) = session_start(req, False)

	if req.method == 'POST':
		old_pw_hash = generate_sha_base64(formdata['old_pw'])
		cursor.execute("SELECT * FROM user WHERE password = %s AND login = %s", (old_pw_hash,s['login']))

		new_pw_bad = cracklib.FascistCheck(formdata['new_pw1'])

		if not cursor.fetchone():
			c['error_msg'] = "old pasword did not match"

		elif formdata['new_pw1'] != formdata['new_pw2']:
			c['error_msg'] = "new passwords did not match"

		elif new_pw_bad:
			c['error_msg'] = "cannot accept new password: " + new_pw_bad

		else:
			new_pw_hash = generate_sha_base64(formdata['new_pw1'])
			cursor.execute("UPDATE user SET password = %s WHERE login = %s", (new_pw_hash, s['login']))
			req.dbc.commit()
			generate_users_file(req.cursor)

			c['info_msg'] = "new password has been set"
			return render_to_string("index.html", c)

	cursor.execute("SELECT email FROM user WHERE login = %s", (s['login'],))
	result = cursor.fetchone()
	c['email'] = result[0]

	return render_to_string("profile.html", c)


def projects(req, **formdata):
	(c, s, cursor) = session_start(req, False)

	if "action" in formdata and "proj_name" in formdata:
		if formdata['action'] == "leave":
			cursor.execute("delete from member where user_id = (select id from user where login = %s) "
				+ "and project_id = (select id from project where project_name = %s)", (s['login'], formdata['proj_name']))
			req.dbc.commit()
			c['info_msg'] = "you left project " + formdata['proj_name']

		elif formdata['action'] == "delete":
			# check whether the person is member of the project he or she wants to delete
			cursor.execute("select * from member where user_id = (select id from user where login = %s) "
				+ "and project_id = (select id from project where project_name = %s)", (s['login'], formdata['proj_name']))
			if cursor.fetchone() != None:
				cursor.execute("update project set deleted = 1 where project_name = %s", (formdata['proj_name'],))
				req.dbc.commit()
				c['info_msg'] = "you deleted project " + formdata['proj_name']
				c['proj_name'] = formdata['proj_name']
				sendmail("dev@spline.de", "deleted_project", c)

	cursor.execute("select project_name from project p join member m on m.project_id = p.id join user u on u.id = m.user_id where p.deleted <> 1 and u.login = %s", (s['login'],))
	c['projects'] = cursor.fetchall()

	return render_to_string("projects.html", c)


def imprint(req):
	(c, s, cursor) = session_start(req, None)
	return render_to_string("imprint.html", c)

def contact(req):
	(c, s, cursor) = session_start(req, None)
	return render_to_string("contact.html", c)

def new_project(req, **formdata):
	(c, s, cursor) = session_start(req, False)

	if req.method == "POST":
		c['name'] = formdata['project_name']
		c['desc'] = formdata['project_desc']
		c['priv'] = formdata['priv']

		# send message to dev.spline.de
		sendmail("dev@spline.de", "new_project", c)

		# confirm to user
		c['info_msg'] = "your application has been sent to the dev.spline.de team. you'll receive a message shortly"
		return render_to_string("index.html", c)

	return render_to_string("new_project.html", c)


def members(req, **formdata):
	(c, s, cursor) = session_start(req, False)

	if not "proj_name" in formdata:
		redirect(req,"index")

	proj = formdata['proj_name']

	cursor.execute("select id from project where project_name = %s", (proj,))
	result = cursor.fetchone()

	if not result:
		c['error_msg'] = "project '%s' does not exist" % proj
		return render_to_string("index.html", c)

	project_id = result[0]

	# if he/she wants to add/delete members, the logged in user must be a member of the project, too
	cursor.execute("select * from member where user_id = (select id from user where login = %s) "
		+ "and project_id = %s", (s['login'], project_id))

	if cursor.fetchone() == None:
		c['error_msg'] = "you are not a member of project '%s'" % proj

	elif "login" in formdata and "action" in formdata:
		who = formdata['login']
		what = formdata['action']

		cursor.execute("select id from user where login = %s", (who, ))
		result = cursor.fetchone()

		if result:
			user_id = result[0]

			if what == "delete":
				cursor.execute("delete from member where user_id = %s and project_id = %s", (user_id, project_id))
				req.dbc.commit()
				generate_users_file(req.cursor)
				c['info_msg'] = "you deleted " + who + " from project " + proj

			elif what == "add":
				cursor.execute("insert into member (user_id, project_id) values (%s, %s)", (user_id, project_id))
				req.dbc.commit()
				c['info_msg'] = "you added " + who + " to project " + proj

		else:
			c['error_msg'] = "invalid user name"

	cursor.execute("select login from user u join member m on u.id = m.user_id "
			+ "where m.project_id = (select id from project where project_name = %s)", (proj,))
	c['members'] = cursor.fetchall()
	c['proj'] = proj

	return render_to_string("members.html", c)


def del_profile(req):
	(c, s, cursor) = session_start(req, False)

	cursor.execute("delete from user where login = %s", (s['login'], ))
	req.dbc.commit()
	generate_users_file(req.cursor)

	s['login'] = None
	s.save()

	c['info_msg'] = "your profile has been deleted successfully"

	return render_to_string("index.html", c)


def list_projects(req):
	(c, s, cursor) = session_start(req, None)

	cursor.execute("SELECT project_name FROM project WHERE private = 0 AND project_name != 'ALL' ORDER BY project_name")
	result = cursor.fetchall()

	c['public_projects'] = []

	for project in result:
		ini = trac.config.Configuration('/var/lib/trac/' + project[0] + '/conf/trac.ini')
		c['public_projects'].append((project[0], ini.get('project', 'name'), ini.get('project','descr')))

	cursor.execute("SELECT project_name FROM project WHERE private = 1 AND project_name != 'ALL' ORDER BY project_name")
	result = cursor.fetchall()

	c['private_projects'] = []

	for project in result:
		ini = trac.config.Configuration('/var/lib/trac/' + project[0] + '/conf/trac.ini')
		c['private_projects'].append((project[0], ini.get('project', 'name'), ini.get('project','descr')))

	return render_to_string("list_projects.html", c)


def genusers(req):
	(c, s, cursor) = session_start(req, None)
	generate_users_file(cursor)
	return "OK"

# this is returned whenever a db error occurs
def db_error(req):
  return render_to_string("db_error.html")