Django - 在调用auth.authenticate()

时间:2016-08-09 13:33:33

标签: angularjs django authentication

我有一个Django项目,其中有一个已安装的应用程序用于登录(login_app)和另一个用于进行结算的应用程序(commandes_app)。

首先,我使用login_app成功登录我的用户。 (用户通过身份验证)

之后,当我尝试使用AngularJS控制器中使用Django commandes_app登录的用户创建账单链接时,我得到AnonymousUser和500错误(“Facture.owner”必须是“用户”实例。)。在尝试创建帐单之前,我不会将用户注销。

我正在使用Django 1.9,AngularJS 1.5。我使用角度LocalStorageModule来存储cookie中的用户信息。 (我已经阅读了一些帖子,说明cookie可能会干扰request.session数据,但我更改了会话存储的cookie以保持用户信息没有成功)。

这是我用来登录用户的Django视图:

@csrf_exempt
def authenticate_view(request):

    username = request.POST.get('username')
    password = request.POST.get('password') 

        user = User.objects.get(username=username)

        if user is not None:

            user = auth.authenticate(username=username, password=password)
            if user is not None:
                if user.is_active:
                    auth.login(request, user)
                    print(user.username) # danielb
                    print(user.is_authenticated()) # True
                    message = getMessageData(user=user, frenchText='utilisateur connecté', englishText='user connected', success=True)
                    return JSONResponse(message, status=201)
                else:
                    message = getMessageData(user=user, frenchText='utilisateur non active', englishText="user isn't activated", success=False)
                    return JSONResponse(message, status=403)
            else:
                message = getMessageData(frenchText="Votre mot de passe est incorrect", englishText="Your password is incorrect.", success=False)
            return JSONResponse(message, status=403)


        else:
            message = getMessageData(frenchText="L'utilisateur n'existe pas", englishText="User doesn't exist", success=False)
            return JSONResponse(message, status=404)

    pass

这是我用来创建帐单的Django视图

class FactureViewSet(viewsets.ModelViewSet):

    queryset = Facture.objects.all()
    serializer_class = FactureSerializer

    def create(self, request):

        serializer = FactureSerializer(data=request.data)
        print(request.user) #  AnonymousUser
        if serializer.is_valid(): # True
            serializer.save(owner = request.user)
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            return Response(serializer.errors,
                        status=status.HTTP_403_FORBIDDEN, request=request)  
    pass
pass

这里是Django settings.py

import os
from django.utils.translation import gettext_lazy as _

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

SECRET_KEY = '7in$561j#(wz)qib6ecmn-s@v38c0l1_c01&o6=nsu2!+d9fms'

DEBUG = True
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
         },
        'simple': {
            'format': '%(levelname)s %(message)s'
        },
    },
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
        },
},
    'loggers': {
        'django': {
            'handlers': ['console'],
            'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'),
        },
        'cms_v0_app.views': {
            'handlers': ['console'],
            'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG'),
        },
        'inventaire_app.views': {
            'handlers': ['console'],
            'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'),
        },
        'commandes_app.views': {
            'handlers': ['console'],
            'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG'),
        },
    },
}

ALLOWED_HOSTS = ['*']
PAYPAL_TEST = True

ALLOWED_HOSTS = ['*']

CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True

GRAPPELLI_ADMIN_TITLE = "Django projet -- Gestion"
GRAPPELLI_SWITCH_USER = True
GRAPPELLI_AUTOCOMPLETE_LIMIT = 10

GRAPPELLI_AUTOCOMPLETE_SEARCH_FIELDS = {
    "cms_v0_app": {
        "Produit": ("msgAlt__icontains", "numeroAcomba__icontains", "fr__descriptionCourte__icontains")
    }
}



# Application definition

INSTALLED_APPS = [
    'grappelli',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    #'django.contrib.sites',
    'rest_framework',
    'paypal.standard.ipn',
    'crispy_forms',
    'login_app',
    'inventaire_app',
    'commandes_app',
    'cms_v0_app',
    'corsheaders',
]

SITE_ID = 1

MIDDLEWARE_CLASSES = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'my_django_project.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
                'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'my_django_projet.wsgi.application'

REST_FRAMEWORK = {
    'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.DjangoFilterBackend',)
}

DATABASES = {
    'default': {
         'ENGINE': 'django.db.backends.postgresql_psycopg2',
         'NAME': 'my_django_projet',
         'USER': 'my_django_projet',
         'PASSWORD': 'my_password',
         'HOST': 'localhost',
         'PORT': '',
    }
}

# Password validation
# https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

#AUTHENTICATION_BACKENDS = ('login_app.backends.ClientAuthBackend', 'django.contrib.auth.backends.ModelBackend')

# Internationalization

LANGUAGE_CODE = 'fr-FR'
TIME_ZONE = 'EST'
USE_I18N = True
USE_L10N = True
USE_TZ = True

LANGUAGES = (
    ('fr', _('Français')),
    ('en', _('Anglais')),
)
DEFAULT_LANGUAGE = 1
# Static files (CSS, JavaScript, Images)

STATIC_URL = '/static/'
STATIC_ROOT = '/var/www/django/www.my_django_projet.com/static'

MEDIA_URL = '/media/'
STATIC_ROOT = '/var/www/django/www.my_django_projet.com/static'

这里是AngularJS应用声明:

'use strict';

angular.module('my_django_project_App', ['ui.router', 'ngResource', 'angular-carousel', 'ngTouch', 'services', 'uiGmapgoogle-maps', 'angularUtils.directives.dirPagination','LocalStorageModule'])

.config(function($stateProvider, $urlRouterProvider, $locationProvider, uiGmapGoogleMapApiProvider, localStorageServiceProvider){ 

// state definition

})

.config(function(uiGmapGoogleMapApiProvider) {
uiGmapGoogleMapApiProvider.configure({
        v: '3.20', //defaults to latest 3.X anyhow
        libraries: 'weather,geometry,visualization'
    })
    })

.config(function (localStorageServiceProvider) {
    localStorageServiceProvider.setPrefix('my_django_projetct_App');
    localStorageServiceProvider.setStorageCookie(0, '/');
    localStorageServiceProvider.setStorageCookieDomain('');
    })

.config(function ($httpProvider) {
    $httpProvider.defaults.xsrfCookieName = 'csrftoken';
    $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
})

.run(function ($rootScope, $state) {
  $rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState) {
        $state.previous = fromState;
      });
    })

.directive("scroll", function($window, $rootScope, $state) {
return {

    link: function(scope, element, attrs) {

        angular.element($window).bind("scroll", function() {

            if(!$state.is('django_project_Informations')){

                scope.demarrerAnimation();
            }


           });
        },   
    };
});

var my_django_project_App = angular.module('my_django_project_App');

my_django_project_App.filter('trustUrl', ['$sce', function ($sce) {
  return function(url) {
            return $sce.trustAsResourceUrl(url);
          };
    }]);

AngularJS控制器部分用于在Django commandes_app视图上发布

fd = new FormData();

fd.append('nomClient', localStorageService.cookie.get("usagerConnecter").username);
fd.append('prenomClient', localStorageService.cookie.get("usagerConnecter").username);


$http.post('http://127.0.0.1:8000/commandes/factures/', fd, {
            transformRequest: angular.identity,
            headers: {'Content-Type': undefined}
            }).success(function(response, status) {

            console.log(response);

        }).error(function(response, status) {

            console.log(response);
        });

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

你必须log the user inlogin() is the process by which a session is allocated to an authenticated user

from django.contrib.auth.views import login
def create(self, request):
    .....
    user = authenticate(username=username, password=password)
    if user:
        login(request, user)
    .....
检查user.is_active之后

和那个authenticate() must return a user object返回用户对象而不是自定义消息和json响应。 Upon successful login, request.user is assigned with the user object returned by the authenticate method of correspinding auth backend。也是为什么有csrf_exempt进行身份验证?强烈建议在发出请求时将csrf_token传递给django。在这种情况下,当您使用django rest框架时,请使用drf session authentication。在此之前,我建议您浏览drf authentication methods。 HTH:)