Django - Auth with mongoengine DB

后端 未结 3 1054
清歌不尽
清歌不尽 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:20

    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" : [ ]
    }
    

提交回复
热议问题