Exemplo n.º 1
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")
Exemplo n.º 2
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=[]))
Exemplo n.º 3
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')
Exemplo n.º 4
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)
Exemplo n.º 5
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})
Exemplo n.º 6
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
        }
    )
Exemplo n.º 7
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))
Exemplo n.º 8
0
def refresh_captcha(request):
    """
    刷新验证码图片
    """
    new_key = CaptchaStore.generate_key()
    new_img = captcha_image_url(new_key)
    return HttpResponse(new_img)
Exemplo n.º 9
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)
Exemplo n.º 10
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})
Exemplo n.º 11
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})
Exemplo n.º 12
0
def generateCap():
    new_key = CaptchaStore.generate_key()
    cap = {
        'key': new_key,
        'image_url': captcha_image_url(new_key),
    }
    return cap
Exemplo n.º 13
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)
        )
Exemplo n.º 14
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)
Exemplo n.º 15
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
Exemplo n.º 16
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')
Exemplo n.º 17
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
Exemplo n.º 18
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)
        )
Exemplo n.º 19
0
def captcha_refresh(request):
	""" Return json with new captcha for ajax refresh request """
	
	new_key = CaptchaStore.generate_key()
	to_json_response = {
					'key': new_key,
					'image_url': captcha_image_url(new_key),
					}
	return HttpResponse(json.dumps(to_json_response), content_type='application/json')
Exemplo n.º 20
0
def captch_refresh(request):
    if request.is_ajax():
        to_json_responce = dict()
        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')
Exemplo n.º 21
0
Arquivo: views.py Projeto: cainlu/exjp
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
Exemplo n.º 22
0
def withdraw(request):
    if request.method == 'GET':
        hashkey = CaptchaStore.generate_key()
        codimg_url = captcha_image_url(hashkey)

        user = request.user
        card = user.user_bankcard.first()
        return render(request,'account/withdraw.html',
                  {'hashkey':hashkey, 'codimg_url':codimg_url, "card":card})
    elif request.method == 'POST':
        user = request.user
        result = {'code':-1, 'res_msg':''}
        withdraw_amount = request.POST.get("amount", None)
        varicode = request.POST.get('varicode', None)
        hashkey = request.POST.get('hashkey', None)
        if not (varicode and withdraw_amount and hashkey):
            result['code'] = 3
            result['res_msg'] = u'传入参数不足!'
            return JsonResponse(result)
        try:
            withdraw_amount = int(withdraw_amount)
        except ValueError:
            result['code'] = -1
            result['res_msg'] = u'参数不合法!'
            return JsonResponse(result)
        if withdraw_amount < 1000 or withdraw_amount > user.balance:
            result['code'] = -1
            result['res_msg'] = u'提现金额错误!'
            return JsonResponse(result)
        # if not user.zhifubao or not user.zhifubao_name:
        #     result['code'] = -1
        #     result['res_msg'] = u'请先绑定支付宝!'
        #     return JsonResponse(result)
        card = user.user_bankcard.first()
        if not card:
            result['code'] = -1
            result['res_msg'] = u'请先绑定银行卡!'
            return JsonResponse(result)

        ret = imageV(hashkey, varicode)
        if ret != 0:
            result['code'] = 2
            result['res_msg'] = u'图形验证码输入错误!'
            result.update(generateCap())
        else:
            translist = charge_money(user, '1', withdraw_amount, u'提现')
            if translist:
                event = UserEvent.objects.create(user=user, event_type='2', invest_account=card.card_number,
                            invest_amount=withdraw_amount, audit_state='1')
                translist.user_event = event
                translist.save(update_fields=['user_event'])
                result['code'] = 0
            else:
                result['code'] = -2
                result['res_msg'] = u'提现失败!'
        return JsonResponse(result)
Exemplo n.º 23
0
 def form_valid(self, form):
     form.save()
     if self.request.is_ajax():
         json_pkt = dict()
         json_pkt["status"] = 1
         json_pkt["new_cptch_key"] = CaptchaStore.generate_key()
         json_pkt["new_cptch_image"] = captcha_image_url(json_pkt["new_cptch_key"])
         return HttpResponse(json.dumps(json_pkt), content_type="application/json")
     else:
         return super(CommentCreateView, self).form_valid(form)
Exemplo n.º 24
0
    def form_valid(self, form):
        form.save()
        if self.request.is_ajax():
            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')
Exemplo n.º 25
0
    def get(self, request):
        """
        Get Captcha details
        B{URL:} ..api/v1/get_captcha/
        """
        response = dict()
        response["new_cptch_key"] = CaptchaStore.generate_key()
        response["new_cptch_image"] = captcha_image_url(response['new_cptch_key'])

        return Response(response)
Exemplo n.º 26
0
def refresh_captcha(request):
    kwargs = {'op_status': 'fail'}

    if request.is_ajax():
        new_key = CaptchaStore.generate_key()
        kwargs['op_status'] = 'success'
        kwargs['key'] = new_key
        kwargs['url'] = captcha_image_url(new_key)

    return json_response(kwargs)
Exemplo n.º 27
0
def captcha_refresh(request):
    """  Return json with new captcha for ajax refresh request """
    if request.is_ajax():
        to_json_responce = dict()

        new_key = CaptchaStore.generate_key()
        to_json_responce['key'] = new_key
        to_json_responce['image_url'] = captcha_image_url(new_key)

        return HttpResponse(json.dumps(to_json_responce), content_type='application/json')
    raise Http404
Exemplo n.º 28
0
def captcha_refresh(request):
    """  Return json with new captcha for ajax refresh request """
    if not request.is_ajax():
        raise Http404

    new_key = CaptchaStore.pick()
    to_json_response = {
        'key': new_key,
        'image_url': captcha_image_url(new_key),
    }
    return HttpResponse(json.dumps(to_json_response), content_type='application/json')
Exemplo n.º 29
0
def captchaview(request):
	if request.is_ajax():
		captchakey = CaptchaStore.generate_key()
		acptchaimg = captcha_image_url(captchakey)
		data = {
			"captchakey": captchakey,
			"acptchaimg": acptchaimg,
		}
		json_data = json.dumps(data)
		return HttpResponse(json_data, content_type='application/json')
	else:
		raise Http404
Exemplo n.º 30
0
def captcha_refresh(request):
    """  Return json with new captcha for ajax refresh request """
    if not request.is_ajax():
        raise Http404

    challenge, response = settings.get_challenge()()

    new_key = create(challenge, response)
    to_json_response = {
        'key': new_key,
        'image_url': captcha_image_url(new_key),
    }
    return HttpResponse(json.dumps(to_json_response), content_type='application/json')
Exemplo n.º 31
0
def challenge(obj):
    from captcha.helpers import captcha_image_url
    return format_html('<img src='+settings.URL + captcha_image_url(obj.hashkey)+'>')
Exemplo n.º 32
0
 def to_representation(self, value):
     result = super().to_representation(value)
     return captcha_image_url(result)
Exemplo n.º 33
0
def g_capture(request):
    if request.method == 'GET':
        cap = dict()
        cap['key'] = CaptchaStore.generate_key()
        cap['img'] = captcha_image_url(cap['key'])
        return JsonResponse(cap)
Exemplo n.º 34
0
def refresh_captcha(request):
    if request.GET.get('newsn') == '1':
        csn = CaptchaStore.generate_key()
        cimageurl = captcha_image_url(csn)
        return HttpResponse(cimageurl)
Exemplo n.º 35
0
 def get(self, 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'])
     return HttpResponse(json.dumps(to_json_response), content_type='application/json')
Exemplo n.º 36
0
def refresh(request):
    to_json_response = dict()
    to_json_response['status'] = 0
    to_json_response['key'] = CaptchaStore.generate_key()
    to_json_response['image_url'] = captcha_image_url(to_json_response['key'])
    return HttpResponse(json.dumps(to_json_response), content_type='application/json')
Exemplo n.º 37
0
def register(request):
    """加载用户注册页与执行"""
    hash_key = CaptchaStore.generate_key()
    image_url = captcha_image_url(hash_key)
    content = {'hash_key': hash_key, 'image_url': image_url}
    return render(request, 'userinfo/register.html', content)
Exemplo n.º 38
0
def password_reset(request):
    data = {}
    hashkey = CaptchaStore.generate_key()
    img_url = captcha_image_url(hashkey)
    data.update({"img_url": img_url, "hashkey": hashkey})
    return render(request, "lkl/password_reset.html", data)
Exemplo n.º 39
0
def add_captcha(ctx):
    hashkey = CaptchaStore.generate_key()
    imgage_url = captcha_image_url(hashkey)
    ctx['hashkey'] = hashkey
    ctx['imgage_url'] = imgage_url
    return ctx
Exemplo n.º 40
0
def set_fenrun(request, child):
    data = {}
    hashkey = CaptchaStore.generate_key()
    img_url = captcha_image_url(hashkey)
    data.update({"img_url": img_url, "hashkey": hashkey})
    user = request.user
    # 分润
    if hasattr(user, "userfenrun"):
        f_point = float(user.userfenrun.point)
        f_rmb = float(user.userfenrun.rmb)
        point_list = [
            x[0] for x in UserFenRun.POINT_CHOICE if float(x[0]) <= f_point
        ]
        rmb_list = [
            x[0] for x in UserFenRun.RMB_CHOICE if float(x[0]) <= f_rmb
        ]
        child_fenrun = {
            "point": json.dumps(point_list),
            "rmb": json.dumps(rmb_list)
        }
    else:
        point_list = []
        child_fenrun = {}
    data.update(child_fenrun)

    if request.method == 'POST':
        # 操作频繁
        key = 'lkl_setfenrun_locked_%s' % (user.id)
        locked = rclient.get(key)
        if locked:
            error = [u"操作太频繁"]
            data.update({"error": error})
            return render(request, "lkl/set_fenrun.html", data)
        else:
            rclient.set(key, True)
            rclient.expire(key, 10)
        # 数值判断
        point = request.POST.get("point")
        rmb = request.POST.get("rmb")
        if point not in point_list or rmb not in rmb_list:
            error = [u"分润点或者秒到点错误"]
            data.update({"error": error})
            return render(request, "lkl/set_fenrun.html", data)
        # 关系判断
        child_user = utils.get_user_by_username(child)
        children = [obj.phone for obj in request.user.children.all()]
        if not child_user or child not in children:
            error = [u"用户不存在或者不是您邀请来的"]
            data.update({"error": error})
            return render(request, "lkl/set_fenrun.html", data)
        # 分润提高判断
        if hasattr(child_user, "userfenrun"):
            old_point = float(child_user.userfenrun.point)
            old_rmb = float(child_user.userfenrun.rmb)
            if float(point) < float(old_point) or float(rmb) < float(old_rmb):
                error = [u"分润点和秒到点只允许提高"]
                data.update({"error": error})
                return render(request, "lkl/set_fenrun.html", data)
        # 判断是否已经有申请未审批,或者上次提交距离7天内
        sq = dbutils.get_last_fenren_order(user, child_user)
        if sq:
            if sq.status == "OK":
                now = datetime.now()
                diff = now - sq.create_time
                if diff.total_seconds() < 3600 * 24 * 30:
                    error = [u"30天内只能申请一次"]
                    data.update({"error": error})
                    return render(request, "lkl/set_fenrun.html", data)
            else:
                error = [u"该用户有未通过分润审核,请等待"]
                data.update({"error": error})
                return render(request, "lkl/set_fenrun.html", data)
        # 创建申请
        FenRunOrder.objects.create(user=user,
                                   child=child_user,
                                   point=point,
                                   rmb=rmb)
        return redirect("friend_list")
    return render(request, "lkl/set_fenrun.html", data)
Exemplo n.º 41
0
def tixian_child_rmb(request):
    data = {"order_type": "CHILD_RMB"}
    hashkey = CaptchaStore.generate_key()
    img_url = captcha_image_url(hashkey)
    data.update({"img_url": img_url, "hashkey": hashkey})
    user = request.user
    # 支付宝账户
    alipays = user.useralipay_set.values("account", "name")
    if alipays:
        alipay = alipays[0]
    else:
        alipay = None
    if alipay is None:
        return redirect("user_alipay")
    data["user_account"] = u"支付宝:%s__%s" % (alipay["account"], alipay["name"])

    if request.method == 'POST':
        # 禁止提现用户
        if user.username in config.DISABLE_TIXIN:
            error = [u"您是合伙人,不允许平台提现"]
            data.update({"error": error})
            return render(request, "lkl/tixian_child_rmb.html", data)
        # 操作频繁
        key = 'lkl_tixian_locked_%s' % (user.id)
        locked = rclient.get(key)
        if locked:
            error = [u"操作太频繁"]
            data.update({"error": error})
            return render(request, "lkl/tixian_child_rmb.html", data)
        else:
            rclient.set(key, True)
            rclient.expire(key, 10)
        # 未结算订单
        if not dbutils.can_tixian(user):
            error = [u"提现间隔大于1分钟且无提现中订单"]
            data.update({"error": error})
            return render(request, "lkl/tixian_child_rmb.html", data)
        # 正式流程
        data.update(request.POST.dict())
        form = TixianRMBForm(data)
        if form.is_valid():
            tx = form.save(commit=False)
            # 判断钱够不够
            _, my_rmb = dbutils.get_userrmb_num(user)
            if my_rmb < tx.rmb:
                error = [u"余额不足"]
                data.update({"error": error})
            else:
                tx.user = user
                tx.fee = int(tx.rmb * 0.1)
                tx.save()
                # 扣钱
                dbutils.sub_userrmb_rmb(user, tx.rmb, True)
                tx.pay_time = datetime.now()
                tx.status = "PD"
                tx.save()
                return redirect("user_info")
        else:
            error = form.errors.get("__all__")
            data.update({"error": error, "errors": form.errors})
    return render(request, "lkl/tixian_child_rmb.html", data)
Exemplo n.º 42
0
 def get(self, request):
     hashkey = CaptchaStore.generate_key()
     image_url = captcha_image_url(hashkey)
     forget_form = ForgetForm()
     return render(request, 'forget.html', locals())
Exemplo n.º 43
0
def captcha():
    # 验证码,第一次请求
    hashkey = CaptchaStore.generate_key()
    image_url = captcha_image_url(hashkey)
    captcha = {'hashkey': hashkey, 'image_url': image_url}
    return captcha
Exemplo n.º 44
0
def refresh_captcha(request):
    json_content = dict()
    json_content['new_cptch_key'] = CaptchaStore.generate_key()
    json_content['new_cptch_image'] = captcha_image_url(json_content['new_cptch_key'])
    return HttpResponse(json.dumps(json_content), content_type='application/json')
Exemplo n.º 45
0
def product(request):
    usr = sup_fn.get_user(request)
    lang = sup_fn.get_lang(request)
    action = request.META.get('PATH_INFO').split('/')[2]
    if action == 'apply':
        bor_list = BorrowRequest.objects.filter(usr_id=usr.id)
        bor_list = [
            bor for bor in bor_list if bor.status not in
            ['PAYBACK COMPLETED', 'REJECTED', 'CANCELLED']
        ]
        num_of_applied_prod = len(bor_list)

        # check which step
        if num_of_applied_prod != 0:
            return redirect('/borrow_now')

        prod_id = request.GET.get('prod_id')
        prod = Product.objects.get(id=prod_id)

        if request.method == 'POST':
            form = CaptchaForm(request.POST)
            if form.is_valid():
                # check hkid cannot repeat from other loan application
                simplified_hkid = request.POST.get('HKID').replace(
                    '(', '').replace(')', '').lower()
                other_bor_list = BorrowRequest.objects.filter(
                    (~Q(usr_id=usr.id)) & Q(simplified_hkid=simplified_hkid))
                if len(other_bor_list) != 0:
                    return redirect(
                        '/ack_page/?action=apply_loan_rejected&reason=repeated_hkid'
                    )

                # check hkid should be consistent with the one on he's lender account
                try:
                    ldr_usr = User.objects.get(email=usr.email, type='L')
                except ObjectDoesNotExist:
                    ''
                else:
                    ldr_details = json.loads(ldr_usr.detail_info)
                    ldr_simplified_hkid = ldr_details['Individual'][
                        'HKID'].replace('(', '').replace(')', '').lower()
                    if simplified_hkid != ldr_simplified_hkid:
                        return redirect(
                            '/ack_page/?action=apply_loan_rejected&reason=hkid_not_matched'
                        )

                # check social score
                fs = classes.FriendlyScore()
                fs.getToken()
                code, fs_usr_details = fs.get(
                    endpoint='users/partner-id/%s/show' % (usr.id), params={})

                social_total_score = 0
                social_fraud_risk_score = 0
                if code == 200:
                    social_total_score = float(fs_usr_details['score_points'])
                    social_fraud_risk_score = float(
                        fs_usr_details['risk_score'])

                prod_id = int(
                    request.META.get('HTTP_REFERER').split('/?prod_id=')[-1])
                prod = Product.objects.get(id=prod_id)

                inputs = {
                    'major':
                    request.POST.get('Subject'),
                    'resident':
                    request.POST.get('Living Status'),
                    'living_with':
                    request.POST.get('Living with'),
                    'university':
                    request.POST.get('Studying University'),
                    'GPA':
                    float(request.POST.get('Overall GPA')),
                    'date_of_birth':
                    request.POST.get('Date of Birth'),
                    'year':
                    request.POST.get('Currently Studying'),
                    'social_total_score':
                    '>400' if social_total_score > 400 else '0-400',
                    'social_fraud_risk_score':
                    '>1' if social_fraud_risk_score > 1 else '0-1',
                    'repayment_plan':
                    prod.repayment_plan,
                }

                result = sup_fn.calculate_loan_amount(inputs)

                discount_rate = 0
                if code == 200:
                    if float(fs_usr_details['score_points']) > 431:
                        discount_rate = 0.1

                ref_num = sup_fn.generate_ref_num('borrow_request', 'LOA')
                amount = min(result['amount'],
                             float(request.POST.get('Applied Amount')))

                if prod.repayment_plan == 'Instalment':
                    rate_per_month = prod.APR_borrower * (
                        1 - discount_rate) * 0.01 / 12
                    instalment_borrower = amount * (
                        rate_per_month /
                        (1 -
                         (1 + rate_per_month)**(-12 *
                                                (prod.repayment_period / 12))))
                    rate_per_month = prod.APR_lender * 0.01 / 12
                    instalment_lender = amount * (
                        rate_per_month /
                        (1 -
                         (1 + rate_per_month)**(-12 *
                                                (prod.repayment_period / 12))))
                elif prod.repayment_plan == 'Balloon Payment' or prod.repayment_plan == 'Promotion Balloon Payment':
                    rate_per_month = prod.APR_borrower * (
                        1 - discount_rate) * 0.01 / 12
                    instalment_borrower = amount * rate_per_month
                    rate_per_month = prod.APR_lender * 0.01 / 12
                    instalment_lender = amount * rate_per_month

                bor_detail_info = OrderedDict()
                for name, value in request.POST.iteritems():
                    if len(name) != 0:
                        if str(name)[0].isupper() and value != '':
                            bor_detail_info[name] = value

                approval_records = {
                    1: {
                        'approval_amount': amount,
                        'APR': prod.APR_borrower * (1 - discount_rate),
                        'tenor': prod.repayment_period,
                    }
                }
                bor_detail_info['Approval Records'] = approval_records

                # if year 1 hasn't GPA
                if request.POST.get('No GPA') == 'on':
                    bor_detail_info['Overall GPA'] = 2

                if result['status'] == 'REJECT':
                    status = 'REJECTED'
                else:
                    status = 'AUTO APPROVED'
                new_bor = BorrowRequest(
                    amount=amount,
                    prod_id=prod_id,
                    usr_id=usr.id,
                    ref_num=ref_num,
                    repaid_month=0,
                    instalment_lender=instalment_lender,
                    instalment_borrower=instalment_borrower,
                    simplified_hkid=simplified_hkid,
                    detail_info=json.dumps(bor_detail_info),
                    discount_rate=discount_rate,
                    status=status,
                    create_timestamp=timezone.localtime(timezone.now()),
                    update_timestamp=timezone.localtime(timezone.now()))
                new_bor.save()

                # update aut
                inputs = {
                    'usr_id':
                    usr.id,
                    'description':
                    'Submitted "%s" application, apply amount $%s' %
                    (prod.name_en, request.POST.get('Applied Amount')),
                    'ref_id':
                    new_bor.id,
                    'model':
                    'BorrowRequest',
                    'by':
                    'Borrower: ' + usr.email,
                    'datetime':
                    timezone.localtime(timezone.now()),
                    'action':
                    'create',
                    'type':
                    'Application',
                    'status':
                    'UNREAD',
                }
                sup_fn.update_aut(inputs)

                inputs = {
                    'usr_id':
                    usr.id,
                    'description':
                    'Auto approved $%s, tenor %s, interest rate %s%s' %
                    (amount, prod.repayment_period, prod.APR_borrower *
                     (1 - discount_rate), '%'),
                    'ref_id':
                    new_bor.id,
                    'model':
                    'BorrowRequest',
                    'by':
                    'Borrower: ' + usr.email,
                    'datetime':
                    timezone.localtime(timezone.now()),
                    'details': {
                        'usr_ip': request.META.get('REMOTE_ADDR')
                    },
                    'action':
                    'create',
                    'type':
                    'Application',
                    'status':
                    'UNREAD',
                }
                sup_fn.update_aut(inputs)
                sup_fn.update_ptn(inputs)

                # sync to usr
                sync_list = [
                    'Home Phone No.', 'Surname', 'Given Name',
                    'Account Number', 'Mobile', 'Gender',
                    'Residential Address', 'Bank Code', 'Living Status',
                    'Living with', 'Date of Birth', 'HKID',
                    'Studying University', 'Subject'
                ]
                sync_dict = {}
                for name in sync_list:
                    try:
                        sync_dict[name] = bor_detail_info[name]
                    except KeyError:
                        continue
                sup_fn.sync_to_usr(usr_id=usr.id, dict=sync_dict)

                if result['status'] == 'REJECT':
                    return redirect('/ack_page/?action=apply_loan_rejected')
                return redirect('/product/upload_docs/?prod_id=' +
                                str(prod_id))
            # if form is not valid
            hashkey = CaptchaStore.generate_key()
            image_url = captcha_image_url(hashkey)

            usr_details = {}
            for k, v in request.POST.iteritems():
                usr_details[k] = v
        else:
            # Captcha
            form = ''
            hashkey = CaptchaStore.generate_key()
            image_url = captcha_image_url(hashkey)
            usr_details = sup_fn.sync_from_usr(usr.id)

        #if lang == 'en':
        content = {
            'lang':
            lang,
            'cate':
            'borrow_now',
            'title':
            prod.name_en + ' - Application Form',
            'form_action':
            '?prod_id=' + str(prod_id),
            'prod':
            prod,
            'usr_id':
            usr.id,
            'usr_details':
            usr_details,
            #'applied_amount_list': ['5000', '10000', '15000', '20000', '25000', '30000', '35000', '40000'],
            'applied_amount_list':
            OrderedDict((
                ('5000', FLOAT_DATA_FORMAT.format(5000)),
                ('10000', FLOAT_DATA_FORMAT.format(10000)),
                ('15000', FLOAT_DATA_FORMAT.format(15000)),
                ('20000', FLOAT_DATA_FORMAT.format(20000)),
                ('25000', FLOAT_DATA_FORMAT.format(25000)),
                ('30000', FLOAT_DATA_FORMAT.format(30000)),
                ('35000', FLOAT_DATA_FORMAT.format(35000)),
                ('40000', FLOAT_DATA_FORMAT.format(40000)),
            )),
            'loan_purpose_list':
            OrderedDict(
                (('Tuition', 'Tuition'), ('Investment',
                                          'Investment'), ('Travel', 'Travel'),
                 ('Debt payment', 'Debt payment'), ('Others', 'Others'))),
            'gender_list':
            OrderedDict((('Male', 'Male'), ('Female', 'Female'))),
            'living_status_list':
            OrderedDict(
                (('Public Housing', 'Public Housing'),
                 ('Owned by Family', 'Owned by Family'), ('Rent', 'Rent'),
                 ('Quarter', 'Quarter'), ('Student Hall of Residence',
                                          'Student Hall of Residence'))),
            'living_with_list':
            OrderedDict((('Parents', 'Parents'), ('Relatives', 'Relatives'),
                         ('Friends or Classmates',
                          'Friends or Classmates'), ('Others', 'Others'))),
            'university_list':
            OrderedDict(
                (('The University of Hong Kong',
                  'The University of Hong Kong'),
                 ('The Chinese University of Hong Kong',
                  'The Chinese University of Hong Kong'),
                 ('The Hong Kong University of Science and Technology',
                  'The Hong Kong University of Science and Technology'),
                 ('The Hong Kong Polytechnic University',
                  'The Hong Kong Polytechnic University'),
                 ('City University of Hong Kong',
                  'City University of Hong Kong'),
                 ('Hong Kong Baptist University',
                  'Hong Kong Baptist University'),
                 ('The Hong Kong Institute of Education',
                  'The Hong Kong Institute of Education'),
                 ('Lingnan University', 'Lingnan University'),
                 ('The Open University of Hong Kong',
                  'The Open University of Hong Kong'))),
            'study_year_list': ['Year 1', 'Year 2', 'Year 3', 'Year 4'],
            'subject_list':
            OrderedDict(
                (('Medical/Health', 'Medical/Health'), ('Law', 'Law'),
                 ('Accounting',
                  'Accounting'), ('Construction and Environment',
                                  'Construction and Environment'),
                 ('Engineering', 'Engineering'), ('Design', 'Design'),
                 ('Business/Finance/Economic', 'Business/Finance/Economic'),
                 ('Education and Language', 'Education and Language'),
                 ('Information Technology/Computing',
                  'Information Technology/Computing'), ('Social Sciences',
                                                        'Social Sciences'),
                 ('Hotel and Tourism', 'Hotel and Tourism'), ('Others',
                                                              'Others'))),
            'form':
            form,
            'hashkey':
            hashkey,
            'image_url':
            image_url,
        }

        # if prod is promotion, only allow to apply $10000
        if prod.repayment_plan == 'Promotion Balloon Payment':
            content['applied_amount_list'] = OrderedDict(
                (('10000', FLOAT_DATA_FORMAT.format(10000)), ))
        if lang == 'zh':
            additional_content = {
                #'cate': 'borrow_now',
                'title':
                prod.name_zh.encode("utf8") + ' - 申請表',
                #'form_action': '?prod_id='+str(prod_id),
                #'prod': prod,
                #'usr_id': usr.id,
                #'usr_details': usr_details,
                #'applied_amount_list': ['5000', '10000', '15000', '20000', '25000', '30000', '35000', '40000'],
                'loan_purpose_list':
                OrderedDict(
                    (('Tuition', '學費'), ('Investment', '投資'), ('Travel', '旅遊'),
                     ('Debt payment', '還款'), ('Others', '其他'))),
                'gender_list':
                OrderedDict((('Male', '男性'), ('Female', '女性'))),
                'living_status_list':
                OrderedDict(
                    (('Public Housing', '公共房屋'), ('Owned by Family', '私人住宅'),
                     ('Rent', '租住'), ('Quarter', '宿舍'),
                     ('Student Hall of Residence', '學生宿舍'))),
                'living_with_list':
                OrderedDict(
                    (('Parents', '父母'), ('Relatives', '親戚'),
                     ('Friends or Classmates', '朋友/同學'), ('Others', '其他'))),
                'university_list':
                OrderedDict(
                    (('The University of Hong Kong', '香港大學'),
                     ('The Chinese University of Hong Kong', '香港中文大學'),
                     ('The Hong Kong University of Science and Technology',
                      '香港科技大學'), ('The Hong Kong Polytechnic University',
                                  '香港理工大學'), ('City University of Hong Kong',
                                              '香港城市大學'),
                     ('Hong Kong Baptist University',
                      '香港浸會大學'), ('The Hong Kong Institute of Education',
                                  '香港教育大學'), ('Lingnan University', '嶺南大學'),
                     ('The Open University of Hong Kong', '香港公開大學'))),
                'study_year_list': ['Year 1', 'Year 2', 'Year 3', 'Year 4'],
                'subject_list':
                OrderedDict(
                    (('Medical/Health', '醫療/健康'), ('Law', '法律'),
                     ('Accounting', '會計'), ('Construction and Environment',
                                            '建築及環境'), ('Engineering', '工程'),
                     ('Design', '設計'), ('Business/Finance/Economic',
                                        '商業/財務/經濟'), ('Education and Language',
                                                      '教育及語言'),
                     ('Information Technology/Computing',
                      '資訊科技/電子計算'), ('Social Sciences', '社會科學'),
                     ('Hotel and Tourism', '酒店及旅遊'), ('Others', '其他'))),
                #'form': form,
                #'hashkey': hashkey,
                #'image_url': image_url,
            }
            content.update(additional_content)

        return render(request, 'peerloan/borrower/loan_application_form.html',
                      content)
    if action == 'upload_docs':
        prod_id = request.GET.get('prod_id')
        prod = Product.objects.get(id=prod_id)
        bor = BorrowRequest.objects.filter(
            usr_id=usr.id, prod_id=prod_id,
            status="AUTO APPROVED").latest('update_timestamp')

        # get repayment table
        inputs = {
            'date_type': 'month only',
            'start_balance': bor.amount,
            'rate_per_month': bor.getBorAPR(prod.APR_borrower) * 0.01 / 12,
            'instalment': bor.instalment_borrower,
            'repayment_plan': prod.repayment_plan,
            'repayment_period': prod.repayment_period,
        }

        repayment_table = sup_fn.generate_repayment_schedule(inputs)

        bank_code_list = {}
        f = open(
            '/home/ubuntu/project_peerloan/peerloan/peerloan_src/bank_code_list.csv',
            'r')
        for row in csv.DictReader(f):
            bank_code_list[str(
                row['Bank_Code']).zfill(3)] = row['Bank_Name_in_English']
        f.close()
        bank_code_list = OrderedDict(
            sorted(bank_code_list.items(), key=lambda kv: kv[1]))

        content = {
            'lang':
            lang,
            'cate':
            'borrow_now',
            'title':
            prod.name_en + ' - Upload Supporting Documents',
            'form_action':
            '/ack/',
            'prod':
            prod,
            'usr_details':
            sup_fn.sync_from_usr(usr.id),
            'bor':
            bor,
            'bor_amount':
            FLOAT_DATA_FORMAT.format(bor.amount),
            'APR':
            FLOAT_DATA_FORMAT.format(
                bor.getBorAPR(prod.APR_borrower if prod.fake_APR_borrower ==
                              None else prod.fake_APR_borrower)),
            'monthly_repayment_amount':
            FLOAT_DATA_FORMAT.format(bor.instalment_borrower),
            'repayment_table':
            repayment_table,
            'bank_code_list':
            bank_code_list,
        }
        if lang == 'zh':
            content['title'] = prod.name_zh.encode("utf8") + ' - 上載申請文件'
        return render(request, 'peerloan/borrower/loan_upload_docs_form.html',
                      content)
    if action == 'confirm_agreement':
        prod_id = request.GET.get('prod_id')
        prod = Product.objects.get(id=prod_id)
        bor = BorrowRequest.objects.filter(
            prod_id=prod_id, usr_id=usr.id,
            status='DOC UPLOADED').latest('update_timestamp')
        details = json.loads(bor.detail_info)

        if prod.repayment_plan == 'Promotion Balloon Payment':
            start_month = 4
        else:
            start_month = 1

        end_month = prod.repayment_period
        start_date = sup_fn.check_future_date_exists(timezone.localtime(
            timezone.now()),
                                                     months=start_month)
        end_date = sup_fn.check_future_date_exists(timezone.localtime(
            timezone.now()),
                                                   months=end_month)

        if prod.repayment_plan == 'Instalment':
            last_instalment_amount = round(bor.instalment_borrower, 2)
        elif prod.repayment_plan == 'Balloon Payment' or prod.repayment_plan == 'Promotion Balloon Payment':
            last_instalment_amount = round(
                bor.instalment_borrower + bor.amount, 2)

        info = {
            'loan_agreement_date':
            datetime.strftime(bor.create_timestamp, '%d/%m/%Y'),
            'loan_drawdown_date':
            datetime.strftime(timezone.localtime(timezone.now()), '%d/%m/%Y'),
            'lender':
            'P L Technology Limited',
            'lender_licence_no':
            '0741/2016',
            'address':
            'Unit 1306, Lucky Centre, 165-171 Wanchai Road, Wanchai',
            'borrower':
            '%s %s' % (details['Surname'], details['Given Name']),
            'HKID':
            details['HKID'],
            'residential_address':
            details['Residential Address'],
            'loan_principal_amount':
            FLOAT_DATA_FORMAT.format(bor.amount),
            'interest_rate':
            FLOAT_DATA_FORMAT.format(
                bor.getBorAPR(prod.APR_borrower if prod.fake_APR_borrower ==
                              None else prod.fake_APR_borrower)),
            'instalment_amount':
            FLOAT_DATA_FORMAT.format(bor.instalment_borrower),
            'due_date':
            str(timezone.localtime(timezone.now()).day) +
            sup_fn.date_postfix(timezone.localtime(timezone.now()).day) +
            ' day of each calendar',
            'first_instalment':
            start_date.strftime('%Y/%m/%d'),
            'first_instalment_amount':
            FLOAT_DATA_FORMAT.format(bor.instalment_borrower),
            'last_instalment':
            end_date.strftime('%Y/%m/%d'),
            'last_instalment_amount':
            FLOAT_DATA_FORMAT.format(last_instalment_amount),
            'bank_name':
            details['Bank Code'] + ' ' +
            sup_fn.bank_code_name_converter(details['Bank Code']),
            'account_number':
            details['Account Number'],
            'account_holder':
            '%s %s' % (details['Surname'], details['Given Name']),
            'mobile':
            details['Mobile'],
        }
        if lang == 'zh':
            info['due_date'] = '每月的第' + str(
                timezone.localtime(timezone.now()).day).encode("utf8") + '天'

        content = {
            'lang': lang,
            'cate': 'borrow_now',
            'title': 'Key Terms of Personal Loan Agreement',
            'form_action': '/ack/',
            'info': info,
            'bor_id': bor.id,
            'bor_ref_num': bor.ref_num
        }
        if lang == 'zh':
            content['title'] = '私人貸款協議之主要條款'

        error = request.GET.get('error')
        if lang == 'en':
            if error == 'invalid_OTP':
                content['error_msg'] = 'Please input a valid OTP'
            if error == 'OTP_not_matched':
                content[
                    'error_msg'] = 'The OTP doesn\'t match to our record, please receive a new OTP and try again'
            if error == 'OTP_expired':
                content[
                    'error_msg'] = 'The OTP is expired, please receive a new OTP first'
        elif lang == 'zh':
            if error == 'invalid_OTP':
                content['error_msg'] = '請輸入一個有效的OTP'
            if error == 'OTP_not_matched':
                content['error_msg'] = '你輸入的OTP與我們的記錄不符合,請重新操作'
            if error == 'OTP_expired':
                content['error_msg'] = '你的OTP已經逾期,請重新獲取OTP'

        return render(request, 'peerloan/borrower/loan_agreement_form.html',
                      content)
    if action == 'confirm_memorandum':
        prod_id = request.GET.get('prod_id')
        prod = Product.objects.get(id=prod_id)
        bor = BorrowRequest.objects.filter(
            prod_id=prod_id, usr_id=usr.id,
            status='FUND MATCHING COMPLETED').latest('update_timestamp')
        if request.method == 'POST':
            form = CaptchaForm(request.POST)
            if form.is_valid():
                draw_down_date = sup_fn.find_earliest_business_day(
                    date=timezone.localtime(timezone.now()), cut_off=16)
                details = json.loads(bor.detail_info)
                details['Confirm Memorandum Date'] = datetime.strftime(
                    draw_down_date, '%Y/%m/%d %H:%M:%S')
                details['Memorandum Captcha'] = str(
                    request.POST.get('captcha_1'))
                bor.detail_info = json.dumps(details)
                bor.status = 'MEMORANDUM CONFIRMED'
                bor.update_timestamp = timezone.localtime(timezone.now())
                bor.save()

                # update aut
                inputs = {
                    'usr_id':
                    usr.id,
                    'description':
                    'Confirmed memorandum with Captcha%s' %
                    (request.POST.get('captcha_1')),
                    'ref_id':
                    bor.id,
                    'model':
                    'BorrowRequest',
                    'by':
                    'Borrower: ' + usr.email,
                    'datetime':
                    timezone.localtime(timezone.now()),
                    'action':
                    'modify',
                    'type':
                    'Disburse',
                    'status':
                    'UNREAD',
                }
                sup_fn.update_aut(inputs)
                sup_fn.update_ptn(inputs)
                action = 'confirm_memorandum'

                return redirect('/ack_page/?action=' + action)

            hashkey = CaptchaStore.generate_key()
            image_url = captcha_image_url(hashkey)
        else:
            # Captcha
            form = ''
            hashkey = CaptchaStore.generate_key()
            image_url = captcha_image_url(hashkey)

        details = json.loads(bor.detail_info)

        draw_down_date = sup_fn.find_earliest_business_day(
            date=timezone.localtime(timezone.now()), cut_off=16)

        if prod.repayment_plan == 'Promotion Balloon Payment':
            start_month = 4
        else:
            start_month = 1

        end_month = prod.repayment_period
        start_date = sup_fn.check_future_date_exists(draw_down_date,
                                                     months=start_month)
        end_date = sup_fn.check_future_date_exists(draw_down_date,
                                                   months=end_month)

        if prod.repayment_plan == 'Instalment':
            last_instalment_amount = round(bor.instalment_borrower, 2)
        elif prod.repayment_plan == 'Balloon Payment' or prod.repayment_plan == 'Promotion Balloon Payment':
            last_instalment_amount = round(
                bor.instalment_borrower + bor.amount, 2)

        info = {
            'loan_agreement_date':
            datetime.strftime(bor.create_timestamp, '%d/%m/%Y'),
            'loan_drawdown_date':
            datetime.strftime(draw_down_date, '%d/%m/%Y'),
            'lender':
            'P L Technology Limited',
            'lender_licence_no':
            '0741/2016',
            'address':
            'Unit 1306, Lucky Centre, 165-171 Wanchai Road, Wanchai',
            'borrower':
            '%s %s' % (details['Surname'], details['Given Name']),
            'HKID':
            details['HKID'],
            'residential_address':
            details['Residential Address'],
            'loan_principal_amount':
            FLOAT_DATA_FORMAT.format(bor.amount),
            'interest_rate':
            FLOAT_DATA_FORMAT.format(
                bor.getBorAPR(prod.APR_borrower if prod.fake_APR_borrower ==
                              None else prod.fake_APR_borrower)),
            'instalment_amount':
            FLOAT_DATA_FORMAT.format(bor.instalment_borrower),
            'due_date':
            str(draw_down_date.day) + sup_fn.date_postfix(draw_down_date.day) +
            ' day of each calendar',
            'first_instalment':
            start_date.strftime('%Y/%m/%d'),
            'first_instalment_amount':
            FLOAT_DATA_FORMAT.format(bor.instalment_borrower),
            'last_instalment':
            end_date.strftime('%Y/%m/%d'),
            'last_instalment_amount':
            FLOAT_DATA_FORMAT.format(last_instalment_amount),
            'bank_name':
            details['Bank Code'] + ' ' +
            sup_fn.bank_code_name_converter(details['Bank Code']),
            'account_number':
            details['Account Number'],
            'account_holder':
            '%s %s' % (details['Surname'], details['Given Name']),
            'mobile':
            details['Mobile'],
        }
        if lang == 'zh':
            info['due_date'] = '每月的第' + str(
                draw_down_date.day).encode("utf8") + '天'

        content = {
            'lang': lang,
            'cate': 'borrow_now',
            'title': 'Memorandum of Agreement',
            'form_action': '?prod_id=' + str(prod_id),
            'info': info,
            'form': form,
            'hashkey': hashkey,
            'image_url': image_url,
        }
        if lang == 'zh':
            content['title'] = '協議備忘錄'
        return render(request, 'peerloan/borrower/loan_memorandum_form.html',
                      content)
    if action == 'invest':
        prod_id = request.GET.get('prod_id')
        prod = Product.objects.get(id=prod_id)
        acc = Account.objects.get(usr_id=usr.id)
        total_usable_amount = acc.balance
        try:
            inv = Investment.objects.get(usr_id=usr.id, prod_id=prod_id)
        except ObjectDoesNotExist:
            # set up new inv
            inv = {'total_amount': total_usable_amount, 'used_amount': 0}
            content = {
                'prod': prod,
                'total_usable_amount': total_usable_amount,
                'inv': inv,
                'sub_cate': prod_id,
                'used_percentage': 0,
                'lang': lang,
            }
            if lang == 'en':
                content[
                    'title'] = 'Setting Up Your Investment - ' + prod.name_en
                content[
                    'instruction'] = """The below investment settings define how you invest the money in this product. After 
				you filled up the below form, Peerloan will allocate your investment fund to the selected product automatically."""
            if lang == 'zh':
                content['title'] = '設置你的投資 - ' + prod.name_zh_hk
                content[
                    'instruction'] = """以下投資設置詳述你將如何投資該產品。在你完成以下表格之後,點點眾貸將會自動地分配你的投資資金到該產品。"""
        else:
            # change inv settings
            total_usable_amount += inv.usable_amount + inv.on_hold_amount

            try:
                used_percentage = round(
                    ((inv.on_hold_amount / prod.min_amount_per_loan) /
                     int(total_usable_amount / prod.min_amount_per_loan)) * 100
                    + 1, 1)
            except ZeroDivisionError:
                used_percentage = 0
            content = {
                'prod': prod,
                'total_usable_amount': total_usable_amount,
                'inv': inv,
                'used_percentage': used_percentage,
                'lang': lang,
            }
            if lang == 'en':
                content[
                    'title'] = 'Change Your Investment Setting - ' + prod.name_en
                content[
                    'instruction'] = """The below investment settings define how you invest the money in this product. After 
				you filled up the below form, Peerloan will allocate your investment fund to the selected product automatically."""
            if lang == 'zh':
                content['title'] = '更換你的投資設置 - ' + prod.name_zh_hk
                content[
                    'instruction'] = """以下投資設置詳述你將如何投資該產品。在你完成以下表格之後,點點眾貸將會自動地分配你的投資資金到該產品。"""
        return render(request, 'peerloan/lender/invest_form.html', content)
    if action == 'transfer':
        inv_list = Investment.objects.filter(usr_id=usr.id)
        rd_prod_list = []
        for inv in inv_list:
            prod = Product.objects.get(id=inv.prod_id)
            rd_prod_list.append({
                'prod_id': str(prod.id),
                'prod_name': str(prod.name_en),
                'usable_amount': str(inv.usable_amount)
            })
        content = {
            'prod_list': rd_prod_list,
        }
        if lang == 'en':
            content['title'] = 'Transfer Fund Between Products'
            content[
                'instruction'] = """Please specify the amount of fund you would like to switch from this portfolio to another portfolio. 
			The instruction will be executed immediately."""
        if lang == 'zh':
            content['title'] = '資金轉賬'
            content['instruction'] = """請說明你希望的轉賬金額及收賬的投資組合。該指示將會被立即執行。"""
        return render(request, 'peerloan/lender/transfer_form.html', content)
Exemplo n.º 46
0
 def get(self, request):
     hashkey = CaptchaStore.generate_key()
     imgage_url = captcha_image_url(hashkey)
     return render(request, "MCM_register.html", {"imgage_url": imgage_url, "hashkey": hashkey})
Exemplo n.º 47
0
 def get(self, request):
     hash_key = CaptchaStore.generate_key()
     image_url = captcha_image_url(hash_key)
     msg = ''
     login_form = LoginForm()
     return render(request, "login.html", locals())
Exemplo n.º 48
0
 def get(self, request):
     captcha_id = CaptchaStore.generate_key()
     return JsonResponse({
         'captcha_id':captcha_id,
         'image_src':captcha_image_url(captcha_id),
     })
Exemplo n.º 49
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 in {'stall', 'consign'}:
         if not request.user.is_authenticated:
             return redirect("pmo2015:register", sub='signupin')
         seller = request.user.seller_set.filter(pmo=self.pmo)
         if seller.count() != 1:
             return redirect("pmo2015: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,
                               'pmo2015/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, 'pmo2015/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('pmo2015:register',
                         kwargs={'sub': 'consign' if is_stall else 'stall'})
             })
             sub = 'wrong'
     elif sub == 'signupin':
         kwargs.update({
             'login_form':
             LoginForm(),
             'signup_form':
             SignupForm(),
             'error_message_login':
             self._err_dict.get(request.GET.get('validated', None), "")
         })
     elif sub == 'battle':
         kwargs.update({'form': BattleForm()})
     return super().get(request, sub, *args, **kwargs)
Exemplo n.º 50
0
def refresh_captcha(request):
    print(1000)
    hashkey = CaptchaStore.generate_key()
    image_url = captcha_image_url(hashkey)
    captcha = {'hashkey': hashkey, 'image_url': image_url}
    return HttpResponse(json.dumps(captcha), content_type='application/json')
Exemplo n.º 51
0
def captcha():
    hashkey = CaptchaStore.generate_key()
    image_url = captcha_image_url(hashkey)
    captcha_code = {"hashkey": hashkey, "image_url": image_url}
    return captcha_code
Exemplo n.º 52
0
 def post_ajax(self, request, *args, **kwargs):
     to_json_response = {}
     to_json_response['captcha_0'] = CaptchaStore.generate_key()
     to_json_response['captcha_img_url'] = captcha_image_url(
         to_json_response['captcha_0'])
     return self.render_json_response(to_json_response)
Exemplo n.º 53
0
def login(request):
    """加载用户登录"""
    hash_key = CaptchaStore.generate_key()
    image_url = captcha_image_url(hash_key)
    content = {'hash_key': hash_key, 'image_url': image_url}
    return render(request, 'userinfo/login.html', content)
Exemplo n.º 54
0
def captcha():
    hashkey = CaptchaStore.generate_key()  # 验证码答案
    image_url = captcha_image_url(hashkey)  # 验证码地址
    captcha = {'hashkey': hashkey, 'image_url': image_url}
    return captcha
Exemplo n.º 55
0
def index(request):
    #跳转页面时,初始化图文验证码表单项,传递到index页面
    hashkey = CaptchaStore.generate_key()
    image_url = captcha_image_url(hashkey)
    register_form = RegisterForm()
    return render(request, 'index.html',locals())
Exemplo n.º 56
0
 def get(self, request):
     hashkey = CaptchaStore.generate_key()
     image_url = captcha_image_url(hashkey)
     return JsonResponse({'hashkey': hashkey, 'image_url': image_url})
Exemplo n.º 57
0
    def get(self, request):

        hashkey = CaptchaStore.generate_key()
        image_url = captcha_image_url(hashkey)
        return render(request, 'register.html', {'form': RegisterForm(), 'hashkey': hashkey, 'image_url': image_url})
Exemplo n.º 58
0
def login(request,
          template_name='registration/login.html',
          redirect_field_name=REDIRECT_FIELD_NAME,
          authentication_form=AuthenticationForm,
          current_app=None,
          extra_context=None):
    if request.GET.get('newsn') == '1':
        csn = CaptchaStore.generate_key()
        cimageurl = captcha_image_url(csn)
        return HttpResponse(cimageurl)
    """
    Displays the login form and handles the login action.
    """
    redirect_to = request.REQUEST.get(redirect_field_name, '')

    human = False
    if request.method == "POST":
        form = CaptchaForm(request.POST)
        if form.is_valid():
            human = True

        if human:
            form = authentication_form(data=request.POST)
            if form.is_valid():
                netloc = urlparse.urlparse(redirect_to)[1]

                # Use default setting if redirect_to is empty
                if not redirect_to:
                    redirect_to = settings.LOGIN_REDIRECT_URL

                # Heavier security check -- don't allow redirection to a different
                # host.
                elif netloc and netloc != request.get_host():
                    redirect_to = settings.LOGIN_REDIRECT_URL

                # Okay, security checks complete. Log the user in.
                auth_login(request, form.get_user())

                if request.session.test_cookie_worked():
                    request.session.delete_test_cookie()

                return HttpResponseRedirect(redirect_to)
        else:
            form = authentication_form(request)
    else:
        form = authentication_form(request)

    request.session.set_test_cookie()

    current_site = get_current_site(request)

    captcha_form = CaptchaForm()

    context = {
        'form': form,
        'captcha_form': captcha_form,
        redirect_field_name: redirect_to,
        'site': current_site,
        'site_name': current_site.name,
    }
    if extra_context is not None:
        context.update(extra_context)
    return TemplateResponse(request,
                            template_name,
                            context,
                            current_app=current_app)
Exemplo n.º 59
0
 def get(self, request):
     hashkey = CaptchaStore.generate_key()  # 验证码答案
     image_url = captcha_image_url(hashkey)  # 验证码地址
     captcha = {'hashkey': hashkey, 'image_url': image_url}
     return render(request, "login.html", locals())
Exemplo n.º 60
0
def register(request):
    logger.debug("in register")
    error_message = ''

    if request.GET and 'refresh_captcha' in request.GET:
        form = Registration_Form()
        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'])

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

    if request.method == 'POST':
        form = Registration_Form(request.POST)
        form.clean()
        if form.is_valid():
            user = form.save(commit=False)
            logger.debug(user)
            try:
                user = VLAB_User.objects.get(email=user.email)
                error_message = 'User is already registered.'
            except VLAB_User.DoesNotExist:
                suffix = re.search("@[\w.]+", user.email)
                logger.debug( "$$$$$$$$$$$$$$$$$$$$"+suffix.group())
                try:
                    allowed_org = Allowed_Organization.objects.get(email_suffix=suffix.group()[1:])
                except Allowed_Organization.DoesNotExist:
                    error_message = 'User organization not registered with Vital!'
                    return render(request, 'vital/user_registration.html', {'form': form, 'error_message':error_message})
                user.sftp_account = user.email[:user.email.find('@')]
                user.sftp_pass = user.password  # workaround to set sftp account
                user.set_password(user.password)  # hashes the password
                activation_code = randint(100000, 999999)
                user.activation_code = activation_code

                #TODO temporary fix until sftp issue solved
                if set('[~!@#$%^&*()_+{}":;\']+$').intersection(user.sftp_pass):
                    error_message = 'Special characters cannot be used in password'
                    return render(request, 'vital/user_registration.html',
                                  {'form': form, 'error_message': error_message})

                logger.debug("Creating SFTP account")
                cmd = 'sudo /home/vital/vital2.0/source/virtual_lab/vital_site/scripts/sftp_account.sh create '+ \
                      user.sftp_account+' '+user.sftp_pass + ' > /home/vital/vital2.0/log/sftp.log'
                p = Popen(cmd.split(), stdout=PIPE, stderr=PIPE)
                out, err = p.communicate()
                if not p.returncode == 0:
                    raise Exception('ERROR : cannot register sftp account. \n Reason : %s' % err.rstrip())
                logger.debug("SFTP account created")

                user.save()

                logger.debug("user registered : "+ user.email)
                send_mail('Activation mail', 'Hi '+user.first_name+',\r\n\n Welcome to Vital. Please use activation '
                                             'code : '+str(activation_code)+' for activating your account.\r\n\nVital',
                          '*****@*****.**', [user.email], fail_silently=False)
                logger.debug("user activation email sent to "+ user.email)
                form = User_Activation_Form(initial={'user_email': user.email})
                return render(request, 'vital/user_registration_validate.html', {'message': 'User has been registered. '
                                                                                            + 'Please check your mail('
                                                                                            + user.email+') for ' +
                                                                                            'activation code',
                                                                                 'form': form})
    else:
        form = Registration_Form()
    return render(request, 'vital/user_registration.html', {'form': form, 'error_message':error_message})