-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
account.py
956 lines (794 loc) · 35 KB
/
account.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
import json
import web
import logging
import json
import re
from infogami.utils import delegate
from infogami import config
from infogami.utils.view import (
require_login, render, render_template, add_flash_message
)
from infogami.infobase.client import ClientException
from infogami.utils.context import context
import infogami.core.code as core
from openlibrary import accounts
from openlibrary.i18n import gettext as _
from openlibrary.core import helpers as h, lending
from openlibrary.core.bookshelves import Bookshelves
from openlibrary.plugins.recaptcha import recaptcha
from openlibrary.plugins import openlibrary as olib
from openlibrary.accounts import (
audit_accounts, Account, OpenLibraryAccount, InternetArchiveAccount, valid_email)
from openlibrary.core.sponsorships import get_sponsored_editions
from openlibrary.plugins.upstream import borrow, forms, utils
from six.moves import range
from six.moves import urllib
logger = logging.getLogger("openlibrary.account")
RESULTS_PER_PAGE = 25
USERNAME_RETRIES = 3
# XXX: These need to be cleaned up
send_verification_email = accounts.send_verification_email
create_link_doc = accounts.create_link_doc
sendmail = accounts.sendmail
LOGIN_ERRORS = {
"invalid_email": "The email address you entered is invalid",
"account_blocked": "This account has been blocked",
"account_locked": "This account has been blocked",
"account_not_found": "No account was found with this email. Please try again",
"account_incorrect_password": "The password you entered is incorrect. Please try again",
"account_bad_password": "Wrong password. Please try again",
"account_not_verified": "Please verify your Open Library account before logging in",
"ia_account_not_verified": "Please verify your Internet Archive account before logging in",
"missing_fields": "Please fill out all fields and try again",
"email_registered": "This email is already registered",
"username_registered": "This username is already registered",
"ia_login_only": "Sorry, you must use your Internet Archive email and password to log in",
"max_retries_exceeded": "A problem occurred and we were unable to log you in.",
"invalid_s3keys": "Login attempted with invalid Internet Archive s3 credentials.",
"wrong_ia_account": "An Open Library account with this email is already linked to a different Internet Archive account. Please contact info@openlibrary.org."
}
class availability(delegate.page):
path = "/internal/fake/availability"
def POST(self):
"""Internal private API required for testing on localhost
"""
return delegate.RawText(json.dumps({}),
content_type="application/json")
class loans(delegate.page):
path = "/internal/fake/loans"
def POST(self):
"""Internal private API required for testing on localhost
"""
return delegate.RawText(json.dumps({}),
content_type="application/json")
class xauth(delegate.page):
path = "/internal/fake/xauth"
def POST(self):
"""Internal private API required for testing login on localhost
which normally would have to hit archive.org's xauth
service. This service is spoofable to return successful and
unsuccessful login attempts depending on the provided GET parameters
"""
i = web.input(email='', op=None)
result = {"error": "incorrect option specified"}
if i.op == "authenticate":
result = {
"success": True,
"version": 1,
"values": {
"access": 'foo',
"secret": 'foo',
},
}
elif i.op == "info":
result = {
"success": True,
"values": {
"locked": False,
"email": "openlibrary@example.org",
"itemname":"@openlibrary",
"screenname":"openlibrary",
"verified": True
},
"version":1
}
return delegate.RawText(json.dumps(result),
content_type="application/json")
class internal_audit(delegate.page):
path = "/internal/account/audit"
def GET(self):
"""Internal API endpoint used for authorized test cases and
administrators to unlink linked OL and IA accounts.
"""
i = web.input(email='', username='', itemname='', key='', unlink='',
new_itemname='')
if i.key != lending.config_internal_tests_api_key:
result = {'error': 'Authentication failed for private API'}
else:
try:
result = OpenLibraryAccount.get(email=i.email, link=i.itemname,
username=i.username)
if result is None:
raise ValueError('Invalid Open Library account email ' \
'or itemname')
result.enc_password = 'REDACTED'
if i.new_itemname:
result.link(i.new_itemname)
if i.unlink:
result.unlink()
except ValueError as e:
result = {'error': str(e)}
return delegate.RawText(json.dumps(result),
content_type="application/json")
class account_migration(delegate.page):
path = "/internal/account/migration"
def GET(self):
i = web.input(username='', email='', key='')
if i.key != lending.config_internal_tests_api_key:
return delegate.RawText(json.dumps({
'error': 'Authentication failed for private API'
}), content_type="application/json")
try:
if i.username:
ol_account = OpenLibraryAccount.get(username=i.username)
elif i.email:
ol_account = OpenLibraryAccount.get(email=i.email)
except Exception as e:
return delegate.RawText(json.dumps({
'error': 'bad-account'
}), content_type="application/json")
if ol_account:
ol_account.enc_password = 'REDACTED'
if ol_account.itemname:
return delegate.RawText(json.dumps({
'status': 'link-exists',
'username': ol_account.username,
'itemname': ol_account.itemname,
'email': ol_account.email.lower()
}), content_type="application/json")
if not ol_account.itemname:
ia_account = InternetArchiveAccount.get(email=ol_account.email.lower())
if ia_account:
ol_account.link(ia_account.itemname)
return delegate.RawText(json.dumps({
'username': ol_account.username,
'status': 'link-found',
'itemname': ia_account.itemname,
'ol-itemname': ol_account.itemname,
'email': ol_account.email.lower(),
'ia': ia_account
}), content_type="application/json")
password = OpenLibraryAccount.generate_random_password(16)
ia_account = InternetArchiveAccount.create(
ol_account.username or ol_account.displayname,
ol_account.email, password, verified=True, retries=USERNAME_RETRIES)
return delegate.RawText(json.dumps({
'username': ol_account.username,
'email': ol_account.email,
'itemname': ia_account.itemname,
'password': password,
'status': 'link-created'
}), content_type="application/json")
class account(delegate.page):
"""Account preferences.
"""
@require_login
def GET(self):
user = accounts.get_current_user()
return render.account(user)
class account_create(delegate.page):
"""New account creation.
Account remains in the pending state until the email is activated.
"""
path = "/account/create"
def GET(self):
f = self.get_form()
return render['account/create'](f)
def get_form(self):
"""
:rtype: forms.RegisterForm
"""
f = forms.Register()
recap = self.get_recap()
f.has_recaptcha = recap is not None
if f.has_recaptcha:
f.inputs = list(f.inputs) + [recap]
return f
def get_recap(self):
if self.is_plugin_enabled('recaptcha'):
public_key = config.plugin_recaptcha.public_key
private_key = config.plugin_recaptcha.private_key
return recaptcha.Recaptcha(public_key, private_key)
def is_plugin_enabled(self, name):
return name in delegate.get_plugins() or "openlibrary.plugins." + name in delegate.get_plugins()
def POST(self):
f = self.get_form() # type: forms.RegisterForm
if f.validates(web.input()):
try:
# Create ia_account: require they activate via IA email
# and then login to OL. Logging in after activation with
# IA credentials will auto create and link OL account.
notifications = ['announce-general'] if f.ia_newsletter.checked else []
InternetArchiveAccount.create(
screenname=f.username.value, email=f.email.value, password=f.password.value,
notifications=notifications, verified=False, retries=USERNAME_RETRIES)
return render['account/verify'](username=f.username.value, email=f.email.value)
except ValueError:
f.note = LOGIN_ERRORS['max_retries_exceeded']
return render['account/create'](f)
del delegate.pages['/account/register']
class account_login_json(delegate.page):
encoding = "json"
path = "/account/login"
def POST(self):
"""Overrides `account_login` and infogami.login to prevent users from
logging in with Open Library username and password if the
payload is json. Instead, if login attempted w/ json
credentials, requires Archive.org s3 keys.
"""
from openlibrary.plugins.openlibrary.code import BadRequest
d = json.loads(web.data())
access = d.get('access', None)
secret = d.get('secret', None)
test = d.get('test', False)
# Try S3 authentication first, fallback to infogami user, pass
if access and secret:
audit = audit_accounts(None, None, require_link=True,
s3_access_key=access,
s3_secret_key=secret, test=test)
error = audit.get('error')
if error:
raise olib.code.BadRequest(error)
web.setcookie(config.login_cookie_name, web.ctx.conn.get_auth_token())
# Fallback to infogami user/pass
else:
from infogami.plugins.api.code import login as infogami_login
infogami_login().POST()
class account_login(delegate.page):
"""Account login.
Login can fail because of the following reasons:
* account_not_found: Error message is displayed.
* account_bad_password: Error message is displayed with a link to reset password.
* account_not_verified: Error page is dispalyed with button to "resend verification email".
"""
path = "/account/login"
def render_error(self, error_key, i):
f = forms.Login()
f.fill(i)
f.note = LOGIN_ERRORS[error_key]
return render.login(f)
def GET(self):
referer = web.ctx.env.get('HTTP_REFERER', '/')
# Don't set referer on user activation
if 'archive.org' in referer:
referer = None
i = web.input(redirect=referer)
f = forms.Login()
f['redirect'].value = i.redirect
return render.login(f)
def POST(self):
i = web.input(username="", connect=None, password="", remember=False,
redirect='/', test=False, access=None, secret=None)
email = i.username # XXX username is now email
audit = audit_accounts(email, i.password, require_link=True,
s3_access_key=i.access,
s3_secret_key=i.secret, test=i.test)
error = audit.get('error')
if error:
return self.render_error(error, i)
expires = 3600 * 24 * 7 if i.remember else ""
web.setcookie('pd', int(audit.get('special_access')) or '',
expires=expires)
web.setcookie(config.login_cookie_name, web.ctx.conn.get_auth_token(),
expires=expires)
blacklist = ["/account/login", "/account/password", "/account/email",
"/account/create"]
if i.redirect == "" or any([path in i.redirect for path in blacklist]):
i.redirect = "/"
raise web.seeother(i.redirect)
def POST_resend_verification_email(self, i):
try:
ol_login = OpenLibraryAccount.authenticate(i.email, i.password)
except ClientException as e:
code = e.get_data().get("code")
if code != "account_not_verified":
return self.error("account_incorrect_password", i)
account = OpenLibraryAccount.get(email=i.email)
account.send_verification_email()
title = _("Hi, %(user)s", user=account.displayname)
message = _("We've sent the verification email to %(email)s. You'll need to read that and click on the verification link to verify your email.", email=account.email)
return render.message(title, message)
class account_verify(delegate.page):
"""Verify user account.
"""
path = "/account/verify/([0-9a-f]*)"
def GET(self, code):
docs = web.ctx.site.store.values(type="account-link", name="code", value=code)
if docs:
doc = docs[0]
account = accounts.find(username = doc['username'])
if account:
if account['status'] != "pending":
return render['account/verify/activated'](account)
account.activate()
user = web.ctx.site.get("/people/" + doc['username']) #TBD
return render['account/verify/success'](account)
else:
return render['account/verify/failed']()
def POST(self, code=None):
"""Called to regenerate account verification code.
"""
i = web.input(email=None)
account = accounts.find(email=i.email)
if not account:
return render_template("account/verify/failed", email=i.email)
elif account['status'] != "pending":
return render['account/verify/activated'](account)
else:
account.send_verification_email()
title = _("Hi, %(user)s", user=account.displayname)
message = _("We've sent the verification email to %(email)s. You'll need to read that and click on the verification link to verify your email.", email=account.email)
return render.message(title, message)
class account_verify_old(account_verify):
"""Old account verification code.
This takes username, email and code as url parameters. The new one takes just the code as part of the url.
"""
path = "/account/verify"
def GET(self):
# It is too long since we switched to the new account verification links.
# All old links must be expired by now.
# Show failed message without thinking.
return render['account/verify/failed']()
class account_validation(delegate.page):
path = '/account/validate'
@staticmethod
def validate_username(username):
if not 3 <= len(username) <= 20:
return _('Username must be between 3-20 characters')
if not re.match('^[A-Za-z0-9-_]{3,20}$', username):
return _('Username may only contain numbers and letters')
ol_account = OpenLibraryAccount.get(username=username)
if ol_account:
return _("Username unavailable")
@staticmethod
def validate_email(email):
if not (email and re.match(r'.*@.*\..*', email)):
return _('Must be a valid email address')
ol_account = OpenLibraryAccount.get(email=email)
if ol_account:
return _('Email already registered')
def GET(self):
i = web.input()
errors = {
'email': None,
'username': None
}
if i.get('email') is not None:
errors['email'] = self.validate_email(i.email)
if i.get('username') is not None:
errors['username'] = self.validate_username(i.username)
return delegate.RawText(json.dumps(errors),
content_type="application/json")
class account_email_verify(delegate.page):
path = "/account/email/verify/([0-9a-f]*)"
def GET(self, code):
link = accounts.get_link(code)
if link:
username = link['username']
email = link['email']
link.delete()
return self.update_email(username, email)
else:
return self.bad_link()
def update_email(self, username, email):
if accounts.find(email=email):
title = _("Email address is already used.")
message = _("Your email address couldn't be updated. The specified email address is already used.")
else:
logger.info("updated email of %s to %s", username, email)
accounts.update_account(username=username, email=email, status="active")
title = _("Email verification successful.")
message = _('Your email address has been successfully verified and updated in your account.')
return render.message(title, message)
def bad_link(self):
title = _("Email address couldn't be verified.")
message = _("Your email address couldn't be verified. The verification link seems invalid.")
return render.message(title, message)
class account_email_verify_old(account_email_verify):
path = "/account/email/verify"
def GET(self):
# It is too long since we switched to the new email verification links.
# All old links must be expired by now.
# Show failed message without thinking.
return self.bad_link()
class account_ia_email_forgot(delegate.page):
path = "/account/email/forgot-ia"
def GET(self):
return render_template('account/email/forgot-ia')
def POST(self):
i = web.input(email='', password='')
err = ""
if valid_email(i.email):
act = OpenLibraryAccount.get(email=i.email)
if act:
if OpenLibraryAccount.authenticate(i.email, i.password) == "ok":
ia_act = act.get_linked_ia_account()
if ia_act:
return render_template('account/email/forgot-ia', email=ia_act.email)
else:
err = "Open Library Account not linked. Login with your Open Library credentials to connect or create an Archive.org account"
else:
err = "Incorrect password"
else:
err = "Sorry, this Open Library account does not exist"
else:
err = "Please enter a valid Open Library email"
return render_template('account/email/forgot-ia', err=err)
class account_ol_email_forgot(delegate.page):
path = "/account/email/forgot"
def GET(self):
return render_template('account/email/forgot')
def POST(self):
i = web.input(username='', password='')
err = ""
act = OpenLibraryAccount.get(username=i.username)
if act:
if OpenLibraryAccount.authenticate(act.email, i.password) == "ok":
return render_template('account/email/forgot', email=act.email)
else:
err = "Incorrect password"
elif valid_email(i.username):
err = "Please enter a username, not an email"
else:
err="Sorry, this user does not exist"
return render_template('account/email/forgot', err=err)
class account_password_forgot(delegate.page):
path = "/account/password/forgot"
def GET(self):
f = forms.ForgotPassword()
return render['account/password/forgot'](f)
def POST(self):
i = web.input(email='')
f = forms.ForgotPassword()
if not f.validates(i):
return render['account/password/forgot'](f)
account = accounts.find(email=i.email)
if account.is_blocked():
f.note = utils.get_error("account_blocked")
return render_template('account/password/forgot', f)
send_forgot_password_email(account.username, i.email)
return render['account/password/sent'](i.email)
class account_password_reset(delegate.page):
path = "/account/password/reset/([0-9a-f]*)"
def GET(self, code):
docs = web.ctx.site.store.values(type="account-link", name="code", value=code)
if not docs:
title = _("Password reset failed.")
message = "Your password reset link seems invalid or expired."
return render.message(title, message)
f = forms.ResetPassword()
return render['account/password/reset'](f)
def POST(self, code):
link = accounts.get_link(code)
if not link:
title = _("Password reset failed.")
message = "The password reset link seems invalid or expired."
return render.message(title, message)
username = link['username']
i = web.input()
accounts.update_account(username, password=i.password)
link.delete()
return render_template("account/password/reset_success", username=username)
class account_audit(delegate.page):
path = "/account/audit"
def POST(self):
"""When the user attempts a login, an audit is performed to determine
whether their account is already linked (in which case we can
proceed to log the user in), whether there is an error
authenticating their account, or whether a /account/connect
must first performed.
Note: Emails are case sensitive behind the scenes and
functions which require them as lower will make them so
"""
i = web.input(email='', password='')
test = i.get('test', '').lower() == 'true'
email = i.get('email')
password = i.get('password')
result = audit_accounts(email, password, test=test)
return delegate.RawText(json.dumps(result),
content_type="application/json")
class account_privacy(delegate.page):
path = "/account/privacy"
@require_login
def GET(self):
user = accounts.get_current_user()
return render['account/privacy'](user.preferences())
@require_login
def POST(self):
user = accounts.get_current_user()
user.save_preferences(web.input())
add_flash_message('note', _("Notification preferences have been updated successfully."))
web.seeother("/account")
class account_notifications(delegate.page):
path = "/account/notifications"
@require_login
def GET(self):
user = accounts.get_current_user()
email = user.email
return render['account/notifications'](user.preferences(), email)
@require_login
def POST(self):
user = accounts.get_current_user()
user.save_preferences(web.input())
add_flash_message('note', _("Notification preferences have been updated successfully."))
web.seeother("/account")
class account_lists(delegate.page):
path = "/account/lists"
@require_login
def GET(self):
user = accounts.get_current_user()
raise web.seeother(user.key + '/lists')
class ReadingLog(object):
"""Manages the user's account page books (reading log, waitlists, loans)"""
def __init__(self, user=None):
self.user = user or accounts.get_current_user()
#self.user.update_loan_status()
self.KEYS = {
'waitlists': self.get_waitlisted_editions,
'loans': self.get_loans,
'want-to-read': self.get_want_to_read,
'currently-reading': self.get_currently_reading,
'already-read': self.get_already_read
}
@property
def lists(self):
return self.user.get_lists()
@property
def reading_log_counts(self):
counts = Bookshelves.count_total_books_logged_by_user_per_shelf(
self.user.get_username())
return {
'want-to-read': counts.get(Bookshelves.PRESET_BOOKSHELVES['Want to Read'], 0),
'currently-reading': counts.get(Bookshelves.PRESET_BOOKSHELVES['Currently Reading'], 0),
'already-read': counts.get(Bookshelves.PRESET_BOOKSHELVES['Already Read'], 0)
}
def get_loans(self):
return borrow.get_loans(self.user)
def get_waitlist_summary(self):
return self.user.get_waitinglist()
def get_waitlisted_editions(self):
"""Gets a list of records corresponding to a user's waitlisted
editions, fetches all the editions, and then inserts the data
from each waitlist record (e.g. position in line) into the
corresponding edition
"""
waitlists = self.user.get_waitinglist()
keyed_waitlists = dict([(w['identifier'], w) for w in waitlists])
ocaids = [i['identifier'] for i in waitlists]
edition_keys = web.ctx.site.things({"type": "/type/edition", "ocaid": ocaids})
editions = web.ctx.site.get_many(edition_keys)
for i in range(len(editions)):
# insert the waitlist_entry corresponding to this edition
editions[i].waitlist_record = keyed_waitlists[editions[i].ocaid]
return editions
def get_want_to_read(self, page=1, limit=RESULTS_PER_PAGE):
work_ids = ['/works/OL%sW' % i['work_id'] for i in Bookshelves.get_users_logged_books(
self.user.get_username(), bookshelf_id=Bookshelves.PRESET_BOOKSHELVES['Want to Read'],
page=page, limit=limit)]
return web.ctx.site.get_many(work_ids)
def get_currently_reading(self, page=1, limit=RESULTS_PER_PAGE):
work_ids = ['/works/OL%sW' % i['work_id'] for i in Bookshelves.get_users_logged_books(
self.user.get_username(), bookshelf_id=Bookshelves.PRESET_BOOKSHELVES['Currently Reading'],
page=page, limit=limit)]
return web.ctx.site.get_many(work_ids)
def get_already_read(self, page=1, limit=RESULTS_PER_PAGE):
work_ids = ['/works/OL%sW' % i['work_id'] for i in Bookshelves.get_users_logged_books(
self.user.get_username(), bookshelf_id=Bookshelves.PRESET_BOOKSHELVES['Already Read'],
page=page, limit=limit)]
return web.ctx.site.get_many(work_ids)
def get_works(self, key, page=1, limit=RESULTS_PER_PAGE):
"""
:rtype: list of openlibrary.plugins.upstream.models.Work
"""
key = key.lower()
if key in self.KEYS:
return self.KEYS[key](page=page, limit=limit)
else: # must be a list or invalid page!
#works = web.ctx.site.get_many([ ... ])
raise
class public_my_books(delegate.page):
path = "/people/([^/]+)/books"
def GET(self, username):
raise web.seeother('/people/%s/books/want-to-read' % username)
class public_my_books(delegate.page):
path = "/people/([^/]+)/books/([a-zA-Z_-]+)"
def GET(self, username, key='loans'):
"""check if user's reading log is public"""
i = web.input(page=1)
user = web.ctx.site.get('/people/%s' % username)
if not user:
return render.notfound("User %s" % username, create=False)
is_public = user.preferences().get('public_readlog', 'no') == 'yes'
logged_in_user = accounts.get_current_user()
if is_public or logged_in_user and logged_in_user.key.split('/')[-1] == username:
readlog = ReadingLog(user=user)
sponsorships = get_sponsored_editions(user)
if key == 'sponsorships':
books = (web.ctx.site.get(
web.ctx.site.things({
'type': '/type/edition',
'isbn_%s' % len(s['isbn']): s['isbn']
})[0]) for s in sponsorships)
else:
books = readlog.get_works(key, page=i.page)
return render['account/books'](
books, key, sponsorship_count=len(sponsorships),
reading_log_counts=readlog.reading_log_counts, lists=readlog.lists,
user=user, logged_in_user=logged_in_user, public=is_public
)
raise web.seeother(user.key)
class readinglog_stats(delegate.page):
path = "/people/([^/]+)/books/([a-zA-Z_-]+)/stats"
def GET(self, username, key='loans'):
user = web.ctx.site.get('/people/%s' % username)
if not user:
return render.notfound("User %s" % username, create=False)
cur_user = accounts.get_current_user()
if not cur_user or cur_user.key.split('/')[-1] != username:
return render.permission_denied(web.ctx.path, 'Permission Denied')
readlog = ReadingLog(user=user)
works = readlog.get_works(key, page=1, limit=2000)
works_json = [
{
'title': w.get('title'),
'key': w.key,
'author_keys': [a.author.key for a in w.get('authors', [])],
'first_publish_year': w.first_publish_year or None,
'subjects': w.get('subjects'),
'subject_people': w.get('subject_people'),
'subject_places': w.get('subject_places'),
'subject_times': w.get('subject_times'),
} for w in works
]
author_keys = set(
a
for work in works_json
for a in work['author_keys']
)
authors_json = [
{
'key': a.key,
'name': a.name,
'birth_date': a.get('birth_date'),
}
for a in web.ctx.site.get_many(list(author_keys))
]
return render['account/readinglog_stats'](
json.dumps(works_json),
json.dumps(authors_json),
len(works_json),
user.key,
user.displayname,
web.ctx.path.rsplit('/', 1)[0],
key,
lang=web.ctx.lang,
)
class account_my_books_redirect(delegate.page):
path = "/account/books/(.*)"
@require_login
def GET(self, rest='loans'):
user = accounts.get_current_user()
username = user.key.split('/')[-1]
raise web.seeother('/people/%s/books/%s' % (username, rest))
class account_my_books(delegate.page):
path = "/account/books"
@require_login
def GET(self):
user = accounts.get_current_user()
username = user.key.split('/')[-1]
raise web.seeother('/people/%s/books' % (username))
# This would be by the civi backend which would require the api keys
class fake_civi(delegate.page):
path = "/internal/fake/civicrm"
def GET(self):
i = web.input(entity='Contact')
contact = {
'values': [{
'contact_id': '270430'
}]
}
contributions = {
'values': [{
"receive_date": "2019-07-31 08:57:00",
"custom_52": "9780062457714",
"total_amount": "50.00",
"custom_53": "ol"
}]
}
entity = contributions if i.entity == 'Contribution' else contact
return delegate.RawText(json.dumps(entity), content_type="application/json")
class import_books(delegate.page):
path = "/account/import"
@require_login
def GET(self):
return render['account/import']()
class fetch_goodreads(delegate.page):
path = "/account/import/goodreads"
def GET(self):
raise web.seeother("/account/import")
@require_login
def POST(self):
books, books_wo_isbns = process_goodreads_csv(web.input())
return render['account/import'](books, books_wo_isbns)
class export_books(delegate.page):
path = "/account/export"
@require_login
def GET(self):
user = accounts.get_current_user()
username = user.key.split('/')[-1]
books = Bookshelves.get_users_logged_books(username, limit=10000)
csv = []
csv.append('Work Id,Edition Id,Bookshelf\n')
mapping = {1:'Want to Read', 2:'Currently Reading', 3:'Already Read'}
for book in books:
row = [
'OL{}W'.format(book['work_id']),
'OL{}M'.format(book['edition_id']) if book['edition_id'] else '',
'{}\n'.format(mapping[book['bookshelf_id']])
]
csv.append(','.join(row))
web.header('Content-Type','text/csv')
web.header('Content-disposition', 'attachment; filename=OpenLibrary_ReadingLog.csv')
csv = ''.join(csv)
return delegate.RawText(csv, content_type="text/csv")
class account_loans(delegate.page):
path = "/account/loans"
@require_login
def GET(self):
user = accounts.get_current_user()
user.update_loan_status()
loans = borrow.get_loans(user)
return render['account/borrow'](user, loans)
# Disabling be cause it prevents account_my_books_redirect from working
# for some reason. The purpose of this class is to not show the "Create" link for
# /account pages since that doesn't make any sense.
# class account_others(delegate.page):
# path = "(/account/.*)"
#
# def GET(self, path):
# return render.notfound(path, create=False)
def send_forgot_password_email(username, email):
key = "account/%s/password" % username
doc = create_link_doc(key, username, email)
web.ctx.site.store[key] = doc
link = web.ctx.home + "/account/password/reset/" + doc['code']
msg = render_template("email/password/reminder", username=username, email=email, link=link)
sendmail(email, msg)
def as_admin(f):
"""Infobase allows some requests only from admin user. This decorator logs in as admin, executes the function and clears the admin credentials."""
def g(*a, **kw):
try:
delegate.admin_login()
return f(*a, **kw)
finally:
web.ctx.headers = []
return g
def process_goodreads_csv(i):
import csv
csv_payload = i.csv if isinstance(i.csv, str) else i.csv.decode()
csv_file = csv.reader(csv_payload.splitlines(), delimiter=',', quotechar='"')
header = next(csv_file)
books = {}
books_wo_isbns = {}
for book in list(csv_file):
_book = dict(zip(header, book))
isbn = _book['ISBN'] = _book['ISBN'].replace('"', '').replace('=', '')
isbn_13 = _book['ISBN13'] = _book['ISBN13'].replace('"', '').replace('=', '')
if isbn != '':
books[isbn] = _book
elif isbn_13 != '':
books[isbn_13] = _book
books[isbn_13]['ISBN'] = isbn_13
else:
books_wo_isbns[_book['Book Id']] = _book
return books, books_wo_isbns