This repository has been archived by the owner on Nov 9, 2017. It is now read-only.
/
validator.py
2936 lines (2452 loc) · 97.5 KB
/
validator.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 cgi
import json
from collections import OrderedDict
from decimal import Decimal
from pylons import c, g, request, response
from pylons.i18n import _
from pylons.controllers.util import abort
from r2.config import feature
from r2.config.extensions import api_type, is_api
from r2.lib import utils, captcha, promote, totp, ratelimit
from r2.lib.filters import unkeep_space, websafe, _force_unicode, _force_utf8
from r2.lib.filters import markdown_souptest
from r2.lib.db import tdb_cassandra
from r2.lib.db.operators import asc, desc
from r2.lib.souptest import (
SoupError,
SoupHostnameLengthError,
SoupUnsupportedEntityError,
)
from r2.lib.template_helpers import add_sr
from r2.lib.jsonresponse import JQueryResponse, JsonResponse
from r2.lib.log import log_text
from r2.lib.permissions import ModeratorPermissionSet
from r2.models import *
from r2.models.promo import Location
from r2.lib.authorize import Address, CreditCard
from r2.lib.utils import constant_time_compare
from r2.lib.require import require, require_split, RequirementException
from r2.lib.errors import errors, RedditError, UserRequiredException
from r2.lib.errors import VerifiedUserRequiredException
from copy import copy
from datetime import datetime, timedelta
from curses.ascii import isprint
import re, inspect
from itertools import chain
from functools import wraps
def visible_promo(article):
is_promo = getattr(article, "promoted", None) is not None
is_author = (c.user_is_loggedin and
c.user._id == article.author_id)
# promos are visible only if comments are not disabled and the
# user is either the author or the link is live/previously live.
if is_promo:
return (c.user_is_sponsor or
is_author or
(not article.disable_comments and
article.promote_status >= PROMOTE_STATUS.promoted))
# not a promo, therefore it is visible
return True
def can_view_link_comments(article):
return (article.subreddit_slow.can_view(c.user) and
visible_promo(article))
def can_comment_link(article):
return (article.subreddit_slow.can_comment(c.user) and
visible_promo(article))
class Validator(object):
notes = None
default_param = None
def __init__(self, param=None, default=None, post=True, get=True, url=True,
get_multiple=False, body=False, docs=None):
if param:
self.param = param
else:
self.param = self.default_param
self.default = default
self.post, self.get, self.url, self.docs = post, get, url, docs
self.get_multiple = get and get_multiple
self.body = body
self.has_errors = False
def set_error(self, error, msg_params={}, field=False, code=None):
"""
Adds the provided error to c.errors and flags that it is come
from the validator's param
"""
if field is False:
field = self.param
c.errors.add(error, msg_params=msg_params, field=field, code=code)
self.has_errors = True
def param_docs(self):
param_info = {}
for param in filter(None, tup(self.param)):
param_info[param] = None
return param_info
def __call__(self, url):
self.has_errors = False
a = []
if self.param:
for p in utils.tup(self.param):
# cgi.FieldStorage is falsy even if it has a filled value
# property. :(
post_val = request.POST.get(p)
if self.post and (post_val or
isinstance(post_val, cgi.FieldStorage)):
val = request.POST[p]
elif ((self.get_multiple and
(self.get_multiple == True or
p in self.get_multiple)) and
request.GET.getall(p)):
val = request.GET.getall(p)
elif self.get and request.GET.get(p):
val = request.GET[p]
elif self.url and url.get(p):
val = url[p]
elif self.body:
val = request.body
else:
val = self.default
a.append(val)
try:
return self.run(*a)
except TypeError, e:
if str(e).startswith('run() takes'):
# Prepend our class name so we know *which* run()
raise TypeError('%s.%s' % (type(self).__name__, str(e)))
else:
raise
def build_arg_list(fn, env):
"""given a fn and and environment the builds a keyword argument list
for fn"""
kw = {}
argspec = inspect.getargspec(fn)
# if there is a **kw argument in the fn definition,
# just pass along the environment
if argspec[2]:
kw = env
#else for each entry in the arglist set the value from the environment
else:
#skip self
argnames = argspec[0][1:]
for name in argnames:
if name in env:
kw[name] = env[name]
return kw
def _make_validated_kw(fn, simple_vals, param_vals, env):
for validator in simple_vals:
validator(env)
kw = build_arg_list(fn, env)
for var, validator in param_vals.iteritems():
kw[var] = validator(env)
return kw
def set_api_docs(fn, simple_vals, param_vals, extra_vals=None):
doc = fn._api_doc = getattr(fn, '_api_doc', {})
param_info = doc.get('parameters', {})
notes = doc.get('notes', [])
for validator in chain(simple_vals, param_vals.itervalues()):
param_docs = validator.param_docs()
if validator.docs:
param_docs.update(validator.docs)
param_info.update(param_docs)
if validator.notes:
notes.append(validator.notes)
if extra_vals:
param_info.update(extra_vals)
doc['parameters'] = param_info
doc['notes'] = notes
def _validators_handle_csrf(simple_vals, param_vals):
for validator in chain(simple_vals, param_vals.itervalues()):
if getattr(validator, 'handles_csrf', False):
return True
return False
def validate(*simple_vals, **param_vals):
"""Validation decorator that delegates error handling to the controller.
Runs the validators specified and calls self.on_validation_error to
process each error. This allows controllers to define their own fatal
error processing logic.
"""
def val(fn):
@wraps(fn)
def newfn(self, *a, **env):
try:
kw = _make_validated_kw(fn, simple_vals, param_vals, env)
except RedditError as err:
self.on_validation_error(err)
for err in c.errors:
self.on_validation_error(c.errors[err])
try:
return fn(self, *a, **kw)
except RedditError as err:
self.on_validation_error(err)
set_api_docs(newfn, simple_vals, param_vals)
newfn.handles_csrf = _validators_handle_csrf(simple_vals, param_vals)
return newfn
return val
def api_validate(response_type=None, add_api_type_doc=False):
"""
Factory for making validators for API calls, since API calls come
in two flavors: responsive and unresponsive. The machinary
associated with both is similar, and the error handling identical,
so this function abstracts away the kw validation and creation of
a Json-y responder object.
"""
def wrap(response_function):
def _api_validate(*simple_vals, **param_vals):
def val(fn):
@wraps(fn)
def newfn(self, *a, **env):
renderstyle = request.params.get("renderstyle")
if renderstyle:
c.render_style = api_type(renderstyle)
elif not c.extension:
# if the request URL included an extension, don't
# touch the render_style, since it was already set by
# set_extension. if no extension was provided, default
# to response_type.
c.render_style = api_type(response_type)
# generate a response object
if response_type == "html" and not request.params.get('api_type') == "json":
responder = JQueryResponse()
else:
responder = JsonResponse()
response.content_type = responder.content_type
try:
kw = _make_validated_kw(fn, simple_vals, param_vals, env)
return response_function(self, fn, responder,
simple_vals, param_vals, *a, **kw)
except UserRequiredException:
responder.send_failure(errors.USER_REQUIRED)
return self.api_wrapper(responder.make_response())
except VerifiedUserRequiredException:
responder.send_failure(errors.VERIFIED_USER_REQUIRED)
return self.api_wrapper(responder.make_response())
extra_param_vals = {}
if add_api_type_doc:
extra_param_vals = {
"api_type": "the string `json`",
}
set_api_docs(newfn, simple_vals, param_vals, extra_param_vals)
newfn.handles_csrf = _validators_handle_csrf(simple_vals,
param_vals)
return newfn
return val
return _api_validate
return wrap
@api_validate("html")
def noresponse(self, self_method, responder, simple_vals, param_vals, *a, **kw):
self_method(self, *a, **kw)
return self.api_wrapper({})
@api_validate("html")
def textresponse(self, self_method, responder, simple_vals, param_vals, *a, **kw):
return self_method(self, *a, **kw)
@api_validate()
def json_validate(self, self_method, responder, simple_vals, param_vals, *a, **kw):
if c.extension != 'json':
abort(404)
val = self_method(self, responder, *a, **kw)
if val is None:
val = responder.make_response()
return self.api_wrapper(val)
def _validatedForm(self, self_method, responder, simple_vals, param_vals,
*a, **kw):
# generate a form object
form = responder(request.POST.get('id', "body"))
# clear out the status line as a courtesy
form.set_text(".status", "")
# do the actual work
val = self_method(self, form, responder, *a, **kw)
# add data to the output on some errors
for validator in chain(simple_vals, param_vals.values()):
if (isinstance(validator, VCaptcha) and
(form.has_errors('captcha', errors.BAD_CAPTCHA) or
(form.has_error() and c.user.needs_captcha()))):
form.new_captcha()
elif (isinstance(validator, (VRatelimit, VThrottledLogin)) and
form.has_errors('ratelimit', errors.RATELIMIT)):
form.ratelimit(validator.seconds)
if val:
return val
else:
return self.api_wrapper(responder.make_response())
@api_validate("html", add_api_type_doc=True)
def validatedForm(self, self_method, responder, simple_vals, param_vals,
*a, **kw):
return _validatedForm(self, self_method, responder, simple_vals, param_vals,
*a, **kw)
@api_validate("html", add_api_type_doc=True)
def validatedMultipartForm(self, self_method, responder, simple_vals,
param_vals, *a, **kw):
def wrapped_self_method(*a, **kw):
val = self_method(*a, **kw)
if val:
return val
else:
data = json.dumps(responder.make_response())
response.content_type = "text/html"
return ('<html><head><script type="text/javascript">\n'
'parent.$.handleResponse()(%s)\n'
'</script></head></html>') % filters.websafe_json(data)
return _validatedForm(self, wrapped_self_method, responder, simple_vals,
param_vals, *a, **kw)
jsonp_callback_rx = re.compile("\\A[\\w$\\.\"'[\\]]+\\Z")
def valid_jsonp_callback(callback):
return jsonp_callback_rx.match(callback)
#### validators ####
class nop(Validator):
def run(self, x):
return x
class VLang(Validator):
@staticmethod
def validate_lang(lang, strict=False):
if lang in g.all_languages:
return lang
else:
if not strict:
return g.lang
else:
raise ValueError("invalid language %r" % lang)
def run(self, lang):
return VLang.validate_lang(lang)
def param_docs(self):
return {
self.param: "a valid IETF language tag (underscore separated)",
}
class VRequired(Validator):
def __init__(self, param, error, *a, **kw):
Validator.__init__(self, param, *a, **kw)
self._error = error
def error(self, e = None):
if not e: e = self._error
if e:
self.set_error(e)
def run(self, item):
if not item:
self.error()
else:
return item
class VThing(Validator):
def __init__(self, param, thingclass, redirect = True, *a, **kw):
Validator.__init__(self, param, *a, **kw)
self.thingclass = thingclass
self.redirect = redirect
def run(self, thing_id):
if thing_id:
try:
tid = int(thing_id, 36)
thing = self.thingclass._byID(tid, True)
if thing.__class__ != self.thingclass:
raise TypeError("Expected %s, got %s" %
(self.thingclass, thing.__class__))
return thing
except (NotFound, ValueError):
if self.redirect:
abort(404, 'page not found')
else:
return None
def param_docs(self):
return {
self.param: "The base 36 ID of a " + self.thingclass.__name__
}
class VLink(VThing):
def __init__(self, param, redirect = True, *a, **kw):
VThing.__init__(self, param, Link, redirect=redirect, *a, **kw)
class VPromoCampaign(VThing):
def __init__(self, param, redirect = True, *a, **kw):
VThing.__init__(self, param, PromoCampaign, *a, **kw)
class VCommentByID(VThing):
def __init__(self, param, redirect = True, *a, **kw):
VThing.__init__(self, param, Comment, redirect=redirect, *a, **kw)
class VAward(VThing):
def __init__(self, param, redirect = True, *a, **kw):
VThing.__init__(self, param, Award, redirect=redirect, *a, **kw)
class VAwardByCodename(Validator):
def run(self, codename, required_fullname=None):
if not codename:
return self.set_error(errors.NO_TEXT)
try:
a = Award._by_codename(codename)
except NotFound:
a = None
if a and required_fullname and a._fullname != required_fullname:
return self.set_error(errors.INVALID_OPTION)
else:
return a
class VTrophy(VThing):
def __init__(self, param, redirect = True, *a, **kw):
VThing.__init__(self, param, Trophy, redirect=redirect, *a, **kw)
class VMessage(Validator):
def run(self, message_id):
if message_id:
try:
aid = int(message_id, 36)
return Message._byID(aid, True)
except (NotFound, ValueError):
abort(404, 'page not found')
class VCommentID(Validator):
def run(self, cid):
if cid:
try:
cid = int(cid, 36)
return Comment._byID(cid, True)
except (NotFound, ValueError):
pass
class VMessageID(Validator):
def run(self, cid):
if cid:
try:
cid = int(cid, 36)
m = Message._byID(cid, True)
if not m.can_view_slow():
abort(403, 'forbidden')
return m
except (NotFound, ValueError):
pass
class VCount(Validator):
def run(self, count):
if count is None:
count = 0
try:
return max(int(count), 0)
except ValueError:
return 0
def param_docs(self):
return {
self.param: "a positive integer (default: 0)",
}
class VLimit(Validator):
def __init__(self, param, default=25, max_limit=100, **kw):
self.default_limit = default
self.max_limit = max_limit
Validator.__init__(self, param, **kw)
def run(self, limit):
default = c.user.pref_numsites
if not default or c.render_style in ("compact", api_type("compact")):
default = self.default_limit # TODO: ini param?
if limit is None:
return default
try:
i = int(limit)
except ValueError:
return default
return min(max(i, 1), self.max_limit)
def param_docs(self):
return {
self.param: "the maximum number of items desired "
"(default: %d, maximum: %d)" % (self.default_limit,
self.max_limit),
}
class VCssMeasure(Validator):
measure = re.compile(r"\A\s*[\d\.]+\w{0,3}\s*\Z")
def run(self, value):
return value if value and self.measure.match(value) else ''
class VLength(Validator):
only_whitespace = re.compile(r"\A\s*\Z", re.UNICODE)
def __init__(self, param, max_length,
min_length=0,
empty_error = errors.NO_TEXT,
length_error = errors.TOO_LONG,
short_error=errors.TOO_SHORT,
**kw):
Validator.__init__(self, param, **kw)
self.max_length = max_length
self.min_length = min_length
self.length_error = length_error
self.short_error = short_error
self.empty_error = empty_error
def run(self, text, text2 = ''):
text = text or text2
if self.empty_error and (not text or self.only_whitespace.match(text)):
self.set_error(self.empty_error, code=400)
elif len(text) > self.max_length:
self.set_error(self.length_error, {'max_length': self.max_length}, code=400)
elif len(text) < self.min_length:
self.set_error(self.short_error, {'min_length': self.min_length},
code=400)
else:
return text
def param_docs(self):
return {
self.param:
"a string no longer than %d characters" % self.max_length,
}
class VUploadLength(VLength):
def run(self, upload, text2=''):
# upload is expected to be a FieldStorage object
if isinstance(upload, cgi.FieldStorage):
return VLength.run(self, upload.value, text2)
else:
self.set_error(self.empty_error, code=400)
def param_docs(self):
kibibytes = self.max_length / 1024
return {
self.param:
"file upload with maximum size of %d KiB" % kibibytes,
}
class VPrintable(VLength):
def run(self, text, text2 = ''):
text = VLength.run(self, text, text2)
if text is None:
return None
try:
if all(isprint(str(x)) for x in text):
return str(text)
except UnicodeEncodeError:
pass
self.set_error(errors.BAD_STRING, code=400)
return None
def param_docs(self):
return {
self.param: "a string up to %d characters long,"
" consisting of printable characters."
% self.max_length,
}
class VTitle(VLength):
def __init__(self, param, max_length = 300, **kw):
VLength.__init__(self, param, max_length, **kw)
def param_docs(self):
return {
self.param: "title of the submission. "
"up to %d characters long" % self.max_length,
}
class VMarkdown(Validator):
def __init__(self, param, renderer='reddit'):
Validator.__init__(self, param)
self.renderer = renderer
def run(self, text, text2=''):
text = text or text2
try:
markdown_souptest(text, renderer=self.renderer)
return text
except SoupError as e:
# Could happen if someone does `�`. It's not a security issue,
# it's just unacceptable.
# TODO: give a better indication to the user of what happened
if isinstance(e, SoupUnsupportedEntityError):
abort(400)
return
import sys
user = "???"
if c.user_is_loggedin:
user = c.user.name
# work around CRBUG-464270
if isinstance(e, SoupHostnameLengthError):
# We want a general idea of how often this is triggered, and
# by what
g.log.warning("CHROME HAX by %s: %s" % (user, text))
abort(400)
return
g.log.error("HAX by %s: %s" % (user, text))
s = sys.exc_info()
# reraise the original error with the original stack trace
raise s[1], None, s[2]
def param_docs(self):
return {
tup(self.param)[0]: "raw markdown text",
}
class VMarkdownLength(VMarkdown):
def __init__(self, param, renderer='reddit', max_length=10000,
empty_error=errors.NO_TEXT, length_error=errors.TOO_LONG):
VMarkdown.__init__(self, param, renderer)
self.max_length = max_length
self.empty_error = empty_error
self.length_error = length_error
def run(self, text, text2=''):
text = text or text2
text = VLength(self.param, self.max_length,
empty_error=self.empty_error,
length_error=self.length_error).run(text)
if text:
return VMarkdown.run(self, text)
else:
return ''
class VSavedCategory(Validator):
savedcategory_rx = re.compile(r"\A[a-z0-9 _]{1,20}\Z")
def run(self, name):
if not name:
return
name = name.lower()
valid = self.savedcategory_rx.match(name)
if not valid:
self.set_error('BAD_SAVE_CATEGORY')
return
return name
def param_docs(self):
return {
self.param: "a category name",
}
class VSubredditName(VRequired):
def __init__(self, item, allow_language_srs=False, *a, **kw):
VRequired.__init__(self, item, errors.BAD_SR_NAME, *a, **kw)
self.allow_language_srs = allow_language_srs
def run(self, name):
if name:
name = sr_path_rx.sub('\g<name>', name.strip())
valid_name = Subreddit.is_valid_name(
name, allow_language_srs=self.allow_language_srs)
if not valid_name:
self.set_error(self._error, code=400)
return str(name)
def param_docs(self):
return {
self.param: "subreddit name",
}
class VAvailableSubredditName(VSubredditName):
def run(self, name):
name = VSubredditName.run(self, name)
if name:
try:
a = Subreddit._by_name(name)
return self.error(errors.SUBREDDIT_EXISTS)
except NotFound:
return name
class VSRByName(Validator):
def __init__(self, sr_name, required=True):
self.required = required
Validator.__init__(self, sr_name)
def run(self, sr_name):
if not sr_name:
if self.required:
self.set_error(errors.BAD_SR_NAME, code=400)
else:
sr_name = sr_path_rx.sub('\g<name>', sr_name.strip())
try:
sr = Subreddit._by_name(sr_name)
return sr
except NotFound:
self.set_error(errors.SUBREDDIT_NOEXIST, code=400)
def param_docs(self):
return {
self.param: "subreddit name",
}
class VSRByNames(Validator):
"""Returns a dict mapping subreddit names to subreddit objects.
sr_names_csv - a comma delimited string of subreddit names
required - if true (default) an empty subreddit name list is an error
"""
def __init__(self, sr_names_csv, required=True):
self.required = required
Validator.__init__(self, sr_names_csv)
def run(self, sr_names_csv):
if sr_names_csv:
sr_names = [sr_path_rx.sub('\g<name>', s.strip())
for s in sr_names_csv.split(',')]
return Subreddit._by_name(sr_names)
elif self.required:
self.set_error(errors.BAD_SR_NAME, code=400)
return {}
def param_docs(self):
return {
self.param: "comma-delimited list of subreddit names",
}
class VSubredditTitle(Validator):
def run(self, title):
if not title:
self.set_error(errors.NO_TITLE)
elif len(title) > 100:
self.set_error(errors.TITLE_TOO_LONG)
else:
return title
class VSubredditDesc(Validator):
def run(self, description):
if description and len(description) > 500:
self.set_error(errors.DESC_TOO_LONG)
return unkeep_space(description or '')
class VAccountByName(VRequired):
def __init__(self, param, error = errors.USER_DOESNT_EXIST, *a, **kw):
VRequired.__init__(self, param, error, *a, **kw)
def run(self, name):
if name:
try:
return Account._by_name(name)
except NotFound: pass
return self.error()
def param_docs(self):
return {self.param: "A valid, existing reddit username"}
class VFriendOfMine(VAccountByName):
def run(self, name):
# Must be logged in
VUser().run()
maybe_friend = VAccountByName.run(self, name)
if maybe_friend:
friend_rel = Account.get_friend(c.user, maybe_friend)
if friend_rel:
return friend_rel
else:
self.error(errors.NOT_FRIEND)
return None
def fullname_regex(thing_cls = None, multiple = False):
pattern = "[%s%s]" % (Relation._type_prefix, Thing._type_prefix)
if thing_cls:
pattern += utils.to36(thing_cls._type_id)
else:
pattern += r"[0-9a-z]+"
pattern += r"_[0-9a-z]+"
if multiple:
pattern = r"(%s *,? *)+" % pattern
return re.compile(r"\A" + pattern + r"\Z")
class VByName(Validator):
# Lookup tdb_sql.Thing or tdb_cassandra.Thing objects by fullname.
splitter = re.compile('[ ,]+')
def __init__(self, param, thing_cls=None, multiple=False, limit=None,
error=errors.NO_THING_ID, ignore_missing=False,
backend='sql', **kw):
# Limit param only applies when multiple is True
if not multiple and limit is not None:
raise TypeError('multiple must be True when limit is set')
self.thing_cls = thing_cls
self.re = fullname_regex(thing_cls)
self.multiple = multiple
self.limit = limit
self._error = error
self.ignore_missing = ignore_missing
self.backend = backend
Validator.__init__(self, param, **kw)
def run(self, items):
if self.backend == 'cassandra':
# tdb_cassandra.Thing objects can't use the regex
if items and self.multiple:
items = [item for item in self.splitter.split(items)]
if self.limit and len(items) > self.limit:
return self.set_error(errors.TOO_MANY_THING_IDS)
if items:
try:
return tdb_cassandra.Thing._by_fullname(
items,
ignore_missing=self.ignore_missing,
return_dict=False,
)
except tdb_cassandra.NotFound:
pass
else:
if items and self.multiple:
items = [item for item in self.splitter.split(items)
if item and self.re.match(item)]
if self.limit and len(items) > self.limit:
return self.set_error(errors.TOO_MANY_THING_IDS)
if items and (self.multiple or self.re.match(items)):
try:
return Thing._by_fullname(
items,
return_dict=False,
ignore_missing=self.ignore_missing,
data=True,
)
except NotFound:
pass
return self.set_error(self._error)
def param_docs(self):
thingtype = (self.thing_cls or Thing).__name__.lower()
if self.multiple:
return {
self.param: ("A comma-separated list of %s [fullnames]"
"(#fullnames)" % thingtype)
}
else:
return {
self.param: "[fullname](#fullnames) of a %s" % thingtype,
}
class VByNameIfAuthor(VByName):
def run(self, fullname):
thing = VByName.run(self, fullname)
if thing:
if not thing._loaded: thing._load()
if c.user_is_loggedin and thing.author_id == c.user._id:
return thing
return self.set_error(errors.NOT_AUTHOR)
def param_docs(self):
return {
self.param: "[fullname](#fullnames) of a thing created by the user",
}
class VCaptcha(Validator):
default_param = ('iden', 'captcha')
def run(self, iden, solution):
if c.user.needs_captcha():
valid_captcha = captcha.valid_solution(iden, solution)
if not valid_captcha:
self.set_error(errors.BAD_CAPTCHA)
g.stats.action_event_count("captcha", valid_captcha)
def param_docs(self):
return {
self.param[0]: "the identifier of the CAPTCHA challenge",
self.param[1]: "the user's response to the CAPTCHA challenge",
}
class VUser(Validator):
def run(self):
if not c.user_is_loggedin:
raise UserRequiredException
class VVerifyPassword(Validator):
def __init__(self, param, fatal=True, *a, **kw):
Validator.__init__(self, param, *a, **kw)
self.fatal = fatal
def run(self, password):
VUser().run()
if not valid_password(c.user, password):
if self.fatal:
abort(403)
self.set_error(errors.WRONG_PASSWORD)
return None
# bcrypt wants a bytestring
return _force_utf8(password)
def param_docs(self):
return {
self.param: "the current user's password",
}
class VModhash(Validator):
handles_csrf = True
default_param = 'uh'
def __init__(self, param=None, fatal=True, *a, **kw):
Validator.__init__(self, param, *a, **kw)
self.fatal = fatal
def run(self, uh):
if uh is None:
uh = request.headers.get('X-Modhash')
if not c.user_is_loggedin or uh != c.user.name:
if self.fatal:
abort(403)
self.set_error('INVALID_MODHASH')
def param_docs(self):
return {
'%s / X-Modhash header' % self.param: 'a [modhash](#modhashes)',
}
class VModhashIfLoggedIn(Validator):
handles_csrf = True
default_param = 'uh'
def __init__(self, param=None, fatal=True, *a, **kw):
Validator.__init__(self, param, *a, **kw)
self.fatal = fatal
def run(self, uh):
# import here so that we don't close around VModhash
# before r2admin can override
if c.user_is_loggedin:
from r2.lib.validator import VModhash
VModhash(fatal=self.fatal).run(uh)