我正在使用Django-rest-auth进行身份验证。在客户端,我可以获得登录用户的用户详细信息,如下所示:
$scope.getUser = function(){
$http.get("https://localhost:8000/rest-auth/user/").then(function(response){
$scope.userData = response.data;
$scope.username = $scope.userData.username;
console.log(response.data);
});
}
但是在服务器端视图中,我的请求并未向我提供任何用户详细信息。我的views.py看起来像下面这样:
#view to call a stored proc that returns an exercise list for a particular user
def get_exercise_state_by_user_id(request):
print(request.user) # this gives me AnonymousUser
print(request.user.id) # this gives me None
results = Exercise_state_ui_model.fetch_exercises(request.user.id, -1)
serializer = ExerciseStateSerializer(results, many=True)
return JSONResponse(serializer.data)
由于“请求”并未向我提供任何用户相关信息,因此无法执行任何操作。
results = Exercise_state_ui_model.fetch_exercises(request.user.id, -1)
可能是什么问题?为什么请求不包含任何用户相关信息?解决方法是什么?
我的settings.py有以下内容:
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'rest_framework',
#following was added to allow cross domain requests
'corsheaders',
#following were added for ssl thing
'djangosecure',
'sslserver',
#following were added for authentication
'rest_framework.authtoken',
'rest_auth',
'allauth',
'allauth.account',
'rest_auth.registration',
'demo',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
'corsheaders.middleware.CorsMiddleware',
'djangosecure.middleware.SecurityMiddleware',
'django.middleware.common.CommonMiddleware',
)
REST_SESSION_LOGIN = True
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
SITE_ID = 1
ACCOUNT_EMAIL_REQUIRED = False
ACCOUNT_AUTHENTICATION_METHOD = 'username'
ACCOUNT_EMAIL_VERIFICATION = 'optional'
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
'rest_framework.authentication.SessionAuthentication'
),
}
更新我的loginCtrl如下所示:
//Login controller
.controller('loginCtrl', function($scope, $location, $state, djangoAuth, $ionicHistory){
$scope.model = {'username':'','password':''};
$scope.complete = false;
$scope.login = function(formData){
$scope.errors = [];
djangoAuth.login($scope.model.username, $scope.model.password)
.then(function(data){
// success case
console.log("Logged in");
//To disable back state
$ionicHistory.nextViewOptions({
disableBack: true
});
//On successful login goto start page
$state.go('start');
},function(data){
// error case
$scope.errors = data;
});
}
})