Skip to content

Instantly share code, notes, and snippets.

@clemesha
Forked from mrchrisadams/http_auth.py
Created August 17, 2009 17:57
Show Gist options
  • Save clemesha/169272 to your computer and use it in GitHub Desktop.
Save clemesha/169272 to your computer and use it in GitHub Desktop.
"""
'How to do basic authentication on twisted web', from here:
http://twistedmatrix.com/pipermail/twisted-python/2009-August/020236.html
Original Copyright (c) 2008 Twisted Matrix Laboratories. See LICENSE for details.
Which I modified to use Twisted's Application framework.
USAGE
-----
1) Make htpasswd file:
$ htpasswd -c .htpassfile some_user #prompts for password
2) Run (tested using Twisted 8.2.0 / Python 2.5 / OS 10.6):
$ twistd -ny http_auth.py
3) Open web browser to http://localhost:PORT
"""
import os
import sys
import crypt
from zope.interface import implements
from twisted.python import log
from twisted.application import internet, service
from twisted.web import server, resource, guard
from twisted.cred.portal import IRealm, Portal
from twisted.cred.checkers import FilePasswordDB
HTPASSFILE = os.path.expanduser("~/.htpassfile")
DOMAIN = "localhost"
PORT = 8000
class GuardedResource(resource.Resource):
"""
A resource which is protected by guard and requires authentication in order
to access.
"""
def getChild(self, path, request):
return self
def render(self, request):
# is served on root
return "Authorized!"
class SimpleRealm(object):
"""
A realm which gives out L{GuardedResource} instances for authenticated
users.
"""
implements(IRealm)
# requestAvatar supplies the username, and checks against the corresponding password
def requestAvatar(self, avatarId, mind, *interfaces):
if resource.IResource in interfaces:
# somewhat confused here...
return resource.IResource, GuardedResource(), lambda: None
raise NotImplementedError()
# compare password,
def cmp_pass(uname, password, storedpass):
return crypt.crypt(password, storedpass[:2])
# checker opens a file called htpasswd, and passing in the hash as defined by the method cmp_pass
checkers = [FilePasswordDB(HTPASSFILE, hash=cmp_pass)]
# guard acts like middleware, forcing all incoming requests to 'yoursite.com' be checked the file defined in checkers
wrapper = guard.HTTPAuthSessionWrapper(Portal(SimpleRealm(), checkers), [guard.BasicCredentialFactory(DOMAIN)])
# serves the this as a resource on port 8080
application = service.Application('http-auth')
serviceCollection = service.IServiceCollection(application)
factory = server.Site(resource=wrapper)
internet.TCPServer(PORT, factory).setServiceParent(serviceCollection)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment