Python+django實現郵箱驗證登入

lm_y發表於2017-09-15

使用者註冊:

類似於使用者登陸,同樣在users.views.py中新增RegisterView(View)類,其中對錶單的get和post作出處理。
如果是get方法,重新返回register頁面讓使用者進行填寫。

    def get(self, request):
        register_form = RegisterForm()
        return render(request, "register.html", {'register_form':register_form})
  • 1
  • 2
  • 3

method = POST時,使用者註冊邏輯:

    def post(self, request):
        # 例項化form,驗證每個欄位是否合法
        register_form = RegisterForm(request.POST)
        pre_check = register_form.is_valid()
        if pre_check:
            # 取出email和password
            user_name = request.POST.get("email", "")
            pass_word = request.POST.get("password", "")
            # 例項化使用者,然後賦值
            user_profile = UserProfile()
            user_profile.username = user_name
            user_profile.email = user_name
            # 新建使用者為非活躍使用者,可通過驗證變為活躍使用者
            user_profile.is_active = False
            # 將明文轉換為密文賦給password
            user_profile.password = make_password(pass_word)
            user_profile.save()  # 儲存到資料庫
            # 此處加入了郵箱驗證的手段
            send_register_email(user_name, "register")
            return render(request, "login.html")
        else:
            # form表單驗證失敗,將錯誤資訊傳給前端
            return render(request, "register.html", {"register_form": register_form})
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

在form.py中新增RegisterForm類對給出表單處理類:

class RegisterForm(forms.Form):
    # 不能為空
    email = forms.EmailField(required=True)
    password = forms.CharField(required=True, min_length=6, max_length=20)
    # 出錯資訊
    captcha = CaptchaField(error_messages={"invalid":u"驗證碼錯誤"})
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

以下為對應的前端程式碼,其中新增了了django的模版用法,均以{% %}的形式在html中加入邏輯, 避免了python程式碼的直接插入,方便維護和修改。

<form id="email_register_form" method="post" action="{% url 'register' %}" autocomplete="off">
                        <div class="form-group marb20 {% if register_form.errors.email %}errorput{% endif %}">
                            <label>郵&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;箱</label>
                            <input  type="text" id="id_email" name="email" value="{{ register_form.email.value }}" placeholder="請輸入您的郵箱地址" />
                        </div>
                        <div class="form-group marb8 {% if register_form.errors.password %}errorput{% endif %}">
                            <label>密&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;碼</label>
                            <input type="password" id="id_password" name="password"  value="{{ register_form.password.value }}" placeholder="請輸入6-20位非中文字元密碼" />
                        </div>
                        <div class="form-group marb8 captcha1 {% if register_form.errors.captcha %}errorput{% endif %}">
                            <label>驗&nbsp;證&nbsp;碼</label>
                            {{ register_form.captcha }}
                        </div>
                        <div class="error btns" id="jsEmailTips">{% for key,error in register_form.errors.items %}{{ error }}{% endfor %} {{ msg }}</div>
                        <div class="auto-box marb8">
                        </div>
                        <input class="btn btn-green" id="jsEmailRegBtn" type="submit" value="註冊並登入" />
                        {% csrf_token %}
                    </form>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

{% csrf_token %}是django為了在使用者提交表單時防止跨站攻擊所做的保護,在表單最後沒有加入的話,不能正常提交
表單中有一項為驗證碼,在django中可以使用django-simple-captcha模組實現:

  • url(r’^captcha/’, include(‘captcha.urls’)) 配置url
  • {{ register_form.captcha }} 配置前端

郵箱驗證:

在users.py中新增了郵箱驗證的model:

class EmailVerifyRecord(models.Model):
    # 驗證碼
    code = models.CharField(max_length=20, verbose_name=u"驗證碼")
    email = models.EmailField(max_length=50, verbose_name=u"郵箱")
    # 包含註冊驗證和找回驗證
    send_type = models.CharField(verbose_name=u"驗證碼型別", max_length=10, choices=(("register",u"註冊"), ("forget",u"找回密碼")))
    send_time = models.DateTimeField(verbose_name=u"傳送時間", default=datetime.now)
    class Meta:
        verbose_name = u"郵箱驗證碼"
        verbose_name_plural = verbose_name
    def __unicode__(self):
        return '{0}({1})'.format(self.code, self.email)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

在setting.py中新增配置郵箱資訊:

EMAIL_HOST = "smtp.163.com"   # 伺服器
EMAIL_PORT = 25               # 一般情況下都為25
EMAIL_HOST_USER = "abc@163.com"   # 賬號
EMAIL_HOST_PASSWORD = "password"  # 密碼
EMAIL_USE_TLS = False             # 一般都為False
EMAIL_FROM = "abc@163.com"        # 郵箱來自
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

建立utils包,新建email_send .py

from random import Random # 用於生成隨機碼 
from django.core.mail import send_mail # 傳送郵件模組
from users.models import EmailVerifyRecord # 郵箱驗證model
from MxOnline.settings import EMAIL_FROM  # setting.py新增的的配置資訊

# 生成隨機字串
def random_str(randomlength=8):
    str = ''
    chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789'
    length = len(chars) - 1
    random = Random()
    for i in range(randomlength):
        str+=chars[random.randint(0, length)]
    return str


def send_register_email(email, send_type="register"):
    email_record = EmailVerifyRecord()
    # 將給使用者發的資訊儲存在資料庫中
    code = random_str(16)
    email_record.code = code
    email_record.email = email
    email_record.send_type = send_type
    email_record.save()
    # 初始化為空
    email_title = ""
    email_body = ""
    # 如果為註冊型別
    if send_type == "register":
        email_title = "註冊啟用連結"
        email_body = "請點選下面的連結啟用你的賬號:http://127.0.0.1:8000/active/{0}".format(code)
        # 傳送郵件
        send_status = send_mail(email_title, email_body, EMAIL_FROM, [email])
        if send_status:
            pass
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35

然後將使用者變為活躍使用者,加入相關的view:

class ActiveUserView(View):
    def get(self, request, active_code):
    # 用code在資料庫中過濾處資訊
        all_records = EmailVerifyRecord.objects.filter(code=active_code)
        if all_records:
            for record in all_records:
                email = record.email
                # 通過郵箱查詢到對應的使用者
                user = UserProfile.objects.get(email=email)
                # 啟用使用者
                user.is_active = True
                user.save()
                        else:
            return render(request, "active_fail.html")
        return render(request, "login.html")
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

配置生成頁面的url:

url(r'^active/(?P<active_code>.*)/$', ActiveUserView.as_view(), name="user_active"),  # 提取出active後的所有字元賦給active_code
  • 1

至此,便可將is_active加入到登陸的限制當中:

                if user.is_active:
                    login(request, user)  # 呼叫login方法登陸賬號
                    return render(request, "index.html")
                else:
                    return render(request, "login.html", {"msg": u"使用者未啟用"})

相關文章