10. HTTP e autenticazione cookie-based

Due dei modi più comuni per restringere l'accesso ad alcune parti di un sito sono:

Queste tecniche possono essere difficoltose da implementare con alcuni application server, Con CherryPy richiedono solo TRE LINEE DI CODICE !

Tutto quello che dovete fare è usare i moduli standard HttpAuthenticate e CookieAuthenticate. Il seguente esempio usa entrambi i moduli.

use HttpAuthenticate, CookieAuthenticate

CherryClass Root:
mask:
    def index(self):
        <html><body>
            <a py-attr="request.base+'/httpProtected/index'" href="">
            Click here to enter a restricted area using HTTP authentication</a><br>
            <a py-attr="request.base+'/cookieProtected/index'" href="">
            Click here to enter a restricted area using cookie authentication</a><br>
            In both cases, the login and password are "login" and "password"
        </body></html>

CherryClass HttpProtected(HttpAuthenticate):
function:
    def getPasswordListForLogin(self, login):
        # Here we define what the login and password are
        if login=='login': return ['password']
        return []
mask:
    def index(self):
        <html><body>You're in</body></html>

CherryClass CookieProtected(CookieAuthenticate):
function:
    def getPasswordListForLogin(self, login):
        # Here we define what the login and password are
        if login=='login': return ['password']
        return []
mask:
    def index(self):
        <html><body>
            You're in<br>
            Click <a href="doLogout">here</a> to log out.
        </body></html>

Come avete potuto vedere tutto ciò di cui abbiamo bisogno è di creare una CherryClass che erediti HttpAuthenticate o CookieAuthenticate e implementare una funzione chiamata getPasswordListForLogin che ritorna una lista di password corrispondeti per un dato login. (questo vi permette di mantenere una master key che lavori per tutti gli utenti, per esempio ...)

Come avete potuto vedere, usare questi moduli è realmente facile.

Nel prossimo capitolo, vedremo come usare un altro modulo standard di CherryPy: Form

See About this document... for information on suggesting changes.