pyramid_cubicweb/login.py
author Christophe de Vienne <christophe@unlish.com>
Wed, 06 Aug 2014 19:04:25 +0200
changeset 11496 500615e26063
parent 11494 79ce84750c18
child 11497 855219da7c70
permissions -rw-r--r--
Use a tween application instead of a catchall route. Using a catchall route has some drawbacks. Especially, we have no mean to have a route that would match only if no other one does AND no view matches either. Said differently, our default handler cannot be plugged on the route level nor the view level, because it is has to be activated only if nothing else works in the pyramid application. Using a tween application allow to handle requests that raises a HTTPNotFound error, while having the pyramid error handler still active between our tween app and the outside world. Related to #4291173

from pyramid import security
from pyramid.httpexceptions import HTTPSeeOther

import cubicweb

from pyramid_cubicweb.core import render_view


def login(request):
    repo = request.registry['cubicweb.repository']

    response = request.response
    user_eid = None

    if '__login' in request.params:
        login = request.params['__login']
        password = request.params['__password']

        try:
            with repo.internal_cnx() as cnx:
                user = repo.authenticate_user(cnx, login, password=password)
                user_eid = user.eid
        except cubicweb.AuthenticationError:
            raise

    if user_eid is not None:
        headers = security.remember(request, user_eid)

        new_path = request.params.get('postlogin_path', '/')

        if new_path == 'login':
            new_path = '/'

        raise HTTPSeeOther(new_path, headers=headers)

    response.text = render_view(request, 'login')
    return response


def includeme(config):
    config.add_route('login', '/login')
    config.add_view(login, route_name='login')