Giter Club home page Giter Club logo

Comments (19)

garrypolley avatar garrypolley commented on June 1, 2024

The example code that is stated to work does not authorize the user from what I can tell.

The example snippet in this repo was tested against Django 1.4 and 1.5 (I think). Can you put a debug statement in the snippet and get the local variables? user is coming back as None which would mean it's messing up in the authenticate call somehow.

from django-mongoengine.

 avatar commented on June 1, 2024

Can you put a debug statement in the snippet and get the local variables? -> How do I do that?
user is always coming back as None whatever the password is good or not.

from django-mongoengine.

rozza avatar rozza commented on June 1, 2024

Aside: This project was never stablised and released. If you are wanting to use it and help maintain it I'll happily hand over repo access to make that happen. Cheers, Ross

from django-mongoengine.

argoyal avatar argoyal commented on June 1, 2024

Can anyone help me with running of the test cases for this application. I am trying to use pytest for the same. Is there something else I should prefer for testing?

from django-mongoengine.

last-partizan avatar last-partizan commented on June 1, 2024

AFAIK we don't us pytest here, we're using nosetests and django testings tools.
I don't recommend running tests on this project, becouse many of them now is broken.
If you want, you can try runing python setup.py test

Try instead this manual on django testing: https://docs.djangoproject.com/en/1.8/topics/testing/overview/

from django-mongoengine.

argoyal avatar argoyal commented on June 1, 2024

I have just one concern here but this is not a django project instead its a project for building django.... so I cannot use python manage.py test for the folder under tests... I will look for nosetests I haven't been working with that testing tool. Also I follow TDD approach so I would learn more with the tests about the code structure. Thank you! 👍

from django-mongoengine.

fmoro avatar fmoro commented on June 1, 2024

Authentication is working fine on my project with a custom AuthenticationMiddleware due to SESSION_KEY issue with new Options Meta class. If you want I can tell you the steps I followed to see if we can incorporate this code in django-mongoengine

from django-mongoengine.

last-partizan avatar last-partizan commented on June 1, 2024

Good idea. Share your steps and middleware and i try to intergrate that into django-mongoengine.

from django-mongoengine.

fmoro avatar fmoro commented on June 1, 2024

Well, the only problem with authentication is when login funciton in django.contrib.auth module, try to store the SESSION_KEY with the following sentence:

 request.session[SESSION_KEY] = user._meta.pk.value_to_string(user)

In Django 1.8 the Meta class is now an Options object type, but for us object._meta is just a dictionary, so there is no pk method, and also, our pk attribute doesn't have value_to_string. And same thing happends with _get_user_session_key function

This is the way I have solve this problem:

First of all I have created an AuthenticationMiddleware and I have switch it in MIDDLEWARE_CLASSES deleting the default django.contrib.auth.middleware.AuthenticationMiddleware.

MIDDLEWARE_CLASSES = (
    ...
    #'django.contrib.auth.middleware.AuthenticationMiddleware',
    'myapp.auth.AuthenticationMiddleware'
)

This is my auth module:

from django_mongoengine.auth.backends import get_user
from django.utils.functional import SimpleLazyObject

from django.contrib.auth import SESSION_KEY, BACKEND_SESSION_KEY, HASH_SESSION_KEY
from django.contrib.auth.signals import user_logged_in
from django.middleware.csrf import rotate_token

#SESSION_KEY = '_auth_user_id'

class AuthenticationMiddleware(object):
    def process_request(self, request):
        assert hasattr(request, 'session'), (
            "The Django authentication middleware requires session middleware "
            "to be installed. Edit your MIDDLEWARE_CLASSES setting to insert "
            "'django.contrib.sessions.middleware.SessionMiddleware' before "
            "'django.contrib.auth.middleware.AuthenticationMiddleware'."
        )
        request.user = SimpleLazyObject(lambda: get_user(_get_user_session_key(request)))

from bson.objectid import ObjectId
def _get_user_session_key(request):
    # This value in the session is always serialized to a string, so we need
    # to convert it back to Python whenever we access it.
    if SESSION_KEY in request.session:
        return ObjectId(request.session[SESSION_KEY])

def login(request, user):
    """
    Persist a user id and a backend in the request. This way a user doesn't
    have to reauthenticate on every request. Note that data set during
    the anonymous session is retained when the user logs in.
    """
    session_auth_hash = ''
    if user is None:
        user = request.user
    if hasattr(user, 'get_session_auth_hash'):
        session_auth_hash = user.get_session_auth_hash()

    if SESSION_KEY in request.session:
        if _get_user_session_key(request) != user.pk or (
                session_auth_hash and
                request.session.get(HASH_SESSION_KEY) != session_auth_hash):
            # To avoid reusing another user's session, create a new, empty
            # session if the existing session corresponds to a different
            # authenticated user.
            request.session.flush()
    else:
        request.session.cycle_key()
    try:
        request.session[SESSION_KEY] = user._meta.pk.value_to_string(user)
    except AttributeError:
        request.session[SESSION_KEY] = str(user.pk)
    request.session[BACKEND_SESSION_KEY] = user.backend
    request.session[HASH_SESSION_KEY] = session_auth_hash
    if hasattr(request, 'user'):
        request.user = user
    rotate_token(request)
    user_logged_in.send(sender=user.__class__, request=request, user=user)

Now we need to create a login view, since django.contrib.auth.views.login uses django.contrib.auth.login and django.contrib.auth._get_user_session_key functions. It is a shame because login view is just a copy of django.contrib.auth.views.login, but we have to ensure that it uses our login and _get_user_session_key function.

from myapp.auth import login as auth_login

@sensitive_post_parameters()
@csrf_protect
@never_cache
def login(request, template_name='registration/login.html',
          redirect_field_name=REDIRECT_FIELD_NAME,
          authentication_form=AuthenticationForm,
          current_app=None, extra_context=None):
    """
    Displays the login form and handles the login action.
    """
    redirect_to = request.POST.get(redirect_field_name,
                                   request.GET.get(redirect_field_name, ''))

    if request.method == "POST":
        form = authentication_form(request, data=request.POST)
        if form.is_valid():

            # Ensure the user-originating redirection url is safe.
            if not is_safe_url(url=redirect_to, host=request.get_host()):
                redirect_to = resolve_url(settings.LOGIN_REDIRECT_URL)

            # Okay, security check complete. Log the user in.
            auth_login(request, form.get_user())

            return HttpResponseRedirect(redirect_to)
    else:
        form = authentication_form(request)

    current_site = get_current_site(request)

    context = {
        'form': form,
        redirect_field_name: redirect_to,
        'site': current_site,
        'site_name': current_site.name,
    }
    if extra_context is not None:
        context.update(extra_context)

    if current_app is not None:
        request.current_app = current_app

    return TemplateResponse(request, template_name, context)

The last step to do is just use this view as login view:

urlpatterns = patterns('',
    url(r'^login/$', 'myapp.views.login', {'template_name': 'my_custom_template.html', 'current_app': 'myappl', 'authentication_form': MyAuthenticationForm}, name='login'),
    ...
)

I think that we could incorporate the autentication middleware and the login view controller on the auth package...

from django-mongoengine.

last-partizan avatar last-partizan commented on June 1, 2024

I fixed it in a somewhat tricky way.

If django auth wants User._meta.pk.value_to_string - i just added this.

from django-mongoengine.

maria avatar maria commented on June 1, 2024

@last-partizan for me it didn't work. I still get the error. Am I missing something? Thanks in advanced.
P.S.: I have Django 1.8, the last version of mongoengine and django-mongoengine.

from django-mongoengine.

last-partizan avatar last-partizan commented on June 1, 2024

@maria are you installed django-mongoengine from git?

from django-mongoengine.

maria avatar maria commented on June 1, 2024

Yes, I forked the repo and install via pip with my URL repo.

from django-mongoengine.

last-partizan avatar last-partizan commented on June 1, 2024

So, what error do you get? last time i checked this using example app, and it was working.

from django-mongoengine.

maria avatar maria commented on June 1, 2024

This is what I get when I try to create a session / login with my user (the model is defined using django-
screenshot 2015-11-26 12 26 35
mongoengine)

from django-mongoengine.

last-partizan avatar last-partizan commented on June 1, 2024

I don't see exact error. try copy-pasting ettire traceback.

from django-mongoengine.

maria avatar maria commented on June 1, 2024

Here it is:

'MetaDict' object has no attribute 'pk'
Request Method: GET
Request URL:    http://192.168.3.3:8000/authenticate/?code=6d77e581ec52af4d2d2e
Django Version: 1.8.6
Exception Type: AttributeError
Exception Value:    
'MetaDict' object has no attribute 'pk'
Exception Location: /usr/local/lib/python2.7/dist-packages/django/contrib/auth/__init__.py in login, line 111
Python Executable:  /usr/bin/python
Python Version: 2.7.6
Python Path:    
['/home/vagrant/cub/cub',
 '/usr/lib/python2.7',
 '/usr/lib/python2.7/plat-x86_64-linux-gnu',
 '/usr/lib/python2.7/lib-tk',
 '/usr/lib/python2.7/lib-old',
 '/usr/lib/python2.7/lib-dynload',
 '/usr/local/lib/python2.7/dist-packages',
 '/usr/lib/python2.7/dist-packages']
Server time:    Thu, 26 Nov 2015 10:35:16 +0000
-----
views.py in login
                        login(request, user) ...
▶ Local vars
/usr/local/lib/python2.7/dist-packages/django/contrib/auth/__init__.py in login
                request.session[SESSION_KEY] = user._meta.pk.value_to_string(user) 

from django-mongoengine.

last-partizan avatar last-partizan commented on June 1, 2024

Check your settings, there must be something like this:

AUTH_USER_MODEL = 'mongo_auth.MongoUser'

AUTHENTICATION_BACKENDS = (
    'django_mongoengine.mongo_auth.backends.MongoEngineBackend',
)

And i just checked example app, it's working. Try to look at the example app code and figure out why it doesn't work for you.

from django-mongoengine.

maria avatar maria commented on June 1, 2024

OK thank you, will do.

from django-mongoengine.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.