[Fixed]-MongoEngine — how to custom User model / custom backend for authenticate()

5👍

Well, looks like the best course of action isn’t to hand over Django’s User to Mongo for authentication to begin with… Got this golden nugget via Twitter:

@blogblimp my short answer: try to avoid replacing Django user models with MongoDB. You lose all the Django power and lose MongoDB's speed.
Seriously, user relates to everything and MongoDB isn't relational.

— Daniel Roy Greenfeld (@pydanny) January 20, 2014

So: I’ll just leverage PostgreSQL for authentication, and Mongo for other objects. That means naming / connecting to two databases in the Django settings. In retrospect, I guess the moral is: never use Mongo just because it’s cool. Mongo is still a second-class citizen in the Django world.

👤Sean

2👍

Maybe I’m a little late, but I could achieve the task of email authentication using mongoengine User + django authenticate, here is how I’m working:

from django.contrib.auth import authenticate, login as do_login, logout as do_logout

def login(request):

    data = extractDataFromPost(request)
    email = data["email"]
    password = data["password"]

    try: 
        user = User.objects.get(username=email)
        if user.check_password(password):
            user.backend = 'mongoengine.django.auth.MongoEngineBackend'
            user = authenticate(username=email, password=password)
            do_login(request, user)
            request.session.set_expiry(3600000) # 1 hour timeout
            return jsonResponse(serializeUser(user)) 
        else:
            result = {'error':True, 'message':'Invalid credentials'}
            return jsonResponse(result) 
    except User.DoesNotExist:
        result = {'error':True, 'message':'Invalid credentials'}
        return jsonResponse(result)

Leave a comment