Adding authorization

Pyramid provides facilities for authentication and authorization. We'll make use of both features to provide security to our application. Our application currently allows anyone with access to the server to view, edit, and add pages to our wiki. We'll change that to allow only people who are members of a group named group:editors to add and edit wiki pages, but we'll continue allowing anyone with access to the server to view pages.

We will also add a login page and a logout link on all the pages. The login page will be shown when a user is denied access to any of the views that require permission, instead of a default "403 Forbidden" page.

We will implement the access control with the following steps:

Then we will add the login and logout features:

  • Add login and logout views (views.py).

  • Add a login template (login.pt).

  • Make the existing views return a logged_in flag to the renderer (views.py).

  • Add a "Logout" link to be shown when logged in and viewing or editing a page (view.pt, edit.pt).

Access control

Add dependencies

Just like in Defining Views, we need a new dependency. We need to add the bcrypt package, to our tutorial package's setup.py file by assigning this dependency to the requires parameter in the setup() function.

Open setup.py and edit it to look like the following:

 1import os
 2
 3from setuptools import setup, find_packages
 4
 5here = os.path.abspath(os.path.dirname(__file__))
 6with open(os.path.join(here, 'README.txt')) as f:
 7    README = f.read()
 8with open(os.path.join(here, 'CHANGES.txt')) as f:
 9    CHANGES = f.read()
10
11requires = [
12    'plaster_pastedeploy',
13    'pyramid >= 1.9a',
14    'pyramid_chameleon',
15    'pyramid_debugtoolbar',
16    'pyramid_retry',
17    'pyramid_tm',
18    'pyramid_zodbconn',
19    'transaction',
20    'ZODB3',
21    'waitress',
22    'docutils',
23    'bcrypt',
24]
25
26tests_require = [
27    'WebTest >= 1.3.1',  # py3 compat
28    'pytest>=3.7.4',
29    'pytest-cov',
30]
31
32setup(
33    name='tutorial',
34    version='0.0',
35    description='myproj',
36    long_description=README + '\n\n' + CHANGES,
37    classifiers=[
38        'Programming Language :: Python',
39        'Framework :: Pyramid',
40        'Topic :: Internet :: WWW/HTTP',
41        'Topic :: Internet :: WWW/HTTP :: WSGI :: Application',
42    ],
43    author='',
44    author_email='',
45    url='',
46    keywords='web pyramid pylons',
47    packages=find_packages(),
48    include_package_data=True,
49    zip_safe=False,
50    extras_require={
51        'testing': tests_require,
52    },
53    install_requires=requires,
54    entry_points={
55        'paste.app_factory': [
56            'main = tutorial:main',
57        ],
58    },
59)

Only the highlighted line needs to be added.

Do not forget to run pip install -e . just like in Running pip install -e ..

Note

We are using the bcrypt package from PyPI to hash our passwords securely. There are other one-way hash algorithms for passwords if bcrypt is an issue on your system. Just make sure that it's an algorithm approved for storing passwords versus a generic one-way hash.

Add users and groups

Create a new tutorial/security.py module with the following content:

 1import bcrypt
 2
 3
 4def hash_password(pw):
 5    hashed_pw = bcrypt.hashpw(pw.encode('utf-8'), bcrypt.gensalt())
 6    # return unicode instead of bytes because databases handle it better
 7    return hashed_pw.decode('utf-8')
 8
 9def check_password(expected_hash, pw):
10    if expected_hash is not None:
11        return bcrypt.checkpw(pw.encode('utf-8'), expected_hash.encode('utf-8'))
12    return False
13
14USERS = {'editor': hash_password('editor'),
15          'viewer': hash_password('viewer')}
16GROUPS = {'editor':['group:editors']}
17
18def groupfinder(userid, request):
19    if userid in USERS:
20        return GROUPS.get(userid, [])

The groupfinder function accepts a userid and a request and returns one of these values:

  • If userid exists in the system, it will return a sequence of group identifiers (or an empty sequence if the user isn't a member of any groups).

  • If the userid does not exist in the system, it will return None.

For example, groupfinder('editor', request ) returns ['group:editor'], groupfinder('viewer', request) returns [], and groupfinder('admin', request) returns None. We will use groupfinder() as an authentication policy "callback" that will provide the principal or principals for a user.

There are two helper methods that will help us later to authenticate users. The first is hash_password which takes a raw password and transforms it using bcrypt into an irreversible representation, a process known as "hashing". The second method, check_password, will allow us to compare the hashed value of the submitted password against the hashed value of the password stored in the user's record. If the two hashed values match, then the submitted password is valid, and we can authenticate the user.

We hash passwords so that it is impossible to decrypt and use them to authenticate in the application. If we stored passwords foolishly in clear text, then anyone with access to the database could retrieve any password to authenticate as any user.

In a production system, user and group data will most often be saved and come from a database, but here we use "dummy" data to represent user and groups sources.

Add an ACL

Open tutorial/models.py and add the following import statement near the top:

4from pyramid.security import (
5    Allow,
6    Everyone,
7    )
8

Add the following lines to the Wiki class:

 9class Wiki(PersistentMapping):
10    __name__ = None
11    __parent__ = None
12    __acl__ = [ (Allow, Everyone, 'view'),
13                (Allow, 'group:editors', 'edit') ]

We import Allow, an action that means that permission is allowed, and Everyone, a special principal that is associated to all requests. Both are used in the ACE entries that make up the ACL.

The ACL is a list that needs to be named __acl__ and be an attribute of a class. We define an ACL with two ACE entries: the first entry allows any user the view permission. The second entry allows the group:editors principal the edit permission.

The Wiki class that contains the ACL is the resource constructor for the root resource, which is a Wiki instance. The ACL is provided to each view in the context of the request as the context attribute.

It's only happenstance that we're assigning this ACL at class scope. An ACL can be attached to an object instance too; this is how "row level security" can be achieved in Pyramid applications. We actually need only one ACL for the entire system, however, because our security requirements are simple, so this feature is not demonstrated. See Assigning ACLs to Your Resource Objects for more information about what an ACL represents.

Add authentication and authorization policies

Open tutorial/__init__.py and add the highlighted import statements:

1from pyramid.config import Configurator
2from pyramid_zodbconn import get_connection
3
4from pyramid.authentication import AuthTktAuthenticationPolicy
5from pyramid.authorization import ACLAuthorizationPolicy
6
7from .models import appmaker
8from .security import groupfinder

Now add those policies to the configuration:

18    settings['tm.manager_hook'] = 'pyramid_tm.explicit_manager'
19    authn_policy = AuthTktAuthenticationPolicy(
20        'sosecret', callback=groupfinder, hashalg='sha512')
21    authz_policy = ACLAuthorizationPolicy()
22    with Configurator(settings=settings) as config:
23        config.set_authentication_policy(authn_policy)
24        config.set_authorization_policy(authz_policy)
25        config.include('pyramid_chameleon')

Only the highlighted lines need to be added.

We are enabling an AuthTktAuthenticationPolicy, which is based in an auth ticket that may be included in the request. We are also enabling an ACLAuthorizationPolicy, which uses an ACL to determine the allow or deny outcome for a view.

Note that the pyramid.authentication.AuthTktAuthenticationPolicy constructor accepts two arguments: secret and callback. secret is a string representing an encryption key used by the "authentication ticket" machinery represented by this policy: it is required. The callback is the groupfinder() function that we created before.

Add permission declarations

Open tutorial/views.py and add a permission='edit' parameter to the @view_config decorators for add_page() and edit_page():

@view_config(name='add_page', context='.models.Wiki',
             renderer='templates/edit.pt',
             permission='edit')
@view_config(name='edit_page', context='.models.Page',
             renderer='templates/edit.pt',
             permission='edit')

Only the highlighted lines, along with their preceding commas, need to be edited and added.

The result is that only users who possess the edit permission at the time of the request may invoke those two views.

Add a permission='view' parameter to the @view_config decorator for view_wiki() and view_page() as follows:

@view_config(context='.models.Wiki',
             permission='view')
@view_config(context='.models.Page', renderer='templates/view.pt',
             permission='view')

Only the highlighted lines, along with their preceding commas, need to be edited and added.

This allows anyone to invoke these two views.

We are done with the changes needed to control access. The changes that follow will add the login and logout feature.

Login, logout

Add login and logout views

We'll add a login view which renders a login form and processes the post from the login form, checking credentials.

We'll also add a logout view callable to our application and provide a link to it. This view will clear the credentials of the logged in user and redirect back to the front page.

Add the following import statements to the head of tutorial/views.py:

from pyramid.view import (
    view_config,
    forbidden_view_config,
    )

from pyramid.security import (
    remember,
    forget,
    )


from .security import USERS, check_password

All the highlighted lines need to be added or edited.

forbidden_view_config() will be used to customize the default 403 Forbidden page. remember() and forget() help to create and expire an auth ticket cookie.

Now add the login and logout views at the end of the file:

 80@view_config(context='.models.Wiki', name='login',
 81             renderer='templates/login.pt')
 82@forbidden_view_config(renderer='templates/login.pt')
 83def login(request):
 84    login_url = request.resource_url(request.context, 'login')
 85    referrer = request.url
 86    if referrer == login_url:
 87        referrer = '/'  # never use the login form itself as came_from
 88    came_from = request.params.get('came_from', referrer)
 89    message = ''
 90    login = ''
 91    password = ''
 92    if 'form.submitted' in request.params:
 93        login = request.params['login']
 94        password = request.params['password']
 95        if check_password(USERS.get(login), password):
 96            headers = remember(request, login)
 97            return HTTPFound(location=came_from,
 98                             headers=headers)
 99        message = 'Failed login'
100
101    return dict(
102        message=message,
103        url=request.application_url + '/login',
104        came_from=came_from,
105        login=login,
106        password=password,
107    )
108
109
110@view_config(context='.models.Wiki', name='logout')
111def logout(request):
112    headers = forget(request)
113    return HTTPFound(location=request.resource_url(request.context),
114                     headers=headers)

login() has two decorators:

  • a @view_config decorator which associates it with the login route and makes it visible when we visit /login,

  • a @forbidden_view_config decorator which turns it into a forbidden view. login() will be invoked when a user tries to execute a view callable for which they lack authorization. For example, if a user has not logged in and tries to add or edit a Wiki page, they will be shown the login form before being allowed to continue.

The order of these two view configuration decorators is unimportant.

logout() is decorated with a @view_config decorator which associates it with the logout route. It will be invoked when we visit /logout.

Add the login.pt Template

Create tutorial/templates/login.pt with the following content:

<!DOCTYPE html>
<html lang="${request.locale_name}">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="pyramid web application">
    <meta name="author" content="Pylons Project">
    <link rel="shortcut icon" href="${request.static_url('tutorial:static/pyramid-16x16.png')}">

    <title>Login - Pyramid tutorial wiki (based on
    TurboGears 20-Minute Wiki)</title>

    <!-- Bootstrap core CSS -->
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    <!-- Custom styles for this scaffold -->
    <link href="${request.static_url('tutorial:static/theme.css')}" rel="stylesheet">

    <!-- HTML5 shiv and Respond.js IE8 support of HTML5 elements and media queries -->
    <!--[if lt IE 9]>
      <script src="//oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js" integrity="sha384-0s5Pv64cNZJieYFkXYOTId2HMA2Lfb6q2nAcx2n0RTLUnCAoTTsS0nKEO27XyKcY" crossorigin="anonymous"></script>
      <script src="//oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js" integrity="sha384-ZoaMbDF+4LeFxg6WdScQ9nnR1QC2MIRxA1O9KWEXQwns1G8UNyIEZIQidzb0T1fo" crossorigin="anonymous"></script>
    <![endif]-->
  </head>

  <body>

    <div class="starter-template">
      <div class="container">
        <div class="row">
          <div class="col-md-2">
            <img class="logo img-responsive" src="${request.static_url('tutorial:static/pyramid.png')}" alt="pyramid web framework">
          </div>
          <div class="col-md-10">
            <div class="content">
              <p>
                <strong>
                  Login
                </strong><br>
                <span tal:replace="message"></span>
              </p>
              <form action="${url}" method="post">
                <input type="hidden" name="came_from" value="${came_from}">
                <div class="form-group">
                  <label for="login">Username</label>
                  <input type="text" name="login" value="${login}">
                </div>
                <div class="form-group">
                  <label for="password">Password</label>
                  <input type="password" name="password" value="${password}">
                </div>
                <div class="form-group">
                  <button type="submit" name="form.submitted" value="Log In" class="btn btn-default">Log In</button>
                </div>
              </form>
            </div>
          </div>
        </div>
        <div class="row">
          <div class="copyright">
            Copyright &copy; Pylons Project
          </div>
        </div>
      </div>
    </div>


    <!-- Bootstrap core JavaScript
    ================================================== -->
    <!-- Placed at the end of the document so the pages load faster -->
    <script src="//code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>
    <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
  </body>
</html>

The above template is referenced in the login view that we just added in views.py.

Return a logged_in flag to the renderer

Open tutorial/views.py again. Add a logged_in parameter to the return value of view_page(), add_page(), and edit_page() as follows:

    return dict(page=context, content=content, edit_url=edit_url,
                logged_in=request.authenticated_userid)
    return dict(page=page, save_url=save_url,
                logged_in=request.authenticated_userid)
    return dict(page=context,
                save_url=request.resource_url(context, 'edit_page'),
                logged_in=request.authenticated_userid)

Only the highlighted lines need to be added or edited.

The pyramid.request.Request.authenticated_userid() will be None if the user is not authenticated, or a userid if the user is authenticated.

Reviewing our changes

Our tutorial/__init__.py will look like this when we're done:

 1from pyramid.config import Configurator
 2from pyramid_zodbconn import get_connection
 3
 4from pyramid.authentication import AuthTktAuthenticationPolicy
 5from pyramid.authorization import ACLAuthorizationPolicy
 6
 7from .models import appmaker
 8from .security import groupfinder
 9
10def root_factory(request):
11    conn = get_connection(request)
12    return appmaker(conn.root())
13
14
15def main(global_config, **settings):
16    """ This function returns a Pyramid WSGI application.
17    """
18    settings['tm.manager_hook'] = 'pyramid_tm.explicit_manager'
19    authn_policy = AuthTktAuthenticationPolicy(
20        'sosecret', callback=groupfinder, hashalg='sha512')
21    authz_policy = ACLAuthorizationPolicy()
22    with Configurator(settings=settings) as config:
23        config.set_authentication_policy(authn_policy)
24        config.set_authorization_policy(authz_policy)
25        config.include('pyramid_chameleon')
26        config.include('pyramid_tm')
27        config.include('pyramid_retry')
28        config.include('pyramid_zodbconn')
29        config.set_root_factory(root_factory)
30        config.add_static_view('static', 'static', cache_max_age=3600)
31        config.scan()
32        return config.make_wsgi_app()

Only the highlighted lines need to be added or edited.

Our tutorial/models.py will look like this when we're done:

 1from persistent import Persistent
 2from persistent.mapping import PersistentMapping
 3
 4from pyramid.security import (
 5    Allow,
 6    Everyone,
 7    )
 8
 9class Wiki(PersistentMapping):
10    __name__ = None
11    __parent__ = None
12    __acl__ = [ (Allow, Everyone, 'view'),
13                (Allow, 'group:editors', 'edit') ]
14
15class Page(Persistent):
16    def __init__(self, data):
17        self.data = data
18
19def appmaker(zodb_root):
20    if 'app_root' not in zodb_root:
21        app_root = Wiki()
22        frontpage = Page('This is the front page')
23        app_root['FrontPage'] = frontpage
24        frontpage.__name__ = 'FrontPage'
25        frontpage.__parent__ = app_root
26        zodb_root['app_root'] = app_root
27    return zodb_root['app_root']

Only the highlighted lines need to be added or edited.

Our tutorial/views.py will look like this when we're done:

  1from docutils.core import publish_parts
  2import re
  3
  4from pyramid.httpexceptions import HTTPFound
  5
  6from pyramid.view import (
  7    view_config,
  8    forbidden_view_config,
  9    )
 10
 11from pyramid.security import (
 12    remember,
 13    forget,
 14    )
 15
 16
 17from .security import USERS, check_password
 18from .models import Page
 19
 20# regular expression used to find WikiWords
 21wikiwords = re.compile(r"\b([A-Z]\w+[A-Z]+\w+)")
 22
 23@view_config(context='.models.Wiki',
 24             permission='view')
 25def view_wiki(context, request):
 26    return HTTPFound(location=request.resource_url(context, 'FrontPage'))
 27
 28@view_config(context='.models.Page', renderer='templates/view.pt',
 29             permission='view')
 30def view_page(context, request):
 31    wiki = context.__parent__
 32
 33    def check(match):
 34        word = match.group(1)
 35        if word in wiki:
 36            page = wiki[word]
 37            view_url = request.resource_url(page)
 38            return '<a href="%s">%s</a>' % (view_url, word)
 39        else:
 40            add_url = request.application_url + '/add_page/' + word
 41            return '<a href="%s">%s</a>' % (add_url, word)
 42
 43    content = publish_parts(context.data, writer_name='html')['html_body']
 44    content = wikiwords.sub(check, content)
 45    edit_url = request.resource_url(context, 'edit_page')
 46    return dict(page=context, content=content, edit_url=edit_url,
 47                logged_in=request.authenticated_userid)
 48
 49@view_config(name='add_page', context='.models.Wiki',
 50             renderer='templates/edit.pt',
 51             permission='edit')
 52def add_page(context, request):
 53    pagename = request.subpath[0]
 54    if 'form.submitted' in request.params:
 55        body = request.params['body']
 56        page = Page(body)
 57        page.__name__ = pagename
 58        page.__parent__ = context
 59        context[pagename] = page
 60        return HTTPFound(location=request.resource_url(page))
 61    save_url = request.resource_url(context, 'add_page', pagename)
 62    page = Page('')
 63    page.__name__ = pagename
 64    page.__parent__ = context
 65    return dict(page=page, save_url=save_url,
 66                logged_in=request.authenticated_userid)
 67
 68@view_config(name='edit_page', context='.models.Page',
 69             renderer='templates/edit.pt',
 70             permission='edit')
 71def edit_page(context, request):
 72    if 'form.submitted' in request.params:
 73        context.data = request.params['body']
 74        return HTTPFound(location=request.resource_url(context))
 75
 76    return dict(page=context,
 77                save_url=request.resource_url(context, 'edit_page'),
 78                logged_in=request.authenticated_userid)
 79
 80@view_config(context='.models.Wiki', name='login',
 81             renderer='templates/login.pt')
 82@forbidden_view_config(renderer='templates/login.pt')
 83def login(request):
 84    login_url = request.resource_url(request.context, 'login')
 85    referrer = request.url
 86    if referrer == login_url:
 87        referrer = '/'  # never use the login form itself as came_from
 88    came_from = request.params.get('came_from', referrer)
 89    message = ''
 90    login = ''
 91    password = ''
 92    if 'form.submitted' in request.params:
 93        login = request.params['login']
 94        password = request.params['password']
 95        if check_password(USERS.get(login), password):
 96            headers = remember(request, login)
 97            return HTTPFound(location=came_from,
 98                             headers=headers)
 99        message = 'Failed login'
100
101    return dict(
102        message=message,
103        url=request.application_url + '/login',
104        came_from=came_from,
105        login=login,
106        password=password,
107    )
108
109
110@view_config(context='.models.Wiki', name='logout')
111def logout(request):
112    headers = forget(request)
113    return HTTPFound(location=request.resource_url(request.context),
114                     headers=headers)

Only the highlighted lines need to be added or edited.

Our tutorial/templates/edit.pt template will look like this when we're done:

 1<!DOCTYPE html>
 2<html lang="${request.locale_name}">
 3  <head>
 4    <meta charset="utf-8">
 5    <meta http-equiv="X-UA-Compatible" content="IE=edge">
 6    <meta name="viewport" content="width=device-width, initial-scale=1.0">
 7    <meta name="description" content="pyramid web application">
 8    <meta name="author" content="Pylons Project">
 9    <link rel="shortcut icon" href="${request.static_url('tutorial:static/pyramid-16x16.png')}">
10
11    <title>${page.__name__} - Pyramid tutorial wiki (based on
12    TurboGears 20-Minute Wiki)</title>
13
14    <!-- Bootstrap core CSS -->
15    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
16
17    <!-- Custom styles for this scaffold -->
18    <link href="${request.static_url('tutorial:static/theme.css')}" rel="stylesheet">
19
20    <!-- HTML5 shiv and Respond.js IE8 support of HTML5 elements and media queries -->
21    <!--[if lt IE 9]>
22      <script src="//oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js" integrity="sha384-0s5Pv64cNZJieYFkXYOTId2HMA2Lfb6q2nAcx2n0RTLUnCAoTTsS0nKEO27XyKcY" crossorigin="anonymous"></script>
23      <script src="//oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js" integrity="sha384-ZoaMbDF+4LeFxg6WdScQ9nnR1QC2MIRxA1O9KWEXQwns1G8UNyIEZIQidzb0T1fo" crossorigin="anonymous"></script>
24    <![endif]-->
25  </head>
26  <body>
27
28    <div class="starter-template">
29      <div class="container">
30        <div class="row">
31          <div class="col-md-2">
32            <img class="logo img-responsive" src="${request.static_url('tutorial:static/pyramid.png')}" alt="pyramid web framework">
33          </div>
34          <div class="col-md-10">
35            <div class="content">
36              <p tal:condition="logged_in" class="pull-right">
37                <a href="${request.application_url}/logout">Logout</a>
38              </p>
39              <p>
40                  Editing <strong><span tal:replace="page.__name__">
41                  Page Name Goes Here</span></strong>
42              </p>
43              <p>You can return to the
44                <a href="${request.application_url}">FrontPage</a>.
45              </p>
46              <form action="${save_url}" method="post">
47                <div class="form-group">
48                  <textarea class="form-control" name="body" tal:content="page.data" rows="10" cols="60"></textarea>
49                </div>
50                <div class="form-group">
51                  <button type="submit" name="form.submitted" value="Save" class="btn btn-default">Save</button>
52                </div>
53              </form>
54            </div>
55          </div>
56        </div>
57        <div class="row">
58          <div class="copyright">
59            Copyright &copy; Pylons Project
60          </div>
61        </div>
62      </div>
63    </div>
64
65
66    <!-- Bootstrap core JavaScript
67    ================================================== -->
68    <!-- Placed at the end of the document so the pages load faster -->
69    <script src="//code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>
70    <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
71  </body>
72</html>

Only the highlighted lines need to be added or edited.

Our tutorial/templates/view.pt template will look like this when we're done:

 1<!DOCTYPE html>
 2<html lang="${request.locale_name}">
 3  <head>
 4    <meta charset="utf-8">
 5    <meta http-equiv="X-UA-Compatible" content="IE=edge">
 6    <meta name="viewport" content="width=device-width, initial-scale=1.0">
 7    <meta name="description" content="pyramid web application">
 8    <meta name="author" content="Pylons Project">
 9    <link rel="shortcut icon" href="${request.static_url('tutorial:static/pyramid-16x16.png')}">
10
11    <title>${page.__name__} - Pyramid tutorial wiki (based on
12    TurboGears 20-Minute Wiki)</title>
13
14    <!-- Bootstrap core CSS -->
15    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
16
17    <!-- Custom styles for this scaffold -->
18    <link href="${request.static_url('tutorial:static/theme.css')}" rel="stylesheet">
19
20    <!-- HTML5 shiv and Respond.js IE8 support of HTML5 elements and media queries -->
21    <!--[if lt IE 9]>
22      <script src="//oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js" integrity="sha384-0s5Pv64cNZJieYFkXYOTId2HMA2Lfb6q2nAcx2n0RTLUnCAoTTsS0nKEO27XyKcY" crossorigin="anonymous"></script>
23      <script src="//oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js" integrity="sha384-ZoaMbDF+4LeFxg6WdScQ9nnR1QC2MIRxA1O9KWEXQwns1G8UNyIEZIQidzb0T1fo" crossorigin="anonymous"></script>
24    <![endif]-->
25  </head>
26  <body>
27
28    <div class="starter-template">
29      <div class="container">
30        <div class="row">
31          <div class="col-md-2">
32            <img class="logo img-responsive" src="${request.static_url('tutorial:static/pyramid.png')}" alt="pyramid web framework">
33          </div>
34          <div class="col-md-10">
35            <div class="content">
36              <p tal:condition="logged_in" class="pull-right">
37                <a href="${request.application_url}/logout">Logout</a>
38              </p>
39              <div tal:replace="structure content">
40                Page text goes here.
41              </div>
42              <p>
43                <a tal:attributes="href edit_url" href="">
44                  Edit this page
45                </a>
46              </p>
47              <p>
48                  Viewing <strong><span tal:replace="page.__name__">
49                  Page Name Goes Here</span></strong>
50              </p>
51              <p>You can return to the
52                <a href="${request.application_url}">FrontPage</a>.
53              </p>
54            </div>
55          </div>
56        </div>
57        <div class="row">
58          <div class="copyright">
59            Copyright &copy; Pylons Project
60          </div>
61        </div>
62      </div>
63    </div>
64
65
66    <!-- Bootstrap core JavaScript
67    ================================================== -->
68    <!-- Placed at the end of the document so the pages load faster -->
69    <script src="//code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>
70    <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
71  </body>
72</html>

Only the highlighted lines need to be added or edited.

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 resource. It is executable by any user.

  • http://localhost:6543/FrontPage invokes the view_page view of the FrontPage Page resource. This is because it's the default view (a view without a name) for Page resources. It is executable by any user.

  • http://localhost:6543/FrontPage/edit_page invokes the edit view for the FrontPage object. It is executable by only the editor user. If a different user (or the anonymous user) invokes it, a login form will be displayed. Supplying the credentials with the username editor, password editor will display the edit page form.

  • http://localhost:6543/add_page/SomePageName invokes the add view for a page. It is executable by only the editor user. If a different user (or the anonymous user) invokes it, a login form will be displayed. Supplying the credentials with the username editor, password editor will display the edit page form.

  • 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, and redirected back to the front page.