Beispiel #1
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
Beispiel #2
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
Beispiel #3
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
Beispiel #4
0
def imageV(key, response):
    try:
        CaptchaStore.objects.get(response=response.lower(),
                                 hashkey=key,
                                 expiration__gt=get_safe_now()).delete()
    except CaptchaStore.DoesNotExist:
        return -1
    return 0
Beispiel #5
0
 def save(self, *args, **kwargs):
     #import ipdb; ipdb.set_trace()
     self.response = six.text_type(self.response).lower()
     if not self.expiration:
         #self.expiration = datetime.datetime.now() + datetime.timedelta(minutes=int(captcha_settings.CAPTCHA_TIMEOUT))
         self.expiration = get_safe_now() + datetime.timedelta(minutes=int(captcha_settings.CAPTCHA_TIMEOUT))
     if not self.hashkey:
         key_ = unicodedata.normalize('NFKD', str(randrange(0, MAX_RANDOM_KEY)) + str(time.time()) + six.text_type(self.challenge)).encode('ascii', 'ignore') + unicodedata.normalize('NFKD', six.text_type(self.response)).encode('ascii', 'ignore')
         if hashlib:
             self.hashkey = hashlib.sha1(key_).hexdigest()
         else:
             self.hashkey = sha.new(key_).hexdigest()
         del(key_)
     super(CaptchaStore, self).save(*args, **kwargs)
 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
Beispiel #7
0
    def testDeleteExpired(self):
        self.default_store.expiration = get_safe_now() - datetime.timedelta(minutes=5)
        self.default_store.save()
        hash_ = self.default_store.hashkey
        r = self.client.post(reverse('captcha-test'), dict(captcha_0=hash_, captcha_1=self.default_store.response, subject='xxx', sender='*****@*****.**'))

        self.assertEqual(r.status_code, 200)
        self.assertFalse('Form validated' in str(r.content))

        # expired -> deleted
        try:
            CaptchaStore.objects.get(hashkey=hash_)
            self.fail()
        except:
            pass
Beispiel #8
0
    def testDeleteExpired(self):
        self.default_store.expiration = get_safe_now() - datetime.timedelta(minutes=5)
        self.default_store.save()
        hash_ = self.default_store.hashkey
        r = self.client.post(reverse('captcha-test'), dict(captcha_0=hash_, captcha_1=self.default_store.response, subject='xxx', sender='*****@*****.**'))

        self.assertEqual(r.status_code, 200)
        self.assertFalse('Form validated' in str(r.content))

        # expired -> deleted
        try:
            CaptchaStore.objects.get(hashkey=hash_)
            self.fail()
        except:
            pass
Beispiel #9
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.")
Beispiel #10
0
 def remove_expired(cls):
     cls.objects.filter(expiration__lte=get_safe_now()).delete()
Beispiel #11
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
Beispiel #12
0
    def test_signup(self):
        """
        测试整个signup流程,大致的流程如下,边界测试写在代码中:
          1.获得登陆界面,按照上面的action发出post请求,应该返回register界面;
          2.按照register界面的action发出post;
          3.从数据库中能够获取到User并且is_activate标记为False(尚未激活);
          4.从邮件中取出激活邮件,从中获取到激活码链接,发送激活请求;
          5.激活成功后:
            a.从数据库取出User应该为激活状态,is_activate=True
            b.user应该有一个拥有的StudyTribe
            c.应该有三个权限组:tribeowner,tribeadmin,tribemember
            d.user属于这个tribe的tribeowner组
            e.tribeowner拥有:enter_tribe,remove_tribe,change_tribe_grade权限
            f.tribeadmin拥有:enter_tribe,remove_tribe权限
            g.tribemember拥有:enter_tribe权限
            f.跳转到选择tribe的界面中
          6.激活失败后显示失败界面
        """
        #随便选了input和对应的验证数,应该会抛出异常
        hashkey_from_page = 'scls'
        input_captcha = 'ss'
        self.assertRaises(Exception, 
                          CaptchaStore.objects.get,
                         {'response':input_captcha,
                          'hashkey':hashkey_from_page,
                          'expiration__gt':get_safe_now()})
        data = {
                'username':'******',
                'email':'*****@*****.**',
                'password1':'123456',
                'password2':'123456',
                'captcha_0':'sdjslf',
                'captcha_1':'XJMD',
                }
        response = self.client.post(reverse('studytribe_sign_main',args=['signup']),data)
        #发送的captcha_0不对,创建不了用户
        self.assertRaises(Exception, 
                          User.objects.get,
                         {'username':'******'})
        #向register发送POST请求获取hashkey_from_page,在数据库中查出challenge
        #然后用这个表单POST,应该成功创建出一个没有激活的帐户
        soup = BeautifulSoup(response.content)
        ne = soup.find('input',{'id':'id_captcha_0'})
        hashkey_from_page = ne['value']
        csobj = CaptchaStore.objects.get(hashkey=hashkey_from_page)
        input_captcha = csobj.challenge
        data['captcha_0'] = hashkey_from_page
        data['captcha_1'] = input_captcha
        response = self.client.post(reverse('studytribe_sign_main',args=['signup']),data)
        user = User.objects.get(username='******')
        self.assertTrue(user is not None)
        self.assertFalse(user.is_active)
        self.assertEquals(len(mail.outbox),1)
        #但此时还没有owned_tribe,激活后才有
        self.assertEquals(len(StudyTribe.objects.all()),0)
        #开始激活
        mail_content = mail.outbox[0].body
        match = re.search('activate/(.*)/' , mail_content)
        activation_key = match.group(1)
        c = self.client
        #用一个错误的激活码
        response = c.get(reverse('userena_activate',
                         kwargs={'activation_key':'sselsjdfkjl'}))
        self.assertFalse(User.objects.get(username__exact='someone').is_active,
                         msg = "After user been activated by a wrong activate_key,the user's is_active property should equals False.")
        #验证失败返回激活失败界面
        self.assertTemplateUsed(response,
                                settings.USER_ACTIVATE_FAIL_TEMPLATE)
        #try the correct activation_key
        response = c.get(reverse('userena_activate',
                         kwargs={'activation_key' : activation_key}))
        self.assertTrue(User.objects.get(username__exact='someone').is_active,
                        msg = "After user been activated,the user's is_active property should equals True.")
        #验证跳转到激活正确界面
        tribe_choose_url = (userena_settings.USERENA_SIGNIN_REDIRECT_URL %  
                            {'username':user.username})
        self.assertRedirects(response,tribe_choose_url)

        #验证权限begin
        user = User.objects.get(username__exact='someone')
        #if there have no tribe,will raise StudyTribe.DoesNotExist exception
        self.assertEquals(len(StudyTribe.objects.all()),1,
                          msg="After user been activated,the user's StudyTribe should be created.")
        permission_group = Group.objects.all()
        self.assertEquals(len(permission_group),3,
                         msg="After user been activated,three permission groups should be created.")
        tribe_owner_name = "tribe_owner:%d" % user.created_tribe.id
        towner = Group.objects.get(name=tribe_owner_name)
        tadmin = Group.objects.get(name="tribe_admin:%d" % user.created_tribe.id)
        tmember = Group.objects.get(name="tribe_member:%d" % user.created_tribe.id)

        owner_permissions = ['enter_studytribe',
                             'add_studytribe',
                             'delete_studytribe',
                             'change_studytribe',
                             'change_studytribe_grade']

        admin_permissions = ['enter_studytribe',
                             'add_studytribe',
                             'delete_studytribe',
                             'change_studytribe']

        member_permissions = ['enter_studytribe']

        owner_group_permissions = get_perms(towner,user.created_tribe)
        self.assertEquals(len(owner_group_permissions),5)
        for perm_code in owner_group_permissions: 
            self.assertTrue(perm_code in owner_permissions)

        admin_group_permissions = get_perms(tadmin,user.created_tribe)
        self.assertEquals(len(admin_group_permissions),4)
        for perm_code in admin_group_permissions: 
            self.assertTrue(perm_code in admin_permissions)

        member_group_permissions = get_perms(tmember,user.created_tribe)
        self.assertEquals(len(member_group_permissions),1)
        for perm_code in member_group_permissions: 
            self.assertTrue(perm_code in member_permissions)

        self.assertEquals(len(user.groups.all()),1)
        self.assertTrue(user.groups.all()[0].name == tribe_owner_name)

        tribe = user.created_tribe
        self.assertTrue(user.has_perm('studygroup.enter_studytribe',tribe))
        self.assertTrue(user.has_perm('studygroup.delete_studytribe',tribe))
        self.assertTrue(user.has_perm('studygroup.change_studytribe_grade',tribe))
        self.assertFalse(user.has_perm('studygroup.change_studytribe_grade'))

        self.assertEquals(len(get_objects_for_user(user,'studygroup.enter_studytribe')),1)
Beispiel #13
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
Beispiel #14
0
def imageV(key, response):
    try:
        CaptchaStore.objects.get(response=response, hashkey=key, expiration__gt=get_safe_now()).delete()
    except CaptchaStore.DoesNotExist:
        return -1
    return 0
Beispiel #15
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
 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 {}
Beispiel #17
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
Beispiel #18
0
 def clean(self, value):
     super(CaptchaField, self).clean(value)
     response, value[1] = value[1].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 Exception:
             # ignore errors
             pass
     else:
         try:
             CaptchaStore.objects.get(response=response, hashkey=value[0], expiration__gt=get_safe_now()).delete()
         except Exception:
             raise ValidationError(getattr(self, 'error_messages', dict()).get('invalid', _('CAPTCHA invalido')))
     return value
Beispiel #19
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
Beispiel #20
0
def imageV_notDelete(key, response):
    try:
        cap = CaptchaStore.objects.get(response=response.lower(), hashkey=key, expiration__gt=get_safe_now())
    except CaptchaStore.DoesNotExist:
        return -1
    return 0