Adding authorization

In the last chapter we built authentication into our wiki. We also went one step further and used the request.user object to perform some explicit authorization checks. This is fine for a lot of applications, but Pyramid provides some facilities for cleaning this up and decoupling the constraints from the view function itself.

We will implement access control with the following steps:

Add user principals

A principal is a level of abstraction on top of the raw userid that describes the user in terms of its capabilities, roles, or other identifiers that are easier to generalize. The permissions are then written against the principals without focusing on the exact user involved.

Pyramid defines two builtin principals used in every application: pyramid.security.Everyone and pyramid.security.Authenticated. On top of these we have already mentioned the required principals for this application in the original design. The user has two possible roles: editor or basic. These will be prefixed by the string role: to avoid clashing with any other types of principals.

Open the file tutorial/security.py and edit it as follows:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
from pyramid.authentication import AuthTktAuthenticationPolicy
from pyramid.authorization import ACLAuthorizationPolicy
from pyramid.security import (
    Authenticated,
    Everyone,
)

from .models import User


class MyAuthenticationPolicy(AuthTktAuthenticationPolicy):
    def authenticated_userid(self, request):
        user = request.user
        if user is not None:
            return user.id

    def effective_principals(self, request):
        principals = [Everyone]
        user = request.user
        if user is not None:
            principals.append(Authenticated)
            principals.append(str(user.id))
            principals.append('role:' + user.role)
        return principals

def get_user(request):
    user_id = request.unauthenticated_userid
    if user_id is not None:
        user = request.dbsession.query(User).get(user_id)
        return user

def includeme(config):
    settings = config.get_settings()
    authn_policy = MyAuthenticationPolicy(
        settings['auth.secret'],
        hashalg='sha512',
    )
    config.set_authentication_policy(authn_policy)
    config.set_authorization_policy(ACLAuthorizationPolicy())
    config.add_request_method(get_user, 'user', reify=True)

Only the highlighted lines need to be added.

Note that the role comes from the User object. We also add the user.id as a principal for when we want to allow that exact user to edit pages which they have created.

Add the authorization policy

We already added the authorization policy in the previous chapter because Pyramid requires one when adding an authentication policy. However, it was not used anywhere, so we'll mention it now.

In the file tutorial/security.py, notice the following lines:

38
39
40
    config.set_authentication_policy(authn_policy)
    config.set_authorization_policy(ACLAuthorizationPolicy())
    config.add_request_method(get_user, 'user', reify=True)

We're using the pyramid.authorization.ACLAuthorizationPolicy, which will suffice for most applications. It uses the context to define the mapping between a principal and permission for the current request via the __acl__.

Add resources and ACLs

Resources are the hidden gem of Pyramid. You've made it!

Every URL in a web application represents a resource (the "R" in Uniform Resource Locator). Often the resource is something in your data model, but it could also be an abstraction over many models.

Our wiki has two resources:

  1. A NewPage. Represents a potential Page that does not exist. Any logged-in user, having either role of basic or editor, can create pages.
  2. A PageResource. Represents a Page that is to be viewed or edited. editor users, as well as the original creator of the Page, may edit the PageResource. Anyone may view it.

Note

The wiki data model is simple enough that the PageResource is mostly redundant with our models.Page SQLAlchemy class. It is completely valid to combine these into one class. However, for this tutorial, they are explicitly separated to make clear the distinction between the parts about which Pyramid cares versus application-defined objects.

There are many ways to define these resources, and they can even be grouped into collections with a hierarchy. However, we're keeping it simple here!

Open the file tutorial/routes.py and edit the following lines:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
from pyramid.httpexceptions import (
    HTTPNotFound,
    HTTPFound,
)
from pyramid.security import (
    Allow,
    Everyone,
)

from .models import Page

def includeme(config):
    config.add_static_view('static', 'static', cache_max_age=3600)
    config.add_route('view_wiki', '/')
    config.add_route('login', '/login')
    config.add_route('logout', '/logout')
    config.add_route('view_page', '/{pagename}', factory=page_factory)
    config.add_route('add_page', '/add_page/{pagename}',
                     factory=new_page_factory)
    config.add_route('edit_page', '/{pagename}/edit_page',
                     factory=page_factory)

def new_page_factory(request):
    pagename = request.matchdict['pagename']
    if request.dbsession.query(Page).filter_by(name=pagename).count() > 0:
        next_url = request.route_url('edit_page', pagename=pagename)
        raise HTTPFound(location=next_url)
    return NewPage(pagename)

class NewPage(object):
    def __init__(self, pagename):
        self.pagename = pagename

    def __acl__(self):
        return [
            (Allow, 'role:editor', 'create'),
            (Allow, 'role:basic', 'create'),
        ]

def page_factory(request):
    pagename = request.matchdict['pagename']
    page = request.dbsession.query(Page).filter_by(name=pagename).first()
    if page is None:
        raise HTTPNotFound
    return PageResource(page)

class PageResource(object):
    def __init__(self, page):
        self.page = page

    def __acl__(self):
        return [
            (Allow, Everyone, 'view'),
            (Allow, 'role:editor', 'edit'),
            (Allow, str(self.page.creator_id), 'edit'),
        ]

The highlighted lines need to be edited or added.

The NewPage class has an __acl__ on it that returns a list of mappings from principal to permission. This defines who can do what with that resource. In our case we want to allow only those users with the principals of either role:editor or role:basic to have the create permission:

30
31
32
33
34
35
36
37
38
class NewPage(object):
    def __init__(self, pagename):
        self.pagename = pagename

    def __acl__(self):
        return [
            (Allow, 'role:editor', 'create'),
            (Allow, 'role:basic', 'create'),
        ]

The NewPage is loaded as the context of the add_page route by declaring a factory on the route:

18
19
    config.add_route('add_page', '/add_page/{pagename}',
                     factory=new_page_factory)

The PageResource class defines the ACL for a Page. It uses an actual Page object to determine who can do what to the page.

47
48
49
50
51
52
53
54
55
56
class PageResource(object):
    def __init__(self, page):
        self.page = page

    def __acl__(self):
        return [
            (Allow, Everyone, 'view'),
            (Allow, 'role:editor', 'edit'),
            (Allow, str(self.page.creator_id), 'edit'),
        ]

The PageResource is loaded as the context of the view_page and edit_page routes by declaring a factory on the routes:

17
18
19
20
21
    config.add_route('view_page', '/{pagename}', factory=page_factory)
    config.add_route('add_page', '/add_page/{pagename}',
                     factory=new_page_factory)
    config.add_route('edit_page', '/{pagename}/edit_page',
                     factory=page_factory)

Add view permissions

At this point we've modified our application to load the PageResource, including the actual Page model in the page_factory. The PageResource is now the context for all view_page and edit_page views. Similarly the NewPage will be the context for the add_page view.

Open the file tutorial/views/default.py.

First, you can drop a few imports that are no longer necessary:

5
6
7
from pyramid.httpexceptions import HTTPFound
from pyramid.view import view_config

Edit the view_page view to declare the view permission, and remove the explicit checks within the view:

18
19
20
21
22
23
@view_config(route_name='view_page', renderer='../templates/view.jinja2',
             permission='view')
def view_page(request):
    page = request.context.page

    def add_link(match):

The work of loading the page has already been done in the factory, so we can just pull the page object out of the PageResource, loaded as request.context. Our factory also guarantees we will have a Page, as it raises the HTTPNotFound exception if no Page exists, again simplifying the view logic.

Edit the edit_page view to declare the edit permission:

38
39
40
41
42
@view_config(route_name='edit_page', renderer='../templates/edit.jinja2',
             permission='edit')
def edit_page(request):
    page = request.context.page
    if 'form.submitted' in request.params:

Edit the add_page view to declare the create permission:

52
53
54
55
56
@view_config(route_name='add_page', renderer='../templates/edit.jinja2',
             permission='create')
def add_page(request):
    pagename = request.context.pagename
    if 'form.submitted' in request.params:

Note the pagename here is pulled off of the context instead of request.matchdict. The factory has done a lot of work for us to hide the actual route pattern.

The ACLs defined on each resource are used by the authorization policy to determine if any principal is allowed to have some permission. If this check fails (for example, the user is not logged in) then an HTTPForbidden exception will be raised automatically. Thus we're able to drop those exceptions and checks from the views themselves. Rather we've defined them in terms of operations on a resource.

The final tutorial/views/default.py should look like the following:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import cgi
import re
from docutils.core import publish_parts

from pyramid.httpexceptions import HTTPFound
from pyramid.view import view_config

from ..models import Page

# regular expression used to find WikiWords
wikiwords = re.compile(r"\b([A-Z]\w+[A-Z]+\w+)")

@view_config(route_name='view_wiki')
def view_wiki(request):
    next_url = request.route_url('view_page', pagename='FrontPage')
    return HTTPFound(location=next_url)

@view_config(route_name='view_page', renderer='../templates/view.jinja2',
             permission='view')
def view_page(request):
    page = request.context.page

    def add_link(match):
        word = match.group(1)
        exists = request.dbsession.query(Page).filter_by(name=word).all()
        if exists:
            view_url = request.route_url('view_page', pagename=word)
            return '<a href="%s">%s</a>' % (view_url, cgi.escape(word))
        else:
            add_url = request.route_url('add_page', pagename=word)
            return '<a href="%s">%s</a>' % (add_url, cgi.escape(word))

    content = publish_parts(page.data, writer_name='html')['html_body']
    content = wikiwords.sub(add_link, content)
    edit_url = request.route_url('edit_page', pagename=page.name)
    return dict(page=page, content=content, edit_url=edit_url)

@view_config(route_name='edit_page', renderer='../templates/edit.jinja2',
             permission='edit')
def edit_page(request):
    page = request.context.page
    if 'form.submitted' in request.params:
        page.data = request.params['body']
        next_url = request.route_url('view_page', pagename=page.name)
        return HTTPFound(location=next_url)
    return dict(
        pagename=page.name,
        pagedata=page.data,
        save_url=request.route_url('edit_page', pagename=page.name),
        )

@view_config(route_name='add_page', renderer='../templates/edit.jinja2',
             permission='create')
def add_page(request):
    pagename = request.context.pagename
    if 'form.submitted' in request.params:
        body = request.params['body']
        page = Page(name=pagename, data=body)
        page.creator = request.user
        request.dbsession.add(page)
        next_url = request.route_url('view_page', pagename=pagename)
        return HTTPFound(location=next_url)
    save_url = request.route_url('add_page', pagename=pagename)
    return dict(pagename=pagename, pagedata='', save_url=save_url)

Viewing the application in a browser

We can finally examine our application in a browser (See Start the application). Launch a browser and visit each of the following URLs, checking that the result is as expected:

  • http://localhost:6543/ invokes the view_wiki view. This always redirects to the view_page view of the FrontPage page object. It is executable by any user.
  • http://localhost:6543/FrontPage invokes the view_page view of the FrontPage page object. There is a "Login" link in the upper right corner while the user is not authenticated, else it is a "Logout" link when the user is authenticated.
  • http://localhost:6543/FrontPage/edit_page invokes the edit_page view for the FrontPage page object. It is executable by only the editor user. If a different user (or the anonymous user) invokes it, then a login form will be displayed. Supplying the credentials with the username editor and password editor will display the edit page form.
  • http://localhost:6543/add_page/SomePageName invokes the add_page view for a page. If the page already exists, then it redirects the user to the edit_page view for the page object. It is executable by either the editor or basic user. If a different user (or the anonymous user) invokes it, then a login form will be displayed. Supplying the credentials with either the username editor and password editor, or username basic and password basic, will display the edit page form.
  • http://localhost:6543/SomePageName/edit_page invokes the edit_page view for an existing page, or generates an error if the page does not exist. It is editable by the basic user if the page was created by that user in the previous step. If, instead, the page was created by the editor user, then the login page should be shown for the basic user.
  • After logging in (as a result of hitting an edit or add page and submitting the login form with the editor credentials), we'll see a "Logout" link in the upper right hand corner. When we click it, we're logged out, redirected back to the front page, and a "Login" link is shown in the upper right hand corner.