-
-
Notifications
You must be signed in to change notification settings - Fork 207
/
participant.py
3832 lines (3485 loc) · 152 KB
/
participant.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
from base64 import b64decode, b64encode
from collections import defaultdict
from datetime import date, timedelta
from decimal import Decimal
from email.utils import formataddr
from hashlib import pbkdf2_hmac, md5, sha1
from operator import attrgetter, itemgetter
from os import urandom
from threading import Lock
from time import sleep
from types import SimpleNamespace
import unicodedata
from urllib.parse import urlencode
import uuid
import aspen_jinja2_renderer
from cached_property import cached_property
from dateutil.parser import parse as parse_date
from html2text import html2text
import mangopay
from markupsafe import escape as htmlescape
from pando import json, Response
from pando.utils import utcnow
from postgres.orm import Model
from psycopg2.errors import IntegrityError, ReadOnlySqlTransaction
from psycopg2.extras import execute_batch, execute_values
import requests
from liberapay.billing.payday import compute_next_payday_date
from liberapay.constants import (
ASCII_ALLOWED_IN_USERNAME, AVATAR_QUERY, BASE64URL_CHARS, CURRENCIES,
DONATION_LIMITS, EMAIL_VERIFICATION_TIMEOUT, EVENTS, HTML_A,
PASSWORD_MAX_SIZE, PASSWORD_MIN_SIZE, PAYPAL_CURRENCIES,
PERIOD_CONVERSION_RATES, PRIVILEGES,
PUBLIC_NAME_MAX_SIZE, SEPA, SESSION, SESSION_REFRESH, SESSION_TIMEOUT,
USERNAME_MAX_SIZE, USERNAME_SUFFIX_BLACKLIST,
)
from liberapay.exceptions import (
BadAmount,
BadDonationCurrency,
BadPasswordSize,
CannotRemovePrimaryEmail,
DuplicateNotification,
EmailAddressIsBlacklisted,
EmailAlreadyTaken,
EmailNotVerified,
InvalidId,
NonexistingElsewhere,
NoSelfTipping,
NoTippee,
TooManyTeamsCreated,
TooManyCurrencyChanges,
TooManyEmailAddresses,
TooManyEmailVerifications,
TooManyPasswordLogins,
TooManyUsernameChanges,
UnableToDistributeBalance,
UnableToSendEmail,
UnexpectedCurrency,
UsernameAlreadyTaken,
UsernameBeginsWithRestrictedCharacter,
UsernameContainsInvalidCharacters,
UsernameEndsWithForbiddenSuffix,
UsernameIsEmpty,
UsernameIsRestricted,
UsernameTooLong,
ValueTooLong,
ValueContainsForbiddenCharacters,
VerificationEmailAlreadySent,
)
from liberapay.i18n import base as i18n
from liberapay.i18n.currencies import Money, MoneyBasket
from liberapay.models._mixin_team import MixinTeam
from liberapay.models.account_elsewhere import AccountElsewhere
from liberapay.models.community import Community
from liberapay.models.tip import Tip
from liberapay.payin.common import resolve_amounts, resolve_take_amounts
from liberapay.payin.prospect import PayinProspect
from liberapay.security.crypto import constant_time_compare
from liberapay.utils import (
deserialize, erase_cookie, get_recordable_headers, serialize, set_cookie,
urlquote,
markdown,
)
from liberapay.utils.emails import (
NormalizedEmailAddress, EmailVerificationResult, check_email_blacklist,
normalize_email_address,
)
from liberapay.utils.types import Object
from liberapay.website import website
email_lock = Lock()
class Participant(Model, MixinTeam):
typname = 'participants'
ANON = False
EMAIL_VERIFICATION_TIMEOUT = EMAIL_VERIFICATION_TIMEOUT
session = None
def __eq__(self, other):
if not isinstance(other, Participant):
return False
return self.id == other.id
def __ne__(self, other):
if not isinstance(other, Participant):
return True
return self.id != other.id
def __repr__(self):
return '<Participant #%r %r>' % (self.id, self.username)
# Constructors
# ============
@classmethod
def make_stub(cls, cursor=None, **kw):
"""Return a new stub participant.
"""
if kw:
cols, vals = zip(*kw.items())
cols = ', '.join(cols)
placeholders = ', '.join(['%s']*len(vals))
x = '({0}) VALUES ({1})'.format(cols, placeholders)
else:
x, vals = 'DEFAULT VALUES', ()
with cls.db.get_cursor(cursor) as c:
return c.one("""
INSERT INTO participants {0}
RETURNING participants.*::participants
""".format(x), vals)
@classmethod
def make_active(cls, kind, currency, username=None, cursor=None, request_data=None):
"""Return a new active participant.
"""
now = utcnow()
d = {
'kind': kind,
'status': 'active',
'join_time': now,
'main_currency': currency,
'accepted_currencies': currency,
}
cols, vals = zip(*d.items())
cols = ', '.join(cols)
placeholders = ', '.join(['%s']*len(vals))
with cls.db.get_cursor(cursor) as c:
p = c.one("""
INSERT INTO participants ({0}) VALUES ({1})
RETURNING participants.*::participants
""".format(cols, placeholders), vals)
p.add_event(c, 'sign_up_request', request_data)
if username:
p.change_username(username, cursor=c)
return p
def make_team(self, name, currency, email=None, email_lang=None, throttle_takes=True):
if email and not isinstance(email, NormalizedEmailAddress):
raise TypeError("expected NormalizedEmailAddress, got %r" % type(email))
with self.db.get_cursor() as c:
c.hit_rate_limit('make_team', self.id, TooManyTeamsCreated)
t = c.one("""
INSERT INTO participants
(kind, status, join_time, throttle_takes, main_currency)
VALUES ('group', 'active', now(), %s, %s)
RETURNING participants.*::participants
""", (throttle_takes, currency))
t.change_username(name, cursor=c)
t.add_member(self, c)
if email:
t.set_email_lang(email_lang, cursor=c)
t.add_email(email, cursor=c)
return t
def leave_team(self, team):
team.set_take_for(self, None, self)
if not team.nmembers:
team.close()
@classmethod
def from_id(cls, id, _raise=True):
"""Return an existing participant based on id.
"""
r = cls.db.one("SELECT p FROM participants p WHERE id = %s", (id,))
if r is None and _raise:
raise InvalidId(id, cls.__name__)
return r
@classmethod
def from_username(cls, username, id_only=False):
"""Return an existing participant based on username.
"""
return cls.db.one("""
SELECT {0} FROM participants p WHERE lower(username) = %s
""".format('p.id' if id_only else 'p'), (username.lower(),))
@classmethod
def from_email(cls, email, id_only=False):
# This query looks for an unverified address if the participant
# doesn't have any verified address
return cls.db.one("""
SELECT {0}
FROM emails e
JOIN participants p ON p.id = e.participant
WHERE lower(e.address) = %s
AND (p.email IS NULL OR lower(p.email) = lower(e.address))
ORDER BY p.email NULLS LAST, p.id ASC
LIMIT 1
""".format('p.id' if id_only else 'p'), (email.lower(),))
@classmethod
def from_mangopay_user_id(cls, mangopay_user_id):
return cls.db.one("""
SELECT p
FROM mangopay_users u
JOIN participants p ON p.id = u.participant
WHERE u.id = %s
""", (mangopay_user_id,))
@classmethod
def check_id(cls, p_id):
try:
p_id = int(p_id)
except (ValueError, TypeError):
return
return cls.db.one("SELECT id FROM participants WHERE id = %s", (p_id,))
@classmethod
def get_id_for(cls, type_of_id, id_value):
return getattr(cls, 'from_' + type_of_id)(id_value, id_only=True)
@classmethod
def authenticate(cls, p_id, secret_id, secret, context='log-in'):
if not secret:
return
try:
p_id = int(p_id)
secret_id = int(secret_id)
except (ValueError, TypeError):
return
if secret_id >= 1: # session token
r = cls.db.one("""
SELECT p, s.secret, s.mtime
FROM user_secrets s
JOIN participants p ON p.id = s.participant
WHERE s.participant = %s
AND s.id = %s
AND s.mtime > %s
""", (p_id, secret_id, utcnow() - SESSION_TIMEOUT))
if not r:
return
p, stored_secret, mtime = r
if constant_time_compare(stored_secret, secret):
p.authenticated = True
p.session = SimpleNamespace(id=secret_id, secret=secret, mtime=mtime)
return p
elif secret_id == 0: # user-input password
r = cls.db.one("""
SELECT p, s.secret
FROM user_secrets s
JOIN participants p ON p.id = s.participant
WHERE s.participant = %s
AND s.id = %s
""", (p_id, secret_id))
if not r:
return
p, stored_secret = r
if context == 'log-in':
cls.db.hit_rate_limit('log-in.password', p.id, TooManyPasswordLogins)
algo, rounds, salt, hashed = stored_secret.split('$', 3)
rounds = int(rounds)
salt, hashed = b64decode(salt), b64decode(hashed)
if constant_time_compare(cls._hash_password(secret, algo, salt, rounds), hashed):
p.authenticated = True
if context == 'log-in':
cls.db.decrement_rate_limit('log-in.password', p.id)
if len(salt) < 32:
# Update the password hash in the DB
hashed = cls.hash_password(secret)
cls.db.run(
"UPDATE user_secrets SET secret = %s WHERE participant = %s AND id = 0",
(hashed, p.id)
)
return p
@classmethod
def get_chargebacks_account(cls, currency):
p = cls.db.one("""
SELECT p
FROM participants p
WHERE mangopay_user_id = 'CREDIT'
""")
if not p:
p = cls.make_stub(
goal=Money(-1, currency),
hide_from_search=3,
hide_from_lists=3,
join_time=utcnow(),
kind='organization',
mangopay_user_id='CREDIT',
status='active',
username='_chargebacks_',
)
wallet = cls.db.one("""
INSERT INTO wallets
(remote_id, balance, owner, remote_owner_id)
VALUES (%s, %s, %s, 'CREDIT')
ON CONFLICT (remote_id) DO UPDATE
SET remote_owner_id = 'CREDIT' -- dummy update
RETURNING *
""", ('CREDIT_' + currency, Money.ZEROS[currency], p.id))
return p, wallet
def refetch(self):
r = self.db.one("SELECT p FROM participants p WHERE id = %s", (self.id,))
r.session = self.session
return r
# Password Management
# ===================
@staticmethod
def _hash_password(password, algo, salt, rounds):
return pbkdf2_hmac(algo, password.encode('utf8'), salt, rounds)
@classmethod
def hash_password(cls, password):
# Using SHA-256 as the HMAC algorithm (PBKDF2 + HMAC-SHA-256)
algo = 'sha256'
# Generate 32 random bytes for the salt
salt = urandom(32)
rounds = website.app_conf.password_rounds
hashed = cls._hash_password(password, algo, salt, rounds)
hashed = '$'.join((
algo,
str(rounds),
b64encode(salt).decode('ascii'),
b64encode(hashed).decode('ascii')
))
return hashed
def update_password(self, password, cursor=None, checked=True):
l = len(password)
if l < PASSWORD_MIN_SIZE or l > PASSWORD_MAX_SIZE:
raise BadPasswordSize
hashed = self.hash_password(password)
p_id = self.id
current_session_id = getattr(self.session, 'id', 0)
with self.db.get_cursor(cursor) as c:
c.run("""
INSERT INTO user_secrets
(participant, id, secret)
VALUES (%(p_id)s, 0, %(hashed)s)
ON CONFLICT (participant, id) DO UPDATE
SET secret = excluded.secret
, mtime = current_timestamp;
DELETE FROM user_secrets
WHERE participant = %(p_id)s
AND id >= 1 AND id <= 20
AND id <> %(current_session_id)s
AND secret NOT LIKE '%%.em';
""", locals())
if checked:
self.add_event(c, 'password-check', None)
@cached_property
def has_password(self):
return self.db.one(
"SELECT participant FROM user_secrets WHERE participant = %s AND id = 0",
(self.id,)
) is not None
def check_password(self, password, context):
if context == 'login':
last_password_check = self.get_last_event_of_type('password-check')
if last_password_check and utcnow() - last_password_check.ts < timedelta(days=180):
return
passhash = sha1(password.encode("utf-8")).hexdigest().upper()
passhash_prefix, passhash_suffix = passhash[:5], passhash[5:]
url = "https://api.pwnedpasswords.com/range/" + passhash_prefix
r = requests.get(url=url)
count = 0
for line in r.text.split():
parts = line.split(":")
if parts[0] == passhash_suffix:
count = int(parts[1])
if count > 500:
status = 'common'
elif count > 0:
status = 'compromised'
else:
status = 'okay'
if context == 'login':
if status != 'okay':
self.notify('password_warning', email=False, type='warning', password_status=status)
self.add_event(website.db, 'password-check', None)
return status
# Session Management
# ==================
@staticmethod
def generate_session_token():
return b64encode(urandom(24), b'-_').decode('ascii')
@staticmethod
def check_session_token(token):
if len(token) < 32:
raise Response(400, "bad token, too short")
if not set(token).issubset(BASE64URL_CHARS):
raise Response(400, "bad token, not base64url")
def regenerate_session(self, session, cookies, suffix='.rg'):
self.session = self.db.one("""
UPDATE user_secrets
SET mtime = current_timestamp
, secret = %(new_secret)s
WHERE participant = %(p_id)s
AND id = %(session_id)s
AND mtime = %(current_mtime)s
RETURNING id, secret, mtime
""", dict(
new_secret=self.generate_session_token() + suffix,
p_id=self.id,
session_id=session.id,
current_mtime=session.mtime,
))
if self.session:
creds = '%i:%i:%s' % (self.id, self.session.id, self.session.secret)
set_cookie(cookies, SESSION, creds, expires=utcnow() + SESSION_TIMEOUT)
def start_session(self, suffix='', token=None, id_min=1, id_max=20,
lifetime=SESSION_TIMEOUT):
"""Start a new session for the user.
Args:
suffix (str):
the session type ('.em' for email sessions, empty for normal sessions)
token (str):
the session token, if it's already been generated
id_min (int):
the lowest acceptable session ID
id_max (int):
the highest acceptable session ID
lifetime (timedelta):
the session timeout, used to determine if existing sessions have expired
The session ID is selected in the following order:
1. if the oldest existing session has expired, then its ID is reused;
2. if there are unused session IDs, then the lowest one is claimed;
3. the oldest session is overwritten, even though it hasn't expired yet.
"""
assert id_min < id_max, (id_min, id_max)
if token:
if not token.endswith(suffix):
self.check_session_token(token)
token += suffix
else:
token = self.generate_session_token() + suffix
p_id = self.id
session = self.db.one("""
WITH oldest_secret AS (
SELECT *
FROM user_secrets
WHERE participant = %(p_id)s
AND id >= %(id_min)s
AND id <= %(id_max)s
ORDER BY mtime
LIMIT 1
)
, unused_id AS (
SELECT i
FROM generate_series(%(id_min)s, %(id_max)s) i
WHERE NOT EXISTS (
SELECT 1
FROM user_secrets s2
WHERE s2.participant = %(p_id)s
AND s2.id = i
)
ORDER BY i
LIMIT 1
)
INSERT INTO user_secrets AS s
(participant, id, secret)
SELECT %(p_id)s
, coalesce(
(SELECT s2.id FROM oldest_secret s2
WHERE s2.mtime < (current_timestamp - %(lifetime)s)
),
(SELECT i FROM unused_id),
(SELECT s2.id FROM oldest_secret s2)
)
, %(token)s
ON CONFLICT (participant, id) DO UPDATE
SET mtime = excluded.mtime
, secret = excluded.secret
WHERE s.mtime = (SELECT s2.mtime FROM oldest_secret s2)
RETURNING *
""", locals())
if session is None:
return self.start_session(token=token, id_min=id_min, id_max=id_max)
return session
def sign_in(self, cookies, session=None, **session_kw):
assert self.authenticated
self.session = session or self.start_session(**session_kw)
creds = '%i:%i:%s' % (self.id, self.session.id, self.session.secret)
set_cookie(cookies, SESSION, creds, self.session.mtime + SESSION_TIMEOUT)
def keep_signed_in(self, cookies):
"""Extend the user's current session.
"""
now = utcnow()
if now - self.session.mtime > SESSION_REFRESH:
self.regenerate_session(self.session, cookies)
def sign_out(self, cookies):
"""End the user's current session.
"""
self.db.run("DELETE FROM user_secrets WHERE participant = %s AND id = %s",
(self.id, self.session.id))
del self.session
erase_cookie(cookies, SESSION)
@property
def session_type(self):
session = self.session
if session:
if not hasattr(session, 'type'):
i = session.secret.rfind('.')
session.type = session.secret[i+1:] if i > 0 else ''
return session.type
# Permissions
# ===========
def has_privilege(self, p):
return self.privileges & PRIVILEGES[p]
@cached_property
def is_admin(self):
return self.privileges & PRIVILEGES['admin']
# Statement
# =========
def get_statement(self, langs, type='profile'):
"""Get the participant's statement in the language that best matches
the list provided, or the participant's "primary" statement if there
are no matches. Returns a tuple `(content, lang)`.
If langs isn't a list but a string, then it's assumed to be a language
code and the corresponding statement content will be returned, or None.
"""
p_id = self.id
if not isinstance(langs, list):
return self.db.one("""
SELECT content
FROM statements
WHERE participant = %(p_id)s
AND type = %(type)s
AND lang = %(langs)s
""", locals())
return self.db.one("""
SELECT content, lang
FROM statements
LEFT JOIN enumerate(%(langs)s::text[]) langs ON langs.value = statements.lang
WHERE participant = %(p_id)s
AND type = %(type)s
ORDER BY langs.rank NULLS LAST, statements.id
LIMIT 1
""", locals(), default=(None, None))
def get_statement_langs(self, type='profile'):
return self.db.all("""
SELECT lang FROM statements WHERE participant=%s AND type=%s
""", (self.id, type))
def upsert_statement(self, lang, statement, type='profile'):
if not statement:
self.db.run("""
DELETE FROM statements
WHERE participant=%s
AND type=%s
AND lang=%s
""", (self.id, type, lang))
return
search_conf = i18n.SEARCH_CONFS.get(lang, 'simple')
self.db.run("""
INSERT INTO statements
(lang, content, participant, search_conf, type, ctime, mtime)
VALUES (%s, %s, %s, %s, %s, now(), now())
ON CONFLICT (participant, type, lang) DO UPDATE
SET content = excluded.content
, mtime = excluded.mtime
""", (lang, statement, self.id, search_conf, type))
# Stubs
# =====
def resolve_stub(self):
rec = self.db.one("""
SELECT platform, user_id, user_name, domain
FROM elsewhere
WHERE participant = %s
""", (self.id,))
if rec:
if rec.user_name:
slug = urlquote(rec.user_name) + ('@' + rec.domain if rec.domain else '')
else:
slug = '~' + urlquote(rec.user_id) + (':' + rec.domain if rec.domain else '')
return '/on/%s/%s/' % (rec.platform, slug)
return None
# Closing
# =======
class AccountNotEmpty(Exception): pass
def final_check(self, cursor):
"""Sanity-check that balance has been dealt with.
"""
if self.balance != 0:
raise self.AccountNotEmpty
class UnknownDisbursementStrategy(Exception): pass
def close(self, disbursement_strategy=None):
"""Close the participant's account.
"""
if disbursement_strategy is None:
pass # No balance, supposedly. final_check will make sure.
elif disbursement_strategy == 'downstream':
# This in particular needs to come before clear_tips_giving.
self.distribute_balances_to_donees()
else:
raise self.UnknownDisbursementStrategy
with self.db.get_cursor() as cursor:
self.clear_tips_giving(cursor)
self.clear_takes(cursor)
if self.kind == 'group':
self.remove_all_members(cursor)
self.clear_subscriptions(cursor)
self.final_check(cursor)
self.update_status('closed', cursor)
def distribute_balances_to_donees(self, arrears_only=False):
"""Distribute the user's balance(s) downstream.
"""
if self.balance == 0:
return
tips = self.db.all("""
SELECT tip.amount, tip.tippee, tip.ctime, tip.periodic_amount
, tip.paid_in_advance, tip.renewal_mode
, tippee_p
, compute_arrears(tip) AS arrears_due
FROM current_tips tip
JOIN participants tippee_p ON tippee_p.id = tip.tippee
WHERE tip.tipper = %s
AND tippee_p.status = 'active'
AND (tippee_p.mangopay_user_id IS NOT NULL OR tippee_p.kind = 'group')
AND tippee_p.is_suspended IS NOT TRUE
""", (self.id,))
if arrears_only:
tips = [tip for tip in tips if tip.arrears_due > 0]
for tip in tips:
if tip.tippee_p.kind == 'group':
currency = tip.amount.currency
tip.team = Participant.from_id(tip.tippee)
unfiltered_takes = tip.team.get_current_takes_for_payment(
currency, 'mangopay', tip.amount
)
tip.takes = [
t for t in unfiltered_takes
if t.has_payment_account and not t.is_suspended and t.member != self.id
]
if len(unfiltered_takes) == 1 and tip.takes and tip.takes[0].amount == 0:
# Team of one with a zero take
tip.takes[0].amount.amount = Decimal('1')
tip.total_takes = MoneyBasket(t.amount for t in tip.takes)
tips = [t for t in tips if getattr(t, 'total_takes', -1) != 0]
if not tips:
raise UnableToDistributeBalance(self.balance)
transfers = []
for wallet in self.get_current_wallets():
if wallet.balance == 0:
continue
currency = wallet.balance.currency
tips_in_this_currency = sorted(
[t for t in tips if t.amount.currency == currency],
key=lambda t: (t.amount, t.ctime), reverse=True
)
if not tips_in_this_currency:
continue
zero = Money.ZEROS[currency]
for_arrears = {
tip.tippee: max(tip.arrears_due, zero) for tip in tips_in_this_currency
}
for_arrears_sum = Money.sum(for_arrears.values(), currency)
if wallet.balance < for_arrears_sum:
for_arrears = resolve_amounts(wallet.balance, for_arrears)
for_arrears_sum = wallet.balance
renewable_tips = [
tip for tip in tips_in_this_currency
if tip.renewal_mode > 0 and tip.tippee_p.accepts_tips
]
if renewable_tips and not arrears_only and wallet.balance > for_arrears_sum:
for tip in renewable_tips:
if tip.paid_in_advance is None:
tip.paid_in_advance = zero
max_advance_weeks = max(
t.paid_in_advance / t.amount for t in renewable_tips
)
if max_advance_weeks < 1:
max_advance_weeks = 1
for tip in renewable_tips:
tip.convergence_amount = max((
tip.amount * max_advance_weeks - tip.paid_in_advance
), zero)
for_advances = resolve_amounts(
wallet.balance - for_arrears_sum,
{tip.tippee: tip.amount for tip in renewable_tips},
{tip.tippee: tip.convergence_amount for tip in renewable_tips},
)
else:
for_advances = {}
for tip in tips_in_this_currency:
arrears = for_arrears.get(tip.tippee, zero)
advance = for_advances.get(tip.tippee, zero)
if tip.tippee_p.kind == 'group':
team_id = tip.tippee
if arrears:
resolved_takes = resolve_amounts(
arrears,
{take.member: take.amount for take in tip.takes},
)
n_weeks = arrears / tip.amount
for take in tip.takes:
resolved_amount = resolved_takes.get(take.member, zero)
if resolved_amount > 0:
unit_amount = (resolved_amount / n_weeks).round_up()
transfers.append(
[take.member, None, resolved_amount, team_id, wallet, unit_amount]
)
if advance:
resolve_take_amounts(advance, tip.takes)
n_weeks = advance / tip.periodic_amount
for take in tip.takes:
resolved_amount = take.resolved_amount
if resolved_amount > 0:
unit_amount = (resolved_amount / n_weeks).round_up()
transfers.append(
[take.member, resolved_amount, None, team_id, wallet, unit_amount]
)
del take.resolved_amount
else:
transfers.append(
[tip.tippee, advance, arrears, None, wallet, tip.amount]
)
if not transfers:
raise UnableToDistributeBalance(self.balance)
from liberapay.billing.transactions import transfer
db = self.db
tipper = self.id
for tippee, advance, arrears, team, wallet, unit_amount in transfers:
if arrears:
context = 'take-in-arrears' if team else 'tip-in-arrears'
balance = transfer(
db, tipper, tippee, arrears, context,
team=team, unit_amount=unit_amount,
tipper_mango_id=self.mangopay_user_id,
tipper_wallet_id=wallet.remote_id
)[0]
if advance:
assert not arrears_only
context = 'take-in-advance' if team else 'tip-in-advance'
balance = transfer(
db, tipper, tippee, advance, context,
team=team, unit_amount=unit_amount,
tipper_mango_id=self.mangopay_user_id,
tipper_wallet_id=wallet.remote_id
)[0]
self.set_attributes(balance=balance)
self.schedule_renewals()
if self.balance != 0:
raise UnableToDistributeBalance(self.balance)
def donate_remaining_balances_to_liberapay(self):
"""Donate what's left in the user's wallets to Liberapay.
"""
self.transfer_remaining_balances_to_liberapay(donate=True)
def transfer_remaining_balances_to_liberapay(self, donate=False):
LiberapayOrg = self.from_username('LiberapayOrg')
Liberapay = self.from_username('Liberapay')
tip = self.get_tip_to(LiberapayOrg)
if not tip.amount:
tip = self.get_tip_to(Liberapay)
context, team = None, None
if donate:
if tip.amount:
if tip.tippee == Liberapay.id:
team = Liberapay.id
else:
context = 'final-gift'
else:
context = 'indirect-payout'
from liberapay.billing.transactions import transfer
for wallet in self.get_current_wallets():
if wallet.balance == 0:
continue
if context:
balance = transfer(
self.db, self.id, LiberapayOrg.id, wallet.balance, context,
team=team, unit_amount=tip.amount.convert(wallet.balance.currency) or None,
tipper_mango_id=self.mangopay_user_id, tipper_wallet_id=wallet.remote_id
)[0]
else:
arrears_due = self.db.one("""
SELECT compute_arrears(tip)
FROM tips tip
WHERE tip.id = %s
""", (tip.id,)).convert(wallet.balance.currency)
arrears = min(max(arrears_due, 0), wallet.balance)
advance = wallet.balance - arrears
assert arrears > 0 or advance > 0
assert (arrears + advance) == wallet.balance
if arrears:
context = 'take-in-arrears' if team else 'tip-in-arrears'
balance = transfer(
self.db, self.id, LiberapayOrg.id, arrears, context,
team=team, unit_amount=tip.amount.convert(wallet.balance.currency) or None,
tipper_mango_id=self.mangopay_user_id, tipper_wallet_id=wallet.remote_id
)[0]
if advance:
context = 'take-in-advance' if team else 'tip-in-advance'
balance = transfer(
self.db, self.id, LiberapayOrg.id, advance, context,
team=team, unit_amount=tip.amount.convert(wallet.balance.currency) or None,
tipper_mango_id=self.mangopay_user_id, tipper_wallet_id=wallet.remote_id
)[0]
self.set_attributes(balance=balance)
def clear_tips_giving(self, cursor):
"""Turn off the renewal of all tips from a given user.
"""
tippees = cursor.all("""
INSERT INTO tips
( ctime, tipper, tippee, amount, period, periodic_amount
, paid_in_advance, is_funded, renewal_mode )
SELECT ctime, tipper, tippee, amount, period, periodic_amount
, paid_in_advance, is_funded, 0
FROM current_tips
WHERE tipper = %s
AND renewal_mode > 0
RETURNING ( SELECT p FROM participants p WHERE p.id = tippee ) AS tippee
""", (self.id,))
for tippee in tippees:
tippee.update_receiving(cursor=cursor)
def clear_takes(self, cursor):
"""Leave all teams by zeroing all takes.
"""
teams = cursor.all("""
SELECT p.*::participants
FROM current_takes x
JOIN participants p ON p.id = x.team
WHERE member=%s
""", (self.id,))
for t in teams:
t.set_take_for(self, None, self, cursor=cursor)
def clear_subscriptions(self, cursor):
"""Unsubscribe from all newsletters.
"""
cursor.run("""
UPDATE subscriptions
SET is_on = false
, mtime = current_timestamp
WHERE subscriber = %s
""", (self.id,))
def erase_personal_information(self):
"""Erase forever the user's personal data (statements, goal, etc).
"""
r = self.db.one("""
DELETE FROM community_memberships WHERE participant=%(id)s;
DELETE FROM subscriptions WHERE subscriber=%(id)s;
UPDATE emails
SET participant = NULL
, verified = NULL
WHERE participant = %(id)s
AND address <> %(email)s;
DELETE FROM notifications WHERE participant=%(id)s;
DELETE FROM statements WHERE participant=%(id)s;
DELETE FROM events
WHERE participant = %(id)s
AND (recorder IS NULL OR recorder = participant)
AND type NOT IN (
'account-kind-change',
'mangopay-account-change',
'set_status'
);
UPDATE participants
SET avatar_url=NULL
, avatar_src=NULL
, avatar_email=NULL
, public_name=NULL
WHERE id=%(id)s
RETURNING *;
""", dict(id=self.id, email=self.get_email_address(allow_disavowed=True)))
self.set_attributes(**r._asdict())
self.add_event(self.db, 'erase_personal_information', None)
def invalidate_exchange_routes(self):
"""Disable any saved payment routes (cards, bank accounts).
"""
routes = self.db.all("""
SELECT r
FROM exchange_routes r
WHERE participant = %s
AND status = 'chargeable'
""", (self.id,))
for route in routes:
route.invalidate()
@cached_property
def closed_time(self):
return self.db.one("""
SELECT ts
FROM events
WHERE participant=%s
AND type='set_status'
AND payload='"closed"'
ORDER BY ts DESC
LIMIT 1
""", (str(self.id),))
# Deleting
# ========
def delete(self):
if self.status != 'closed':
self.close()
with self.db.get_cursor() as cursor:
cursor.run("""
UPDATE emails SET participant = NULL, verified = NULL WHERE participant = %(p_id)s;
DELETE FROM events WHERE participant = %(p_id)s;
DELETE FROM user_secrets
WHERE participant = %(p_id)s
AND id >= 1
AND mtime <= (current_timestamp - %(SESSION_TIMEOUT)s);
DELETE FROM participants WHERE id = %(p_id)s;
""", dict(p_id=self.id, SESSION_TIMEOUT=SESSION_TIMEOUT))
# Emails
# ======
def add_email(self, email, cursor=None):
"""
This is called when
1) Adding a new email address
2) Resending the verification email for an unverified email address
Returns the number of emails sent.
"""
if not isinstance(email, NormalizedEmailAddress):
email = normalize_email_address(email)
# Check that this address isn't already verified