Debian Codegraph @

docs/advanced.rst

raw
1 Advanced topics
2 ===============
3
4 Configuration toggles
5 +++++++++++++++++++++
6
7 The following configuration elements can be defined (in your ``settings.py``)
8
9 CAPTCHA_FONT_PATH
10 -----------------
11
12 Full path and filename of a TrueType (TTF), OpenType, or pilfont font file used to render text.
13
14 Defaults to: ``fonts/Vera.ttf`` (included in the application, GPL font).
15
16 Note that your Pillow installation must support TTF and/or OpenFont if you want to use these kind of glyphs (most modern distributions of Pillow do.)
17
18 Note: as of version 0.4.6, ``CAPTCHA_FONT_PATH`` may be an iterable of font paths, in which case a font will be picked randomly from the list for each CAPTCHA.
19
20 CAPTCHA_FONT_SIZE
21 -----------------
22
23 Font-size in pixels of the rendered text.
24
25 Defaults to '22'.
26
27 CAPTCHA_IMAGE_SIZE
28 ------------------
29
30 Image size in pixels of generated captcha, specified as a tuple (width, height)
31
32 Defaults to `None` (automatically calculated)
33
34 CAPTCHA_LETTER_ROTATION
35 -----------------------
36
37 A random rotation in this interval is applied to each letter in the challenge text.
38
39 Defaults to ``(-35,35)``.
40
41 New in version 0.1.6: set this to None to disable letter rotation.
42
43 CAPTCHA_BACKGROUND_COLOR
44 ------------------------
45
46 Background-color of the captcha. Can be expressed as html-style #rrggbb, rgb(red, green, blue), or common html names (e.g. "red").
47
48 Defaults to: ``'#ffffff'``
49
50 CAPTCHA_FOREGROUND_COLOR
51 ------------------------
52
53 Foreground-color of the captcha.
54
55 Defaults to ``'#001100'``
56
57 CAPTCHA_LETTER_COLOR_FUNCT
58 ------------------------
59 A string representing a Python callable (i.e., a function) to determine the color of the letters in the CAPTCHA.
60
61 Defaults to ``'None'`` (uses CAPTCHA_FOREGROUND_COLOR) for all letters.
62
63 This function is called for each letter of the CAPTCHA string.
64 It takes two arguments: the first is the index of the current letter, and the second is the entire CAPTCHA string.
65
66 CAPTCHA_CHALLENGE_FUNCT
67 ------------------------
68
69 String representing a python callable (i.e. a function) to use as challenge generator.
70
71 See Generators below for a list of available generators and a guide on how to write your own.
72
73 Defaults to: ``'captcha.helpers.random_char_challenge'``
74
75 CAPTCHA_MATH_CHALLENGE_OPERATOR
76 -------------------------------
77
78 When using the ``math_challenge``, lets you choose the multiplication operator. Use lowercase ``'x'`` for cross sign.
79
80 Defaults to: ``'*'`` (asterisk sign)
81
82 CAPTCHA_NOISE_FUNCTIONS
83 ------------------------
84
85 List of strings of python callables that take a Pillow ``DrawImage`` object and an ``Image`` image as input, modify the ``DrawImage``, then return it.
86
87 Defaults to: ``('captcha.helpers.noise_arcs','captcha.helpers.noise_dots',)``
88
89 A null noise helper function useful when debugging issues is available at ``'captcha.helpers.noise_null'``.
90
91
92 CAPTCHA_FILTER_FUNCTIONS
93 ------------------------
94
95 List of strings of python callables that take a PIL ``Image`` object as input, modify it and return it.
96
97 These are called right before the rendering, i.e. after the noise functions.
98
99 Defaults to: ``('captcha.helpers.post_smooth',)``
100
101
102 CAPTCHA_WORDS_DICTIONARY
103 ------------------------
104
105 Required for the ``word_challenge`` challenge function only. Points a file containing a list of words, one per line.
106
107 Defaults to: ``'/usr/share/dict/words'``
108
109 CAPTCHA_FLITE_PATH
110 ------------------------
111
112 Full path to the ``flite`` executable. When defined, will automatically add audio output to the captcha.
113
114 Defaults to: ``None`` (no audio output)
115
116 CAPTCHA_SOX_PATH
117 ------------------------
118
119 Full path to the ``sox`` executable. If audio output is enabled via ``CAPTCHA_FLITE_PATH``, the generated output audio file is identical across multiple generations (unlike CAPTCHA images which get different random noise each time they are rendered). User appleorange1_ has shown_ that this could be used to pre-generate a "rainbow-table" of all possible input strings and a hash of the generated output soundfile, thus rendering an attack on audio CAPTCHAs trivial.
120
121 If sox_ is installed and used via this settings, random brown noise is injected into the generated audio file, rendering attacks via a rainbow table impossible.
122
123 Defaults to: ``None`` (no audio output)
124
125 .. _appleorange1: https://github.com/appleorange1
126 .. _shown: https://github.com/appleorange1/django-simple-captcha-cracker-poc
127 .. _sox: http://sox.sourceforge.net/
128
129
130 CAPTCHA_TIMEOUT
131 ---------------
132
133 Integer. Lifespan, in minutes, of the generated captcha.
134
135 Defaults to: 5
136
137 CAPTCHA_LENGTH
138 ------------------------
139
140 Sets the length, in chars, of the generated captcha. (for the ``'captcha.helpers.random_char_challenge'`` challenge)
141
142 Defaults to: 4
143
144 CAPTCHA_DICTIONARY_MIN_LENGTH
145 -----------------------------
146
147 When using the word_challenge challenge function, controls the minimum length of the words to be randomly picked from the dictionary file.
148
149 Defaults to: 0
150
151 CAPTCHA_DICTIONARY_MAX_LENGTH
152 -----------------------------
153
154 When using the word_challenge challenge function, controls the maximal length of the words to be randomly picked from the dictionary file.
155
156 Defaults to: 99
157
158 Note: it's perfectly safe to specify e.g. ``CAPTCHA_DICTIONARY_MIN_LENGTH = CAPTCHA_DICTIONARY_MAX_LENGTH = 6`` but it's considered an error to define ``CAPTCHA_DICTIONARY_MAX_LENGTH`` to be smaller than ``CAPTCHA_DICTIONARY_MIN_LENGTH``.
159
160
161 CAPTCHA_TEST_MODE
162 ------------------------
163
164 New in version 0.3.6
165
166 When set to True, the string "PASSED" (any case) will be accepted as a valid response to any CAPTCHA.
167 Use this for testing purposes. Warning: do NOT set this to True in production.
168
169 Defaults to: False
170
171
172 CAPTCHA_GET_FROM_POOL
173 ---------------------
174
175 By default, `django-simple-captcha` generates a new captcha when needed and stores it in the database. This occurs in a `HTTP GET request`, which may not be wished. This default behavior may also conflict with a load balanced infrastructure, where there is more than one database to read data from. If this setting is `True`, when a new captcha is needed, a random one will be just read from a pool of captchas saved previously in the database. In this case, the custom management command `captcha_create_pool` must be run regularly in intervals slightly shorter than `CAPTCHA_TIMEOUT`. A good value for `CAPTCHA_TIMEOUT` could be 1446 (24 hours and 6 minutes) when adding captchas to the pool every 24 hours, and setting `CAPTCHA_GET_FROM_POOL_TIMEOUT` (see below) to 5 minutes. This means that 6 minutes before the last captchas expires, new captchas will be created, and no captcha will be used whose expiration is less than 5 minutes. In this case, use a cronjob or similar to run `python manage.py captcha_create_pool` every 24 hours.
176
177 Defaults to: False
178
179
180 CAPTCHA_GET_FROM_POOL_TIMEOUT
181 -----------------------------
182
183 This is a timeout value in minutes used only if `CAPTCHA_GET_FROM_POOL` (see above) is `True`. When picking up randomly from the pool, this setting will prevent to pick up a captcha that expires sooner than `CAPTCHA_GET_FROM_POOL_TIMEOUT`.
184
185 Defaults to: 5
186
187
188 CAPTCHA_2X_IMAGE
189 ----------------
190
191 When set to True, a double resolution version of the captcha image is made served by adding `@2` to the end of the image URL (`image/<key>@2/`). Note that this makes the image slightly more readable on e.g. HiDPI screens, but could also make the CAPTCHA potentially easier to break by a bot.
192
193 Defaults to: True
194
195
196 CAPTCHA_ANIMATED
197 ----------------
198
199 Renders an animated CAPTCHA, each frame containing an individual character from the challenge. By default returns an AVIF animation if the installed Pillow version supports it, otherwise falls back to animated GIFs.
200
201 Defaults to: False
202
203 Rendering
204 +++++++++
205
206 ``CaptchaTextInput`` supports the widget rendering using template introduced in Django 1.11.
207 To change the output HTML, change the ``template_name`` to a custom template or modify ``get_context`` method to provide further context.
208 See https://docs.djangoproject.com/en/dev/ref/forms/renderers/ for description of rendering API.
209 Keep in mind that ``CaptchaTextInput`` is a subclass of ``MultiWidget`` which affects the context, see https://docs.djangoproject.com/en/2.0/ref/forms/widgets/#multiwidget.
210
211 For example, you would::
212
213 class CustomCaptchaTextInput(CaptchaTextInput):
214 template_name = 'custom_field.html'
215
216 class CaptchaForm(forms.Form):
217 captcha = CaptchaField(widget=CustomCaptchaTextInput)
218
219
220 And then have a ``custom_field.html`` template::
221
222 {% load i18n %}
223 {% spaceless %}
224 <div class="form-group">
225 <label class="control-label">{{ label }}</label>
226 <div class="form-group">
227 <div class="input-group mb-3">
228 <div class="input-group-prepend">
229 {% if audio %}
230 <a title="{% trans "Play CAPTCHA as audio file" %}" href="{{ audio }}">
231 {% endif %}
232 <img src="{{ image }}" alt="captcha" class="captcha" />
233 </div>
234 {% include "django/forms/widgets/multiwidget.html" %}
235 </div>
236 </div>
237 </div>
238 {% endspaceless %}
239
240
241 .. note:: For this to work, you MUST
242 add ``django.forms`` to your ``INSTALLED_APPS`` and
243 set ``FORM_RENDERER = 'django.forms.renderers.TemplatesSetting'`` in your settings.py.
244 (See here_ for an explanation)
245
246 .. _here: https://docs.djangoproject.com/en/2.0/ref/forms/renderers/#django.forms.renderers.TemplatesSetting
247
248
249
250 Context
251 -------
252
253 The following context variables are passed to the three "individual" templates:
254
255 * ``image``: The URL of the rendered CAPTCHA image
256 * ``name``: name of the field (i.e. the name of your form field)
257 * ``key``: the hashed value (identifier) of this CAPTCHA: this is stored and passed in the hidden input
258 * ``id``: the HTML ``id`` attribute to be used
259
260 The ``captcha/field.html`` template receives the following context:
261
262 * ``image``: the rendered (HTML) image and optionally audio elements
263 * ``hidden_field``: the rendered hidden input
264 * ``text_field``: the rendered text input
265
266 Note: these elements have been marked as safe, you can render them straight into your template.
267
268 .. _generators_ref:
269
270 Generators and modifiers
271 ++++++++++++++++++++++++
272
273 Random chars
274 ------------
275
276 .. image:: _static/random_chars.png
277
278 Classic captcha that picks four random chars. This is case insensitive. ::
279
280 CAPTCHA_CHALLENGE_FUNCT = 'captcha.helpers.random_char_challenge'
281
282
283 Simple Math
284 ------------
285
286 .. image:: _static/math.png
287
288 Another classic, that challenges the user to resolve a simple math challenge by randomly picking two numbers between one and nine, and a random operator among plus, minus, times. ::
289
290 CAPTCHA_CHALLENGE_FUNCT = 'captcha.helpers.math_challenge'
291
292
293 Dictionary Word
294 ----------------
295
296 .. image:: _static/dict.png
297
298 Picks a random word from a dictionary file. Note, you must define ``CAPTCHA_WORDS_DICTIONARY`` in your configuration to use this generator. ::
299
300 CAPTCHA_CHALLENGE_FUNCT = 'captcha.helpers.word_challenge'
301
302
303 Roll your own
304 -------------
305
306 To have your own challenge generator, simply point ``CAPTCHA_CHALLENGE_FUNCT`` to a function that returns a tuple of strings: the first one (the challenge) will be rendered in the captcha, the second is the valid response to the challenge, e.g. ``('5+10=', '15')``, ``('AAAA', 'aaaa')``
307
308 This sample generator that returns six random digits::
309
310 import random
311
312 def random_digit_challenge():
313 ret = u''
314 for i in range(6):
315 ret += str(random.randint(0,9))
316 return ret, ret