2014-04-04 12 views
8

Chcę obsłużyć uwierzytelnienia w moim projekcie Django z moją bazą danych Mongoengine.Django - Auth z mongoengine DB

Próbowałem kilku przykładów na ten temat odpowiedziałem w starych pytaniach, ale nie działał. Używam Django 1.6 i mongoengine. Wszystko jest zainstalowane, działa i mogę tworzyć i zapisywać dokumenty w mojej bazie danych Mongoengine.

Obserwuję http://mongoengine-odm.readthedocs.org/en/latest/django.html

i pojawia się następujący błąd:

Kiedy biegnę:

>>> from django.contrib.auth.models import User 
>>> user = User.objects.create_user('john', '[email protected]', 'johnpassword') 

uzyskać to:

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' 
>>> 

naprawdę don” t zrozumieć 2 rzeczy:

-Do muszę utworzyć i zdefiniować bazę danych, w której będą zapisywane użytkownicy, lub będą one tworzone automatycznie?

-Czym jest menedżer? Nie zdefiniowałem żadnego menedżera rzeczy

Na początku myślałem, że rejestr został zapisany w db. zwany "mongo_auth.MongoUser", ale nie zapisał go w żadnym miejscu.

Oto modele:

# 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) 

settings.py jest prawidłowo skonfigurowany jak mówi instrukcja.

EDIT @cestDiego:

Moje ustawienia są dokładnie takie same, zauważyłem o backend Db ponieważ tworzy bazę danych, która mnie nie interesuje, bo używam Mongo ... W każdym razie jestem z ussing mongoengine.django.auth import użytkownika, ale teraz gdy próbuję utworzyć Użytkownikowi zwraca mi:

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

Może jesteśmy dostosowywania uwierzytelniania i dlatego nie działa, nie mam pojęcia. Czy masz również ten problem?

DRUGA EDYCJA:

czytałem i musimy użyć Djangos auth po skonfigurować odpowiednie ustawienia, a zarówno zrobiliśmy.

Następnie należy zaimportować uwierzytelnienie importu z django.contrib.auth i użyć uwierzytelniania, jak jest to przewidziane w dokumentach Django, z nadzieją, że pomoże;

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.") 

Odpowiedz

6

Ja rozwiązuje problem

W Django 1.6 ...

Moja settings.py wygląda następująco:

""" 
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#[email protected]+#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/' 

i moje poglądy. py wygląda następująco:

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','[email protected]') 
    return HttpResponse("SAVED") 

teraz obiekt użytkownika zostanie zapisany w DB jak:

{ 
    "_id" : ObjectId("53465fa60f04c6552ab77475"), 
    "_cls" : "User", 
    "username" : "boba", 
    "email" : "[email protected]", 
    "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" : [ ] 
} 
+0

Otrzymuję błąd w tej linii user.backend = 'mongoengine.django.auth.MongoEngineBackend' Błąd jest "MetaDict" obiekt ma brak atrybutu "pk" –

6

Hej, jestem w takiej samej sytuacji jak ty. Jak mogę dowiedzieć się, masz je w settings.py

AUTH_USER_MODEL = 'mongo_auth.MongoUser' 
MONGOENGINE_USER_DOCUMENT = 'mongoengine.django.auth.User' 

I

'mongoengine.django.mongo_auth' 

Oznacza to w zainstalowanych aplikacjach to, że teraz używasz metody uwierzytelniania Mongoengine, pierwsza linia jesteś używając importu metody uwierzytelniania DJANGO, więc jest problem.Nie tworzysz żadnych baz danych w mongodb, ale w manekinie ustawiłeś z backend.dummy w ORMie Django.

Nie wiem, jak korzystać z metody autorskiej mongoengine, jeśli to zrozumiesz, proszę mi ją wyjaśnić;) Mam nadzieję, że wyjaśniłem ci trochę problem, z którym się oboje tu spotykamy. To tylko kwestia głębszego czytania dokumentów.

EDIT: (1 minuta po odpowiedzi) Znalazłem to w dokumentacji, którą powiązany:

MongoEngine includes a Django authentication backend, which uses MongoDB. >The User model is a MongoEngine Document, but implements most of the >methods and attributes that the standard Django User model does - so the >two are moderately compatible.

więc to oznacza, że ​​w przypadku, zamienić

from django.contrib.auth import User 

do

from mongoengine.django.auth import User 
1

Nie mogę odtworzyć komunikatu o błędzie, który otrzymujesz, @Bugfixer. Zakładam, że tak się dzieje, ponieważ ustawiłeś AUTH_USER_MODEL na swoich ustawieniach, ten wpis powinien być w twoich ustawieniach tylko, jeśli masz niestandardowy model użytkownika.

spróbuje umieścić w tej odpowiedzi dokładnie to, co zrobiłem, aby go uruchomić z modelem użytkownika niestandardowego, na których mogę dodać tablicę Ulubione:

settings.py

from mongoengine import * 

DATABASES = { 
    'default': { 
     'ENGINE': 'django.db.backends.dummy', 
    } 
} 

AUTHENTICATION_BACKENDS = (
    'mongoengine.django.auth.MongoEngineBackend', 
    ... 
) 

INSTALLED_APPS = (
    'django.contrib.auth', 
    'mongoengine.django.mongo_auth', 
    .... 
) 

SESSION_ENGINE = 'mongoengine.django.sessions' 

AUTH_USER_MODEL=('mongo_auth.MongoUser') 
MONGOENGINE_USER_DOCUMENT = 'MyAwesomeApp.app.models.CustomUser' 

modele .py

from mongoengine.django.auth import User 
from mongoengine import * 

class CustomUser(User): 

    """Extend mongoengine User model""" 
    favorites = ListField(ReferenceField(MyReferencedModel, dbref=False)) 

    USERNAME_FIELD = 'username' 
    REQUIRED_FIELDS =() #must be list or tuple 

    def toJSON(self): 
     fav_list = [] 

     for f in self.favorites:     
      fav_list.append(f.toJSON()) 

     userJSON = {} 
     userJSON['id'] = str(self.pk) 
     userJSON['favorites'] = fav_list 
     userJSON['email'] = str(self.email) 
     userJSON['last_name'] = str(self.last_name) 
     userJSON['first_name'] = str(self.first_name) 
     userJSON['username'] = str(self.username) 
     return simplejson.dumps(userJSON) 

views.py

from MyAwesomeApp.app.models import CustomUser 

#util 
def extractDataFromPost(request): 
    rawData = request.body.replace('false', 'False') 
    rawData = rawData.replace('true', 'True') 
    rawData = rawData.replace('null', 'None') 
    return eval(rawData) 

#util 
def jsonResponse(responseDict): 
    return HttpResponse(simplejson.dumps(responseDict), mimetype='application/json') 

def createUser(request): 
    data = extractDataFromPost(request) 

    email = data["email"] 
    password = data["password"] 
    user_type = data["user_type"] 

    try: 
     user = CustomUser.objects.get(username=email) 
     return jsonResponse({'error':True, 'message': 'Email já cadastrado'}) 
    except CustomUser.DoesNotExist: 
     user = CustomUser.create_user(email, password, email) 
     user.favorites = [] 
     user.save() 
     user = authenticate(username=email, password=password) 
     user.backend = 'mongoengine.django.auth.MongoEngineBackend' 
     login(request, user) 
     request.session.set_expiry(3600000) # 1 hour timeout 
     del user.password 
     return HttpResponse(simplejson.dumps(user.toJSON())) 

Daj mi znać, jeśli masz jakiekolwiek problemy.

Pozdrowienia

+0

Hi Andre, to daje mi, że „Ad” (w models.py) nie jest zdefiniowana, nie mogę zrozumieć to, co to jest. – BugFixer

+0

To tylko przykład modelu. Edytowałeś odpowiedź z łatwiejszą nazwą. o/ –

+0

Dlaczego próbujesz uwierzytelniać się z mongoengine na początek? Czy próbowałeś użyć auth, który jest dołączony do Django, z samym ORM Django? ORM jest w rzeczywistości kompatybilny z MongoDB ... Spróbuj wyszukać: ** Djongo ** – nesdis

Powiązane problemy