zoukankan      html  css  js  c++  java
  • 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")
        
  • 相关阅读:
    PAT(B) 1037 在霍格沃茨找零钱(Java)
    PAT(B) 1043 输出PATest(Java)统计
    PAT(B) 1063 计算谱半径(Java)
    绘制虚线
    contentMode
    数字签名是什么
    动态设置 button的 name 的话 闪动的问题 解决
    setValuesForKeysWithDictionary 的用法
    获得 当前时间
    iOS 键盘类型
  • 原文地址:https://www.cnblogs.com/linjiqin/p/3638501.html
Copyright © 2011-2022 走看看