Djangoカスタムログイン検証バックグラウンド

13674 ワード

メールアドレス/携帯番号/ニックネームの登録をサポートし、django 1.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")