06登录

drf登录

authtoken

# 把'rest_framework.authtoken',注册进apps里
# makemigrations
# migrate

url.py

from rest_framework.authtoken import views
    url(r'^api-token-auth/', views.obtain_auth_token),

settings.py

# django restframework 配置
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASS': (
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.TokenAuthentication',
    )
    }

如果需要在某些方法内单独加auth

1.将settings.py中的auth全局变量删除

# django restframework 配置
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASS': (
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        # 'rest_framework.authentication.TokenAuthentication',
    ),
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 10,
}
  1. 在需要加auth的view方法中加入
from rest_framework.authentication import TokenAuthentication
    authentication_classes = (TokenAuthentication,)  # 登录验证

jwt

pip install djangorestframework-jwt

In your settings.py, add JSONWebTokenAuthentication to Django REST framework's DEFAULT_AUTHENTICATION_CLASSES.

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.BasicAuthentication',
    ),
}

In your urls.py add the following URL route to enable obtaining a token via a POST included the user's username and password.

from rest_framework_jwt.views import obtain_jwt_token
#...

urlpatterns = [
    '',
    # ...

    url(r'^api-token-auth/', obtain_jwt_token),
]

用户能使用手机号登录

settings.py

AUTHENTICATION_BACKENDS = (
    'users.views.CustomBackend',
)

user下的views

from django.shortcuts import render
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
from django.db.models import Q
# Create your views here.
User = get_user_model()


class CustomBackend(ModelBackend):
    """
    自定义用户验证
    """
    def authenticate(self, username=None, password=None, **kwargs):
        try:
            user = User.objects.get(Q(username=username)|Q(mobile=username))
            if user.check_password(password):
                return user
        except Exception as e:
            return None

jwt的token失效时间配置

import datetime
JWT_AUTH = {
    'JWT_EXPIRATION_DELTA': datetime.timedelta(days=7),
    'JWT_AUTH_HEADER_PREFIX': 'JWT',
}

接口权限

只有在登录状态下才能访问

from rest_framework.permissions import IsAuthenticated

# views类里的方法
    permission_classes = (IsAuthenticated,)  # 用户未登录则无法请求该接口

删除操作时,判断是否为本用户

# -*- coding: utf-8 -*-
__author__ = 'bobby'
from rest_framework import permissions


class IsOwnerOrReadOnly(permissions.BasePermission):
    """
    Object-level permission to only allow owners of an object to edit it.
    Assumes the model instance has an `owner` attribute.
    """

    def has_object_permission(self, request, view, obj):
        # Read permissions are allowed to any request,
        # so we'll always allow GET, HEAD or OPTIONS requests.
        if request.method in permissions.SAFE_METHODS:
            return True

        # Instance must have an attribute named `owner`.
        return obj.user == request.user
from rest_framework.permissions import IsAuthenticated
from utils.permissions import IsOwnerOrReadOnly
    permission_classes = (IsAuthenticated, IsOwnerOrReadOnly)

序列化时获取当前用户 及判断是否已收藏

class UserFavSerializer(serializers.ModelSerializer):
    # 获取当前用户
    user = serializers.HiddenField(
        default=serializers.CurrentUserDefault()
    )

    class Meta:
        model = UserFav
        # 联合索引 -drf的功能
        validators = [
            UniqueTogetherValidator(
                queryset=UserFav.objects.all(),
                fields=('user', 'goods'),
                message="已经收藏"
            )
        ]

        fields = ("user", "goods", "id")