This repository has been archived by the owner on Nov 9, 2017. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
Copy pathapi.py
5248 lines (4427 loc) · 194 KB
/
api.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
# The contents of this file are subject to the Common Public Attribution
# License Version 1.0. (the "License"); you may not use this file except in
# compliance with the License. You may obtain a copy of the License at
# http://code.reddit.com/LICENSE. The License is based on the Mozilla Public
# License Version 1.1, but Sections 14 and 15 have been added to cover use of
# software over a computer network and provide for limited attribution for the
# Original Developer. In addition, Exhibit A has been modified to be consistent
# with Exhibit B.
#
# Software distributed under the License is distributed on an "AS IS" basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
# the specific language governing rights and limitations under the License.
#
# The Original Code is reddit.
#
# The Original Developer is the Initial Developer. The Initial Developer of
# the Original Code is reddit Inc.
#
# All portions of the code written by reddit are Copyright (c) 2006-2015 reddit
# Inc. All Rights Reserved.
###############################################################################
import csv
from collections import defaultdict
import hashlib
import re
import urllib
import urllib2
from r2.controllers.reddit_base import (
abort_with_error,
cross_domain,
generate_modhash,
is_trusted_origin,
MinimalController,
paginated_listing,
RedditController,
set_user_cookie,
)
from pylons.i18n import _
from pylons import request, response
from pylons import tmpl_context as c
from pylons import app_globals as g
from r2.lib.validator import *
from r2.models import *
from r2.lib import amqp
from r2.lib import recommender
from r2.lib import hooks
from r2.lib.ratelimit import SimpleRateLimit
from r2.lib.utils import (
blockquote_text,
extract_user_mentions,
get_title,
query_string,
randstr,
sanitize_url,
timefromnow,
timeuntil,
tup,
)
from r2.lib.pages import (
BoringPage,
ClickGadget,
CssError,
FormPage,
Reddit,
responsive,
UploadedImage,
UrlParser,
WrappedUser,
)
from r2.lib.pages import FlairList, FlairCsv, FlairTemplateEditor, \
FlairSelector
from r2.lib.pages import PrefApps
from r2.lib.pages import (
BannedTableItem,
ContributorTableItem,
FriendTableItem,
InvitedModTableItem,
ModTableItem,
MutedTableItem,
ReportForm,
SubredditReportForm,
SubredditStylesheet,
WikiBannedTableItem,
WikiMayContributeTableItem,
)
from r2.lib.pages.things import (
default_thing_wrapper,
hot_links_by_url_listing,
wrap_links,
)
from r2.lib.menus import CommentSortMenu
from r2.lib.captcha import get_iden
from r2.lib.strings import strings
from r2.lib.template_helpers import format_html, header_url
from r2.lib.filters import _force_unicode, _force_utf8, websafe_json, websafe, spaceCompress
from r2.lib.db import queries
from r2.lib import media
from r2.lib.db import tdb_cassandra
from r2.lib import promote
from r2.lib import tracking, emailer, newsletter
from r2.lib.subreddit_search import search_reddits
from r2.lib.filters import safemarkdown
from r2.lib.media import str_to_image
from r2.controllers.api_docs import api_doc, api_section
from r2.controllers.oauth2 import require_oauth2_scope, allow_oauth2_access
from r2.lib.template_helpers import (
add_sr,
get_domain,
make_url_protocol_relative,
)
from r2.lib.system_messages import (
notify_user_added,
send_ban_message,
send_mod_removal_message,
)
from r2.controllers.ipn import generate_blob, update_blob
from r2.controllers.login import handle_login, handle_register
from r2.lib.lock import TimeoutExpired
from r2.lib.csrf import csrf_exempt
from r2.lib.voting import cast_vote
from r2.models import wiki
from r2.models.ip import set_account_ip
from r2.models.recommend import AccountSRFeedback, FEEDBACK_ACTIONS
from r2.models.rules import SubredditRules
from r2.models.vote import Vote
from r2.lib.merge import ConflictException
from datetime import datetime, timedelta
from urlparse import urlparse
class ApiminimalController(MinimalController):
"""
Put API calls in here which don't rely on the user being logged in
"""
# Since this is only a MinimalController, the
# @allow_oauth2_access decorator has little effect other than
# (1) to add the endpoint to /dev/api/oauth, and
# (2) to future-proof in case the function moves elsewhere
@allow_oauth2_access
@csrf_exempt
@validatedForm()
@api_doc(api_section.captcha)
def POST_new_captcha(self, form, jquery, *a, **kw):
"""
Responds with an `iden` of a new CAPTCHA.
Use this endpoint if a user cannot read a given CAPTCHA,
and wishes to receive a new CAPTCHA.
To request the CAPTCHA image for an iden, use
[/captcha/`iden`](#GET_captcha_{iden}).
"""
iden = get_iden()
jquery("body").captcha(iden)
form._send_data(iden = iden)
class ApiController(RedditController):
"""
Controller which deals with almost all AJAX site interaction.
"""
@validatedForm()
def ajax_login_redirect(self, form, jquery, dest):
form.redirect("/login" + query_string(dict(dest=dest)))
@require_oauth2_scope("read")
@validate(
things=VByName('id', multiple=True, ignore_missing=True, limit=100),
url=VUrl('url'),
)
@api_doc(api_section.links_and_comments, uses_site=True)
def GET_info(self, things, url):
"""
Return a listing of things specified by their fullnames.
Only Links, Comments, and Subreddits are allowed.
"""
if url:
return self.GET_url_info()
thing_classes = (Link, Comment, Subreddit)
things = things or []
things = filter(lambda thing: isinstance(thing, thing_classes), things)
c.update_last_visit = False
listing = wrap_links(things)
return BoringPage(_("API"), content=listing).render()
@require_oauth2_scope("read")
@validate(
url=VUrl('url'),
count=VLimit('limit'),
things=VByName('id', multiple=True, limit=100),
)
def GET_url_info(self, url, count, things):
"""
Return a list of links with the given URL.
If a subreddit is provided, only links in that subreddit will be
returned.
"""
if things and not url:
return self.GET_info()
c.update_last_visit = False
if url:
listing = hot_links_by_url_listing(url, sr=c.site, num=count)
else:
listing = None
return BoringPage(_("API"), content=listing).render()
@json_validate()
def GET_me(self, responder):
"""Get info about the currently authenticated user.
Response includes a modhash, karma, and new mail status.
"""
if c.user_is_loggedin:
user_data = Wrapped(c.user).render()
user_data['data'].update({'features': feature.all_enabled(c.user)})
return user_data
else:
return {'data': {'features': feature.all_enabled(None)}}
@json_validate(user=VUname(("user",)))
@api_doc(api_section.users)
def GET_username_available(self, responder, user):
"""
Check whether a username is available for registration.
"""
if not (responder.has_errors("user", errors.BAD_USERNAME)):
return bool(user)
@csrf_exempt
@json_validate(user=VUname(("user",)))
def POST_check_username(self, responder, user):
"""
Check whether a username is valid.
"""
if not (responder.has_errors("user",
errors.USERNAME_TOO_SHORT,
errors.USERNAME_INVALID_CHARACTERS,
errors.USERNAME_TAKEN_DEL,
errors.USERNAME_TAKEN)):
# Pylons does not handle 204s correctly.
return {}
@csrf_exempt
@json_validate(password=VPassword(("passwd")))
def POST_check_password(self, responder, password):
"""
Check whether a password is valid.
"""
if not (responder.has_errors("passwd", errors.SHORT_PASSWORD) or
responder.has_errors("passwd", errors.BAD_PASSWORD)):
# Pylons does not handle 204s correctly.
return {}
@csrf_exempt
@json_validate(email=ValidEmail("email"),
newsletter_subscribe=VBoolean("newsletter_subscribe", default=False),
sponsor=VBoolean("sponsor", default=False))
def POST_check_email(self, responder, email, newsletter_subscribe, sponsor):
"""
Check whether an email is valid. Allows blank emails.
Additionally checks if a newsletter is requested, and will be strict
on blank emails if so.
"""
if newsletter_subscribe and not email:
c.errors.add(errors.NEWSLETTER_NO_EMAIL, field="email")
responder.has_errors("email", errors.NEWSLETTER_NO_EMAIL)
return
if sponsor and not email:
c.errors.add(errors.SPONSOR_NO_EMAIL, field="email")
responder.has_errors("email", errors.SPONSOR_NO_EMAIL)
return
if not (responder.has_errors("email", errors.BAD_EMAIL)):
# Pylons does not handle 204s correctly.
return {}
@cross_domain(allow_credentials=True)
@json_validate(
VModhashIfLoggedIn(),
VRatelimit(rate_ip=True, prefix="rate_newsletter_"),
email=ValidEmail("email"),
source=VOneOf('source', ['newsletterbar', 'standalone'])
)
def POST_newsletter(self, responder, email, source):
"""Add an email to our newsletter."""
VRatelimit.ratelimit(rate_ip=True,
prefix="rate_newsletter_")
try:
newsletter.add_subscriber(email, source=source)
except newsletter.EmailUnacceptableError as e:
c.errors.add(errors.NEWSLETTER_EMAIL_UNACCEPTABLE, field="email")
responder.has_errors("email", errors.NEWSLETTER_EMAIL_UNACCEPTABLE)
return
except newsletter.NewsletterError as e:
g.log.warning("Failed to subscribe: %r" % e)
abort(500)
@allow_oauth2_access
@json_validate()
@api_doc(api_section.captcha)
def GET_needs_captcha(self, responder):
"""
Check whether CAPTCHAs are needed for API methods that define the
"captcha" and "iden" parameters.
"""
return bool(c.user.needs_captcha())
@require_oauth2_scope("privatemessages")
@validatedForm(
VCaptcha(),
VUser(),
VModhash(),
from_sr=VSRByName('from_sr', required=False),
to=VMessageRecipient('to'),
subject=VLength('subject', 100, empty_error=errors.NO_SUBJECT),
body=VMarkdownLength(['text', 'message'], max_length=10000),
)
@api_doc(api_section.messages)
def POST_compose(self, form, jquery, from_sr, to, subject, body):
"""
Handles message composition under /message/compose.
"""
if (form.has_errors("to",
errors.USER_DOESNT_EXIST, errors.NO_USER,
errors.SUBREDDIT_NOEXIST, errors.USER_BLOCKED,
) or
form.has_errors("subject", errors.NO_SUBJECT) or
form.has_errors("subject", errors.TOO_LONG) or
form.has_errors("text", errors.NO_TEXT, errors.TOO_LONG) or
form.has_errors("message", errors.TOO_LONG) or
form.has_errors("captcha", errors.BAD_CAPTCHA) or
form.has_errors("from_sr", errors.SUBREDDIT_NOEXIST)):
return
if form.has_errors("to", errors.USER_MUTED):
g.events.muted_forbidden_event("muted", target=to,
request=request, context=c)
form.set_inputs(to="", subject="", text="", captcha="")
return
if from_sr and isinstance(to, Subreddit):
c.errors.add(errors.NO_SR_TO_SR_MESSAGE, field="from")
form.has_errors("from", errors.NO_SR_TO_SR_MESSAGE)
return
if from_sr and BlockedSubredditsByAccount.is_blocked(to, from_sr):
c.errors.add(errors.USER_BLOCKED_MESSAGE, field="to")
form.has_errors("to", errors.USER_BLOCKED_MESSAGE)
return
if from_sr and from_sr._spam:
return
if from_sr:
if not from_sr.is_moderator_with_perms(c.user, "mail"):
abort(403)
elif from_sr.is_muted(to) and not c.user_is_admin:
c.errors.add(errors.MUTED_FROM_SUBREDDIT, field="to")
form.has_errors("to", errors.MUTED_FROM_SUBREDDIT)
g.events.muted_forbidden_event("muted mod", subreddit=from_sr,
target=to, request=request, context=c)
form.set_inputs(to="", subject="", text="", captcha="")
return
# Don't allow mods in timeout to send a message
VNotInTimeout().run(target=to, subreddit=from_sr)
m, inbox_rel = Message._new(c.user, to, subject, body, request.ip,
sr=from_sr, from_sr=True)
else:
# Only let users in timeout message the admins
if (to and not (isinstance(to, Subreddit) and
'/r/%s' % to.name == g.admin_message_acct)):
VNotInTimeout().run(target=to)
m, inbox_rel = Message._new(c.user, to, subject, body, request.ip)
form.set_text(".status", _("your message has been delivered"))
form.set_inputs(to = "", subject = "", text = "", captcha="")
queries.new_message(m, inbox_rel)
@require_oauth2_scope("submit")
@json_validate()
@api_doc(api_section.subreddits, uses_site=True)
def GET_submit_text(self, responder):
"""Get the submission text for the subreddit.
This text is set by the subreddit moderators and intended to be
displayed on the submission form.
See also: [/api/site_admin](#POST_api_site_admin).
"""
if c.site.over_18 and not c.over18:
submit_text = None
submit_text_html = None
else:
submit_text = c.site.submit_text
submit_text_html = safemarkdown(c.site.submit_text)
return {'submit_text': submit_text,
'submit_text_html': submit_text_html}
@require_oauth2_scope("submit")
@validatedForm(
VUser(),
VModhash(),
VCaptcha(),
VRatelimit(rate_user=True, rate_ip=True, prefix="rate_submit_"),
VShamedDomain('url'),
sr=VSubmitSR('sr', 'kind'),
url=VUrl('url'),
title=VTitle('title'),
sendreplies=VBoolean('sendreplies'),
selftext=VMarkdown('text'),
kind=VOneOf('kind', ['link', 'self']),
extension=VLength("extension", 20,
docs={"extension": "extension used for redirects"}),
resubmit=VBoolean('resubmit'),
)
@api_doc(api_section.links_and_comments)
def POST_submit(self, form, jquery, url, selftext, kind, title,
sr, extension, sendreplies, resubmit):
"""Submit a link to a subreddit.
Submit will create a link or self-post in the subreddit `sr` with the
title `title`. If `kind` is `"link"`, then `url` is expected to be a
valid URL to link to. Otherwise, `text`, if present, will be the
body of the self-post.
If a link with the same URL has already been submitted to the specified
subreddit an error will be returned unless `resubmit` is true.
`extension` is used for determining which view-type (e.g. `json`,
`compact` etc.) to use for the redirect that is generated if the
`resubmit` error occurs.
"""
from r2.models.admintools import is_banned_domain
if url:
if url.lower() == 'self':
url = kind = 'self'
# VUrl may have replaced 'url' by adding 'http://'
form.set_inputs(url=url)
is_self = (kind == "self")
if not kind or form.has_errors('sr', errors.INVALID_OPTION):
return
if form.has_errors('captcha', errors.BAD_CAPTCHA):
return
if form.has_errors('sr',
errors.SUBREDDIT_NOEXIST,
errors.SUBREDDIT_NOTALLOWED,
errors.SUBREDDIT_REQUIRED,
errors.INVALID_OPTION,
errors.NO_SELFS,
errors.NO_LINKS,
errors.IN_TIMEOUT,
):
return
if not sr.can_submit_text(c.user) and is_self:
# this could happen if they actually typed "self" into the
# URL box and we helpfully translated it for them
c.errors.add(errors.NO_SELFS, field='sr')
form.has_errors('sr', errors.NO_SELFS)
return
if form.has_errors("title", errors.NO_TEXT, errors.TOO_LONG):
return
if not sr.should_ratelimit(c.user, 'link'):
c.errors.remove((errors.RATELIMIT, 'ratelimit'))
else:
if form.has_errors('ratelimit', errors.RATELIMIT):
return
if not is_self:
if form.has_errors("url", errors.NO_URL, errors.BAD_URL):
return
if form.has_errors("url", errors.DOMAIN_BANNED):
g.stats.simple_event('spam.shame.link')
return
if not resubmit:
listing = hot_links_by_url_listing(url, sr=sr, num=1)
links = listing.things
if links:
c.errors.add(errors.ALREADY_SUB, field='url')
form.has_errors('url', errors.ALREADY_SUB)
u = links[0].already_submitted_link(url, title)
if extension:
u = UrlParser(u)
u.set_extension(extension)
u = u.unparse()
form.redirect(u)
return
if not c.user_is_admin and is_self:
if len(selftext) > Link.SELFTEXT_MAX_LENGTH:
c.errors.add(errors.TOO_LONG, field='text',
msg_params={'max_length': Link.SELFTEXT_MAX_LENGTH})
form.set_error(errors.TOO_LONG, 'text')
return
VNotInTimeout().run(action_name="submit", details_text=kind, target=sr)
if not request.POST.get('sendreplies'):
sendreplies = is_self
# get rid of extraneous whitespace in the title
cleaned_title = re.sub(r'\s+', ' ', title, flags=re.UNICODE)
cleaned_title = cleaned_title.strip()
l = Link._submit(
is_self=is_self,
title=cleaned_title,
content=selftext if is_self else url,
author=c.user,
sr=sr,
ip=request.ip,
sendreplies=sendreplies,
)
if not is_self:
ban = is_banned_domain(url)
if ban:
g.stats.simple_event('spam.domainban.link_url')
admintools.spam(l, banner = "domain (%s)" % ban.banmsg)
hooks.get_hook('banned_domain.submit').call(item=l, url=url,
ban=ban)
if sr.should_ratelimit(c.user, 'link'):
VRatelimit.ratelimit(rate_user=True, rate_ip = True,
prefix = "rate_submit_")
queries.new_link(l)
l.update_search_index()
g.events.submit_event(l, request=request, context=c)
path = add_sr(l.make_permalink_slow())
if extension:
path += ".%s" % extension
form.redirect(path)
form._send_data(url=path)
form._send_data(id=l._id36)
form._send_data(name=l._fullname)
@csrf_exempt
@validatedForm(VRatelimit(rate_ip = True,
rate_user = True,
prefix = 'fetchtitle_'),
VUser(),
url = VSanitizedUrl('url'))
def POST_fetch_title(self, form, jquery, url):
if form.has_errors('ratelimit', errors.RATELIMIT):
form.set_text(".title-status", "")
return
VRatelimit.ratelimit(rate_ip = True, rate_user = True,
prefix = 'fetchtitle_', seconds=1)
if url:
title = get_title(url)
if title:
form.set_inputs(title = title)
form.set_text(".title-status", "")
else:
form.set_text(".title-status", _("no title found"))
form._send_data(title=title)
def _login(self, responder, user, rem = None):
"""
AJAX login handler, used by both login and register to set the
user cookie and send back a redirect.
"""
c.user = user
c.user_is_loggedin = True
self.login(user, rem = rem)
if request.params.get("hoist") != "cookie":
responder._send_data(modhash=generate_modhash())
responder._send_data(cookie = user.make_cookie())
responder._send_data(need_https=feature.is_enabled("force_https"))
@csrf_exempt
@cross_domain(allow_credentials=True)
@validatedForm(
VLoggedOut(),
user=VThrottledLogin(['user', 'passwd']),
rem=VBoolean('rem'),
)
def POST_login(self, form, responder, user, rem=None, **kwargs):
"""Log into an account.
`rem` specifies whether or not the session cookie returned should last
beyond the current browser session (that is, if `rem` is `True` the
cookie will have an explicit expiration far in the future indicating
that it is not a session cookie).
"""
kwargs.update(dict(
controller=self,
form=form,
responder=responder,
user=user,
rem=rem,
))
return handle_login(**kwargs)
@csrf_exempt
@cross_domain(allow_credentials=True)
@validatedForm(
VRatelimit(rate_ip=True, prefix="rate_register_"),
name=VUname(['user']),
email=ValidEmail("email"),
password=VPasswordChange(['passwd', 'passwd2']),
rem=VBoolean('rem'),
newsletter_subscribe=VBoolean('newsletter_subscribe', default=False),
sponsor=VBoolean('sponsor', default=False),
)
def POST_register(self, form, responder, name, email, password, **kwargs):
"""Create a new account.
`rem` specifies whether or not the session cookie returned should last
beyond the current browser session (that is, if `rem` is `True` the
cookie will have an explicit expiration far in the future indicating
that it is not a session cookie).
"""
kwargs.update(dict(
controller=self,
form=form,
responder=responder,
name=name,
email=email,
password=password,
))
return handle_register(**kwargs)
@require_oauth2_scope("modself")
@noresponse(VUser(),
VModhash(),
container = VByName('id'))
@api_doc(api_section.moderation)
def POST_leavemoderator(self, container):
"""Abdicate moderator status in a subreddit.
See also: [/api/friend](#POST_api_friend).
"""
if container and container.is_moderator(c.user):
container.remove_moderator(c.user)
ModAction.create(container, c.user, 'removemoderator', target=c.user,
details='remove_self')
@require_oauth2_scope("modself")
@noresponse(VUser(),
VModhash(),
container = VByName('id'))
@api_doc(api_section.moderation)
def POST_leavecontributor(self, container):
"""Abdicate approved submitter status in a subreddit.
See also: [/api/friend](#POST_api_friend).
"""
if container and container.is_contributor(c.user):
container.remove_contributor(c.user)
_sr_friend_types = (
'moderator',
'moderator_invite',
'contributor',
'banned',
'muted',
'wikibanned',
'wikicontributor',
)
_sr_friend_types_with_permissions = (
'moderator',
'moderator_invite',
)
# Changes to this dict should also update docstrings for
# POST_friend and POST_unfriend
api_friend_scope_map = {
'moderator': {"modothers"},
'moderator_invite': {"modothers"},
'contributor': {"modcontributors"},
'banned': {"modcontributors"},
'muted': {"modcontributors"},
'wikibanned': {"modcontributors", "modwiki"},
'wikicontributor': {"modcontributors", "modwiki"},
'friend': None, # Handled with API v1 endpoint
'enemy': {"privatemessages"}, # Only valid for POST_unfriend
}
def check_api_friend_oauth_scope(self, type_):
if c.oauth_user:
needed_scopes = self.api_friend_scope_map[type_]
if needed_scopes is None:
# OAuth2 access not allowed for this friend rel type
# via /api/friend
self._auth_error(400, "invalid_request")
if not c.oauth_scope.has_access(c.site.name, needed_scopes):
# Token does not have the necessary scope to complete
# this request.
self._auth_error(403, "insufficient_scope")
@allow_oauth2_access
@noresponse(VUser(),
VModhash(),
nuser = VExistingUname('name'),
iuser = VByName('id'),
container = nop('container'),
type = VOneOf('type', ('friend', 'enemy') +
_sr_friend_types))
@api_doc(api_section.users, uses_site=True)
def POST_unfriend(self, nuser, iuser, container, type):
"""Remove a relationship between a user and another user or subreddit
The user can either be passed in by name (nuser)
or by [fullname](#fullnames) (iuser). If type is friend or enemy,
'container' MUST be the current user's fullname;
for other types, the subreddit must be set
via URL (e.g., /r/funny/api/unfriend)
OAuth2 use requires appropriate scope based
on the 'type' of the relationship:
* moderator: `modothers`
* moderator_invite: `modothers`
* contributor: `modcontributors`
* banned: `modcontributors`
* muted: `modcontributors`
* wikibanned: `modcontributors` and `modwiki`
* wikicontributor: `modcontributors` and `modwiki`
* friend: Use [/api/v1/me/friends/{username}](#DELETE_api_v1_me_friends_{username})
* enemy: `privatemessages`
Complement to [POST_friend](#POST_api_friend)
"""
self.check_api_friend_oauth_scope(type)
victim = iuser or nuser
if not victim:
abort(400, 'No user specified')
if type in self._sr_friend_types:
mod_action_by_type = dict(
banned='unbanuser',
moderator='removemoderator',
moderator_invite='uninvitemoderator',
wikicontributor='removewikicontributor',
wikibanned='wikiunbanned',
contributor='removecontributor',
muted='unmuteuser',
)
action = mod_action_by_type.get(type, type)
if isinstance(c.site, FakeSubreddit):
abort(403, 'forbidden')
container = c.site
if not (c.user == victim and type == 'moderator'):
# The requesting user is marked as spam or banned, and is
# trying to do a mod action. The only action they should be
# allowed to do and have it stick is demodding themself.
if c.user._spam:
return
VNotInTimeout().run(action_name=action, target=victim)
else:
container = VByName('container').run(container)
if not container:
return
# The user who made the request must be an admin or a moderator
# for the privilege change to succeed.
# (Exception: a user can remove privilege from oneself)
required_perms = []
if c.user != victim:
if type.startswith('wiki'):
required_perms.append('wiki')
else:
required_perms.append('access')
# ability to unmute requires access and mail permissions
if type == 'muted':
required_perms.append('mail')
if (
not c.user_is_admin and
type in self._sr_friend_types and
not container.is_moderator_with_perms(c.user, *required_perms)
):
abort(403, 'forbidden')
if (
type == "moderator" and
not c.user_is_admin and
not container.can_demod(c.user, victim)
):
abort(403, 'forbidden')
# if we are (strictly) unfriending, the container had better
# be the current user.
if type in ("friend", "enemy") and container != c.user:
abort(403, 'forbidden')
fn = getattr(container, 'remove_' + type)
new = fn(victim)
# for mod removals, let the now ex-mod know (NOTE: doing this earlier
# will make the message show up in their mod inbox, which they will
# immediately lose access to.)
if new and type == 'moderator' and victim != c.user:
send_mod_removal_message(container, c.user, victim)
# Log this action
if new and type in self._sr_friend_types:
ModAction.create(container, c.user, action, target=victim)
if type == "friend" and c.user.gold:
c.user.friend_rels_cache(_update=True)
if type in ('banned', 'wikibanned'):
container.unschedule_unban(victim, type)
if type == 'muted':
MutedAccountsBySubreddit.unmute(container, victim)
@require_oauth2_scope("modothers")
@validatedForm(VSrModerator(), VModhash(),
target=VExistingUname('name'),
type_and_permissions=VPermissions('type', 'permissions'))
@api_doc(api_section.users, uses_site=True)
def POST_setpermissions(self, form, jquery, target, type_and_permissions):
if form.has_errors('name', errors.USER_DOESNT_EXIST, errors.NO_USER):
return
if form.has_errors('type', errors.INVALID_PERMISSION_TYPE):
return
if form.has_errors('permissions', errors.INVALID_PERMISSIONS):
return
if c.user._spam:
return
type, permissions = type_and_permissions
update = None
if type in ("moderator", "moderator_invite"):
if not c.user_is_admin:
if type == "moderator" and (
c.user == target or not c.site.can_demod(c.user, target)):
abort(403, 'forbidden')
if (type == "moderator_invite"
and not c.site.is_unlimited_moderator(c.user)):
abort(403, 'forbidden')
# Don't allow mods in timeout to set permissions
VNotInTimeout().run(action_name="editsettings",
details_text="set_permissions", target=target)
if type == "moderator":
rel = c.site.get_moderator(target)
if type == "moderator_invite":
rel = c.site.get_moderator_invite(target)
rel.set_permissions(permissions)
rel._commit()
update = rel.encoded_permissions
ModAction.create(c.site, c.user, action='setpermissions',
target=target, details='permission_' + type,
description=update)
if update:
row = form.closest('tr')
editor = row.find('.permissions').data('PermissionEditor')
editor.onCommit(update)
@allow_oauth2_access
@validatedForm(
VUser(),
VModhash(),
friend=VExistingUname('name'),
container=nop('container'),
type=VOneOf('type', ('friend',) + _sr_friend_types),
type_and_permissions=VPermissions('type', 'permissions'),
note=VLength('note', 300),
ban_reason=VLength('ban_reason', 100),
duration=VInt('duration', min=1, max=999),
ban_message=VMarkdownLength('ban_message', max_length=1000,
empty_error=None),
)
@api_doc(api_section.users, uses_site=True)
def POST_friend(self, form, jquery, friend,
container, type, type_and_permissions, note, ban_reason,
duration, ban_message):
"""Create a relationship between a user and another user or subreddit
OAuth2 use requires appropriate scope based
on the 'type' of the relationship:
* moderator: Use "moderator_invite"
* moderator_invite: `modothers`
* contributor: `modcontributors`
* banned: `modcontributors`
* muted: `modcontributors`
* wikibanned: `modcontributors` and `modwiki`
* wikicontributor: `modcontributors` and `modwiki`
* friend: Use [/api/v1/me/friends/{username}](#PUT_api_v1_me_friends_{username})
* enemy: Use [/api/block](#POST_api_block)
Complement to [POST_unfriend](#POST_api_unfriend)
"""
self.check_api_friend_oauth_scope(type)
if type in self._sr_friend_types:
if isinstance(c.site, FakeSubreddit):
abort(403, 'forbidden')
container = c.site
else:
container = VByName('container').run(container)
if not container:
return
if type == "moderator" and not c.user_is_admin:
# attempts to add moderators now create moderator invites.
type = "moderator_invite"
fn = getattr(container, 'add_' + type)
# Make sure the user making the request has the correct permissions
# to be able to make this status change
if type in self._sr_friend_types:
mod_action_by_type = {
"banned": "banuser",
"muted": "muteuser",
"contributor": "addcontributor",
"moderator": "addmoderator",
"moderator_invite": "invitemoderator",
}
action = mod_action_by_type.get(type, type)
if c.user_is_admin:
has_perms = True
elif type.startswith('wiki'):
has_perms = container.is_moderator_with_perms(c.user, 'wiki')
elif type == 'moderator_invite':
has_perms = container.is_unlimited_moderator(c.user)
else:
has_perms = container.is_moderator_with_perms(c.user, 'access')
if not has_perms:
abort(403, 'forbidden')
# Don't let banned users make subreddit access changes
if c.user._spam:
return
VNotInTimeout().run(action_name=action, target=friend)
if type == 'moderator_invite':
invites = sum(1 for i in container.each_moderator_invite())
if invites >= g.sr_invite_limit:
c.errors.add(errors.SUBREDDIT_RATELIMIT, field="name")
form.set_error(errors.SUBREDDIT_RATELIMIT, "name")
return