Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
pyramid.pdf
Скачиваний:
10
Добавлен:
24.03.2015
Размер:
3.82 Mб
Скачать

37. SQLALCHEMY + URL DISPATCH WIKI TUTORIAL

37.6.6 Viewing the Application in a Browser

We can finally examine our application in a browser (See Starting the Application). The views we’ll try are as follows:

Visiting http://localhost:6543 in a browser invokes the view_wiki view. This always redirects to the view_page view of the FrontPage page object.

Visiting http://localhost:6543/FrontPage in a browser invokes the view_page view of the front page page object.

Visiting http://localhost:6543/FrontPage/edit_page in a browser invokes the edit view for the front page object.

Visiting http://localhost:6543/add_page/SomePageName in a browser invokes the add view for a page.

Try generating an error within the body of a view by adding code to the top of it that generates an exception (e.g. raise Exception(’Forced Exception’)). Then visit the error-raising view in a browser. You should see an interactive exception handler in the browser which allows you to examine values in a post-mortem mode.

37.7 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 possess a specific username (editor) to add and edit wiki pages but we’ll continue allowing anyone with access to the server to view pages.

We will do the following steps:

Add a root factory with an ACL (models.py).

Add an authentication policy and an authorization policy (__init__.py).

Add an authentication policy callback (new security.py module).

Add login and logout views (views.py).

Add permission declarations to the edit_page and add_page views (views.py).

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

Add a login template (new login.pt).

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

The source code for this tutorial stage can be browsed at http://github.com/Pylons/pyramid/tree/1.3- branch/docs/tutorials/wiki2/src/authorization/.

472

37.7. ADDING AUTHORIZATION

37.7.1 Adding A Root Factory

Open models.py and add the following statements:

1

2

3

4

5

6

7

8

9

from pyramid.security import ( Allow,

Everyone,

)

class RootFactory(object):

__acl__ = [ (Allow, Everyone, ’view’),

(Allow, ’group:editors’, ’edit’) ] def __init__(self, request):

pass

We’re going to start to use a custom root factory within our __init__.py file. The objects generated by the root factory will be used as the context of each request to our application. Those context objects will be decorated with security declarations. When we use a custom root factory to generate our contexts, we can begin to make use of the declarative security features of Pyramid.

We’ll modify our __init__.py, passing in a root factory to our Configurator constructor. We’ll point it at the new class we created inside our models.py file.

The RootFactory class we’ve just added will be used by Pyramid to construct a context object. The context is attached to the request object passed to our view callables as the context attribute.

The context object generated by our root factory will possess an __acl__ attribute that allows pyramid.security.Everyone (a special principal) to view all pages, while allowing only a principal named group:editors to edit and add pages. The __acl__ attribute attached to a context is interpreted specially by Pyramid as an access control list during view callable execution. See Assigning ACLs to your Resource Objects for more information about what an ACL represents.

latex-note.png

Although we don’t use the functionality here, the factory used to create route contexts may differ per-route as opposed to globally. See the factory argument to pyramid.config.Configurator.add_route() for more info.

We’ll pass the RootFactory we created in the step above in as the root_factory argument to a

Configurator.

473

37. SQLALCHEMY + URL DISPATCH WIKI TUTORIAL

37.7.2 Add an Authorization Policy and an Authentication Policy

We’re going to be making several changes to our __init__.py file which will help us configure an authorization policy.

For any Pyramid application to perform authorization, we need to add a security.py module (we’ll do that shortly) and we’ll need to change our __init__.py file to add an authentication policy and an authorization policy which uses the security.py file for a callback.

We’ll enable an AuthTktAuthenticationPolicy and an ACLAuthorizationPolicy to implement declarative security checking. Open tutorial/__init__.py and add these import statements:

1

2

3

from pyramid.authentication import AuthTktAuthenticationPolicy from pyramid.authorization import ACLAuthorizationPolicy

from tutorial.security import groupfinder

Now add those policies to the configuration:

1

2

3

4

5

6

7

authn_policy = AuthTktAuthenticationPolicy( ’sosecret’, callback=groupfinder)

authz_policy = ACLAuthorizationPolicy() config = Configurator(settings=settings,

root_factory=’tutorial.models.RootFactory’) config.set_authentication_policy(authn_policy) config.set_authorization_policy(authz_policy)

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 a groupfinder function in the current directory’s security.py file. We haven’t added that module yet, but we’re about to.

Viewing Your Changes

When we’re done configuring a root factory, adding a authentication and authorization policies, and adding routes for /login and /logout, your application’s __init__.py will look like this:

474

37.7. ADDING AUTHORIZATION

1 from pyramid.config import Configurator

2 from pyramid.authentication import AuthTktAuthenticationPolicy

3 from pyramid.authorization import ACLAuthorizationPolicy

4

5 from sqlalchemy import engine_from_config

6

7 from tutorial.security import groupfinder

8

9 from .models import DBSession

10

11def main(global_config, **settings):

12""" This function returns a Pyramid WSGI application.

13"""

14engine = engine_from_config(settings, ’sqlalchemy.’)

15DBSession.configure(bind=engine)

16authn_policy = AuthTktAuthenticationPolicy(

17’sosecret’, callback=groupfinder)

18authz_policy = ACLAuthorizationPolicy()

19config = Configurator(settings=settings,

20

root_factory=’tutorial.models.RootFactory’)

21config.set_authentication_policy(authn_policy)

22config.set_authorization_policy(authz_policy)

23config.add_static_view(’static’, ’static’, cache_max_age=3600)

24config.add_route(’view_wiki’, ’/’)

25config.add_route(’login’, ’/login’)

26config.add_route(’logout’, ’/logout’)

27config.add_route(’view_page’, ’/{pagename}’)

28config.add_route(’add_page’, ’/add_page/{pagename}’)

29config.add_route(’edit_page’, ’/{pagename}/edit_page’)

30config.scan()

31return config.make_wsgi_app()

37.7.3 Adding an authentication policy callback

Add a tutorial/security.py module within your package (in the same directory as __init__.py, views.py, etc.) with the following content:

1 USERS = {’editor’:’editor’,

2’viewer’:’viewer’}

3 GROUPS = {’editor’:[’group:editors’]}

4

5 def groupfinder(userid, request):

475

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]