Django自定義登陸驗證后台


支持郵箱/手機號/昵稱登錄,在django1.6.2測試成功。
1、models

# -*- encoding: utf-8 -*-
from django.db import models
from django.contrib.auth.models import AbstractUser

from common.thumbs import ImageWithThumbsField

class User(AbstractUser):
    avatar = ImageWithThumbsField('頭像', max_length=200, blank=True, null=True, upload_to='avatar/%Y/%m/%d/%H/%M%S', sizes=((30, 30), (50, 50), (100, 100), (180, 180), ))
    mobile = models.CharField(max_length=100, null=True, blank=True, db_index=True)

2、自定義登陸驗證后台

#coding=utf-8
'''
自定義登陸驗證后台

Created on 2014年3月31日

@author: linjiqin
'''
import re

from accounts.models import User


class LoginBackend(object):
    def authenticate(self, username=None, password=None):
        if username:
            #email
            if re.match("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$", username) != None:
                try:
                    user = User.objects.get(email=username)
                    if user.check_password(password):
                        return user
                except User.DoesNotExist:
                    return None
            #mobile
            elif len(username)==11 and re.match("^(1[3458]\d{9})$", username) != None:
                try:
                    user = User.objects.get(mobile=username)
                    if user.check_password(password):
                        return user
                except User.DoesNotExist:
                    return None  
            #nick
            else:
                try:
                    user = User.objects.get(username=username)
                    if user.check_password(password):
                        return user
                except User.DoesNotExist:
                    return None                
        else:
            return None

    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None

 

3、settings.py中添加自定義驗證后台

AUTHENTICATION_BACKENDS = (
    'accounts.backends.LoginBackend',
)

 

4、在視圖中使用自定義后台驗證

# -*- encoding: utf-8 -*-
from django.conf import settings
from django.contrib import auth
from django.http import Http404, HttpResponse, HttpResponseRedirect
from django.utils import simplejson
from django.views.decorators.csrf import csrf_exempt, csrf_protect
from django.views.decorators.cache import never_cache
from django.views.decorators.http import require_POST

@require_POST
def login(request):
    username = request.POST['username']
    password = request.POST['password']
    
    result = {"status": False, "data":""}
    
    if username=="" or username.isspace():
        result = {"status": False, "data":"用戶名不能為空"}
        return HttpResponse(simplejson.dumps(result, ensure_ascii = False), mimetype="application/json")
    if password=="" or password.isspace():
        result = {"status": False, "data":"密碼不能為空"}
        return HttpResponse(simplejson.dumps(result, ensure_ascii = False), mimetype="application/json")
    
    user = auth.authenticate(username=username, password=password)
    if user is not None:
        if user.is_active:
            auth.login(request, user)
            result = {"status": True, "data":"OK"}
            return HttpResponse(simplejson.dumps(result, ensure_ascii = False), mimetype="application/json")
        else:
            result = {"status": False, "data":"["+username+"]已被暫時禁用"}
            return HttpResponse(simplejson.dumps(result, ensure_ascii = False), mimetype="application/json")
    else:
        result = {"status": False, "data":"用戶名或密碼不正確,請重試"}
        return HttpResponse(simplejson.dumps(result, ensure_ascii = False), mimetype="application/json")
    

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM