1. 程式人生 > >驗證碼與session的應用

驗證碼與session的應用

每個使用者獨一無二的驗證碼可以儲存在session裡,這樣提交到登入檢視函式,就會有一把鑰匙,儲存個人驗證碼,就可以在檢視函式裡進行驗證了.

獲取動態圖片

def get_valid_img(request):
    def get_random_color():
        return (random.randint(0,255),random.randint(0,255),random.randint(0,255))
    img=Image.new('RGB',(300,36),get_random_color())
    draw=ImageDraw.Draw(img)
    font=ImageFont.truetype('kumo.ttf',30)
    verificaton_code = ''
    for i in range(6):
        random_num=str(random.randint(0,9))
        random_upper_alp=chr(random.randint(65,90))
        random_lowwer_alp=chr(random.randint(97,122))
        number=random.choice([random_num,random_lowwer_alp,random_upper_alp])
        draw.text((i*30+50,0),number,get_random_color(),font)
        verificaton_code+=number
    print(verificaton_code)
    # 劃線
    width=300
    heigh=36
    for i in range(6):
        x1=random.randint(0,width)
        y1=random.randint(0,heigh)
        x2=random.randint(0,width)
        y2=random.randint(0,heigh)
        draw.line((x1,y1,x2,y2),get_random_color())
    for i in range(10):
        draw.point((random.randint(0,width),random.randint(0,heigh)),get_random_color())
        x=random.randint(0,width)
        y=random.randint(0,heigh)
        draw.arc((x,y,x+5,y+5),0,100,get_random_color())
    # 存在記憶體
    f = BytesIO()
    img.save(f, 'png')
    data = f.getvalue()
    # 把驗證碼存在各自的session
    request.session['verificaton_code']=verificaton_code
    return HttpResponse(data)

登入檢視函式

def login(request):
    if request.is_ajax():
        res={'user':None,'error_msg':None}
        name=request.POST.get('name')
        pwd=request.POST.get('pwd')
        validcode=request.POST.get('validcode')
        verification_code=request.session['verificaton_code']
        if validcode.upper()==verification_code.upper():
            obj=auth.authenticate(request,username=name,password=pwd)
            if obj:
                auth.login(request,obj)
                res['user']=name
            else:
                res['error_msg']='使用者名稱或密碼錯誤'
        else:
            res['error_msg']='驗證碼錯誤'
        return JsonResponse(res)
    else:
        return render(request,'login.html')

login頁面和ajax

<body>
<div class="container" style="margin-top: 60px">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            {% csrf_token %}
            <div class="form-group">
                <label for="name">使用者名稱</label>
                <input class="form-control" type="text" name="name" id="name">
            </div>
            <div class="form-group">
                <label for="pwd">密碼</label>
                <input class="form-control" type="password" name="pwd" id="pwd">
            </div>
            <div class="form-group">
                <label for="">驗證碼</label>
                <div class="row">
                    <div class="col-md-6">
                        <input type="text" class="form-control" id="validcode">
                    </div>
                    <div class="col-md-6">
                        <img width="350" height="36" src="/get_valid_img/" alt="" id="img">
                    </div>
                </div>
            </div>
            <span id="msg"></span>
            <button class="btn btn-success pull-right" id="log_btn">登入</button>
        </div>
    </div>
</div>
</body>
<script>
    $(function () {
        $('#img').click(function () {
            this.src+='?';
        });
        $('#log_btn').click(function () {
            $.ajax({
                url:'',
                type:'post',
                data:{
                    name:$('#name').val(),
                    pwd:$('#pwd').val(),
                    validcode:$('#validcode').val(),
                    csrfmiddlewaretoken:$('[name="csrfmiddlewaretoken"]').val()
                },
                success:function (res) {
                    if(res.user){
                        location.href='/index/'
                    }else{
                        $('#msg').html('');
                        $('#msg').html(res.error_msg);
                    }
                }
            })
        })
    })
</script>