Back to index

plone3  3.1.7
authenticator.py
Go to the documentation of this file.
00001 import hmac
00002 import sha
00003 from zope.component import getUtility
00004 from zope.interface import implements
00005 from AccessControl import getSecurityManager
00006 from zExceptions import Forbidden
00007 from ZPublisher.HTTPRequest import HTTPRequest
00008 from Products.Five import BrowserView
00009 from plone.keyring.interfaces import IKeyManager
00010 from plone.protect.interfaces import IAuthenticatorView
00011 from plone.protect.utils import protect
00012 from zope.deprecation import deprecated
00013 
00014 
00015 def _getUserName():
00016     user=getSecurityManager().getUser()
00017     if user is None:
00018         return "Anonymous User"
00019     return user.getUserName()
00020 
00021 
00022 def _verify(request):
00023     auth=request.get("_authenticator")
00024     if auth is None:
00025         return False
00026 
00027     manager=getUtility(IKeyManager)
00028     ring=manager[u"_system"]
00029     user=_getUserName()
00030 
00031     for key in ring:
00032         if key is None:
00033             continue
00034         correct=hmac.new(key, user, sha).hexdigest()
00035         if correct==auth:
00036             return True
00037 
00038     return False
00039 
00040 
00041 class AuthenticatorView(BrowserView):
00042     implements(IAuthenticatorView)
00043 
00044     def authenticator(self):
00045         manager=getUtility(IKeyManager)
00046         secret=manager.secret()
00047         user=_getUserName()
00048         auth=hmac.new(secret, user, sha).hexdigest()
00049         return '<input type="hidden" name="_authenticator" value="%s"/>' % \
00050                 auth
00051 
00052 
00053     def verify(self):
00054         return _verify(self.request)
00055 
00056 
00057 def check(request):
00058     if isinstance(request, HTTPRequest):
00059         if not _verify(request):
00060             raise Forbidden('Form authenticator is invalid.')
00061 
00062 
00063 def AuthenticateForm(callable):
00064     return protect(check)(callable)
00065 
00066 deprecated("AuthenticateForm", "Please use the plone.protect.protect decorator")
00067 
00068 
00069 __all__ = [ "AuthenticatorView", "AuthenticateForm", "check" ]
00070