Skip to content

basic authentication #1

Description

@depaolim

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

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions