Django - 使用 mongoengine DB 进行身份验证 [英] Django - Auth with mongoengine DB

查看:33
本文介绍了Django - 使用 mongoengine DB 进行身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用我的 mongoengine db 在我的 Django 项目中处理身份验证.

我尝试了一些关于在旧问题中回答的这些内容的示例,但它没有运行.我正在使用 Django 1.6 和 mongoengine.一切都已安装、运行,我可以创建文档并将其保存到我的 Mongoengine 数据库中.

我正在关注 http://mongoengine-odm.readthedocs.org/en/latest/django.html

我收到以下错误:

当我跑步时:

<预><代码>>>>从 django.contrib.auth.models 导入用户>>>user = User.objects.create_user('john', 'lennon@thebeatles.com', 'johnpassword')

我明白了:

回溯(最近一次调用最后一次):文件<console>",第 1 行,在 <module> 中文件/REBORN/reb_env/local/lib/python2.7/site-packages/django/db/models/manager.py",第 273 行,在 __get__self.model._meta.object_name, self.model._meta.swappedAttributeError: Manager 不可用;用户已被替换为 'mongo_auth.MongoUser'>>>

我真的不明白两件事:

-我必须创建和定义存储用户的数据库还是自动创建用户?

-什么是经理?我还没有定义任何经理的东西

一开始我以为寄存器保存在数据库中.名为mongo_auth.MongoUser",但它没有保存在任何地方.

这是模型:

# 在这里创建你的模型.从 mongoengine 进口 *类简介(文档):email = StringField(required=True)first_name = StringField(max_length=50)last_name = StringField(max_length=50)类 auth_user(文档):用户名 = StringField(max_length=50)电子邮件 = StringField(max_length=50)密码 = StringField(max_length=50)

settings.py 已按照手册所述正确配置.

编辑@cestDiego:

我的设置完全一样,我注意到了 Db 后端,因为它为我创建了一个我不感兴趣的数据库,因为我使用 mongo...无论如何我现在使用 from mongoengine.django.auth import User 但是当我尝试创建用户时,它返回给我:

<预><代码>>>>user = User.objects.create_user('john', 'lennon@thebeatles.com', 'johnpassword')回溯(最近一次调用最后一次):文件<console>",第 1 行,在 <module> 中AttributeError: 'QuerySet' 对象没有属性 'create_user'

也许我们正在自定义身份验证,这就是为什么不起作用,不知道.你也有这个问题吗?

第二次

我正在阅读,在配置正确的设置后,我们必须使用 Django 身份验证,正如我们所做的那样.

然后必须导入 from django.contrib.auth import authentication 并使用 Django 文档中提供的身份验证,希望能帮助;D.

from django.shortcuts 导入渲染# 在此处创建您的视图.从 django.http 导入 HttpResponse从 game.models 导入 *从 mongoengine 进口 *从模型导入用户从 django.contrib.auth 导入身份验证定义登录(请求):用户 = 验证(用户名 ='约翰',密码 ='秘密')如果用户不是无:# 为用户验证的密码如果 user.is_active:print("用户有效、活跃且已通过身份验证")别的:print("密码有效,但账号已被禁用!")别的:# 认证系统无法验证用户名和密码print("用户名和密码不正确.")

解决方案

我解决了问题

在 Django 1.6 中...

我的 settings.py 看起来像这样:

<代码>"""prova 项目的 Django 设置.有关此文件的更多信息,请参见https://docs.djangoproject.com/en/1.6/topics/settings/有关设置及其值的完整列表,请参阅https://docs.djangoproject.com/en/1.6/ref/settings/"""# 像这样在项目中构建路径: os.path.join(BASE_DIR, ...)导入操作系统BASE_DIR = os.path.dirname(os.path.dirname(__file__))# 快速启动开发设置 - 不适合生产# 见 https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/# 安全警告:对生产中使用的密钥保密!SECRET_KEY = '^%r&tw5_steltu_ih&n6lvht0gs(0p#0p5z0br@+#l1o(iz_t6')# 安全警告:不要在生产中打开调试运行!调试 = 真TEMPLATE_DEBUG = 真ALLOWED_HOSTS = []# 应用定义安装_应用程序 = ('django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles','django.contrib.sessions',)MIDDLEWARE_CLASSES = ('django.contrib.sessions.middleware.SessionMiddleware','django.middleware.common.CommonMiddleware','django.middleware.csrf.CsrfViewMiddleware','django.contrib.auth.middleware.AuthenticationMiddleware','django.contrib.messages.middleware.MessageMiddleware','django.middleware.clickjacking.XFrameOptionsMiddleware','django.contrib.sessions.middleware.SessionMiddleware',)ROOT_URLCONF = 'prova.urls'WSGI_APPLICATION = 'prova.wsgi.application'# 数据库# https://docs.djangoproject.com/en/1.6/ref/settings/#databases数据库 = {'默认': {'引擎':'django.db.backends.dummy'}}AUTHENTICATION_BACKENDS = ('mongoengine.django.auth.MongoEngineBackend',)SESSION_ENGINE = 'mongoengine.django.sessions'SESSION_SERIALIZER = 'mongoengine.django.sessions.BSONSerializer'# 国际化# https://docs.djangoproject.com/en/1.6/topics/i18n/LANGUAGE_CODE = 'en-us'TIME_ZONE = 'UTC'USE_I18N = 真USE_L10N = 真USE_TZ = 真# 静态文件(CSS、JavaScript、图像)# https://docs.djangoproject.com/en/1.6/howto/static-files/STATIC_URL = '/静态/'

我的 views.py 看起来像:

from django.shortcuts 导入渲染# 在此处创建您的视图.从 django.http 导入 HttpResponse从 game.models 导入 *从 mongoengine 进口 *#from django.contrib.auth 导入认证从 mongoengine.django.auth 导入用户定义登录(请求):连接('重生')从 django.contrib.auth 导入登录从 mongoengine.django.auth 导入用户从 mongoengine.queryset 导入DoesNotExist从 django.contrib 导入消息尝试:user = User.objects.get(username='bob')#request.POST['username'])if user.check_password('bobpass'):#request.POST['password']):user.backend = 'mongoengine.django.auth.MongoEngineBackend'打印登录(请求,用户)request.session.set_expiry(60 * 60 * 1) # 1 小时超时打印返回"return HttpResponse("LOGUEJAT")#redirect('index')别的:打印疾病"messages.add_message(request,messages.ERROR,u"登录名或密码不正确!")除了不存在:messages.add_message(request,messages.ERROR,u"登录名或密码不正确!")返回渲染(请求,'login.html',{})定义注销(请求):#未测试从 django.contrib.auth 导入注销注销(请求)返回重定向('登录')定义创建用户(请求):连接('重生')User.create_user('boba','bobpass','bobsaget@fullhouse.gov')返回 HttpResponse("SAVED")

现在用户对象保存在数据库中,如:

<代码>{"_id" : ObjectId("53465fa60f04c6552ab77475"),"_cls": "用户","用户名": "boba","email": "bobsaget@fullhouse.gov",密码":pbkdf2_sha256$12000$ZYbCHP1K1kDE$Y4LnGTdKhh1irJVktWo1QZX6AlEFn+1daTEvQAMMehA=",is_staff":假,is_active":真,is_superuser":假,"last_login" : ISODate("2014-04-10T09:08:54.551Z"),"date_joined" : ISODate("2014-04-10T09:08:54.550Z"),用户权限":[]}

I want to handle authentications in my Django project with my mongoengine db.

I tried a few examples about this stuff answered in old questions but it didn't run. I'm using Django 1.6 and mongoengine. Everything is installed, running and I can create and save documents to my Mongoengine DB.

I'm following http://mongoengine-odm.readthedocs.org/en/latest/django.html

And i get the following error:

When i run:

>>> from django.contrib.auth.models import User
>>> user = User.objects.create_user('john', 'lennon@thebeatles.com', 'johnpassword')

I get this:

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/REBORN/reb_env/local/lib/python2.7/site-packages/django/db/models/manager.py", line 273, in __get__
    self.model._meta.object_name, self.model._meta.swapped
AttributeError: Manager isn't available; User has been swapped for 'mongo_auth.MongoUser'
>>> 

I really don't understand 2 things:

-Do I must create and define the database where the users will be stored or they will be created automatically?

-What is Manager? I haven't defined any manager stuff

At the beggining i thought that the register was saved in a db. callled 'mongo_auth.MongoUser' but it didn't save it in nowhere.

Here is the models:

# Create your models here.
from mongoengine import *

class Profile(Document):
    email = StringField(required=True)
    first_name = StringField(max_length=50)
    last_name = StringField(max_length=50)

class auth_user(Document):
    username = StringField(max_length=50)
    email = StringField(max_length=50)
    password = StringField(max_length=50)

The settings.py is properly configured as the manual says.

EDIT @cestDiego:

My settings are exactly the same, I've noticed about the Db backend because it creates me a database which am not interested because I use mongo...Anyway I'm ussing from mongoengine.django.auth import User now but when I try to create an User it returns me :

>>> user = User.objects.create_user('john', 'lennon@thebeatles.com', 'johnpassword')
Traceback (most recent call last):
  File "<console>", line 1, in <module>
AttributeError: 'QuerySet' object has no attribute 'create_user'

Maybe we are customizing the auth and that's why not work, no idea. Do you have this problem too ?

SECOND EDIT:

I was reading and we have to use Djangos auth, after configure the right settings, as both we have done.

Then must import the from django.contrib.auth import authenticate and use authenticate as it is provided in Django docs, hope to help ;D.

from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse
from game.models import *
from mongoengine import *
from models import User
from django.contrib.auth import authenticate

def login(request):
        user = authenticate(username='john', password='secret')
        if user is not None:
            # the password verified for the user
            if user.is_active:
                print("User is valid, active and authenticated")
            else:
                print("The password is valid, but the account has been disabled!")
        else:
            # the authentication system was unable to verify the username and password
            print("The username and password were incorrect.")

解决方案

I solve the problem

In Django 1.6...

My settings.py looks like this:

"""
Django settings for prova project.

For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '^%r&tw5_steltu_ih&n6lvht0gs(0p#0p5z0br@+#l1o(iz_t6'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

TEMPLATE_DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.sessions',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
)

ROOT_URLCONF = 'prova.urls'

WSGI_APPLICATION = 'prova.wsgi.application'


# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.dummy'
    }
}
AUTHENTICATION_BACKENDS = (
    'mongoengine.django.auth.MongoEngineBackend',
)
SESSION_ENGINE = 'mongoengine.django.sessions'
SESSION_SERIALIZER = 'mongoengine.django.sessions.BSONSerializer'
# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/

STATIC_URL = '/static/'

and my views.py looks like:

from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse
from game.models import *  
from mongoengine import *
#from django.contrib.auth import authenticate
from mongoengine.django.auth import User

def login(request):
    connect('reborn')
    from django.contrib.auth import login
    from mongoengine.django.auth import User
    from mongoengine.queryset import DoesNotExist
    from django.contrib import messages
    try:
        user = User.objects.get(username='bob')#request.POST['username'])
        if user.check_password('bobpass'):#request.POST['password']):
            user.backend = 'mongoengine.django.auth.MongoEngineBackend'
            print login(request, user)
            request.session.set_expiry(60 * 60 * 1) # 1 hour timeout
            print "return"
            return HttpResponse("LOGUEJAT")#redirect('index')
        else:
            print "malament"
            messages.add_message(request,messages.ERROR,u"Incorrect login name or password !")
    except DoesNotExist:
        messages.add_message(request,messages.ERROR,u"Incorrect login name or password !")
    return render(request, 'login.html', {})

def logout(request):#NOT TESTED
    from django.contrib.auth import logout
    logout(request)
    return redirect('login')

def createuser(request): 
    connect('reborn')
    User.create_user('boba','bobpass','bobsaget@fullhouse.gov')
    return HttpResponse("SAVED")

now the user object is saved in DB like:

{
    "_id" : ObjectId("53465fa60f04c6552ab77475"),
    "_cls" : "User",
    "username" : "boba",
    "email" : "bobsaget@fullhouse.gov",
    "password" : "pbkdf2_sha256$12000$ZYbCHP1K1kDE$Y4LnGTdKhh1irJVktWo1QZX6AlEFn+1daTEvQAMMehA=",
    "is_staff" : false,
    "is_active" : true,
    "is_superuser" : false,
    "last_login" : ISODate("2014-04-10T09:08:54.551Z"),
    "date_joined" : ISODate("2014-04-10T09:08:54.550Z"),
    "user_permissions" : [ ]
}

这篇关于Django - 使用 mongoengine DB 进行身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆