summaryrefslogtreecommitdiffstats
path: root/py-bin/jabberman.py
blob: fd131dae36efb3ab556c5558efdd8a63ccf81bef (plain)
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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
#jabber manager

import shelve, sqlite3, atexit, bcrypt, sha, hmac, random, os, time, re, datetime, string
import config
from ejabberdctl import EJabberdCtl

class JabberUserOld:
	def __init__(self, user_id):
		self.user, self.domain = user_id.split("@")
		self.accounts = []
		
	def get_user_id(self):
		return self.user + "@" + self.domain
		
	def get_default_jabber_id(self):
		return self.user + "@jabber." + self.domain
		
	def is_active(self):
		return hasattr(self, "password_hash")

	def check_password(self, password):
		if not self.is_active():
			return False
		return self.password_hash == self.__hash_password(password)

	def set_password(self, password):
		self.password_hash = self.__hash_password(password)
		
	def __hash_password(self, password):
		return sha.new(password).hexdigest()
	
	@staticmethod
	def generate_token():
		data = str(random.getrandbits(256)) + str(time.time()*1000) + str(os.getpid())
		return "+" + hmac.new(config.the_secret, data, sha).hexdigest()
	
	def set_token(self, token):
		self.token = token
		
	def validate_token(self, token):
		if token[1:] == self.token[1:]:
			if self.__is_token_expired():
				return (False, "Benutzerkonto bereits aktiviert.")
			return (True, self)
		else:
			return (False, "Zugriff verweigert.")
		
	def __is_token_expired(self):
		return self.token[0] != "+"
	
	def expire_token(self):
		self.token = "-" + self.token[1:]
		
	def add_account(self, jabber_id):
		self.accounts.append(jabber_id)
		
	def has_account(self, jabber_id):
		return jabber_id in self.accounts
		
	def get_account_list(self):
		return list(self.accounts)
		
	def get_extra_account_list(self):
		default_acc = self.get_default_jabber_id()
		return filter(lambda acc: acc != default_acc, self.accounts)
		
	def remove_account(self, jabber_id):
		self.accounts.remove(jabber_id)

class JabberAccountOld:
	def __init__(self, jabber_id):
		self.user, self.server = jabber_id.split("@")
	
	def get_jabber_id(self):
		return self.user + "@" + self.server

# FIXME: error handling (especially sqlite)
# FIXME: use cryptographically secure RNG fro token generation
# FIXME: what about time-zones? was utcnow ok?
# FIXME: handle transactions properly
# TODO: create dummy "unit-test" based on a db fixture

class JabberUser:
	def __init__(self, id, jid, password, web_user_id):
		self.id, self.jid, self.password, self.web_user_id = id, jid, password, web_user_id
	
	def get_jabber_id(self):
		return self.jid
	
	@staticmethod
	def generate_token():
		data = str(random.getrandbits(256)) + str(time.time()*1000) + str(os.getpid())
		return "+" + hmac.new(config.the_secret, data, sha).hexdigest()
	
	def set_token(self, token):
		self.token = token

class WebUser:
	def __init__(self, id, email, token, token_date):
		self.id, self.email, self.token, self.token_date = id, email, token, token_date

	def get_primary_jid(self):
		user, server = self.email.split("@")
		return user + "@jabber." + server 

class JabberDB:
	def __init__(self):
		self.__connection = sqlite3.connect(config.sqlite_path)
		atexit.register(self.__connection.close) # FIXME: test that!
		
	def login_user(self, user_id, password):
		user = self.get_web_user(user_id)
		primary_jid = user.get_primary_jid()
		if user and self.validate_jid(primary_jid, password):
			return user
		return None
		
	def generate_token(self, user_id):
		if self.get_web_user(user_id):
			return (False, "Benutzer existiert bereits!")
		
		return (True, JabberUser.generate_token())
		
	def prepare_user(self, user_id):
		if self.get_web_user(user_id):
			return (False, "Benutzer existiert bereits!")
			
		#user = JabberUser(user_id)
		#user.set_token(token)
		#self.__store_user(user)
		generate_web_user(user_id)
		
		return (True, "Benutzer registriert, Aktivierung noch ausstehend.")
		
	def validate_token(self, user_id, token):
		user = self.get_web_user(user_id)
		if not user:
			return (False, "Zugriff verweigert.")
		#fixme: is this actually needed?
		return user.token == token
	
	def activate_user(self, user_id, password, token):
		user = self.get_web_user(user_id)
		if not user:
			return (False, "Zugriff verweigert.")
		
		success = update_web_user(self, user_id, password, token)
		if not success:
			return (False, status)
		
		return (True, user)
		
	def add_account(self, user_id, jabber_id, password, check_only = False):
		user = self.get_web_user(user_id)
		if not user:
			return (False, "Zugriff verweigert.")
		
		account = self.is_jid(jabber_id)
		if account:
			return (False, "Sorry, Jabber Benutzerkonto %s bereits vergeben." % jabber_id)
		
		if check_only:
			return (True, "Jabber kann hinzugefuegt werden.")
		
		self.create_jid(jabber_id, password, user.id)
		
		return (True, "Jabber Konto hinzugefuegt.")
	
	def remove_account(self, user_id, jabber_id, check_only = False):
		user = self.get_web_user(user_id)
		if (not user) or (not user.has_account(jabber_id)):
			return (False, "Zugriff verweigert.")
			
		if check_only:
			return (True, "Jabber darf geloescht werden.")
		
		self.delete_jid(jabber_id)
		
		return (True, "Jabber Konto geloescht.")
		
	def change_primary_jid_password(self, user_id, password):
		user = self.get_web_user(user_id)
		if not user:
			return (False, "Zugriff verweigert.")
		
		primary_jid = user.get_primary_jid()
		self.update_jid(primary_jid, password)
		return (True, "Passwort geaendert.")

	def generate_web_user(self, email):
		token = str(random.getrandbits(60))
		print token
		token_date = datetime.datetime.utcnow()

		cur = self.__connection.cursor()
		cur.execute("INSERT INTO web_users VALUES (NULL,?,?,?)", (email, token, token_date))
		self.__connection.commit()

	def get_web_user(self, email):
		cur = self.__connection.cursor()
		cur.execute("SELECT * FROM web_users where email=?", (email,))
		row = cur.fetchone()
		#FIXME: fix this call
		return WebUser(row[0],row[1],row[2],row[3])

	def update_web_user(self, email, plain_pwd, provided_token):
		cur = self.__connection.cursor()
		cur.execute("SELECT * FROM web_users where email=?", (email,))
		row = cur.fetchone()
		if row == None:
			return False
		web_user_id, token, token_date = row[0]

		if provided_token != token:
			return False

		cur.execute("UPDATE web_users SET token=NULL WHERE web_user_id=?", (web_user_id,))
		self.__connection.commit()

		user, domain = email.split("@")
		jid = user + "@jabber." + domain
		self.create_jid(jid, plain_pwd, web_user_id)
		return True

	def validate_jid(self, jid, plain_pwd):
		cur = self.__connection.cursor()
		cur.execute("SELECT * FROM jabber_users where jid=?", (jid,))
		row = cur.fetchone()

		if row == None:
			return False
		crypted_pwd = row[2]
		return crypted_pwd == bcrypt.hashpw(plain_pwd, crypted_pwd)

	def create_jid(self, jid, plain_pwd, web_user_id):
		crypted_pwd = bcrypt.hashpw(plain_pwd, bcrypt.gensalt());

		cur = self.__connection.cursor()
		cur.execute("INSERT INTO jabber_users VALUES (NULL,?,?,?)", (jid, crypted_pwd, web_user_id))
		self.__connection.commit()

	def update_jid(self, jid, plain_pwd):
		crypted_pwd = bcrypt.hashpw(plain_pwd, bcrypt.gensalt());

		cur = self.__connection.cursor()
		cur.execute("UPDATE jabber_users SET password=?", (crypted_pwd,))
		self.__connection.commit()
		return True

	def is_jid(self, jid):
		cur = self.__connection.cursor()
		cur.execute("SELECT * FROM jabber_users where jid=?", (jid,))
		row = cur.fetchone()
		return row != None and row[1] == jid

	def delete_jid(self, jid):
		cur = self.__connection.cursor()
		cur.execute("DELETE FROM jabber_users WHERE jid=?", (jid,))
		self.__connection.commit()

	def delete_web_user(self, email):
		cur = self.__connection.cursor()
		cur.execute("DELETE FROM web_users WHERE email=?", (email,))
		self.__connection.commit()

	def select_jids(self, email):
		cur = self.__connection.cursor()
		cur.execute("SELECT * FROM web_users where email=?", (email,))
		row = cur.fetchone()
		web_user_id = row[0]

		cur.execute("SELECT * FROM jabber_users where web_user_id=?", (web_user_id,))
		rows = cur.fetchall()

		#FIXME: return typed jids
		return rows

	def select_web_users(self):
		cur = self.__connection.cursor()
		cur.execute("SELECT * FROM web_users")
		rows = cur.fetchall()

		#FIXME: return typed web users
		return rows
		


class JabberDBOld:
	def __init__(self):
		self.db = shelve.open(config.jabberdb_path, 'c')
		atexit.register(self.db.close)
		
	def login_user(self, user_id, password):
		user = self.__load_user(user_id)
		if user and user.check_password(password):
			return user
		return None
		
	def generate_token(self, user_id):
		if self.__load_user(user_id):
			return (False, "Benutzer existiert bereits!")
		
		return (True, JabberUser.generate_token())
		
	def prepare_user(self, user_id, token):
		if self.__load_user(user_id):
			return (False, "Benutzer existiert bereits!")
			
		user = JabberUser(user_id)
		user.set_token(token)
		self.__store_user(user)
		
		return (True, "Benutzer registriert, Aktivierung noch ausstehend.")
		
	def validate_token(self, user_id, token):
		user = self.__load_user(user_id)
		if not user:
			return (False, "Zugriff verweigert.")
		
		return user.validate_token(token)
	
	def activate_user(self, user_id, password, token):
		user = self.__load_user(user_id)
		if not user:
			return (False, "Zugriff verweigert.")
			
		ok, status = user.validate_token(token)
		if not ok:
			return (False, status)
			
		user.expire_token()
		user.set_password(password)
		self.__store_user(user)
		
		return (True, user)
		
	def add_account(self, user_id, jabber_id, check_only = False):
		user = self.__load_user(user_id)
		if not user:
			return (False, "Zugriff verweigert.")
		
		account = self.__load_account(jabber_id)
		if account:
			return (False, "Sorry, Jabber Benutzerkonto %s bereits vergeben." % jabber_id)
		
		if check_only:
			return (True, "Jabber kann hinzugefuegt werden.")
		
		account = JabberAccount(jabber_id)
		self.__store_account(account)
		user.add_account(jabber_id)
		self.__store_user(user)
		
		return (True, "Jabber Konto hinzugefuegt.")
	
	def remove_account(self, user_id, jabber_id, check_only = False):
		user = self.__load_user(user_id)
		if (not user) or (not user.has_account(jabber_id)):
			return (False, "Zugriff verweigert.")
			
		if check_only:
			return (True, "Jabber darf geloescht werden.")
		
		self.__delete_account(jabber_id)
		user.remove_account(jabber_id)
		self.__store_user(user)
		
		return (True, "Jabber Konto geloescht.")
		
	def change_password(self, user_id, password):
		user = self.__load_user(user_id)
		if not user:
			return (False, "Zugriff verweigert.")
		
		user.set_password(password)
		self.__store_user(user)
		return (True, "Passwort geaendert.")
		
	def __load_user(self, user_id):
		return self.db.get("#usr#" + user_id)
		
	def __store_user(self, user):
		self.db["#usr#" + user.get_user_id()] = user
	
	def __load_account(self, jabber_id):
		return self.db.get("#acc#" + jabber_id)
		
	def __store_account(self, account):
		self.db["#acc#" + account.get_jabber_id()] = account
		
	def __delete_account(self, jabber_id):
		del(self.db["#acc#" + jabber_id])


class JabberManager:
	def __init__(self, session):
		self.jadb = JabberDB()
		self.session = session
		self.current_user, self.authenticated = None, False
		self.ejctl = EJabberdCtl()
		
	def get_user(self):
		return self.current_user
		
	def authenticate(self):
		if self.authenticated == True:
			return True 
		if (not "uid" in self.session) or (not "pass" in self.session):
			return (False, "Nicht angemeldet.")
		ok, status_or_user = self.login(
			self.session["uid"], self.session["pass"])
		return (ok, status_or_user)
		
	def login(self, user_id, password):
		ok, status = self.check_user_id(user_id)
		if not ok:
			return (False, status)
		
		self.current_user = self.jadb.login_user(user_id, password)
		if self.current_user:
			self.__set_session(user_id, password = password)
		else:
			self.__clear_session()
			return (False, "Benutzername oder Passwort falsch.")

		self.authenticated = True
		return (True, self.current_user)
		
	def logout(self):
		self.current_user, self.authenticated = None, False
		self.__clear_session()
		
	def generate_token(self, user_id):
		ok, status = self.check_user_id(user_id)
		if not ok:
			return (False, status)
		
		return self.jadb.generate_token(user_id)
	
	def prepare_user(self, user_id, token):
		ok, status = self.check_user_id(user_id)
		if not ok:
			return (False, status)
		
		return self.jadb.prepare_user(user_id, token)
		
	def validate_token(self, user_id, token):
		if user_id == "":
			try:
				user_id, token = self.session["uid"], self.session["tok"]
			except Exception:
				return (False, "Zugriff verweigert.")
		
		ok, status = self.check_user_id(user_id)
		if not ok:
			return (False, "Zugriff verweigert.")
		
		ok, status_or_user = self.jadb.validate_token(user_id, token)
		if ok:
			self.current_user = status_or_user
			self.__set_session(user_id, token = token)
		return (ok, status_or_user)
	
	def activate_user(self, password):
		try:
			user_id, token = self.session["uid"], self.session["tok"]
		except Exception:
			return (False, "Zugriff verweigert.")
		ok, status = self.check_user_id(user_id)
		if not ok:
			return (False, "Zugriff verweigert.")

		ok, status_or_user = self.jadb.activate_user(user_id, password, token) 
		if ok:
			self.current_user, self.authenticated = status_or_user, True
			self.__set_session(user_id, password = password)
		else:
			self.__clear_session()
			return (False, status_or_user)
		
		ok, status = self.add_account(self.current_user.get_default_jabber_id())
		if not ok:
			#todo: handle this smarter somehow
			return (False, status)
		
		return (True, status)
		
	def change_password(self, password):
		if not self.authenticated:
			return (False, "Zugriff verweigert.")
		
		user_id = self.current_user.get_user_id()
		ok, status = self.jadb.change_password(user_id, password) 
		if ok:
			self.__set_session(user_id, password = password)
		else:
			self.__clear_session()
			return (False, status)
		
		for jabber_id in self.current_user.get_account_list():
			acc = JabberAccount(jabber_id)
			if not self.ejctl.change_password(acc.user, acc.server, password):
				msg = "Konnte Jaber Passwort fuer %s nicht setzen." % acc.get_jabber_id()
				return (False, msg)
		
		return (True, "Passwort erfolgreich geaendert.")
		
	def is_acceptable_password(self, password, password2):
		if password != password2:
			return (False, "Passwoerter nicht identisch.")
		if len(password) < config.min_password_length:
			return (False, "Passwort ist zu kurz.")
		if not re.match(config.password_re, password):
			return (False, "Passwort enthaelt unerlaubte Zeichen.")
		return (True, "Passwort OK.")
	
	def add_account(self, jabber_id):
		if not self.authenticated:
			return (False, "Zugriff verweigert.")
			
		ok, status = JabberManager.check_jabber_id(jabber_id)
		if not ok:
			return (False, status)
		
		acc = JabberAccount(jabber_id)
		try:
			password = self.session["pass"]
		except Exception:
			return (False, "Zugriff verweigert.")
		
		user_id = self.current_user.get_user_id()
		ok, status = self.jadb.add_account(user_id, jabber_id, check_only = True)
		if not ok:
			return (False, status)
		
		if not self.ejctl.create_account(acc.user, acc.server, password):
			return (False, "Konnte Konto %s nicht erstellen." % acc.get_jabber_id())
			
		user_id = self.current_user.get_user_id()
		return self.jadb.add_account(user_id, jabber_id)
		
	def remove_account(self, jabber_id):
		if not self.authenticated:
			return (False, "Zugriff verweigert.")
			
		ok, status = JabberManager.check_jabber_id(jabber_id)
		if not ok:
			return (False, "Zugriff verweigert.")
		
		user_id = self.current_user.get_user_id()
		if jabber_id == self.current_user.get_default_jabber_id():
			return (False, "Hauptkonto darf nicht geloescht werden!")
			
		ok, status = self.jadb.remove_account(user_id, jabber_id, check_only = True)
		if not ok:
			return (False, status)
		
		acc = JabberAccount(jabber_id)
		if not self.ejctl.remove_account(acc.user, acc.server):
			return (False, "Konnte Konto %s nicht loeschen." % acc.get_jabber_id())
		
		return self.jadb.remove_account(user_id, jabber_id)
		
	def __set_session(self, user_id, password = None, token = None):
		self.__clear_session()
		self.session["uid"] = user_id
		if password:
			self.session["pass"] = password
		if token:
			self.session["tok"] = token
		
	def __clear_session(self):
		if self.session.get("uid"):
			del(self.session["uid"])
		if self.session.get("pass"):
			del(self.session["pass"])
		if self.session.get("token"):
			del(self.session["tok"])
			
	@staticmethod
	def __check_account_form(acc_type, domains, account):
		try:
			user, domain = account.split("@")
		except ValueError:
			status = "Ungueltige %s Adresse. Erwartete Form: user@domain." % acc_type
			return (False, status)
		
		if not re.match(config.user_re, user):
			return (False, "Benutzername enthaelt unerlaubte Zeichen.")
		if string.lower(user) in config.forbidden_users:
			return (False, "Benutzername %s nicht erlaubt." % user)
		if domain not in domains:
			return (False, "Domain %s nicht erlaubt." % domain)
		return (True, "%s Adresse akzeptiert." % acc_type)
		
	@staticmethod
	def check_user_id(user_id):
		return JabberManager.__check_account_form("E-Mail", config.mail_domains, user_id)
		
	@staticmethod
	def check_jabber_id(jabber_id):
		domains = map(lambda d: "jabber." + d, config.mail_domains) + config.extra_domains
		return JabberManager.__check_account_form("Jabber", domains, jabber_id)