Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

basic authentication #1

Open
depaolim opened this issue Mar 19, 2012 · 0 comments
Open

basic authentication #1

depaolim opened this issue Mar 19, 2012 · 0 comments

Comments

@depaolim
Copy link

support fo basic authentication via decorator

Implementation proposal:

import base64

from django.http import HttpResponse
from django.contrib.auth import authenticate, login


def basicauth_required(realm=""):
    "Based on http://djangosnippets.org/snippets/243/"

    def external_wrapper(view):
        def wrapper(request, *args, **kwargs):
            if 'HTTP_AUTHORIZATION' in request.META:
                auth = request.META['HTTP_AUTHORIZATION'].split()               
                if len(auth) == 2:
                    if auth[0].lower() == "basic":
                        uname, passwd = base64.b64decode(auth[1]).split(':')
                        user = authenticate(username=uname, password=passwd)
                        if user is not None:
                            if user.is_active:
                                login(request, user)
                                request.user = user
                                return view(request, *args, **kwargs)

            # the authorization attempt failed. Send a 401
            # back to them to ask them to authenticate.
            #
            response = HttpResponse()
            response.status_code = 401
            response['WWW-Authenticate'] = 'Basic realm="%s"' % realm
            return response
        return wrapper
    return external_wrapper
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant