Пример #1
0
 def post(self, request):
     login_form = LoginForm(request.POST)
     if login_form.is_valid():
         username = request.POST.get('username', '')
         password = request.POST.get('password', '')
         user = authenticate(username=username, password=password)
         if user is not None:
             if user.is_active:
                 login(request, user)
                 return redirect('/')
             else:
                 hashkey = CaptchaStore.generate_key()
                 image_url = captcha_image_url(hashkey)
                 return render(request, "Login.html", {
                     'msg': '账号未激活',
                     'hashkey': hashkey,
                     'image_url': image_url
                 })
         else:
             hashkey = CaptchaStore.generate_key()
             image_url = captcha_image_url(hashkey)
             return render(request, "Login.html", {
                 'msg': '账号或者密码错误',
                 'hashkey': hashkey,
                 'image_url': image_url
             })
     else:
         hashkey = CaptchaStore.generate_key()
         image_url = captcha_image_url(hashkey)
         return render(
             request, "Login.html", {
                 'login_form': login_form,
                 'hashkey': hashkey,
                 'image_url': image_url
             })
Пример #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
Пример #3
0
def login(request):
    if request.method == 'POST':
        login_form = form.loginForm(request.POST)
        message = "验证码错误!"
        hash_key = CaptchaStore.generate_key()
        image_url = captcha_image_url(hash_key)
        if login_form.is_valid():
            email = login_form.cleaned_data['email']
            password = login_form.cleaned_data['password']
            try:
                user = models.User.objects.get(email=email)
                if user.password == password:
                    request.session['user_id'] = user.id
                    request.session['user_name'] = user.username
                    return redirect('/home/')
                else:
                    message = "密码不正确!"
            except Exception as e:
                print e
                message = "用户不存在!"
        return render(request, 'general/login.html', locals())
    else:
        login_form = form.loginForm()
        hash_key = CaptchaStore.generate_key()
        image_url = captcha_image_url(hash_key)
        return render(request, 'general/login.html', locals())
Пример #4
0
 def post(self, request):
     login_form = LoginForm(request.POST)
     email = request.POST.get("email", "")
     pass_word = request.POST.get("password", "")
     if login_form.is_valid():
         filter_result = User.objects.filter(email__exact=email)
         username = filter_result[0].username
         user = authenticate(username=username, password=pass_word)
         if user is not None:
             if user.is_active:
                 login(request, user)
                 return render(request, "login_success.html", locals())
             else:
                 hash_key = CaptchaStore.generate_key()
                 image_url = captcha_image_url(hash_key)
                 msg = _("用户被暂停,请联系系统管理员")
                 return render(request, "login.html", locals())
         else:
             # 图片验证码
             # hashkey验证码生成的秘钥,image_url验证码的图片地址
             hash_key = CaptchaStore.generate_key()
             image_url = captcha_image_url(hash_key)
             msg = _("用户名或者密码错误")
             return render(request, "login.html", locals())
     else:
         hash_key = CaptchaStore.generate_key()
         image_url = captcha_image_url(hash_key)
         msg = _("验证码错误")
         # Python内置了一个locals()函数,它返回当前所有的本地变量字典
         return render(request, "login.html", locals())
Пример #5
0
def login(request):  
    #刷新验证码
    if request.GET.get('newsn')=='1':
        csn=CaptchaStore.generate_key()
        cimageurl= captcha_image_url(csn)
        return HttpResponse(cimageurl)

    t = loader.get_template('backstage/login.html')  
    c = RequestContext(request, {'foo': 'bar'})

    if request.POST:
        form = CaptchaTestForm(request.POST)

        # Validate the form: the captcha field will automatically
        # check the input
        if form.is_valid():
            human = True

        to_json_response = dict()
        to_json_response['status'] = 0
        to_json_response['form_errors'] = form.errors

        to_json_response['new_cptch_key'] = CaptchaStore.generate_key()
        to_json_response['new_cptch_image'] = captcha_image_url(to_json_response['new_cptch_key'])

        return HttpResponse(json.dumps(to_json_response), content_type='application/json')

    else:
        form = CaptchaTestForm()  

        #return HttpResponse(t.render(c))
        #return render_to_response('backend/login.html',locals())
        return render_to_response('backstage/login.html',
            locals(),
            context_instance=RequestContext(request, processors=[]))
Пример #6
0
def register(request):
    if request.method == 'POST':
        register_form = form.registerForm(request.POST)
        message = "验证码错误!"
        hash_key = CaptchaStore.generate_key()
        image_url = captcha_image_url(hash_key)
        step = 1
        if register_form.is_valid():
            email = request.session.get('email', '')
            username = register_form.cleaned_data['username']
            password = register_form.cleaned_data['password']
            if username != '' and password != '' and email != '':
                try:
                    try:
                        user = models.User.objects.get(email=email)
                        message = '该用户已存在'
                    except models.User.DoesNotExist:
                        user = models.User.objects.create(email=email,
                                                          username=username,
                                                          password=password)
                        if user:
                            message = "注册成功"
                            return redirect('/home/')
                        else:
                            message = "注册失败"
                except:
                    message = "注册失败!"
        return render(request, 'general/register.html', locals())
    else:
        register_form = form.registerForm()
        hash_key = CaptchaStore.generate_key()
        image_url = captcha_image_url(hash_key)
        return render(request, 'general/register.html', locals())
Пример #7
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",
    )
Пример #8
0
def add_comment(request, slug):
    """ function view for adding comment via ajax """
    post = get_object_or_404(Posts, slug=slug)
    full_form = CommentForm(request.POST)
    if request.is_ajax():
        if full_form.is_valid():
            new_comment = full_form.save(commit=False)
            new_comment.post = post
            new_comment.save()
            to_json_response = dict()
            to_json_response['status'] = 1
            to_json_response['new_cptch_key'] = CaptchaStore.generate_key()
            to_json_response['new_cptch_image'] = captcha_image_url(
                to_json_response['new_cptch_key'])
            to_json_response[
                'new_comment_author_name'] = new_comment.author_name
            to_json_response['new_comment_pub_date'] = str(
                new_comment.pub_date)
            to_json_response['new_comment_body'] = new_comment.comment_body
            to_json_response['new_comment_id'] = new_comment.id
        else:
            to_json_response = dict()
            to_json_response['status'] = 0
            to_json_response['form_errors'] = full_form.errors
            to_json_response['new_cptch_key'] = CaptchaStore.generate_key()
            to_json_response['new_cptch_image'] = captcha_image_url(
                to_json_response['new_cptch_key'])

    return HttpResponse(json.dumps(to_json_response),
                        content_type='application/json')
 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')
Пример #10
0
 def setUp(self):
     CaptchaStore.generate_key()
     self.hashkey = CaptchaStore.objects.all()[0].hashkey
     self.response = CaptchaStore.objects.all()[0].response
     self.user = User.objects.create_user(username='******',
                                          email='*****@*****.**',
                                          password='******')
Пример #11
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
Пример #12
0
 def setUp(self):
     CaptchaStore.generate_key()
     self.hashkey = CaptchaStore.objects.all()[0].hashkey
     self.response = CaptchaStore.objects.all()[0].response
     self.user = User.objects.create_user(username='******',
                                          email='*****@*****.**',
                                          password='******')
Пример #13
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
Пример #14
0
def login(request):
    # if request.method=="POST":
    #     data = request.POST
    #     msg = "登录失败"
    #     print(type(User.objects))
    #     obj = User.objects.filter(username = data.get('username'))
    #     if(obj is not None and len(obj) > 0):
    #         obj = obj.values()[0]
    #         if(check_password(data.get('pwd'), obj.get('password'))):
    #             msg = ""
    # return render(request, 'index.html', {'msg': msg})

    if request.method == "GET":
        form = FormL()  # 初始化form对象
        key = CaptchaStore.generate_key()
        imgUrl = captcha_image_url(key)
        return render(request, "login.html", locals())
    else:
        form = FormL(request.POST)  # 将数据传给form对象
        if form.is_valid():  # 进行校验
            data = form.cleaned_data
            request.session['username'] = data.get('name')
            request.session['is_login'] = True
            return redirect("/index")
        else:  # 校验失败
            key = CaptchaStore.generate_key()
            imgUrl = captcha_image_url(key)
            clear_errors = form.errors.get("__all__")  # 获取全局钩子错误信息
            return render(request, "login.html", locals())
Пример #15
0
def vote(request, question_id):

    response_json = {}
    if request.method == 'POST':
        form = RadioVoteForm(request.POST)
        if form.is_valid():
            p = get_object_or_404(Question, pk=question_id)
            try:
                selected_choice = p.choice_set.get(pk=request.POST['choice'])
            except (KeyError, Choice.DoesNotExist):
                response_json['error'] = "You didn't select a choice."
            else:
                selected_choice.votes += 1
                selected_choice.save()
                response_json['status'] = 1
                response_json['new_cptch_key'] = CaptchaStore.generate_key()
                response_json['new_cptch_image'] = captcha_image_url(response_json['new_cptch_key'])
        else:
            response_json['status'] = 0
            response_json['form_errors'] = form.errors
            response_json['new_cptch_key'] = CaptchaStore.generate_key()
            response_json['new_cptch_image'] = captcha_image_url(response_json['new_cptch_key'])
            print >>sys.stderr, 'VOTE FORM ERROR: ' + str(form.errors)
    else:
        response_json['error'] = "Method is not POST"
    return HttpResponse(json.dumps(response_json), content_type="application/json")
Пример #16
0
 def post(self, request):
     reset_form = ResetForm(request.POST)
     username = request.user.username
     password = request.POST.get("password_before", "")
     user = authenticate(username=username,
                         password=password,
                         type="expert")
     if user is None:
         hash_key = CaptchaStore.generate_key()
         image_url = captcha_image_url(hash_key)
         return render(request, "main_reset.html", {
             "hash_key": hash_key,
             "image_url": image_url,
             "msg": "用户密码错误!"
         })
     if reset_form.is_valid():
         username = request.user.username
         password = request.POST.get("password_after", "")
         user = UserProfile.objects.get(username=username)
         user.password = make_password(password)
         user.save()
         login(request, user)
         response = HttpResponse()
         response.write(
             "<script> alert('修改密码成功'); location='/main/';</script>")
         return response
     else:
         hash_key = CaptchaStore.generate_key()
         image_url = captcha_image_url(hash_key)
         return render(
             request, "main_reset.html", {
                 "hash_key": hash_key,
                 "image_url": image_url,
                 "reset_form": reset_form
             })
Пример #17
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
Пример #18
0
def send_message(request):
    """ function for ajax view of sending email to site admin """
    full_form = ContactForm(request.POST)
    if request.is_ajax():
        if full_form.is_valid():
            subject = f'Письмо с сайта vcard, от { full_form.cleaned_data["your_name"]} { full_form.cleaned_data["your_email"]}'
            email_from = settings.DEFAULT_FROM_EMAIL
            message = f'от { full_form.cleaned_data["your_email"]}  \r\n {full_form.cleaned_data["message"]}'
            recipient_list = [settings.DEFAULT_EMAIL_TO]
            try:
                send_mail(subject, message, email_from, recipient_list)
            except Exception as E:
                print(E)
            to_json_response = dict()
            to_json_response['status'] = 1
            to_json_response['new_cptch_key'] = CaptchaStore.generate_key()
            to_json_response['new_cptch_image'] = captcha_image_url(
                to_json_response['new_cptch_key'])

        else:
            to_json_response = dict()
            to_json_response['status'] = 0
            to_json_response['form_errors'] = full_form.errors

            to_json_response['new_cptch_key'] = CaptchaStore.generate_key()
            to_json_response['new_cptch_image'] = captcha_image_url(
                to_json_response['new_cptch_key'])
        return HttpResponse(json.dumps(to_json_response),
                            content_type='application/json')
Пример #19
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')
Пример #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")
Пример #21
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
Пример #22
0
 def test_empty_pool_fallback(self):
     __current_test_get_from_pool_setting = settings.CAPTCHA_GET_FROM_POOL
     settings.CAPTCHA_GET_FROM_POOL = True
     CaptchaStore.objects.all().delete()  # Delete objects created during SetUp
     with LogCapture() as l:
         CaptchaStore.pick()
     l.check(('captcha.models', 'ERROR', "Couldn't get a captcha from pool, generating"),)
     self.assertEqual(CaptchaStore.objects.count(), 1)
     settings.CAPTCHA_GET_FROM_POOL = __current_test_get_from_pool_setting
Пример #23
0
 def test_empty_pool_fallback(self):
     __current_test_get_from_pool_setting = settings.CAPTCHA_GET_FROM_POOL
     settings.CAPTCHA_GET_FROM_POOL = True
     CaptchaStore.objects.all().delete()  # Delete objects created during SetUp
     with LogCapture() as l:
         CaptchaStore.pick()
     l.check(('captcha.models', 'ERROR', "Couldn't get a captcha from pool, generating"),)
     self.assertEqual(CaptchaStore.objects.count(), 1)
     settings.CAPTCHA_GET_FROM_POOL = __current_test_get_from_pool_setting
Пример #24
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
Пример #25
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
Пример #26
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
Пример #27
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='验证码不能为空')
Пример #28
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
 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 {}
Пример #30
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
Пример #31
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)
Пример #32
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 {}
Пример #33
0
def set_captcha(key):
    g = GenCaptcha()
    ans, buffer = g.create_img()
    try:
        # try to get if already there
        s = CaptchaStore.objects.get(key=key)
        s.answer = ans
        s.save()
    except ObjectDoesNotExist:
        # not exist, create new
        s = CaptchaStore(key=key, answer=ans)
        s.save()

    return buffer.read()
Пример #34
0
def check(key, ans):
    CaptchaStore.clean_expire()

    try:
        s = CaptchaStore.objects.get(key=key)
    except ObjectDoesNotExist:
        return False
    else:
        if s.answer == ans.lower():
            s.delete()
            return True
        else:
            s.delete()
            return False
Пример #35
0
    def test_login_error_message(self):
        self.add_user()
        resp = self.client.post(reverse('logout'))
        captcha = CaptchaStore.objects.get(hashkey=CaptchaStore.generate_key())
        data = self.manual_login_data(captcha)
        data['password'] = '******'
        resp = self.client.post(reverse('login'), data, follow=True)
        self.assertContains(resp, u'用户名或密码错误')

        captcha = CaptchaStore.objects.get(hashkey=CaptchaStore.generate_key())
        data = self.manual_login_data(captcha)
        data['captcha_1'] = 'worng'
        resp = self.client.post(reverse('login'), data, follow=True)
        self.assertContains(resp, u'验证码错误')
Пример #36
0
    def testE_add_exit_user(self):
        request_data = {
            'username': '******',
            'email': '*****@*****.**',
            'password': '******',
            'captcha_key': 4456,
            'captcha_answer': 'ut2x'
        }

        c = CaptchaStore(key=request_data['captcha_key'],
                         answer=request_data['captcha_answer'])
        c.save()

        request = self.factory.post(self.base_url,
                                    data=request_data,
                                    format='json')
        self.view(request)

        c = CaptchaStore(key=request_data['captcha_key'],
                         answer=request_data['captcha_answer'])
        c.save()

        request = self.factory.post(self.base_url,
                                    data=request_data,
                                    format='json')
        res = self.view(request)
        self.assertEqual(res.status_code, status.HTTP_409_CONFLICT)
Пример #37
0
def register(request):
    """
    用户注册
    """
    if request.is_ajax():  # 请求ajax则返回新的image_url和key
        result = dict()
        result['key'] = CaptchaStore.generate_key()
        result['image_url'] = captcha_image_url(result['key'])
        return JsonResponse(result)
    if request.method == "POST":
        register_form = RegisterForm(request.POST)
        if register_form.is_valid():
            username = register_form.cleaned_data['username']
            password1 = register_form.cleaned_data['password1']
            password2 = register_form.cleaned_data['password2']
            if password1 != password2:
                msg = "两次输入的密码不同!"
                return render(request, "users/register.html", {
                    'register_form': register_form,
                    'msg': msg
                })
            else:
                same_user = UserProfile.objects.filter(username=username)
                if same_user:  # 用户名唯一
                    msg = '用户名已经存在,请重新选择用户名!'
                    return render(request, "users/register.html", {
                        'register_form': register_form,
                        'msg': msg
                    })
                new_user = UserProfile()
                new_user.username = username
                new_user.password = make_password(password1)  # 使用加密密
                new_user.save()
                return redirect('/login/')  # 自动跳转到登录页面
        else:
            return render(request, "users/register.html",
                          {'register_form': register_form})

    else:
        register_form = RegisterForm()
        hashkey = CaptchaStore.generate_key()
        image_url = captcha_image_url(hashkey)
        return render(
            request, "users/register.html", {
                'register_form': register_form,
                "hashkey": hashkey,
                "image_url": image_url,
            })
Пример #38
0
def generateCap():
    new_key = CaptchaStore.generate_key()
    cap = {
        'key': new_key,
        'image_url': captcha_image_url(new_key),
    }
    return cap
Пример #39
0
def forgot(request):
    # 用于刷新验证码
    hashkey = CaptchaStore.generate_key()  
    image_url = captcha_image_url(hashkey)
    if request.method == 'POST':
        form = ForgotForm(request.POST)       
        if form.is_valid():
            email = request.POST.get("email")
            try:
                user = User.objects.get(email=email)
            except:
                user = None
                form.errors['email'] = '此邮箱未注册'
            if user:
                resetBiz = ResetPwdBiz()
                resetBiz.send_email(email)

                return render_to_response("forget.html",
                    {"success": form},
                    context_instance = RequestContext(request)
                    )
            return render_to_response("forget.html",
                {"hashkey": hashkey, "image_url": image_url, "form": form},
                context_instance = RequestContext(request)
                )
        return render_to_response("forget.html",
            {"hashkey": hashkey, "image_url": image_url, "form": form},
            context_instance = RequestContext(request)
            )
    return render_to_response("forget.html",
        {"hashkey": hashkey, "image_url": image_url},
        context_instance = RequestContext(request)
        )
Пример #40
0
def mailbox(request,template_name="oa/site/email.html",domain="domain"):
    site = get_site(request)
    if not site:
        return render(request, "404.html")
    school = site.school
    
    if request.GET.get('newsn')=='1':
        csn=CaptchaStore.generate_key()
        cimageurl= captcha_image_url(csn)
        parent_domain = helpers.get_parent_domain(request)
        return HttpResponse(parent_domain + cimageurl)
    
    if request.method == 'POST':
        form = MailBoxForm(request.POST)
        print form.errors,'eeeeeeeeeeeeeeeeeee'
        if request.is_ajax():
            return helpers.ajax_validate_form(form)
        
        if form.is_valid():
            human = True
            mail = form.save(commit=False)
#            mail.user = school.header
            mail.site = site
            mail.save()
            if mail.id:
                messages.success(request, u'已成功发送%s ' % mail.title)
                return redirect(request.get_full_path())
    else:
        form = MailBoxForm()
    ctx = {'form':form,'class':'startes','site':site}
    return render(request, template_name, ctx)
Пример #41
0
def bbs_pub(request):
    categories = Category.objects.all()
    hashkey = CaptchaStore.generate_key()  
    image_url = captcha_image_url(hashkey)  
    if request.method == 'POST':
        form = BbsPubForm(request.POST)

        if form.is_valid():
            cd = form.cleaned_data
            bbsBiz = BbsBiz()         
            bbs_category = bbsBiz.getCategory(cd['bbs_category'])
            bbs_author = bbsBiz.getBbsAuthorByReq(request.user)

            if bbs_category and bbs_author:
                bbs_content = remove_tags(cd['bbs_content'], "html body script")
                BBS.objects.create(
                    bbs_title = cd['bbs_title'],
                    bbs_content = bbs_content,
                    view_count = 0,
                    bbs_category = bbs_category,
                    bbs_author = bbs_author,
                )
                return HttpResponseRedirect(reverse('home'))      
        return render_to_response("bbs_pub.html", {"form": form,
            "categories": categories,
            "hashkey": hashkey, "image_url": image_url},
            context_instance = RequestContext(request))

    form = BbsPubForm()
    return render_to_response("bbs_pub.html",
        {"form": form, "categories": categories,
        "hashkey": hashkey, "image_url": image_url},
        context_instance = RequestContext(request))
Пример #42
0
def login_page(request):
    """
    Display the login form.
    """
    flag =request.GET.get('flag',0)
    csrf_token = csrf(request)['csrf_token']
    if (settings.FEATURES['AUTH_USE_CERTIFICATES'] and
            ssl_get_cert_from_request(request)):
        # SSL login doesn't require a login view, so redirect
        # to course now that the user is authenticated via
        # the decorator.
        return redirect('/course')
    form = CaptchaLoginForm()

    if request.is_ajax():
        new_cptch_key = CaptchaStore.generate_key()
        cpt_image_url = captcha_image_url(new_cptch_key)

        return JsonResponse({'captcha_image_url': cpt_image_url})

    return render_to_response(
        'login.html',
        {
            'flag':flag,
            'csrf': csrf_token,
            'forgot_password_link': "//{base}/login#forgot-password-modal".format(base=settings.LMS_BASE),
            'platform_name': microsite.get_value('platform_name', settings.PLATFORM_NAME),
            'form': form
        }
    )
Пример #43
0
def refresh_captcha(request):
    """
    刷新验证码图片
    """
    new_key = CaptchaStore.generate_key()
    new_img = captcha_image_url(new_key)
    return HttpResponse(new_img)
Пример #44
0
def new_captcha(request):
    if request.is_ajax():
        print('This is a ajax')
        csn=CaptchaStore.generate_key()
        imageurl = captcha_image_url(csn)
        data = {"imageurl": imageurl, "csn": csn}
        return JsonResponse(data)
Пример #45
0
    def form_valid(self, form):
        #form.save()
        if self.request.is_ajax():
            to_json_response = dict()

            to_json_response['new_cptch_key'] = CaptchaStore.generate_key()
            to_json_response['new_cptch_image'] = captcha_image_url(to_json_response['new_cptch_key'])

            #[验证用户名密码](http://www.cnblogs.com/linjiqin/p/3638501.html)
            username = self.request.POST['username']
            password = self.request.POST['password']
            if username=="" or username.isspace():
                to_json_response['status'] = 0
                to_json_response['data'] = "用户名不能为空"
            if password=="" or password.isspace():
                to_json_response['status'] = 0
                to_json_response['data'] = "密码不能为空"

            user = auth.authenticate(username=username, password=password)
            if user is not None:
                if user.is_active:
                    auth.login(self.request, user)
                    to_json_response['status'] = 1
                    to_json_response['data'] = "OK"
                else:
                    to_json_response['status'] = 0
                    to_json_response['data'] = "["+username+"]已被暂时禁用"
            else:
                to_json_response['status'] = 0
                to_json_response['data'] = "用户名或密码不正确,请重试"

            return HttpResponse(json.dumps(to_json_response), content_type='application/json')
Пример #46
0
def forgot_passwd(request):
    if request.method == "POST":
        if not request.is_ajax():
            raise Http404
        result={}
        passwd = request.POST.get('passwd', '')
        telcode = request.POST.get("code", '')
        mobile = request.POST.get('mobile', '')
        if not (passwd and telcode and mobile):
            result['code'] = '3'
            result['res_msg'] = u'传入参数不足!'
            return JsonResponse(result)
        ret = verifymobilecode(mobile,telcode)
        if ret != 0:
            result['code'] = 1
            if ret == -1:
                result['res_msg'] = u'请先获取手机验证码'
            elif ret == 1:
                result['res_msg'] = u'手机验证码输入错误!'
            elif ret == 2:
                result['res_msg'] = u'手机验证码已过期,请重新获取'
        else:
            user = MyUser.objects.get(mobile=mobile)
            user.set_password(passwd)
            user.save(update_fields=["password"])
            result['code'] = 0
        return JsonResponse(result)
    else:
        hashkey = CaptchaStore.generate_key()
        codimg_url = captcha_image_url(hashkey)
        return render(request,'registration/forgot_passwd.html',
                  {'hashkey':hashkey, 'codimg_url':codimg_url})
Пример #47
0
    def post(self, request):
        register_form = RegisterForm(request.POST)
        if register_form.is_valid():
            user_name = request.POST.get('email', '')

            if MyUser.objects.filter(email=user_name):
                return render(request, 'users/register.html',
                              {'register_form': register_form,
                               'msg': '用户已经存在'
                               })

            password = request.POST.get('password', '')
            user = MyUser()
            user.username = user_name
            user.email = user_name
            user.is_active = False
            user.password = make_password(password)
            user.save()

            send_register_email(user_name)

            messages.add_message(request, messages.SUCCESS, '注册成功!请在邮箱中点击激活链接激活账号!')
            return render(request, 'users/register.html', {})
        else:
            hashkey = CaptchaStore.generate_key()
            image_url = captcha_image_url(hashkey)
            return render(request, 'users/register.html', {
                'register_form': register_form,
                'hashkey': hashkey,
                'image_url': image_url})
Пример #48
0
    def post(self, request):
        result = {}
        (check_sign_result, check_code, check_msg) = check_sign(request)
        if not check_sign_result:
            result['code'] = check_code
            result['msg'] = check_msg
            return Response(result)
        try:
            mobile = request.POST.get('mobile', '')
            if not local_mobile_phone_validator(mobile):
                msg = u'手机号码不合法。'
                result['code'] = 234
                result['msg'] = msg
                return Response(result)
            else:
                try:
                    userprofile = UserProfile.objects.get(mobile_phone=mobile)
                    current_key = CaptchaStore.generate_key()
                    image_url = captcha_image_url(current_key)
                    http_host = request.get_host()
                    img = ''.join(['http://', http_host, image_url])
                    current_store = CaptchaStore.objects.get(hashkey=current_key)
                    img_value = current_store.challenge

                    result['code'] = 199
                    result['msg'] = u'获取图片验证码成功'
                    result['img'] = img
                    result['imgvalue'] = img_value
                except UserProfile.DoesNotExist:
                    result['code'] = 240
                    result['msg'] = u'不存在使用这个手机号的用户'
            return Response(result)
        except Exception, e:
            traceback.print_exc()
            return Response({'msg': u'获取图片验证码失败', 'code': 238})
Пример #49
0
def view_captcha(request):

    to_json_response = dict()
    to_json_response['status'] = 1

    to_json_response['new_cptch_key'] = CaptchaStore.generate_key()
    to_json_response['new_cptch_image'] = captcha_image_url(to_json_response['new_cptch_key'])

    # save a persistent copy of the captcha key for later verification (at function "reset")
    response = CaptchaStore.objects.get(hashkey=to_json_response['new_cptch_key']).response.upper()
    request.session['captcha_rk'] = response

    logger.debug("Captcha key {}".format(to_json_response['new_cptch_key']))
    logger.debug("Captcha image url {}".format(to_json_response['new_cptch_image']))

    # download captcha file and convert it to base64 string
    domain = request.get_host()
    address = "http://" + domain + to_json_response['new_cptch_image']
    file = requests.get(address, stream=True)
    capt = base64.b64encode(file.raw.data).decode('utf-8')

    c_response = dict()
    c_response['status'] = 1
    c_response['imageBase64'] = capt

    logger.debug(c_response)
    HttpResponse.status_code = 200
    return HttpResponse(json.dumps(c_response), content_type='application/json')
Пример #50
0
    def post(self, request):
        # 获取邮箱和密码,并校验
        register_form = RegisterForm(request.POST)
        if register_form.is_valid():
            # 获取邮箱
            user_name = request.POST.get('email', '')
            # 根据user_name查询数据库
            if Myuser.objects.filter(email=user_name):
                # 可以查询到用户
                return render(request, 'users/register.html', {
                    'register_form': register_form,
                    'msg': '用户已经存在'
                })
            # 完善用户信息
            password = request.POST.get('password', '')
            user_profile = Myuser()
            user_profile.username = user_name
            user_profile.email = user_name
            user_profile.is_active = False
            user_profile.password = make_password(password)
            user_profile.save()

            # 发送邮件
            send_register_email(user_name)
            messages.add_message(request, messages.SUCCESS, '注册成功!请在邮箱中点击激活链接激活账号!')
            return render(request, 'users/register.html', {})
        else:
            hashkey = CaptchaStore.generate_key()
            image_url = captcha_image_url(hashkey)
            return render(request, 'users/register.html', {
                'register_form': register_form,
                'hashkey': hashkey,
                'image_url': image_url})
Пример #51
0
def register(request):
    data = {}
    if request.user.is_authenticated:
        return redirect("vuser_account")
    if request.method == 'POST':
        form = RegisterForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            sex = form.cleaned_data.get('sex')
            name = form.cleaned_data.get('name')
            user = User.objects.create_user(username=username,
                                            password=password)
            user.save()
            UserProfile.objects.create(user=user,
                                       phone=user.username,
                                       sex=sex,
                                       name=name,
                                       father=form.get_father_user())
            auth.login(request, user)
            return redirect("vuser_account")
        else:
            error = form.errors.get("__all__")
            data.update({"error": error, "errors": form.errors})
    hashkey = CaptchaStore.generate_key()
    img_url = captcha_image_url(hashkey)
    data.update({"img_url": img_url, "hashkey": hashkey})
    return render(request, "kk/register.html", data)
Пример #52
0
def resend_activation_link(request):
    if Site._meta.installed:
        site = Site.objects.get_current()
    else:
        site = RequestSite(request)

    if request.method == 'POST' and request.is_ajax():
        captcha_key = CaptchaStore.generate_key()
        captcha_image = captcha_image_url(captcha_key)
        form = ResendActivationEmailForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data["email"]
            users = get_user_model().objects.filter(email=email, is_active=False)
            if not users.count():
                form._errors["email"] = (_("Account for email address is not registered or already activated."),)
            else:
                for user in users:
                    for profile in RegistrationProfile.objects.filter(user=user):
                        if profile.activation_key_expired():
                            salt = hashlib.sha1(str(random.random())).hexdigest()[:5]
                            profile.activation_key = hashlib.sha1(salt + user.username).hexdigest()
                            profile.save()
                            user.date_joined = timezone.now()
                            user.save()
                        profile.send_activation_email(site)

                # messages.add_message(request, messages.INFO, _('Resend activation link done'))
                return ajaxResponse(False, response_header=_('Resend activation link done'), captcha_key=captcha_key,
                                    captcha_image=captcha_image)
        return ajaxResponse(True, form=form, captcha_key=captcha_key, captcha_image=captcha_image)

    form = ResendActivationEmailForm()
    return render(request, "registration/resend_activation_email_form.html", {"form": form})
Пример #53
0
 def get(self, request, sub=None, *args, **kwargs):
     if request.GET.get('newsn') == '1':
         csn = CaptchaStore.generate_key()
         cimageurl = captcha_image_url(csn)
         return HttpResponse(cimageurl)
     if sub == 'wrong':
         raise Http404
     if sub == 'stall':
         if not request.user.is_authenticated():
             return redirect("dashboard:register", sub='signupin')
         seller = request.user.seller_set.filter(pmo=self.pmo)
         if seller.count() != 1:
             return redirect("dashboard:register", sub='signupin')
         seller = seller[0]
         if 'item_id' in request.GET:
             item_id = request.GET['item_id']
             item = Item.objects.filter(pk=item_id, pmo=self.pmo, seller=seller)
             if item.count() == 1:
                 return render(
                     request,
                     'dashboard/register/stall/itemform.html',
                     {
                         'item': item[0],
                         'images': self._get_images(item[0])
                     }
                 )
             else:
                 return HttpResponse("")
         if 'page' in request.GET:
             try:
                 page = int(request.GET['page'])
             except ValueError:
                 raise Http404
             items, page = self._get_items(seller, page)
             return render(request, 'dashboard/register/stall/itemtable.html', {
                 'items': items,
                 'page': page
             })
         is_stall = sub == 'stall'
         if seller.is_stall == is_stall:
             sub = 'stall'
             items, page = self._get_items(seller)
             kwargs.update({
                 'seller': seller,
                 'items': items,
                 'page': page,
             })
         else:
             kwargs.update({
                 'is_stall': is_stall,
                 'correct_url': reverse('dashboard:register', kwargs={'sub': 'consign' if is_stall else 'stall'})
             })
             sub = 'wrong'
     elif sub == 'signupin':
         kwargs.update({
             'login_form': LoginForm(),
             'error_message_login': self._err_dict.get(request.GET.get('validated', None), "")
         })
     return super().get(request, sub, *args, **kwargs)
Пример #54
0
def renew_captcha(request):
    if request.is_ajax():
        to_json_responce = {}
        to_json_responce['new_cptch_key'] = CaptchaStore.generate_key()
        to_json_responce['new_cptch_image'] = captcha_image_url(to_json_responce['new_cptch_key'])
        return HttpResponse(json.dumps(to_json_responce), content_type='application/json')
    else:
        raise PermissionDenied
Пример #55
0
def reload_captcha(request):
    form = CaptchaForm()
    print "==================check======================"
    to_json_response = dict()
    to_json_response['status'] = 1
    to_json_response['new_cptch_key'] = CaptchaStore.generate_key()
    to_json_response['new_cptch_image'] = captcha_image_url(to_json_response['new_cptch_key'])
    return HttpResponse(json.dumps(to_json_response), content_type='application/json')
Пример #56
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."
Пример #57
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.")
Пример #58
0
def captcha_refresh(request):
    to_json = {}
    if request.is_ajax():
        to_json['key'] = CaptchaStore.generate_key()
        to_json['image'] = captcha_image_url(to_json['key'])
        return HttpResponse(json.dumps(to_json), content_type='application/json')
    else:
        raise Http404
Пример #59
0
def register(request):
    hashkey = CaptchaStore.generate_key()  
    image_url = captcha_image_url(hashkey)
    if request.method == 'POST':
        form = RegisterForm(request.POST)       
        if form.is_valid():
            userBiz = UserBiz()
            error_dict = userBiz.userValidate(form)

            if error_dict:
                for errorName in error_dict.keys():
                    form.errors[errorName] = error_dict[errorName]
                hashkey = CaptchaStore.generate_key()  
                image_url = captcha_image_url(hashkey)
                return render_to_response("register.html",
                    {"form": form, "hashkey": hashkey, "image_url": image_url,},
                    context_instance = RequestContext(request)
                    )

            cd = form.cleaned_data
            username = cd['username']
            password = cd['password1']
            new_user = User.objects.create_user(
                    username=username,
                    password=password,
                    email=cd['email']
                    )

            userBiz.save(new_user)
            BBS_user.objects.create(user=new_user, )

            user = auth.authenticate(username=username, password=password)
            if user is not None and user.is_active:
                auth.login(request, user)
            return HttpResponseRedirect(reverse('home'))
        return render_to_response("register.html",
            {"form": form, "hashkey": hashkey, "image_url": image_url,},
            context_instance = RequestContext(request)
            )

    form = RegisterForm()
    return render_to_response("register.html",
        {"form": form, "hashkey": hashkey, "image_url": image_url,},
        context_instance = RequestContext(request)
        )
Пример #60
0
def captcha_refresh(request):
    response = HttpResponse()
    new_captcha_key = CaptchaStore.generate_key()
    new_captcha_image = captcha_image_url(new_captcha_key)
    new_captcha_hashkey = new_captcha_image.split('/')[3]
    result = json.dumps({'state':'1', 'new_captcha_image':new_captcha_image, \
                         'new_captcha_hashkey':new_captcha_hashkey})
    response.write(result)
    return response