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

37. SQLALCHEMY + URL DISPATCH WIKI TUTORIAL

6

7

if userid in USERS:

return GROUPS.get(userid, [])

The groupfinder function defined here is an authentication policy “callback”; it is a callable that accepts a userid and a request. If the userid exists in the system, the callback 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, the callback will return None. In a production system, user and group data will most often come from a database, but here we use “dummy” data to represent user and groups sources. Note that the editor user is a member of the group:editors group in our dummy group data (the GROUPS data structure).

We’ve given the editor user membership to the group:editors by mapping him to this group in the GROUPS data structure (GROUPS = {’editor’:[’group:editors’]}). Since the groupfinder function consults the GROUPS data structure, this will mean that, as a result of the ACL attached to the context object returned by the root factory, and the permission associated with the add_page and edit_page views, the editor user should be able to add and edit pages.

37.7.4 Adding Login and Logout Views

To our views.py we’ll add a login view callable 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.

The login view callable will look something like this:

1

@view_config(route_name=’login’, renderer=’templates/login.pt’)

2

@forbidden_view_config(renderer=’templates/login.pt’)

3

def login(request):

4

login_url = request.route_url(’login’)

5referrer = request.url

6if referrer == login_url:

7

referrer = ’/’ # never use the login form itself as came_from

8

came_from

= request.params.get(’came_from’, referrer)

9

message =

’’

10

login = ’’

 

11

password = ’’

12

if ’form.submitted’ in request.params:

13

login

= request.params[’login’]

14

password = request.params[’password’]

476

37.7. ADDING AUTHORIZATION

15

16

17

18

19

20

21

22

23

24

25

26

27

if USERS.get(login) == password: headers = remember(request, login)

return HTTPFound(location = came_from, headers = headers)

message = ’Failed login’

return dict(

message = message,

url = request.application_url + ’/login’, came_from = came_from,

login = login, password = password,

)

The logout view callable will look something like this:

1 @view_config(route_name=’logout’) 2 def logout(request):

3headers = forget(request)

4return HTTPFound(location = request.route_url(’view_wiki’),

5

headers = headers)

The login view callable is decorated with two decorators, a @view_config decorator, which associates it with the login route, and a @forbidden_view_config decorator which turns it in to an exception view. The one which associates it with the login route makes it visible when we visit /login. The other one makes it a forbidden view. The forbidden view is displayed whenever Pyramid or your application raises an pyramid.httpexceptions.HTTPForbidden exception. In this case, we’ll be relying on the forbidden view to show the login form whenver someone attempts to execute an action which they’re not yet authorized to perform.

The logout view callable is decorated with a @view_config decorator which associates it with the logout route. This makes it visible when we visit /logout.

We’ll need to import some stuff to service the needs of these two functions: the pyramid.view.forbidden_view_config class, a number of values from the pyramid.security module, and a value from our newly added tutorial.security package. Add the following import statements to the head of the views.py file:

1

2

3

4

from pyramid.view import ( view_config, forbidden_view_config,

)

5

477

37. SQLALCHEMY + URL DISPATCH WIKI TUTORIAL

6

7

8

9

10

11

12

from pyramid.security import ( remember,

forget, authenticated_userid,

)

from .security import USERS

37.7.5 Changing Existing Views

Add permision declarations

Then we need to change each of our view_page, edit_page and add_page view callables in views.py. Within each of these views, we’ll need to pass a “logged in” parameter to its template. We’ll add something like this to each view body:

1

2

from pyramid.security import authenticated_userid logged_in = authenticated_userid(request)

Return a logged_in flag to the renderer

We’ll then change the return value of these views to pass the resulting logged_in value to the template, e.g.:

1

2

3

4

return dict(page = page, content = content,

logged_in = logged_in, edit_url = edit_url)

We’ll also need to add a permission value to the @view_config decorator for each of the add_page and edit_page view callables. For each, we’ll add permission=’edit’, for example:

1

2

@view_config(route_name=’edit_page’, renderer=’templates/edit.pt’, permission=’edit’)

478

37.7. ADDING AUTHORIZATION

See the permission=’edit’ we added there? This indicates that the view callables which these views reference cannot be invoked without the authenticated user possessing the edit permission with respect to the current context.

Adding these permission arguments causes Pyramid to make the assertion that only users who possess the effective edit permission at the time of the request may invoke those two views. We’ve granted the group:editors principal the edit permission in the root factory via its ACL, so only a user who is a member of the group named group:editors will be able to invoke the views associated with the add_page or edit_page routes.

37.7.6 Adding the login.pt Template

Add a login.pt template to your templates directory. It’s referred to within the login view we just added to views.py.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" xmlns:tal="http://xml.zope.org/namespaces/tal">

<head>

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

<meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/> <meta name="keywords" content="python web application" />

<meta name="description" content="pyramid web application" /> <link rel="shortcut icon"

href="${request.static_url(’tutorial:static/favicon.ico’)}" /> <link rel="stylesheet"

href="${request.static_url(’tutorial:static/pylons.css’)}" type="text/css" media="screen" charset="utf-8" />

<!--[if lte IE 6]> <link rel="stylesheet"

href="${request.static_url(’tutorial:static/ie6.css’)}" type="text/css" media="screen" charset="utf-8" />

<![endif]-->

</head>

<body>

<div id="wrap">

<div id="top-small">

<div class="top-small align-center">

<div>

<img width="220" height="50" alt="pyramid" src="${request.static_url(’tutorial:static/pyramid-small.png’)}" />

</div>

479

37. SQLALCHEMY + URL DISPATCH WIKI TUTORIAL

</div>

</div>

<div id="middle">

<div class="middle align-right">

<div id="left" class="app-welcome align-left"> <b>Login</b><br/>

<span tal:replace="message"/>

</div>

<div id="right" class="app-welcome align-right"></div>

</div>

</div>

<div id="bottom">

<div class="bottom">

<form action="${url}" method="post">

<input type="hidden" name="came_from" value="${came_from}"/> <input type="text" name="login" value="${login}"/><br/> <input type="password" name="password"

value="${password}"/><br/>

<input type="submit" name="form.submitted" value="Log In"/>

</form>

</div>

</div>

</div>

<div id="footer"> <div class="footer"

>© Copyright 2008-2011, Agendaless Consulting.</div>

</div>

</body>

</html>

37.7.7 Add a “Logout” link when logged in

We’ll also need to change our edit.pt and view.pt templates to display a “Logout” link if someone is logged in. This link will invoke the logout view.

To do so we’ll add this to both templates within the <div id="right" class="app-welcome align-right"> div:

<span tal:condition="logged_in">

<a href="${request.application_url}/logout">Logout</a>

</span>

480

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