Django - Auth with mongoengine DB

后端 未结 3 1052
清歌不尽
清歌不尽 2020-12-08 17:31

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

3条回答
  •  情话喂你
    2020-12-08 18:27

    I could not reproduce the error message you are getting, @Bugfixer. I assume it is happening because you have AUTH_USER_MODEL set on your settings, this entry should be in your settings only if you have a custom user model.

    Will try to put in this answer exactly what I did to make it run with a custom user model on which I add a favorites array:

    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'
    

    models.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())) 
    

    Let me know if you have any trouble.

    Regards

提交回复
热议问题