This repository was archived by the owner on Nov 29, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathauth.py
More file actions
2271 lines (1951 loc) · 87.5 KB
/
Copy pathauth.py
File metadata and controls
2271 lines (1951 loc) · 87.5 KB
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
# -*- coding=utf-8 -*-
"""All classes relative to users and their online identities."""
from datetime import datetime, timedelta
from itertools import chain, permutations
import urllib
import hashlib
import simplejson as json
from collections import defaultdict
from enum import IntEnum
import re
from abc import abstractmethod
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy import (
Boolean,
Column,
String,
ForeignKey,
Integer,
UnicodeText,
DateTime,
Time,
Binary,
inspect,
event,
Index,
func,
UniqueConstraint,
Text
)
from pyramid.httpexceptions import HTTPBadRequest, HTTPUnauthorized
from sqlalchemy import orm
from pyramid.i18n import TranslationStringFactory
from sqlalchemy.orm import (
relationship, backref, deferred)
from sqlalchemy.orm.attributes import NO_VALUE
from sqlalchemy.sql.functions import count
from ..lib import config, logging
from ..lib.locale import to_posix_string
from ..lib.model_watcher import get_model_watcher
from ..lib.exceptions import LocalizableError, LocalizableMultipleErrors, LocalizableErrorWithMapping
from ..lib.sqla import CrudOperation, PrivateObjectMixin
from ..lib.sqla_types import (
URLString, EmailString, EmailUnicode, CaseInsensitiveWord, CoerceUnicode)
from ..lib.sentry import capture_exception
from . import Base, DiscussionBoundBase
from ..auth import (
ASSEMBL_PERMISSIONS,
CrudPermissions,
IF_OWNED,
P_ADMIN_DISC,
P_OVERRIDE_SOCIAL_AUTOLOGIN,
P_READ,
P_SELF_REGISTER_REQUEST,
P_SELF_REGISTER,
P_SYSADMIN,
R_PARTICIPANT,
R_CATCHER,
SYSTEM_ROLES
)
from .langstrings import Locale
from assembl.models.cookie_types import CookieTypes, AcceptedCookies, RejectedCookies
log = logging.getLogger('assembl')
_ = TranslationStringFactory('assembl')
# None-tolerant min, max
def minN(a, b):
if a is None:
return b
if b is None:
return a
return min(a, b)
def maxN(a, b):
if a is None:
return b
if b is None:
return a
return max(a, b)
def hash(content, size):
return hashlib.md5(content).hexdigest()[-size:]
class AgentProfile(Base):
"""An agent identified on the platform.
Agents can be :py:class:`User` or simply the author of an
imported message; they could also be a group, bot or computer.
Agents have at least one :py:class:`AbstractAgentAccount`.
"""
__tablename__ = "agent_profile"
id = Column(Integer, primary_key=True)
name = Column(CoerceUnicode(1024))
description = Column(UnicodeText)
type = Column(String(60))
__mapper_args__ = {
'polymorphic_identity': 'agent_profile',
'polymorphic_on': type,
'with_polymorphic': '*'
}
def __repr__(self):
r = super(AgentProfile, self).__repr__()
name = self.name or ""
return r[:-1] + name.encode("ascii", "ignore") + ">"
def get_preferred_email_account(self):
if inspect(self).attrs.accounts.loaded_value is NO_VALUE:
account = self.db.query(AbstractAgentAccount).filter(
(AbstractAgentAccount.profile_id == self.id) &
(AbstractAgentAccount.email != None) & (AbstractAgentAccount.email != '') # noqa: E711
).order_by(
AbstractAgentAccount.verified.desc(),
AbstractAgentAccount.preferred.desc()).first()
if account:
return account
elif self.accounts:
accounts = [a for a in self.accounts if a.email]
accounts.sort(key=lambda e: (not e.verified, not e.preferred))
if accounts:
return accounts[0]
def get_preferred_email(self, anonymous=False):
preferred_account = self.get_preferred_email_account()
if preferred_account is not None:
if anonymous:
return "@".join(map(lambda x: hash(x, 10), preferred_account.email.split("@"))) + ".com"
return preferred_account.email
def anonymous_name(self):
CHARACTER_COUNT = 10
if self.name:
return hash(self.name.encode('utf-8'), CHARACTER_COUNT)
return hash("User_" + str(self.id), CHARACTER_COUNT)
def real_name(self):
if not self.name:
for acc in self.identity_accounts:
name = acc.real_name()
if name:
self.name = name
break
return self.name
def display_name(self):
# TODO: Prefer types?
display_name = self.get_override_display_name()
if display_name:
return display_name
if self.name:
return self.name
for acc in self.identity_accounts:
if acc.username:
return acc.display_name()
for acc in self.accounts:
name = acc.display_name()
if name:
return name
def get_override_display_name(self):
"""
Override a display name by the pattern dictated by a Social Auth backend
"""
display_name = None
for account in self.identity_accounts:
name = account.get_forced_display_name()
if name:
display_name = name
return display_name
def merge(self, other_profile):
"""Merge another profile on this profile, because they are the same entity.
This identity is usually found out after an email account is verified,
or a social account is added to another account.
All foreign keys that refer to the other agent profile must now refer
to this one."""
from .social_auth import SocialAuthAccount
log.warn("Merging AgentProfiles: %d <= %d" % (self.id, other_profile.id))
session = self.db
assert self.id
assert not (
isinstance(other_profile, User) and not isinstance(self, User))
my_accounts = {a.signature(): a for a in self.accounts}
my_social_emails = {s.email.lower() for s in self.accounts
if isinstance(s, SocialAuthAccount) and s.email}
for other_account in other_profile.accounts[:]:
my_account = my_accounts.get(other_account.signature())
if my_account:
# if chrono order of accounts corresponds to merge priority
if my_account.prefer_newest_info_on_merge == (
my_account.id > other_account.id):
# prefer info from my_account
my_account.merge(other_account)
session.delete(other_account)
else:
other_account.merge(my_account)
other_account.profile = self
session.delete(my_account)
elif (isinstance(other_account, EmailAccount) and
other_account.email.lower() in my_social_emails):
pass
else:
other_account.profile = self
if other_profile.name and not self.name:
self.name = other_profile.name
for post in other_profile.posts_created[:]:
post.creator = self
post.creator_id = self.id
for post in other_profile.posts_moderated[:]:
post.moderator = self
post.moderator_id = self.id
for attachment in other_profile.attachments[:]:
attachment.creator = self
from .action import Action
for action in session.query(Action).filter_by(actor_id=other_profile.id).all():
action.actor = self
action.actor_id = self.id
my_status_by_discussion = {
s.discussion_id: s for s in self.agent_status_in_discussion
}
with self.db.no_autoflush:
for status in other_profile.agent_status_in_discussion[:]:
if status.discussion_id in my_status_by_discussion:
my_status = my_status_by_discussion[status.discussion_id]
my_status.user_created_on_this_discussion |= status.\
user_created_on_this_discussion
my_status.first_visit = minN(my_status.first_visit,
status.first_visit)
my_status.last_visit = maxN(my_status.last_visit,
status.last_visit)
my_status.first_subscribed = minN(
my_status.first_subscribed, status.first_subscribed)
my_status.last_unsubscribed = minN(
my_status.last_unsubscribed, status.last_unsubscribed)
status.delete()
else:
status.agent_profile = self
def has_permission(self, verb, subject):
if self is subject.owner:
return True
return self.db.query(Permission).filter_by(
actor_id=self.id,
subject_id=subject.id,
verb=verb,
allow=True
).one()
def avatar_url(self, size=32, app_url=None, email=None):
is_machine = getattr(self, 'is_machine', False)
default_config = 'machine.default_image_url' if is_machine else 'avatar.default_image_url'
default_icon = 'machine.png' if is_machine else 'user.png'
default = config.get(default_config) or \
(app_url and app_url + '/static/img/icon/' + default_icon)
offline_mode = config.get('offline_mode')
if offline_mode == "true":
return default
for acc in self.identity_accounts:
url = acc.avatar_url(size)
if url:
return url
# Otherwise: Use the gravatar URL
email = email or self.get_preferred_email()
if not email:
return default
default = config.get('avatar.gravatar_default') or default
return EmailAccount.avatar_url_for(email, size, default)
def external_avatar_url(self):
return "/user/id/%d/avatar/" % (self.id,)
def get_agent_preload(self, view_def='default'):
result = self.generic_json(view_def, user_id=self.id)
return json.dumps(result)
@classmethod
def count_posts_in_discussion_all_profiles(cls, discussion):
from .post import Post, countable_publication_states
return dict(discussion.db.query(
Post.creator_id, count(Post.id)).filter_by(
discussion_id=discussion.id, hidden=False).filter(
Post.publication_state.in_(countable_publication_states)).group_by(
Post.creator_id))
def count_posts_in_discussion(self, discussion_id):
from .post import Post, countable_publication_states
return self.db.query(Post).filter_by(
creator_id=self.id,
discussion_id=discussion_id).filter(
Post.publication_state.in_(countable_publication_states)).count()
def count_posts_in_current_discussion(self):
"CAN ONLY BE CALLED FROM API V2"
from ..auth.util import get_current_discussion
discussion = get_current_discussion()
if discussion is None:
return None
return self.count_posts_in_discussion(discussion.id)
def get_status_in_discussion(self, discussion_id):
return self.db.query(AgentStatusInDiscussion).filter_by(
discussion_id=discussion_id, profile_id=self.id).first()
@property
def status_in_current_discussion(self):
# Use from api v2
from ..auth.util import get_current_discussion
discussion = get_current_discussion()
if discussion:
return self.get_status_in_discussion(discussion.id)
def is_visiting_discussion(self, discussion_id):
from assembl.models.discussion import Discussion
d = Discussion.get(discussion_id)
self.update_agent_status_last_visit(d)
# True iff the user visits current discussion for the first time
@property
def is_first_visit(self):
status = self.status_in_current_discussion
if status:
return status.last_visit == status.first_visit
return True
@property
def last_visit(self):
status = self.status_in_current_discussion
if status:
return status.last_visit
@property
def first_visit(self):
status = self.status_in_current_discussion
if status:
return status.first_visit
@property
def was_created_on_current_discussion(self):
# Use from api v2
status = self.status_in_current_discussion
if status:
return status.user_created_on_this_discussion
return False
def is_owner(self, user_id):
return user_id == self.id
def get_preferred_locale(self):
# TODO: per-user preferred locale
# Want a 2-letter locale string
# Currently expecting only a scalar value, not a list. Might change
# In the near future.
prefs = self.language_preference
prefs.sort() # natural order defined on class
if prefs is None or len(prefs) is 0:
# Correct way is to get the default from the app global config
prefs = config.get_config().\
get('available_languages', 'fr_CA en_CA').split()[0]
assert prefs[0]
return prefs[0]
return Locale.locale_collection_byid[prefs[0].locale_id]
def successful_social_login(self):
self.successful_login(True)
def successful_login(self, social=False):
"A successful email login"
self.last_login = datetime.utcnow()
if not social:
self.last_assembl_login = self.last_login
def assembl_login_expiry(self):
duration = config.get('login_expiry_email', None)
if duration is None:
# default to no expiry
duration = config.get('login_expiry_default', 0)
if not duration:
return None
last_login = self.last_assembl_login
if not last_login:
# Return a date saying it's just expired.
return datetime.utcnow() - timedelta(1)
return last_login + timedelta(float(duration))
def login_expiry_req(self):
"""Get login expiry date. May be None."""
from assembl.auth.util import get_current_discussion
discussion = None
try:
# If called from within request
discussion = get_current_discussion()
except Exception:
# This is actually called from changes.json, so the request
# and discussion are inaccessible in that case.
pass
return self.login_expiry(discussion)
def login_expiry(self, discussion=None):
"""When will this account's login expire, maybe in the context
of a specific discussion."""
accounts = [a for a in self.social_accounts if a.verified]
autologin = None
if discussion:
autologin = discussion.preferences['authorization_server_backend']
from ..auth.util import user_has_permission
if autologin and not user_has_permission(
discussion.id, self.id, P_OVERRIDE_SOCIAL_AUTOLOGIN):
# the discussion restricts access to this specific
# social identity provider. The override permission
# bypasses that, mostly for external moderators.
autologin_accs_expiry = [
a.login_expiry() for a in accounts
if a.provider_with_idp == autologin]
if len(autologin_accs_expiry):
if None in autologin_accs_expiry:
return None
return max(autologin_accs_expiry)
# No social login, treat as already expired
return datetime.utcnow() - timedelta(1)
expiries = [a.login_expiry() for a in accounts]
expiries.append(self.assembl_login_expiry())
if None in expiries:
return None
return max(expiries)
def login_expired(self, discussion):
expiry = self.login_expiry(discussion)
if expiry is None:
return False
return expiry < datetime.utcnow()
@classmethod
def graphene_type(cls):
return 'AgentProfile'
class AbstractAgentAccount(Base):
"""An abstract class for online accounts that identify AgentsProfiles
The main subclasses are :py:class:`EmailAccount` and
:py:class:`.social_auth.SocialAuthAccount`."""
__tablename__ = "abstract_agent_account"
prefer_newest_info_on_merge = True
id = Column(Integer, primary_key=True)
type = Column(String(60))
profile_id = Column(
Integer,
ForeignKey('agent_profile.id', ondelete='CASCADE', onupdate='CASCADE'),
nullable=False, index=True)
profile = relationship('AgentProfile', backref=backref(
'accounts', cascade="all, delete-orphan"))
preferred = Column(Boolean(), default=False, server_default='0')
verified = Column(Boolean(), default=False, server_default='0')
# Note some social accounts don't disclose email (eg twitter), so nullable
# Virtuoso + nullable -> no unique index (sigh)
# Also, unverified emails are allowed to collide.
# IMPORTANT: Use email_ci below when appropriate.
email = Column(EmailString(100))
# Access to email as a case-insensitive object,
# for comparison and search purposes.
@hybrid_property
def email_ci(self):
return CaseInsensitiveWord(self.email)
__table_args__ = (
Index("ix_public_abstract_agent_account_email_ci", func.lower(email)),)
full_name = Column(CoerceUnicode(512))
def signature(self):
"Identity of signature implies identity of underlying account"
return ('abstract_agent_account', self.id)
def merge(self, other):
pass
def is_owner(self, user_id):
return self.profile_id == user_id
@classmethod
def restrict_to_owners(cls, query, user_id):
"filter query according to object owners"
return query.filter(cls.profile_id == user_id)
__mapper_args__ = {
'polymorphic_identity': 'abstract_agent_account',
'polymorphic_on': type,
'with_polymorphic': '*'
}
crud_permissions = CrudPermissions(
P_READ, P_SYSADMIN, P_SYSADMIN, P_SYSADMIN,
P_READ, P_READ, P_READ)
@classmethod
def user_can_cls(cls, user_id, operation, permissions):
s = super(AbstractAgentAccount, cls).user_can_cls(
user_id, operation, permissions)
return IF_OWNED if s is False else s
def user_can(self, user_id, operation, permissions):
# bypass for permission-less new users
if user_id == self.profile_id:
return True
return super(AbstractAgentAccount, self).user_can(
user_id, operation, permissions)
def update_from_json(
self, json, user_id=None, context=None, jsonld=None,
permissions=None, parse_def_name='default_reverse'):
# DO NOT update email... but we still want
# to allow to set it on create.
if 'email' in json:
del json['email']
return super(AbstractAgentAccount, self).update_from_json(
json, user_id, context, jsonld, permissions, parse_def_name)
class EmailAccount(AbstractAgentAccount):
"""An email account"""
__mapper_args__ = {
'polymorphic_identity': 'agent_email_account',
}
profile_e = relationship(AgentProfile, backref=backref('email_accounts'))
def display_name(self):
if self.verified:
return self.email
def signature(self):
return ('agent_email_account',
self.email.lower() if self.email else None)
def merge(self, other):
"""Merge another EmailAccount on this one, because they are the same email."""
log.warn("Merging EmailAccounts: %d, %d" % (self.id, other.id))
if other.verified:
self.verified = True
def other_account(self):
if not self.verified:
return self.db.query(self.__class__).filter_by(
email_ci=self.email_ci, verified=True).first()
def avatar_url(self, size=32, default=None):
return self.avatar_url_for(self.email, size, default)
def unique_query(self):
query, _ = super(EmailAccount, self).unique_query()
return query.filter_by(
type=self.type, email_ci=self.email_ci, verified=True), self.verified
@staticmethod
def avatar_url_for(email, size=32, default=None):
args = {'s': str(size)}
if default:
args['d'] = default
return "//www.gravatar.com/avatar/%s?%s" % (
hashlib.md5(email.lower()).hexdigest(), urllib.urlencode(args))
@staticmethod
def get_or_make_profile(session, email, name=None):
emails = list(session.query(EmailAccount).filter_by(
email_ci=email).all())
# We do not want unverified user emails
# This is costly. I should have proper boolean markers
emails = [e for e in emails if e.verified or not isinstance(e.profile, User)]
user_emails = [e for e in emails if isinstance(e.profile, User)]
if user_emails:
assert len(user_emails) == 1
return user_emails[0]
elif emails:
# should also be 1 but less confident.
return emails[0]
else:
profile = AgentProfile(name=name)
emailAccount = EmailAccount(email=email, profile=profile)
session.add(emailAccount)
return emailAccount
class IdentityProvider(Base):
"""An identity provider (or sometimes a category of identity providers.)
This is a service that provides online identities, expressed as
:py:class:`.social_auth.SocialAuthAccount`."""
__tablename__ = "identity_provider"
id = Column(Integer, primary_key=True)
provider_type = Column(String(32), nullable=False)
name = Column(String(60), nullable=False)
# TODO: More complicated model, where trust also depends on realm.
trust_emails = Column(Boolean, default=True)
@classmethod
def get_by_type(cls, provider_type, create=True):
db = cls.default_db()
provider = db.query(cls).filter_by(
provider_type=provider_type).first()
if create and not provider:
# TODO: Better heuristic for name
name = provider_type.split("-")[0]
provider = cls(
provider_type=provider_type, name=name)
db.add(provider)
db.flush()
return provider
@classmethod
def populate_db(cls, db=None):
db = db or cls.default_db()
providers = config.get("login_providers") or []
trusted_providers = config.get("trusted_login_providers") or []
if not isinstance(providers, list):
providers = providers.split()
if not isinstance(trusted_providers, list):
trusted_providers = trusted_providers.split()
db.execute("lock table %s in exclusive mode" % cls.__table__.name)
db_providers = db.query(cls).all()
db_providers_by_type = {
p.provider_type: p for p in db_providers}
for provider in providers:
db_provider = db_providers_by_type.get(provider, None)
if db_provider is None:
db.add(cls(
name=provider, provider_type=provider,
trust_emails=(provider in trusted_providers)))
else:
db_provider.trust_emails = (provider in trusted_providers)
# copied from zxcvbn/src/feedback.coffee
# because extracting from another library is needlessly complicated
zxcvbn_messages = [
_('Straight rows of keys are easy to guess.'),
_('Short keyboard patterns are easy to guess.'),
_('Repeats like "aaa" are easy to guess.'),
_('Repeats like "abcabcabc" are only slightly harder to guess than "abc".'),
_("Sequences like abc or 6543 are easy to guess."),
_("Recent years are easy to guess."),
_("Dates are often easy to guess."),
_('This is a top-10 common password.'),
_('This is a top-100 common password.'),
_('This is a very common password.'),
_('This is similar to a commonly used password.'),
_('A word by itself is easy to guess.'),
_('Names and surnames by themselves are easy to guess.'),
_('Common names and surnames are easy to guess.'),
_("Use a few words, avoid common phrases."),
_("No need for symbols, digits, or uppercase letters."),
_('Add another word or two. Uncommon words are better.'),
_('Use a longer keyboard pattern with more turns.'),
_('Avoid repeated words and characters.'),
_('Avoid sequences.'),
_('Avoid recent years.'),
_('Avoid years that are associated with you.'),
_('Avoid dates and years that are associated with you.'),
_("Capitalization doesn't help very much."),
_("All-uppercase is almost as easy to guess as all-lowercase."),
_("Reversed words aren't much harder to guess."),
_("Predictable substitutions like '@' instead of 'a' don't help very much."),
]
class AgentStatusInDiscussion(DiscussionBoundBase):
"""Information about a user's activity in a discussion
Whether the user has logged in and is subscribed to notifications."""
__tablename__ = 'agent_status_in_discussion'
__table_args__ = (
UniqueConstraint('discussion_id', 'profile_id'), )
id = Column(Integer, primary_key=True)
discussion_id = Column(
Integer, ForeignKey("discussion.id", ondelete='CASCADE', onupdate='CASCADE'), nullable=False, index=True)
discussion = relationship(
"Discussion", backref=backref("agent_status_in_discussion", cascade="all, delete-orphan"))
profile_id = Column(Integer, ForeignKey("agent_profile.id", ondelete='CASCADE', onupdate='CASCADE'), nullable=False, index=True)
agent_profile = relationship(
AgentProfile, backref=backref("agent_status_in_discussion", cascade="all, delete-orphan"))
first_visit = Column(DateTime)
last_visit = Column(DateTime)
first_subscribed = Column(DateTime)
last_unsubscribed = Column(DateTime)
user_created_on_this_discussion = Column(Boolean, server_default='0')
accepted_cookies = Column(Text()) # JSON blob
def __init__(self, *args, **kwargs):
super(AgentStatusInDiscussion, self).__init__(*args, **kwargs)
self._convert_cookies_to_enums()
@orm.reconstructor
def init_on_load(self):
self._convert_cookies_to_enums()
def _convert_cookies_to_enums(self):
# A private variable _accepted_cookies is used to track the Enum-list of cookies supported
if '_accepted_cookies' not in vars(self):
if not self.accepted_cookies:
self._accepted_cookies = list()
else:
self._accepted_cookies = [CookieTypes(c.strip()) for c in self.accepted_cookies.split(",")]
return self._accepted_cookies
def _save_cookies(self):
if '_accepted_cookies' in vars(self):
self.accepted_cookies = ",".join([c.value for c in self._accepted_cookies])
@property
def cookies(self):
return self._accepted_cookies
@property
def has_any_accepted_cookies(self):
if self.cookies and len(self.cookies) > 0:
for cookie in self.cookies:
if cookie in AcceptedCookies:
return True
return False
return False
@property
def has_any_rejected_cookies(self):
if self.cookies and len(self.cookies) > 0:
for cookie in self.cookies:
if cookie in RejectedCookies:
return True
return False
return False
def has_cookie(self, cookie):
if isinstance(cookie, basestring):
cookie = CookieTypes(cookie)
if self.cookies and len(self.cookies) > 0:
return cookie in self.cookies
return False
def update_cookie(self, cookie):
"""
@param: cookies: a CookieType to be added to the list of accepted cookies.
"""
if isinstance(cookie, basestring):
cookie = CookieTypes(cookie)
if cookie not in self._accepted_cookies:
self._accepted_cookies.append(cookie)
self._save_cookies()
def delete_cookie(self, cookie):
"""
@param: cookie to be removed from the list of accepted_cookies
"""
if isinstance(cookie, basestring):
cookie = CookieTypes(cookie)
if cookie in self._accepted_cookies:
i = self._accepted_cookies.index(cookie)
self._accepted_cookies.pop(i)
self._save_cookies()
def load_cookies_from_request(self, request, force_read=False):
cookies = request.cookies
if not cookies:
return
if len(self.cookies) == 0 or force_read:
cookie_list = cookies.get('cookies_configuration', "")
cookie_piwik = cookies.get('piwik_ignore', "")
cookie_list = [c.strip() for c in cookie_list.split(",") if c]
for cookie in cookie_list:
try:
cookie = CookieTypes(cookie)
self.update_cookie(cookie)
except ValueError:
# Not a cookie of concern. Don't load.
pass
if cookie_piwik:
self.update_cookie('REJECT_TRACKING_ON_DISCUSSION')
def get_discussion_id(self):
return self.discussion_id or self.discussion.id
@classmethod
def get_discussion_conditions(cls, discussion_id, alias_maker=None):
return (cls.discussion_id == discussion_id,)
def is_owner(self, user_id):
return user_id == self.profile_id
crud_permissions = CrudPermissions(
P_READ, P_ADMIN_DISC, P_ADMIN_DISC, P_ADMIN_DISC, P_READ, P_READ, P_READ)
@event.listens_for(AgentStatusInDiscussion, 'after_insert', propagate=True)
def send_user_to_socket_for_asid(mapper, connection, target):
agent_profile = target.agent_profile
if not target.agent_profile:
agent_profile = AgentProfile.get(target.profile_id)
agent_profile.send_to_changes(
connection, CrudOperation.UPDATE, target.discussion_id)
class User(AgentProfile):
"""
A user of the platform.
"""
__tablename__ = "user"
__mapper_args__ = {
'polymorphic_identity': 'user'
}
id = Column(
Integer,
ForeignKey('agent_profile.id', ondelete='CASCADE', onupdate='CASCADE'),
primary_key=True
)
preferred_email = Column(EmailUnicode(100))
verified = Column(Boolean(), default=False)
password = deferred(Column(Binary(115)))
timezone = Column(Time(True))
last_login = Column(DateTime)
last_assembl_login = Column(DateTime)
login_failures = Column(Integer, default=0)
creation_date = Column(
DateTime, nullable=False, default=datetime.utcnow)
social_accounts = relationship('SocialAuthAccount')
is_deleted = Column(Boolean(), default=False)
is_machine = Column(Boolean(), default=False)
last_accepted_cgu_date = Column(DateTime)
last_accepted_privacy_policy_date = Column(DateTime)
last_rejected_cgu_date = Column(DateTime)
last_rejected_privacy_policy_date = Column(DateTime)
last_accepted_user_guideline_date = Column(DateTime)
last_rejected_user_guideline_date = Column(DateTime)
def __init__(self, **kwargs):
password = kwargs.pop('password', None)
super(User, self).__init__(**kwargs)
if password is not None:
self.password_p = password
@classmethod
def populate_db(cls, db=None):
default_config = config.get_config()
# retrieve the configured machines
machines_data = default_config.get('machines', '')
if machines_data:
from ..auth.util import add_user
db = db or cls.default_db()
# retrieve existing machines
machines = db.query(cls).filter(
cls.is_machine == True # noqa: E712
)
# retrieve machines ids
all_machines_ids = [machine.username_p for machine in machines]
machines_data = [machine.split(',') for machine in machines_data.split('/')]
machines_data = {machine[0].strip(): {'name': machine[1].strip(), 'password': machine[2].strip()}
for machine in machines_data}
# retrieve the not existing machines
machines_ids = [id for id in machines_data if id not in all_machines_ids]
# add the not existing machines
for machine_id in machines_ids:
machine = machines_data[machine_id]
add_user(
machine.get('name'),
None,
machine.get('password'),
R_CATCHER,
username=machine_id,
is_machine=True,
flush=False,
db=db
)
@property
def real_name_p(self):
return self.real_name()
@real_name_p.setter
def real_name_p(self, name):
if name:
name = name.strip()
if not name:
return
elif len(name) < 3:
if not self.name or len(self.name) < len(name):
self.name = name
else:
self.name = name
@property
def user_last_accepted_cgu_date(self):
return self.last_accepted_cgu_date
@user_last_accepted_cgu_date.setter
def user_last_accepted_cgu_date(self, date=None):
date = date or datetime.utcnow()
self.last_accepted_cgu_date = date
@property
def user_last_accepted_privacy_policy_date(self):
return self.last_accepted_privacy_policy_date
@user_last_accepted_privacy_policy_date.setter
def user_last_accepted_privacy_policy_date(self, date=None):
date = date or datetime.utcnow()
self.last_accepted_privacy_policy_date = date
@property
def user_last_accepted_user_guideline_date(self):
return self.last_accepted_user_guideline_date
@user_last_accepted_user_guideline_date.setter
def user_last_accepted_user_guideline_date(self, date=None):
date = date or datetime.utcnow()
self.last_accepted_user_guideline_date = date
@property
def user_last_rejected_cgu_date(self):
return self.last_rejected_cgu_date
@user_last_rejected_cgu_date.setter
def user_last_rejected_cgu_date(self, date=None):
date = date or datetime.utcnow()
self.last_rejected_cgu_date = date
@property
def user_last_rejected_privacy_policy_date(self):
return self.last_rejected_privacy_policy_date
@user_last_rejected_privacy_policy_date.setter
def user_last_rejected_privacy_policy_date(self, date=None):
date = date or datetime.utcnow()
self.last_rejected_privacy_policy_date = date
@property
def user_last_rejected_user_guideline_date(self):
return self.last_rejected_user_guideline_date
@user_last_rejected_user_guideline_date.setter
def user_last_rejected_user_guideline_date(self, date=None):
date = date or datetime.utcnow()
self.last_rejected_user_guideline_date = date
@property
def username_p(self):
if self.username:
return self.username.username
@username_p.setter
def username_p(self, name):
if self.username:
if name:
self.username.username = name
else:
self.db.delete(self.username)
elif name:
self.username = Username(username=name)
@username_p.deleter
def username_p(self):
if self.username:
self.db.delete(self.username)
@property
def password_p(self):
return ""
def validate_password(self, password):
from ..auth.password import verify_password
# check length
minimum_password_length = int(config.get("minimum_password_length", 5))
if len(password) < minimum_password_length:
raise LocalizableErrorWithMapping(
_("Password shorter than ${minlen} characters"),
mapping={"minlen": minimum_password_length})
# look for presence of required elements (see regexp)
password_required_classes = config.get("password_required_classes", None)
if password_required_classes:
if not isinstance(password_required_classes, dict):
# Should be done upstream to optimize