-
Notifications
You must be signed in to change notification settings - Fork 38
/
SQLUsers.py
executable file
·1599 lines (1405 loc) · 59.3 KB
/
SQLUsers.py
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
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from datetime import datetime, timedelta
import time, random, re, hashlib, base64
import logging
import smtplib
from email.mime.text import MIMEText
import _thread as thread
try:
from sqlalchemy import create_engine, Table, Column, Integer, String, MetaData, ForeignKey, Boolean, Text, DateTime, ForeignKeyConstraint, UniqueConstraint
from sqlalchemy.orm import mapper, sessionmaker, relation
from sqlalchemy.exc import IntegrityError
except ImportError as e:
print("ERROR: sqlalchemy isn't installed: " + str(e))
print("ERROR: please install sqlalchemy, on debian the command is sth. like: ")
print("sudo apt-get install python-sqlalchemy")
import sys
sys.exit(1)
metadata = MetaData()
##########################################
users_table = Table('users', metadata,
Column('id', Integer, primary_key=True),
Column('username', String(40), unique=True), # unicode
Column('password', String(64)), # unicode(BASE64(ASCII)) (unicode is added by DB on write)
Column('register_date', DateTime),
Column('last_login', DateTime),
Column('last_ip', String(15)), # would need update for ipv6
Column('last_agent', String(254)),
Column('last_sys_id', String(16)),
Column('last_mac_id', String(16)),
Column('ingame_time', Integer),
Column('access', String(32)),
Column('email', String(254), unique=True, nullable=True), # http://www.rfc-editor.org/errata_search.php?rfc=3696&eid=1690
Column('bot', Integer),
mysql_charset='utf8',
)
class User():
def __init__(self, username, password, last_ip, email, access='agreement'):
self.username = username
self.password = password
self.last_login = datetime.now()
self.register_date = datetime.now()
self.last_ip = last_ip
self.last_agent = ""
self.email = email
self.ingame_time = 0
self.bot = 0
self.access = access # user, moderator, admin, bot, agreement, fresh
self.last_sys_id = ""
self.last_mac_id = ""
def __repr__(self):
return "<User('%s', '%s')>" % (self.username, self.password)
##########################################
verifications_table = Table('verifications', metadata,
Column('id', Integer, primary_key=True),
Column('user_id', Integer, ForeignKey('users.id', onupdate='CASCADE', ondelete='CASCADE')),
Column('email', String(254), unique=True),
Column('code', Integer),
Column('expiry', DateTime),
Column('attempts', Integer),
Column('resends', Integer),
Column('reason', Text),
mysql_charset='utf8',
)
class Verification(object):
def __init__(self, user_id, email, digits, reason):
self.user_id = user_id
self.email = email
assert(digits>=4)
self.code = random.randint(10**(digits-1),10**(digits)-1)
self.expiry = datetime.now() + timedelta(days=2)
self.attempts = 0
self.resends = 0
self.reason = reason
def __repr__(self):
return "<Verification('%s', '%s', '%s', '%s', '%s', %i, %i)>" % (self.id, self.user_id, self.email, self.code, self.expiry, self.attempts, self.resends)
mapper(Verification, verifications_table)
##########################################
logins_table = Table('logins', metadata,
Column('id', Integer, primary_key=True),
Column('user_id', Integer, ForeignKey('users.id', onupdate='CASCADE', ondelete='CASCADE')),
Column('ip_address', String(15), nullable=False),
Column('time', DateTime),
Column('agent', String(64)),
Column('last_sys_id', String(16)),
Column('last_mac_id', String(16)),
Column('local_ip', String(15)), # needs update for ipv6
Column('country', String(4)),
Column('end', DateTime),
mysql_charset='utf8',
)
class Login(object):
def __init__(self, now, user_id, ip_address, agent, last_sys_id, last_mac_id, local_ip, country):
self.user_id = user_id
self.ip_address = ip_address
self.time = now
self.agent = agent
self.last_sys_id = last_sys_id
self.last_mac_id = last_mac_id
self.local_ip = local_ip
self.country = country
def __repr__(self):
return "<Login('%s', '%s')>" % (self.user_id, self.time)
mapper(Login, logins_table)
##########################################
bridged_users_table = Table('bridged_users', metadata,
Column('id', Integer, primary_key=True),
Column('external_id', String(20)),
Column('location', String(20)),
Column('external_username', String(20)),
Column('last_bridged', DateTime),
UniqueConstraint('external_id', 'location', name='uix_bridged_users_1'),
UniqueConstraint('external_username', 'location', name='uix_bridged_users_2'),
mysql_charset='utf8',
)
class BridgedUser(object):
def __init__(self, location, external_id, external_username, last_bridged):
self.external_id = external_id
self.location = location
self.external_username = external_username
self.last_bridged = last_bridged
def __repr__(self):
return "<BridgedUser('%s', '%s', '%s', '%s')>" % (self.id, self.external_id, self.location, self.last_bridged)
mapper(BridgedUser, bridged_users_table)
##########################################
renames_table = Table('renames', metadata,
Column('id', Integer, primary_key=True),
Column('user_id', Integer, ForeignKey('users.id', onupdate='CASCADE', ondelete='CASCADE')),
Column('original', String(40)),
Column('time', DateTime),
mysql_charset='utf8',
)
class Rename(object):
def __init__(self, original):
self.original = original
self.time = datetime.now()
def __repr__(self):
return "<Rename of '%s'>" % (self.original)
mapper(Rename, renames_table)
##########################################
ignores_table = Table('ignores', metadata,
Column('id', Integer, primary_key=True),
Column('user_id', Integer, ForeignKey('users.id', onupdate='CASCADE', ondelete='CASCADE')),
Column('ignored_user_id', Integer, ForeignKey('users.id', onupdate='CASCADE', ondelete='CASCADE')),
Column('reason', String(128)),
Column('time', DateTime),
mysql_charset='utf8',
)
class Ignore(object):
def __init__(self, user_id, ignored_user_id, reason):
self.user_id = user_id
self.ignored_user_id = ignored_user_id
self.reason = reason
self.time = datetime.now()
def __repr__(self):
return "<Ignore('%s', '%s', '%s', '%s')>" % (self.user_id, self.ignored_user_id, self.reason, self.time)
mapper(Ignore, ignores_table)
##########################################
friends_table = Table('friends', metadata,
Column('id', Integer, primary_key=True),
Column('first_user_id', Integer, ForeignKey('users.id', onupdate='CASCADE', ondelete='CASCADE')),
Column('second_user_id', Integer, ForeignKey('users.id', onupdate='CASCADE', ondelete='CASCADE')),
Column('time', DateTime),
mysql_charset='utf8',
)
class Friend(object):
def __init__(self, first_user_id, second_user_id):
self.first_user_id = first_user_id
self.second_user_id = second_user_id
self.time = datetime.now()
def __repr__(self):
return "<Friends('%s', '%s')>" % self.first_user_id, self.second_user_id
mapper(Friend, friends_table)
##########################################
friendRequests_table = Table('friendRequests', metadata,
Column('id', Integer, primary_key=True),
Column('user_id', Integer, ForeignKey('users.id', onupdate='CASCADE', ondelete='CASCADE')),
Column('friend_user_id', Integer, ForeignKey('users.id', onupdate='CASCADE', ondelete='CASCADE')),
Column('msg', String(128)),
Column('time', DateTime),
mysql_charset='utf8',
)
class FriendRequest(object):
def __init__(self, user_id, friend_user_id, msg):
self.user_id = user_id
self.friend_user_id = friend_user_id
self.msg = msg
self.time = datetime.now()
def __repr__(self):
return "<FriendRequest('%s', '%s', '%s')>" % self.user_id, self.friend_user_id, self.msg
mapper(FriendRequest, friendRequests_table)
##########################################
mapper(User, users_table, properties={
'logins':relation(Login, backref='user', cascade="all, delete, delete-orphan"),
'renames':relation(Rename, backref='user', cascade="all, delete, delete-orphan"),
## FIXME: all of these generate "Could not determine join condition between parent/child tables on relation User.XXXX"
'ignores':relation(Ignore, cascade="all, delete, delete-orphan", foreign_keys=[Ignore.user_id]),
'friends1':relation(Friend, cascade="all, delete, delete-orphan", foreign_keys=[Friend.first_user_id]),
'friends2':relation(Friend, cascade="all, delete, delete-orphan", foreign_keys=[Friend.second_user_id]),
'friend-requests-by-me':relation(FriendRequest, cascade="all, delete, delete-orphan", foreign_keys=[FriendRequest.user_id]),
'friend-requests-for-me':relation(FriendRequest, cascade="all, delete, delete-orphan", foreign_keys=[FriendRequest.friend_user_id]),
})
##########################################
channels_table = Table('channels', metadata,
Column('id', Integer, primary_key=True),
Column('name', String(40), unique=True),
Column('key', String(32)),
Column('owner_user_id', Integer, ForeignKey('users.id', onupdate='CASCADE', ondelete='SET NULL'), nullable=True),
Column('topic', Text),
Column('topic_user_id', Integer, ForeignKey('users.id', onupdate='CASCADE', ondelete='SET NULL'), nullable=True),
Column('antispam', Boolean),
Column('censor', Boolean),
Column('store_history', Boolean),
Column('last_used', DateTime),
mysql_charset='utf8',
)
class Channel(object):
def __init__(self, name):
self.name = name
self.key = None
self.owner_user_id = None
self.topic = None
self.topic_user_id = None
self.antispam = False
self.censor = False
self.store_history = False
self.last_used = None
def __repr__(self):
return "<Channel('%s')>" % self.name
mapper(Channel, channels_table)
##########################################
channelshistory_table = Table('channel_history', metadata,
Column('id', Integer, primary_key=True),
Column('channel_id', Integer, ForeignKey('channels.id', onupdate='CASCADE', ondelete='CASCADE')),
Column('user_id', Integer, ForeignKey('users.id', onupdate='CASCADE', ondelete='CASCADE')),
Column('bridged_id', Integer, ForeignKey('bridged_users.id', onupdate='CASCADE', ondelete='CASCADE'), nullable=True),
Column('time', DateTime),
Column('msg', Text),
Column('ex_msg', Boolean),
mysql_charset='utf8',
)
class ChannelHistory(object):
def __init__(self, channel_id, user_id, bridged_id, time, msg, ex_msg):
self.channel_id = channel_id
self.user_id = user_id
self.bridged_id = bridged_id
self.time = time
self.msg = msg
self.ex_msg = ex_msg
def __repr__(self):
return "<ChannelHistory('%s')>" % self.channel_id
mapper(ChannelHistory, channelshistory_table)
##########################################
channelops_table = Table('channel_ops', metadata,
Column('id', Integer, primary_key=True),
Column('channel_id', Integer, ForeignKey('channels.id', onupdate='CASCADE', ondelete='CASCADE')),
Column('user_id', Integer, ForeignKey('users.id', onupdate='CASCADE', ondelete='CASCADE')),
)
class ChannelOp(object):
def __init__(self, channel_id, user_id):
self.channel_id = channel_id
self.user_id = user_id
def __repr__(self):
return "<ChannelOp(%s,%s)>" % (self.channel_id, self.user_id)
mapper(ChannelOp, channelops_table)
##########################################
channelbans_table = Table('channel_bans', metadata,
Column('id', Integer, primary_key=True),
Column('channel_id', Integer, ForeignKey('channels.id', onupdate='CASCADE', ondelete='CASCADE')),
Column('issuer_user_id', Integer, ForeignKey('users.id', onupdate='CASCADE', ondelete='SET NULL'), nullable=True),
Column('user_id', Integer, ForeignKey('users.id', onupdate='CASCADE', ondelete='CASCADE')),
Column('ip_address', String(15)),
Column('expires', DateTime),
Column('reason', Text)
)
class ChannelBan(object):
def __init__(self, channel_id, issuer_user_id, user_id, ip_address, expires, reason):
self.channel_id = channel_id
self.issuer_user_id = issuer_user_id
self.user_id = user_id
self.ip_address = ip_address
self.expires = expires
self.reason = reason
def __repr__(self):
return "<ChannelBan(%s,%s)>" % (self.channel_id, self.user_id)
mapper(ChannelBan, channelbans_table)
##########################################
channelbridgedbans_table = Table('channel_bridged_bans', metadata,
Column('id', Integer, primary_key=True),
Column('channel_id', Integer, ForeignKey('channels.id', onupdate='CASCADE', ondelete='CASCADE')),
Column('issuer_user_id', Integer, ForeignKey('users.id', onupdate='CASCADE', ondelete='SET NULL'), nullable=True),
Column('bridged_id', Integer, ForeignKey('bridged_users.id', onupdate='CASCADE', ondelete='CASCADE')),
Column('expires', DateTime),
Column('reason', Text)
)
class ChannelBridgedBan(object):
def __init__(self, channel_id, issuer_user_id, bridged_id, expires, reason):
self.channel_id = channel_id
self.issuer_user_id = issuer_user_id
self.bridged_id = bridged_id
self.expires = expires
self.reason = reason
def __repr__(self):
return "<ChannelBridgedBan(%s,%s)>" % (self.channel_id, self.bridged_id)
mapper(ChannelBridgedBan, channelbridgedbans_table)
##########################################
channelmutes_table = Table('channel_mutes', metadata,
Column('id', Integer, primary_key=True),
Column('channel_id', Integer, ForeignKey('channels.id', onupdate='CASCADE', ondelete='CASCADE')),
Column('issuer_user_id', Integer, ForeignKey('users.id', onupdate='CASCADE', ondelete='SET NULL'), nullable=True),
Column('user_id', Integer, ForeignKey('users.id', onupdate='CASCADE', ondelete='CASCADE')),
Column('expires', DateTime),
Column('reason', Text)
)
class ChannelMute(object):
def __init__(self, channel_id, issuer_user_id, user_id, expires, reason):
self.channel_id = channel_id
self.issuer_user_id = issuer_user_id
self.user_id = user_id
self.expires = expires
self.reason = reason
def __repr__(self):
return "<ChannelMute(%s,%s)>" % (self.channel_id, self.user_id)
mapper(ChannelMute, channelmutes_table)
##########################################
channelforwards_table = Table('channel_forwards', metadata,
Column('id', Integer, primary_key=True),
Column('channel_from_id', Integer, ForeignKey('channels.id', onupdate='CASCADE', ondelete='CASCADE')),
Column('channel_to_id', Integer, ForeignKey('channels.id', onupdate='CASCADE', ondelete='CASCADE')),
UniqueConstraint('channel_from_id', 'channel_to_id', name='uix_channelforwards'),
)
class ChannelForward(object):
def __init__(self, channel_from_id, channel_to_id):
self.channel_from_id = channel_from_id
self.channel_to_id = channel_to_id
def __repr__(self):
return "<ChannelForward(%s,%s)>" % (self.channel_id_from, self.channel_id_to)
mapper(ChannelForward, channelforwards_table)
##########################################
ban_table = Table('ban', metadata, # server bans
Column('id', Integer, primary_key=True),
Column('issuer_user_id', Integer, ForeignKey('users.id', onupdate='CASCADE', ondelete='SET NULL'), nullable=True), # user which set ban
Column('user_id', Integer, ForeignKey('users.id', onupdate='CASCADE', ondelete='CASCADE')), # user id which is banned (optional)
Column('ip', String(60)), #ip which is banned (optional)
Column('email', String(254)), #email which is banned (optional)
Column('reason', Text),
Column('end_date', DateTime),
mysql_charset='utf8',
)
class Ban(object):
def __init__(self, issuer_user_id, duration, reason, user_id=None, ip=None, email=None):
self.issuer_user_id = issuer_user_id
self.user_id = user_id
self.ip = ip
self.email = email
self.reason = reason
self.end_date = datetime.now() + timedelta(duration)
def __repr__(self):
user_id_str = str(self.user_id)+', ' if self.user_id else ""
ip_str = self.ip+', ' if self.ip else ""
email_str = self.email+', ' if self.email else ""
ban_str = user_id_str + ip_str + email_str
return "<Ban: %s (%s, %s)>" % (ban_str, self.issuer_user_id, self.end_date)
mapper(Ban, ban_table)
##########################################
blacklisted_email_domain_table = Table('blacklisted_email_domains', metadata, # email domains that can't be used for account verification
Column('id', Integer, primary_key=True),
Column('issuer_user_id', Integer, ForeignKey('users.id', onupdate='CASCADE', ondelete='SET NULL'), nullable=True), # user which set ban
Column('domain', String(254), unique=True),
Column('reason', Text),
Column('start_time', DateTime),
)
class BlacklistedEmailDomain(object):
def __init__(self, issuer_user_id, domain, reason):
self.issuer_user_id = issuer_user_id
self.domain = domain
self.reason = reason
self.start_time = datetime.now()
def __repr__(self):
return "<Domain: %s (%s, since %s)>" % (self.domain, self.issuer_user_id, self.start_time)
mapper(BlacklistedEmailDomain, blacklisted_email_domain_table)
##########################################
min_spring_version_table = Table('min_spring_version', metadata,
Column('id',Integer, primary_key=True),
Column('min_spring_version', String(128)),
Column('start_time', DateTime),
)
class MinSpringVersion(object):
def __init__(self, min_spring_version, start_time):
self.min_spring_version = min_spring_version
self.start_time = start_time
def __repr__(self):
return "<Version: %d (since %s)>" % (self.min_spring_version, self.start_time)
mapper(MinSpringVersion, min_spring_version_table)
##########################################
class session_manager():
# on-demand sessionmaker
def __init__(self, root, engine):
self._root = root
metadata.create_all(engine)
self.sessionmaker = sessionmaker(bind=engine, autoflush=True)
self.session = None
def sess(self):
if not self.session:
self.session = self.sessionmaker()
return self.session
# guarded access
def commit_guard(self):
if self.session:
self.session.commit()
def rollback_guard(self):
if self.session:
self.session.rollback()
def close_guard(self):
if self.session:
self.session.close()
self.session = None
##########################################
class OfflineClient():
def __init__(self, sqluser):
self.username = sqluser.username
self.password = sqluser.password
self.id = sqluser.id
self.user_id = sqluser.id
self.ingame_time = sqluser.ingame_time
self.bot = sqluser.bot
self.last_login = sqluser.last_login
self.register_date = sqluser.register_date
self.last_ip = sqluser.last_ip
self.last_agent = sqluser.last_agent
self.last_sys_id = sqluser.last_sys_id
self.last_mac_id = sqluser.last_mac_id
self.access = sqluser.access
self.email = sqluser.email
class UsersHandler:
def __init__(self, root):
self._root = root
def sess(self):
return self._root.session_manager.sess()
def clientFromID(self, user_id):
entry = self.sess().query(User).filter(User.id==user_id).first()
if not entry: return None
return OfflineClient(entry)
def clientFromUsername(self, username):
entry = self.sess().query(User).filter(User.username==username).first()
if not entry: return None
return OfflineClient(entry)
def remaining_ban_str(self, dbban, now):
timeleft = int((dbban.end_date - now).total_seconds())
remaining = 'less than one hour remaining'
if timeleft > 60*60*24*900:
remaining = ''
elif timeleft > 60*60*24:
remaining = '%s days remaining' % (int(timeleft / (60 * 60 * 24)))
elif timeleft > 60*60:
remaining = '%s hours remaining' % (int(timeleft / (60 * 60)))
return remaining
def check_banned(self, username, ip):
dbuser = self.sess().query(User).filter(User.username == username).first()
if not dbuser:
return False, ""
now = datetime.now()
dbban = self._root.bandb.check_ban(dbuser.id, ip, dbuser.email, now)
if dbban and not dbuser.access=='admin':
reason = 'You are banned: (%s), ' %(dbban.reason)
reason += self.remaining_ban_str(dbban, now)
return True, reason
return False, ""
def check_login_user(self, username, password):
# password here is unicode(BASE64(MD5(...))), matches the register_user DB encoding
dbuser = self.sess().query(User).filter(User.username == username).first()
if (not dbuser):
return False, 'Invalid username or password'
if dbuser.username != username:
# user tried to login with wrong upper/lower case somewhere in their username
return False, "Invalid username -- did you mean '%s'" % dbuser.username
if dbuser.password != password:
return False, 'Invalid username or password'
return True, ""
def login_user(self, username, password, ip, agent, last_sys_id, last_mac_id, local_ip, country):
now = datetime.now()
dbuser = self.sess().query(User).filter(User.username == username).first()
dbuser.logins.append(Login(now, dbuser.id, ip, agent, last_sys_id, last_mac_id, local_ip, country))
dbuser.last_ip = ip
dbuser.last_agent = agent
dbuser.last_sys_id = last_sys_id
dbuser.last_mac_id = last_mac_id
dbuser.last_login = now
self.sess().commit()
return dbuser
def set_user_password(self, username, password):
dbuser = self.sess().query(User).filter(User.username==username).first()
dbuser.password = password
self.sess().commit()
def end_session(self, user_id):
entry = self.sess().query(User).filter(User.id==user_id).first()
if entry and not entry.logins[-1].end:
entry.logins[-1].end = datetime.now()
entry.last_login = datetime.now() # in real its last online / last seen
self.sess().commit()
def check_user_name(self, user_name):
if len(user_name) > 20: return False, 'Username too long'
if self._root.censor:
if not self._root.SayHooks._nasty_word_censor(user_name):
return False, 'Name failed to pass profanity filter.'
return True, ""
def check_register_user(self, username, email=None, ip_address=None):
assert(type(username) == str)
status, reason = self.check_user_name(username)
if not status:
return False, reason
dbuser = self.sess().query(User).filter(User.username == username).first()
if dbuser:
return False, 'Username is already in use.'
if email:
dbemail = self.sess().query(User).filter(User.email == email).first()
if dbemail:
return False, 'Email address is already in use.'
if ip_address:
ipban = self._root.bandb.check_ban(None, ip_address)
if ipban:
return False, 'Account registration failed: %s' % ipban.reason
return True, ""
def register_user(self, username, password, ip, email):
# note: password here is BASE64(MD5(...)) and already in unicode
# assume check_register_user was already called
entry = User(username, password, ip, email)
self.sess().add(entry)
self.sess().commit()
return True, 'Account registered successfully.'
def rename_user(self, username, newname):
if newname == username:
return False, 'You already have that username.'
results = self.sess().query(User).filter(User.username==newname).first()
if results:
return False, 'Username already exists.'
entry = self.sess().query(User).filter(User.username==username).first()
if not entry:
return False, 'You don\'t seem to exist anymore. Contact an admin or moderator.'
entry.renames.append(Rename(username))
entry.username = newname
self.sess().commit()
return True, 'Account renamed successfully.'
def save_user(self, obj):
# assert(isinstance(obj, User) or isinstance(obj, Client))
entry = self.sess().query(User).filter(User.username==obj.username).first()
if (entry != None):
# caller might have changed these!
entry.password = obj.password
entry.ingame_time = obj.ingame_time
entry.access = obj.access
entry.bot = obj.bot
entry.last_sys_id = obj.last_sys_id
entry.last_mac_id = obj.last_mac_id
entry.email = obj.email
self.sess().commit()
def get_user_id_with_email(self, email):
if email == '':
return False, 'Email address is blank'
response = self.sess().query(User).filter(User.email == email)
dbuser = response.first()
if not dbuser:
return False, 'No user with email address %s was found' % email
for entry in response: # pick oldest with a valid date, if multiple choices
if (entry.register_date and dbuser.register_date and entry.register_date < dbuser.register_date) or not dbuser.register_date:
db_user = entry
return True, dbuser.id
def confirm_agreement(self, client):
entry = self.sess().query(User).filter(User.username==client.username).first()
if entry: entry.access = 'user'
self.sess().commit()
def get_lastlogin(self, username):
entry = self.sess().query(User).filter(User.username==username).first()
if entry: return True, entry.last_login
else: return False, 'User not found.'
def get_registration_date(self, username):
entry = self.sess().query(User).filter(User.username==username).first()
if entry and entry.register_date: return True, entry.register_date
else: return False, 'User or date not found in database'
def get_ingame_time(self, username):
entry = self.sess().query(User).filter(User.username==username).first()
if entry: return True, entry.ingame_time
else: return False, 'User not found in database'
def get_account_access(self, username):
entry = self.session.query(User).filter(User.username==username).first()
if entry:
return True, entry.access
else: return False, 'User not found in database'
def find_ip(self, ip):
results = self.sess().query(User).filter(User.last_ip==ip)
return results
def get_ip(self, username):
entry = self.sess().query(User).filter(User.username==username).first()
if not entry:
return None
return entry.last_ip
def list_mods(self):
response_mods = self.sess().query(User).filter('mod' == User.access)
mods = ""
for user in response_mods:
mods += user.username + " "
admins = ""
response_admins = self.sess().query(User).filter('admin' == User.access)
for user in response_admins:
admins += user.username + " "
return admins, mods
def remove_user(self, user):
entry = self.sess().query(User).filter(User.username==user).first()
if not entry:
return False, 'User not found.'
self.sess().delete(entry)
self.sess().commit()
return True, 'Success.'
def clean(self):
now = datetime.now()
#delete users:
# which didn't accept agreement after three days
response = self.sess().query(User).filter(User.register_date < now - timedelta(days=3)).filter(User.access == "agreement")
logging.info("deleting %i users who failed to verify registration", response.count())
response.delete(synchronize_session=False)
# which have no ingame time, last login > 1 month ago, not bot, not mod
response = self.sess().query(User).filter(User.ingame_time == 0).filter(User.last_login < now - timedelta(days=28)).filter(User.bot == 0).filter(User.access == "user")
logging.info("deleting %i inactive users with no ingame time", response.count())
response.delete(synchronize_session=False)
# last login > 5 years
response = self.sess().query(User).filter(User.last_login < now - timedelta(days=1825))
logging.info("deleting %i very inactive users", response.count())
response.delete(synchronize_session=False)
# old messages > 2 weeks
response = self.sess().query(ChannelHistory).filter(ChannelHistory.time < now - timedelta(days=14))
logging.info("deleting %i channel history messages", response.count())
response.delete(synchronize_session=False)
self.sess().commit()
def audit_access(self):
now = datetime.now()
# remove botflags from clients that didn't log in for 1 year
response = self.sess().query(User).filter(User.last_login < now - timedelta(days=365)).filter(User.bot == 1)
logging.info("removing %i botflags from inactive hosts", response.count())
for user in response:
user.bot = 0
# remove moderator/admin access from clients that didn't log in for 1 year:
response = self.sess().query(User).filter(User.last_login < now - timedelta(days=365)).filter(User.access == "admin")
logging.info("removing %i inactive admins", response.count())
for user in response:
user.access = "user"
response = self.sess().query(User).filter(User.last_login < now - timedelta(days=365)).filter(User.access == "mod")
logging.info("removing %i inactive mods", response.count())
for user in response:
user.access = "user"
self.sess().commit()
def ignore_user(self, user_id, ignore_user_id, reason=None):
entry = Ignore(user_id, ignore_user_id, reason)
self.sess().add(entry)
self.sess().commit()
def unignore_user(self, user_id, unignore_user_id):
entry = self.sess().query(Ignore).filter(Ignore.user_id == user_id).filter(Ignore.ignored_user_id == unignore_user_id).one()
self.sess().delete(entry)
self.sess().commit()
# returns id-s of users who had their ignore removed
def globally_unignore_user(self, unignore_user_id):
q = self.sess().query(Ignore).filter(Ignore.ignored_user_id == unignore_user_id)
userids = [ignore.user_id for ignore in q.all()]
# could be done in one query + hook, fix if bored
self.sess().query(Ignore).filter(Ignore.ignored_user_id == unignore_user_id).delete()
self.sess().commit()
return userids
def is_ignored(self, user_id, ignore_user_id):
exists = self.sess().query(Ignore).filter(Ignore.user_id == user_id).filter(Ignore.ignored_user_id == ignore_user_id).count() > 0
return exists
def get_ignore_list(self, user_id):
users = self.sess().query(Ignore).filter(Ignore.user_id == user_id).all()
users = [(user.ignored_user_id, user.reason) for user in users]
return users
def get_ignored_user_ids(self, user_id):
user_ids = self.sess().query(Ignore.ignored_user_id).filter(Ignore.user_id == user_id).all()
user_ids = [user_id for user_id, in user_ids]
return user_ids
def friend_users(self, user_id, friend_user_id):
entry = Friend(user_id, friend_user_id)
self.sess().add(entry)
self.sess().commit()
def unfriend_users(self, first_user_id, second_user_id):
self.sess().query(Friend).filter(Friend.first_user_id == first_user_id).filter(Friend.second_user_id == second_user_id).delete()
self.sess().query(Friend).filter(Friend.second_user_id == first_user_id).filter(Friend.first_user_id == second_user_id).delete()
self.sess().commit()
def are_friends(self, first_user_id, second_user_id):
q1 = self.sess().query(Friend).filter(Friend.first_user_id == first_user_id)
q2 = self.sess().query(Friend).filter(Friend.second_user_id == second_user_id)
exists = q1.union(q2).count() > 0
return exists
def get_friend_user_ids(self, user_id):
q1 = self.sess().query(Friend.second_user_id).filter(Friend.first_user_id == user_id)
q2 = self.sess().query(Friend.first_user_id).filter(Friend.second_user_id == user_id)
user_ids = q1.union(q2).all()
user_ids = [user_id for user_id, in user_ids]
return user_ids
def has_friend_request(self, user_id, friend_user_id):
request = self.sess().query(FriendRequest).filter(FriendRequest.user_id == user_id).filter(FriendRequest.friend_user_id == friend_user_id)
exists = request.count() > 0
return exists
def add_friend_request(self, user_id, friend_user_id, msg=None):
entry = FriendRequest(user_id, friend_user_id, msg)
self.sess().add(entry)
self.sess().commit()
def remove_friend_request(self, user_id, friend_user_id):
self.sess().query(FriendRequest).filter(FriendRequest.user_id == user_id).filter(FriendRequest.friend_user_id == friend_user_id).delete()
self.sess().commit()
# this returns all friend requests sent _to_ user_id
def get_friend_request_list(self, user_id):
reqs = self.sess().query(FriendRequest).filter(FriendRequest.friend_user_id == user_id).all()
users = [(req.user_id, req.msg) for req in reqs]
return users
def add_channel_message(self, channel_id, user_id, bridged_id, msg, ex_msg, date=None):
if date is None:
date = datetime.now()
entry = ChannelHistory(channel_id, user_id, bridged_id, date, msg, ex_msg)
self.sess().add(entry)
self.sess().commit()
return entry.id
def get_channel_messages(self, user_id, channel_id, last_msg_id):
# returns a list of channel messages since last_msg_id for the specific userid when he is subscribed to the channel
# [[date, username, msg, id], ...]
res = self.sess().query(ChannelHistory.time, ChannelHistory.msg, ChannelHistory.ex_msg, User.username, BridgedUser.external_username, BridgedUser.location, ChannelHistory.id).filter(ChannelHistory.channel_id == channel_id).filter(ChannelHistory.id > last_msg_id).join(User, isouter=True).join(BridgedUser, isouter=True).order_by(ChannelHistory.id).all()
msgs = []
for (time, msg, ex_msg, username, external_username, location, id) in res:
if not username:
msgs.append((time, "?", msg, ex_msg, id))
elif external_username:
bridged_username = external_username + ":" + location
msgs.append((time, bridged_username, msg, ex_msg, id))
else:
msgs.append((time, username, msg, ex_msg, id))
return msgs
class OfflineBridgedClient():
def __init__(self, sqluser):
# db fields
self.bridged_id = sqluser.id
self.location = sqluser.location
self.external_id = sqluser.external_id
self.external_username = sqluser.external_username
self.last_bridged = sqluser.last_bridged
# non-db fields
self.username = self.external_username + ':' + self.location
self.channels = set()
self.bridge_user_id = None
class BridgedUsersHandler:
def __init__(self, root):
self._root = root
def sess(self):
return self._root.session_manager.sess()
def bridgedClient(self, location, external_id):
entry = self.sess().query(BridgedUser).filter(BridgedUser.external_id == external_id).filter(BridgedUser.location == location).first()
if not entry:
return
return OfflineBridgedClient(entry)
def bridgedClientFromID(self, bridged_id):
entry = self.sess().query(BridgedUser).filter(BridgedUser.id == bridged_id).first()
if not entry:
return
return OfflineBridgedClient(entry)
def bridgedClientFromUsername(self, username):
external_username,location = username.split(':',1)
if not external_username or not location:
return
entry = self.sess().query(BridgedUser).filter(BridgedUser.external_username == external_username).filter(BridgedUser.location == location).first()
if not entry:
return
return OfflineBridgedClient(entry)
def new_bridge_user(self, location, external_id, external_username):
now = datetime.now()
entry = BridgedUser(location, external_id, external_username, now)
self.sess().add(entry)
self.sess().commit()
bridgedUser = self.sess().query(BridgedUser).filter(BridgedUser.external_id == external_id).filter(BridgedUser.location == location).first()
return entry
def bridge_user(self, location, external_id, external_username):
bridgedUser = self.sess().query(BridgedUser).filter(BridgedUser.external_id == external_id).filter(BridgedUser.location == location).first()
entry = self.sess().query(BridgedUser).filter(BridgedUser.external_username == external_username).filter(BridgedUser.location == location).first()
if (entry and entry.external_id != external_id):
return False, "Another bridged user (external_id '%s') with location '%s' is currently associated to the external username '%s'" % (entry.external_id, location, external_username)
if not bridgedUser:
entry = self.new_bridge_user(location, external_id, external_username)
return True, OfflineBridgedClient(entry)
bridgedUser.external_username = external_username
bridgedUser.last_bridged = datetime.now()
self.sess().commit()
return True, OfflineBridgedClient(bridgedUser)
def clean(self):
# remove any bridged user that wasn't seen for 30 days and isn't banned from any channels
bridge_bans = self.sess().query(ChannelBridgedBan.bridged_id).distinct()
ignore_ids = set(b.bridged_id for b in bridge_bans)
now = datetime.now()
response = self.sess().query(BridgedUser).filter(BridgedUser.last_bridged < now - timedelta(days=30)).filter(not BridgedUser.id in ignore_ids)
logging.info("deleting %i inactive bridged users", response.count())
response.delete(synchronize_session=False)
self.sess().commit()
class BansHandler:
def __init__(self, root):
self._root = root
def sess(self):
return self._root.session_manager.sess()
def check_ban(self, user_id=None, ip=None, email=None, now=None):
# check if any of the args are currently banned
# fixme: its probably possible to do this with a single db command!
if not now:
now = datetime.now()
if user_id:
userban = self.sess().query(Ban).filter(Ban.user_id == user_id, now <= Ban.end_date).first()
if userban:
return userban
if ip:
ipban = self.sess().query(Ban).filter(Ban.ip == ip, now <= Ban.end_date).first()
if ipban:
return ipban
if email:
emailban = self.sess().query(Ban).filter(Ban.email == email, now <= Ban.end_date).first()
if emailban:
return emailban
return None
def ban(self, issuer, duration, reason, username):
# ban the user_id, current ip, and current email, of the target username (as a single ban)
try:
duration = float(duration)
except:
return False, 'Duration must be a float, cannot convert %s' % duration
entry = self.sess().query(User).filter(User.username==username).first()
if not entry:
return False, "Unable to ban %s, user doesn't exist" % username
ban = Ban(issuer.user_id, duration, reason, entry.id, entry.last_ip, entry.email)
self.sess().add(ban)
self.sess().commit()
return True, 'Successfully banned %s, %s, %s for %s days.' % (username, entry.last_ip, entry.email, duration)
def ban_specific(self, issuer, duration, reason, arg):
# arg might be username, ip or email; ban it
try:
duration = float(duration)
except:
return False, 'Duration must be a float, cannot convert %s' % duration
email_match,_ = self._root.verificationdb.valid_email_addr(arg)
ip_match = re.match(r"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b", arg)
entry = self.sess().query(User).filter(User.username==arg).first()
if email_match:
ban = Ban(issuer.user_id, duration, reason, None, None, arg)
elif ip_match:
ban = Ban(issuer.user_id, duration, reason, None, arg, None)
elif entry:
ban = Ban(issuer.user_id, duration, reason, entry.id, None, None)
else:
return False, "Unable to match '%s' to username/ip/email" % arg
self.sess().add(ban)
self.sess().commit()
return True, 'Successfully banned %s for %s days' % (arg, duration)
def unban(self, issuer, arg):
# arg might be username, ip or email; remove all associated bans
email_match,_ = self._root.verificationdb.valid_email_addr(arg)
ip_match = re.match(r"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b", arg)
entry = self.sess().query(User).filter(User.username==arg).first()
if not (email_match or ip_match or entry):
return False, "Unable to match '%s' to username/ip/email" % arg
result = []
n_unban = 0
if email_match:
results = self.sess().query(Ban).filter(Ban.email==arg)
for result in results:
self.sess().delete(result)
n_unban += 1
if ip_match:
results = self.sess().query(Ban).filter(Ban.ip==arg)
for result in results:
self.sess().delete(result)
n_unban += 1
if entry:
results = self.sess().query(Ban).filter(Ban.user_id==entry.id)
for result in results:
self.sess().delete(result)
n_unban += 1
self.sess().commit()
if n_unban>0:
return True, 'Successfully removed %s bans relating to %s' % (n_unban, arg)
else:
return False, 'No matching bans for %s' % arg
def check_blacklist(self, email):
partition = email.partition('@')
if partition[1]=="":
return None
domain = partition[2]
entry = self.sess().query(BlacklistedEmailDomain).filter(BlacklistedEmailDomain.domain==domain).first()
if entry:
return entry