Exemplo n.º 1
0
def ajax_captcha(request):
    if request.method == "POST":
        response = request.POST.get("response")
        key = request.POST.get("key")

        if response and key:
            CaptchaStore.remove_expired()

            # Note that CaptchaStore displays the response in uppercase in the
            # image and in the string representation of the object but the
            # actual value stored in the database is lowercase!
            deleted, _ = CaptchaStore.objects.filter(response=response.lower(),
                                                     hashkey=key).delete()

            if deleted > 0:
                request.session["captcha_validation_time"] = time.time()
                return JsonResponse({"valid": True})

    key = CaptchaStore.generate_key()
    return JsonResponse(
        {
            "key": key,
            "image": request.build_absolute_uri(captcha_image_url(key))
        },
        status=401,
        content_type="application/json",
    )
Exemplo n.º 2
0
    def clean(self, value):
        super(CaptchaField, self).clean(value)
        CaptchaStore.remove_expired()

        response, value[1] = (value[1] or '').strip().lower(), ''
        hashkey = value[0]

        if settings.CAPTCHA_TEST_MODE and response.lower() == 'passed':
            # automatically pass the test
            try:
                # try to delete the captcha based on its hash
                CaptchaStore.objects.get(hashkey=hashkey).delete()
            except CaptchaStore.DoesNotExist:
                # ignore errors
                pass
        elif not self.required and not response:
            pass
        else:
            # let enable validity_count times
            # of clean() method
            if hashkey in self.validity_cache and self.validity_cache[hashkey] > 0:
                self.validity_cache[hashkey] -= 1
                return value
            try:
                captcha = CaptchaStore.objects.get(
                    response=response,
                    hashkey=hashkey,
                    expiration__gt=get_safe_now())
                self.validity_cache[hashkey] = self.validity_count - 1
                captcha.delete()
            except CaptchaStore.DoesNotExist:
                raise ValidationError(
                    getattr(self, 'error_messages', {}).get('invalid',
                                                            _('Invalid CAPTCHA')))
        return value
Exemplo n.º 3
0
 def clean(self, value):
     super(CaptchaField, self).clean(value)
     response, value[1] = (value[1] or "").strip().lower(), ""
     if not settings.CAPTCHA_GET_FROM_POOL:
         CaptchaStore.remove_expired()
     if settings.CAPTCHA_TEST_MODE and response.lower() == "passed":
         # automatically pass the test
         try:
             # try to delete the captcha based on its hash
             CaptchaStore.objects.get(hashkey=value[0]).delete()
         except CaptchaStore.DoesNotExist:
             # ignore errors
             pass
     elif not self.required and not response:
         pass
     else:
         try:
             CaptchaStore.objects.get(
                 response=response,
                 hashkey=value[0],
                 expiration__gt=timezone.now()).delete()
         except CaptchaStore.DoesNotExist:
             raise ValidationError(
                 getattr(self, "error_messages",
                         {}).get("invalid",
                                 ugettext_lazy("Invalid CAPTCHA")))
     return value
Exemplo n.º 4
0
 def clean(self, value):
     super(CaptchaField, self).clean(value)
     response, value[1] = (value[1] or '').strip().lower(), ''
     CaptchaStore.remove_expired()
     if captcha_settings.CAPTCHA_TEST_MODE and response.lower() == 'passed':
         # automatically pass the test
         try:
             # try to delete the captcha based on its hash
             CaptchaStore.objects.get(hashkey=value[0]).delete()
         except CaptchaStore.DoesNotExist:
             # ignore errors
             pass
     elif not self.required and not response:
         pass
     else:
         # https://code.google.com/p/django-simple-captcha/issues/detail?id=4
         try:
             CaptchaStore.objects.get(response=response,
                                      hashkey=value[0],
                                      expiration__gt=get_safe_now())
             self.second_time_validate_delete(value[0])
             self.hashKey = value[0]
         except CaptchaStore.DoesNotExist:
             raise ValidationError(
                 getattr(self, 'error_messages',
                         {}).get('invalid', _('Invalid CAPTCHA')))
     return value
Exemplo n.º 5
0
 def clean(self, value):
     super(CaptchaField, self).clean(value)
     response, value[1] = (value[1] or '').strip().lower(), ''
     CaptchaStore.remove_expired()
     if settings.CAPTCHA_TEST_MODE and response.lower() == 'passed':
         # automatically pass the test
         try:
             # try to delete the captcha based on its hash
             CaptchaStore.objects.get(hashkey=value[0]).delete()
         except CaptchaStore.DoesNotExist:
             # ignore errors
             pass
     elif not self.required and not response:
         pass
     else:
         try:
             CaptchaStore.objects.get(
                 response=response,
                 hashkey=value[0],
                 expiration__gt=get_safe_now()).delete()
         except CaptchaStore.DoesNotExist:
             raise ValidationError(
                 getattr(self, 'error_messages',
                         {}).get('invalid',
                                 ugettext_lazy('Invalid CAPTCHA')))
     return value
Exemplo n.º 6
0
 def clean(self, value):
     super(CaptchaField, self).clean(value)
     response, value[1] = value[1].strip().lower(), ''
     CaptchaStore.remove_expired()
     try:
         store = CaptchaStore.objects.get(response=response, hashkey=value[0], expiration__gt=datetime.datetime.now())
     except Exception:
         raise ValidationError(getattr(self,'error_messages',dict()).get('invalid', _('Invalid CAPTCHA')))
     return value
Exemplo n.º 7
0
 def clean(self, value):
     super(CaptchaField, self).clean(value)
     response, value[1] = value[1].strip().lower(), ''
     CaptchaStore.remove_expired()
     try:
         store = CaptchaStore.objects.get(response=response, hashkey=value[0], expiration__gt=get_safe_now())
         store.delete()
     except Exception:
         raise ValidationError(getattr(self, 'error_messages', dict()).get('invalid', _(u'.کد امنیتی وارد شده صحیح نمی باشد')))
     return value
Exemplo n.º 8
0
 def clean(self, value):
     super(CaptchaField, self).clean(value)
     response, value[1] = value[1].strip().lower(), ''
     CaptchaStore.remove_expired()
     try:
         store = CaptchaStore.objects.get(response=response,hashkey=value[0], expiration__gt=datetime.datetime.now())
         store.delete()
     except Exception:
         raise ValidationError('Error')
     return value
Exemplo n.º 9
0
 def clean(self, value):
     super(CaptchaField, self).clean(value)
     response, value[1] = value[1].strip().lower(), ''
     CaptchaStore.remove_expired()
     try:
         store = CaptchaStore.objects.get(response=response, hashkey=value[0], expiration__gt=get_safe_now())
         store.delete()
     except Exception:
         raise ValidationError(getattr(self, 'error_messages', dict()).get('invalid', _('Invalid CAPTCHA')))
     return value
Exemplo n.º 10
0
def check_captcha(key, value):
    if value:
        CaptchaStore.remove_expired()
        try:
            CaptchaStore.objects.get(response=value,
                                     hashkey=key,
                                     expiration__gt=timezone.now()).delete()
        except CaptchaStore.DoesNotExist as e:
            raise CaptchaFailException(code=10007, message='验证码校验失败')
    else:
        raise CaptchaFailException(code=10008, message='验证码不能为空')
 def validate(self, attrs):
     response = (attrs.get('response') or '').lower()
     hashkey = attrs.get('hashkey', '')
     CaptchaStore.remove_expired()
     if not self.required and not response:
         pass
     else:
         try:
             CaptchaStore.objects.get(response=response, hashkey=hashkey, expiration__gt=get_safe_now()).delete()
         except CaptchaStore.DoesNotExist:
             raise ValidationError(self.error_messages['invalid_captcha'])
     return {}
Exemplo n.º 12
0
 def list(self, request):
     pp = self.get_serializer(data=request.GET)
     if pp.is_valid():
         CaptchaStore.remove_expired()  # 删除失效的验证码,过期时间为五分钟
         captcha_key = CaptchaStore.pick()
         to_json_response = {
             'key': captcha_key,
             'url': captcha_image_url(captcha_key),
         }
         return Response(to_json_response)
     else:
         raise ParseError(pp.errors)
Exemplo n.º 13
0
 def clean(self, value):
     super(CaptchaField, self).clean(value)
     response, value[1] = value[1].strip().lower(), ""
     CaptchaStore.remove_expired()
     try:
         store = CaptchaStore.objects.get(
             response=response, hashkey=value[0], expiration__gt=datetime.datetime.now()
         )
         store.delete()
     except Exception:
         raise ValidationError(u"Введённый текст не совпадает с текстом на картинке")
     return value
Exemplo n.º 14
0
def valifiedCapture(request):
    captureKey = request.POST.get('captureKey', '')
    captureWord = request.POST.get('capture', '')
    response, captureWord = (captureWord or '').strip().lower(), ''
    CaptchaStore.remove_expired()
    try:
        CaptchaStore.objects.get(response=response,
                                 hashkey=captureKey,
                                 expiration__gt=get_safe_now()).delete()
        return True
    except CaptchaStore.DoesNotExist:
        return False
Exemplo n.º 15
0
 def validate(self, attrs):
     response = (attrs.get('response') or '').lower()
     hashkey = attrs.get('hashkey', '')
     CaptchaStore.remove_expired()
     if not self.required and not response:
         pass
     else:
         try:
             CaptchaStore.objects.get(response=response,
                                      hashkey=hashkey).delete()
         except CaptchaStore.DoesNotExist:
             raise ValidationError(self.error_messages['invalid_captcha'])
     return {}
 def handle(self, **options):
     verbose = int(options.get('verbosity'))
     count = options.get('pool_size')
     CaptchaStore.create_pool(count)
     verbose and self.stdout.write('Created %d new captchas\n' % count)
     options.get('cleanup_expired') and CaptchaStore.remove_expired()
     options.get('cleanup_expired') and verbose and self.stdout.write('Expired captchas cleaned up\n')
Exemplo n.º 17
0
def check_captcha(captcha_code, captcha_hash):
    """
    :param captcha_code: 用户输入的验证码
    :param captcha_hash: 验证码的hash key
    :return: bool
    """
    CaptchaStore.remove_expired()

    if CaptchaStore.objects.filter(response=captcha_code, hashkey=captcha_hash).exists():
        CaptchaStore.objects.filter(response=captcha_code, hashkey=captcha_hash).delete()
        return True

    if settings.ENVIRONMENT == settings.DEVELOPMENT:
        return True

    return False
Exemplo n.º 18
0
 def handle(self, **options):
     verbose = int(options.get('verbosity'))
     count = options.get('pool_size')
     CaptchaStore.create_pool(count)
     verbose and self.stdout.write('Created %d new captchas\n' % count)
     options.get('cleanup_expired') and CaptchaStore.remove_expired()
     options.get('cleanup_expired') and verbose and self.stdout.write(
         'Expired captchas cleaned up\n')
Exemplo n.º 19
0
    def handle(self, **options):
        from captcha.models import CaptchaStore
        import datetime
        expired_keys = CaptchaStore.objects.filter(expiration__lte=datetime.datetime.now()).count()

        print "Currently %s expired hashkeys" % expired_keys
        try:
            CaptchaStore.remove_expired()
        except:
            print "Unable to delete expired hashkeys."
            sys.exit(1)


        if expired_keys > 0:
            print "Expired hashkeys removed."
        else:
            print "No keys to remove."
Exemplo n.º 20
0
 def handle(self, **options):
     verbose = int(options.get("verbosity"))
     count = options.get("pool_size")
     CaptchaStore.create_pool(count)
     verbose and self.stdout.write("Created %d new captchas\n" % count)
     options.get("cleanup_expired") and CaptchaStore.remove_expired()
     options.get("cleanup_expired") and verbose and self.stdout.write(
         "Expired captchas cleaned up\n")
Exemplo n.º 21
0
 def handle(self, **options):
     from captcha.models import CaptchaStore
     verbose = int(options.get('verbosity'))
     expired_keys = CaptchaStore.objects.filter(expiration__lte=get_safe_now()).count()
     if verbose >= 1:
         print("Currently %d expired hashkeys" % expired_keys)
     try:
         CaptchaStore.remove_expired()
     except:
         if verbose >= 1:
             print("Unable to delete expired hashkeys.")
         sys.exit(1)
     if verbose >= 1:
         if expired_keys > 0:
             print("%d expired hashkeys removed." % expired_keys)
         else:
             print("No keys to remove.")
Exemplo n.º 22
0
    def handle(self, **options):
        from captcha.models import CaptchaStore
        import datetime
        expired_keys = CaptchaStore.objects.filter(
            expiration__lte=datetime.datetime.now()).count()

        print "Currently %s expired hashkeys" % expired_keys
        try:
            CaptchaStore.remove_expired()
        except:
            print "Unable to delete expired hashkeys."
            sys.exit(1)

        if expired_keys > 0:
            print "Expired hashkeys removed."
        else:
            print "No keys to remove."
Exemplo n.º 23
0
 def clean(self, value):
     super(CaptchaField, self).clean(value)
     response, value[1] = (value[1] or '').strip().lower(), ''
     CaptchaStore.remove_expired()
     if settings.CATPCHA_TEST_MODE and response.lower() == 'passed':
         # automatically pass the test
         try:
             # try to delete the captcha based on its hash
             CaptchaStore.objects.get(hashkey=value[0]).delete()
         except CaptchaStore.DoesNotExist:
             # ignore errors
             pass
     else:
         try:
             CaptchaStore.objects.get(response=response, hashkey=value[0], expiration__gt=get_safe_now()).delete()
         except CaptchaStore.DoesNotExist:
             raise ValidationError(getattr(self, 'error_messages', {}).get('invalid', ugettext_lazy('Invalid CAPTCHA')))
     return value
Exemplo n.º 24
0
 def clean(self, value):
     super(CaptchaField, self).clean(value)
     response, value[1] = value[1].strip().lower(), ''
     CaptchaStore.remove_expired()
     if django_settings.DEBUG and response.lower() == 'passed':
         # automatically pass the test
         try:
             # try to delete the captcha based on its hash
             CaptchaStore.objects.get(hashkey=value[0]).delete()
         except Exception:
             # ignore errors
             pass
     else:
         try:
             store = CaptchaStore.objects.get(response=response, hashkey=value[0], expiration__gt=get_safe_now())
             store.delete()
         except Exception:
             raise ValidationError(getattr(self, 'error_messages', dict()).get('invalid', _('Invalid CAPTCHA')))
     return value
Exemplo n.º 25
0
 def clean(self, value):
     super(MyCaptchaField, self).clean(value)
     response, value[1] = (value[1] or "").strip().lower(), ""
     CaptchaStore.remove_expired()
     if settings.CAPTCHA_TEST_MODE and response.lower() == "passed":
         # automatically pass the test
         try:
             # try to delete the captcha based on its hash
             CaptchaStore.objects.get(hashkey=value[0]).delete()
         except CaptchaStore.DoesNotExist:
             # ignore errors
             pass
     elif not self.required and not response:
         pass
     else:
         try:
             CaptchaStore.objects.get(response=response, hashkey=value[0], expiration__gt=get_safe_now()).delete()
         except CaptchaStore.DoesNotExist:
             raise ValidationError(getattr(self, "error_messages", {}).get("invalid", _("Invalid CAPTCHA")))
     return value
Exemplo n.º 26
0
    def handle_noargs(self, **options):
        from django.db import transaction
        from django.contrib.sessions.models import Session
        Session.objects.filter(
            expire_date__lt=datetime.datetime.now()).delete()
        transaction.commit_unless_managed()
        print 'Session cleaned.'

        try:
            from captcha.models import CaptchaStore
        except:
            pass
        else:
            CaptchaStore.remove_expired()
            print 'Captcha cleaned.'

        #Удаляем неиспользующиеся файлы из upload
        from django.db.models import get_app, get_models
        from django.db.models.fields import files

        #Перечисляем приложения
        for app in conf.APPS:
            app = get_app(app)

            #Перечисляем модели
            for model in get_models(app):
                #Перечисляем поля модели
                for field in model._meta.fields:
                    if isinstance(field, files.FileField) or isinstance(
                            field, files.ImageField):
                        #Получаем пути файловых полей
                        upload_to = os.path.realpath(
                            os.path.join(settings.MEDIA_ROOT, field.upload_to))
                        if os.path.exists(upload_to):
                            #Перечисляем все файлы
                            for filename in os.listdir(upload_to):
                                fullname = os.path.join(upload_to, filename)
                                if os.path.isfile(fullname):
                                    print '.', fullname
                                    value_filename = ''.join([
                                        settings.MEDIA_URL, field.upload_to,
                                        filename
                                    ])
                                    #Проверяем используется ли файл в модели
                                    flag = False
                                    for row in model.objects.all():
                                        value = getattr(row, field.name, None)
                                        if value:
                                            value = unicode(value.url)

                                            pattern = re.compile(
                                                r'%s' % value, re.IGNORECASE)
                                            if pattern.search(value_filename):
                                                flag = True
                                    if not flag:
                                        os.remove(
                                            os.path.join(upload_to, filename))
                                        print 'DELETE'
        print 'Model files cleaned.'

        from django.core.cache import cache
        cache.clear()
        print 'Cache cleaned.'

        try:
            from sorl.thumbnail import default
        except:
            pass
        else:
            try:
                default.kvstore.cleanup()
            except:
                print 'except in kvstore.cleanup'

            try:
                default.kvstore.clear()
            except:
                print 'except in kvstore.clear'

            try:
                cache_dir = os.path.realpath(
                    os.path.join(settings.MEDIA_ROOT, 'cache'))
                for dirpath, dirnames, filenames in os.walk(cache_dir,
                                                            topdown=False):
                    for filename in filenames:
                        os.remove(os.path.join(dirpath, filename))
                    for filename in dirnames:
                        os.rmdir(os.path.join(dirpath, filename))
            except:
                print 'except in remove files and dirs'
            print 'Sorl.thumbnail cleaned.'

        try:
            from watermark.models import Watermark
        except:
            pass
        else:
            for str in Watermark.objects.all():
                if str.image or str.wimage:
                    im_path = os.path.realpath(
                        os.path.join(os.path.dirname(settings.MEDIA_ROOT),
                                     '%s') % str.image)
                    wm_path = os.path.realpath(
                        os.path.join(os.path.dirname(settings.MEDIA_ROOT),
                                     '%s') % str.wimage)
                    if not os.path.exists(wm_path) or not os.path.exists(
                            im_path):
                        str.delete()

            path = os.path.join(settings.MEDIA_ROOT, 'cache')
            for dirpath, dirnames, filenames in os.walk(path):
                for filename in filenames:
                    r = re.compile(
                        '^([a-zA-Z0-9_-]+)_watermark\.([a-zA-Z0-9_-]+)$',
                        re.IGNORECASE)
                    if r.findall(filename):
                        if not Watermark.objects.filter(
                                wimage=os.path.join(dirpath, filename).replace(
                                    os.path.dirname(settings.MEDIA_ROOT), '')):
                            os.remove(os.path.join(dirpath, filename))
            print 'Wotermark cleaned.'
Exemplo n.º 27
0
def validate_captcha(key, value):
    value = value.lower()
    CaptchaStore.remove_expired()
    captcha = CaptchaStore.objects.filter(hashkey=key, response=value)
    if not captcha.count():
        raise serializers.ValidationError('Captcha is not correct.')
Exemplo n.º 28
0
def check_captcha(request):
    """ Check a submitted captcha.

        This Django view function checks that the submitted captcha value
        matches the captcha value in the database.

        The following parameters are required:

            'key'

                The captcha key returned by a previous call to
                create_captcha(), above.

            'value'

                The captcha value, as typed by the user.

        Upon completion, we return an HttpResponse consisting of an object with
        the following fields, in JSON format:

            'success'

                True if an only if the entered captcha value was correct.

        Note that this view function supports JSON-P via a "callback"
        parameter.
    """

    # Grab our HTTP request parameters.

    if request.method == "GET":
        params = request.GET
    elif request.method == "POST":
        params = request.POST
    else:
        raise RuntimeError("Unsupported HTTP method: " + request.method)

    if "key" in params:
        key = params['key']
    else:
        raise RuntimeError("Missing parameter: 'key'")

    if "value" in params:
        value = params['value'].strip().lower()
    else:
        raise RuntimeError("Missing parameter: 'value'")

    # Check to see that this captcha is still valid.  Note that this logic is
    # derived from the captcha.fields.CaptchaField.validate() method.

    CaptchaStore.remove_expired()
    try:
        captcha = CaptchaStore.objects.get(response__iexact=value, hashkey=key,
                                           expiration__gt=get_safe_now())
        captcha.delete()
        success = True
    except CaptchaStore.DoesNotExist:
        success = False

    # Format the data to return back to the caller.

    results = json.dumps({'success' : success})

    # Handle JSON-P, if necessary.

    if "callback" in params:
        results = params['callback'] + "(" + results + ")"

    # Finally, return the results back to the caller.

    response = HttpResponse(results, mimetype="application/json")
    response["Access-Control-Allow-Origin"] = "*"
    return response