Tres Seaver
2010-10-01 9a8e60493792285aaa660c6839d739174fb30553
docs/api.rst
@@ -71,6 +71,71 @@
       who_api = context.who_api_factory(request.environ)
.. _writing_custom_login_view:
Writing a Custom Login View
---------------------------
:class:`repoze.who.api.API` provides a helper method to assist developers
who want to control the details of the login view.  The following
BFG example illustrates how this API might be used:
.. code-block:: python
   :linenos:
    def login_view(context, request):
        message = ''
        who_api = get_api(request.environ)
        if 'form.login' in request.POST:
            creds = {}
            creds['login'] = request.POST['login']
            creds['password'] = request.POST['password']
            authenticated, headers = who_api.login(creds)
            if authenticated:
                return HTTPFound(location='/', headers=headers)
            message = 'Invalid login.'
        else:
            # Forcefully forget any existing credentials.
            _, headers = who_api.login({})
        request.response_headerlist = headers
        if 'REMOTE_USER' in request.environ:
            del request.environ['REMOTE_USER']
        return {'message': message}
This application is written as a "hybrid":  the :mod:`repoze.who` middleware
injects the API object into the WSGI enviornment on each request.
- In line 4, this  application extracts the API object from the environ
  using :func:`repoze.who.api:get_api`.
- Lines 6 - 8 fabricate a set of credentials, based on the values the
  user entered in the form.
- In line 9, the application asks the API to authenticate those credentials,
  returning an identity and a set of respones headers.
- Lines 10 and 11 handle the case of successful authentication:  in this
  case, the application redirects to the site root, setting the headers
  returned by the API object, which will "remember" the user across requests.
- Line 13 is reached on failed login.  In this case, the headers returned
  in line 9 will be "forget" headers, clearing any existing cookies or other
  tokens.
- Lines 14 - 16 perform a "fake" login, in order to get the "forget" headers.
- Line 18 sets the "forget" headers to clear any authenticated user for
  subsequent requests.
- Lines 19 - 20 clear any authenticated user for the current request.
- Line 22 returns any message about a failed login to the rendering template.
.. _interfaces:
Interfaces