Source

PylonsWikiNG / src / authorization / tutorial / security.py

from webob.exc import HTTPFound

from repoze.bfg.view import bfg_view
from repoze.bfg.exceptions import Forbidden

from repoze.bfg.security import remember
from repoze.bfg.security import forget

USERS = {'editor':'editor',
          'viewer':'viewer'}
GROUPS = {'editor':['group:editors']}

def groupfinder(userid, request):
    if userid in USERS:
        return GROUPS.get(userid, [])

class LoginView(object):
    def __init__(self, request):
        self.request = request

    @bfg_view(renderer='login.mak', context=Forbidden)
    @bfg_view(name='login', renderer='login.mak')
    def login(self):
        login_url = self.request.application_url + '/login'
        referrer = self.request.url
        if referrer == login_url:
            referrer = '/' # never use the login form itself as came_from
        came_from = self.request.params.get('came_from', referrer)
        message = ''
        login = ''
        password = ''
        if 'form.submitted' in self.request.params:
            login = self.request.params['login']
            password = self.request.params['password']
            if USERS.get(login) == password:
                headers = remember(self.request, login)
                return HTTPFound(location=came_from, headers=headers)
            message = 'Failed login'
    
        return dict(
            message = message,
            url = login_url,
            came_from = came_from,
            login = login,
            password = password,
        )
    
    @bfg_view(name='logout', permission='view')
    def logout(self):
        headers = forget(self.request)
        return HTTPFound(
            location=self.request.application_url,
            headers=headers
            )