This repository has been archived by the owner on Oct 12, 2017. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 15
/
AuthenticationAndAccessRestrictions
320 lines (247 loc) · 11.3 KB
/
AuthenticationAndAccessRestrictions
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
= Simple authentication and access restrictions helpers =
This small module provides CherryPy apps with facilities to specify in configuration and/or with decorators that specfic access restrictions apply to parts of the site. If those restrictions are not met, a user is redirect to a login page.
This is not meant to be a standalone module, just an example that you would include in your project and modify/extend to suit your needs.
Usage example is included below.
{{{
#!python
# -*- encoding: UTF-8 -*-
#
# Form based authentication for CherryPy. Requires the
# Session tool to be loaded.
#
import cherrypy
SESSION_KEY = '_cp_username'
def check_credentials(username, password):
"""Verifies credentials for username and password.
Returns None on success or a string describing the error on failure"""
# Adapt to your needs
if username in ('joe', 'steve') and password == 'secret':
return None
else:
return u"Incorrect username or password."
# An example implementation which uses an ORM could be:
# u = User.get(username)
# if u is None:
# return u"Username %s is unknown to me." % username
# if u.password != md5.new(password).hexdigest():
# return u"Incorrect password"
def check_auth(*args, **kwargs):
"""A tool that looks in config for 'auth.require'. If found and it
is not None, a login is required and the entry is evaluated as a list of
conditions that the user must fulfill"""
conditions = cherrypy.request.config.get('auth.require', None)
if conditions is not None:
username = cherrypy.session.get(SESSION_KEY)
if username:
cherrypy.request.login = username
for condition in conditions:
# A condition is just a callable that returns true or false
if not condition():
raise cherrypy.HTTPRedirect("/auth/login")
else:
raise cherrypy.HTTPRedirect("/auth/login")
cherrypy.tools.auth = cherrypy.Tool('before_handler', check_auth)
def require(*conditions):
"""A decorator that appends conditions to the auth.require config
variable."""
def decorate(f):
if not hasattr(f, '_cp_config'):
f._cp_config = dict()
if 'auth.require' not in f._cp_config:
f._cp_config['auth.require'] = []
f._cp_config['auth.require'].extend(conditions)
return f
return decorate
# Conditions are callables that return True
# if the user fulfills the conditions they define, False otherwise
#
# They can access the current username as cherrypy.request.login
#
# Define those at will however suits the application.
def member_of(groupname):
def check():
# replace with actual check if <username> is in <groupname>
return cherrypy.request.login == 'joe' and groupname == 'admin'
return check
def name_is(reqd_username):
return lambda: reqd_username == cherrypy.request.login
# These might be handy
def any_of(*conditions):
"""Returns True if any of the conditions match"""
def check():
for c in conditions:
if c():
return True
return False
return check
# By default all conditions are required, but this might still be
# needed if you want to use it inside of an any_of(...) condition
def all_of(*conditions):
"""Returns True if all of the conditions match"""
def check():
for c in conditions:
if not c():
return False
return True
return check
# Controller to provide login and logout actions
class AuthController(object):
def on_login(self, username):
"""Called on successful login"""
def on_logout(self, username):
"""Called on logout"""
def get_loginform(self, username, msg="Enter login information", from_page="/"):
return """<html><body>
<form method="post" action="/auth/login">
<input type="hidden" name="from_page" value="%(from_page)s" />
%(msg)s<br />
Username: <input type="text" name="username" value="%(username)s" /><br />
Password: <input type="password" name="password" /><br />
<input type="submit" value="Log in" />
</body></html>""" % locals()
@cherrypy.expose
def login(self, username=None, password=None, from_page="/"):
if username is None or password is None:
return self.get_loginform("", from_page=from_page)
error_msg = check_credentials(username, password)
if error_msg:
return self.get_loginform(username, error_msg, from_page)
else:
cherrypy.session[SESSION_KEY] = cherrypy.request.login = username
self.on_login(username)
raise cherrypy.HTTPRedirect(from_page or "/")
@cherrypy.expose
def logout(self, from_page="/"):
sess = cherrypy.session
username = sess.get(SESSION_KEY, None)
sess[SESSION_KEY] = None
if username:
cherrypy.request.login = None
self.on_logout(username)
raise cherrypy.HTTPRedirect(from_page or "/")
}}}
The developer must at least modify check_credentials to suit whatever means your applications has for matching usernames to passwords. The {{{member_of}}} condition also should be altered in lieu with your user/groups model if you have one.
You'll also probably want to customize the methods in {{{AuthController}}}.
== How it works ==
The {{{check_auth}}} function runs for every request before the handler, but after the handler has been choosen by the dispatcher. It examines {{{cherrypy.request.config}}} for an entry named {{{auth.require}}}. If that entry is not None, a valid login is required. Furthermore, it is evaluated as a list of conditions.
Each condition is a callable that returns True or False depending on if the user meets the condition. A condition can get the current username from {{{cherrypy.request.login}}}. If any of the conditions are not met, the user is redirected to the login page.
Here is an example of how to use this, given that the above is saved in {{{auth.py}}}:
{{{
#!python
import cherrypy
from auth import AuthController, require, member_of, name_is
class RestrictedArea:
# all methods in this controller (and subcontrollers) is
# open only to members of the admin group
_cp_config = {
'auth.require': [member_of('admin')]
}
@cherrypy.expose
def index(self):
return """This is the admin only area."""
class Root:
_cp_config = {
'tools.sessions.on': True,
'tools.auth.on': True
}
auth = AuthController()
restricted = RestrictedArea()
@cherrypy.expose
@require()
def index(self):
return """This page only requires a valid login."""
@cherrypy.expose
def open(self):
return """This page is open to everyone"""
@cherrypy.expose
@require(name_is("joe"))
def only_for_joe(self):
return """Hello Joe - this page is available to you only"""
# This is only available if the user name is joe _and_ he's in group admin
@cherrypy.expose
@require(name_is("joe"))
@require(member_of("admin")) # equivalent: @require(name_is("joe"), member_of("admin"))
def only_for_joe_admin(self):
return """Hello Joe Admin - this page is available to you only"""
if __name__ == '__main__':
cherrypy.quickstart(Root())
}}}
Hope someone finds it useful..
For any questions, you'll find me on #cherrypy or at arnarbi -at- gmail
-- Arnar Birgisson
----
Here is slight modification of code so that after loging user is redirected to page he requested
{{{
#!python
import urllib
def check_auth(*args, **kwargs):
"""A tool that looks in config for 'auth.require'. If found and it
is not None, a login is required and the entry is evaluated as alist of
conditions that the user must fulfill"""
conditions = cherrypy.request.config.get('auth.require', None)
# format GET params
get_parmas = urllib.quote(cherrypy.request.request_line.split()[1])
if conditions is not None:
username = cherrypy.session.get(SESSION_KEY)
if username:
cherrypy.request.login = username
for condition in conditions:
# A condition is just a callable that returns true orfalse
if not condition():
# Send old page as from_page parameter
raise cherrypy.HTTPRedirect("/auth/login?from_page=%s" % get_parmas)
else:
# Send old page as from_page parameter
raise cherrypy.HTTPRedirect("/auth/login?from_page=%s" %get_parmas)
}}}
-- Ivan
----
I think line 127 of the example code should contain 'cherrypy.session.regenerate()', to prevent [https://secure.wikimedia.org/wikipedia/en/wiki/Session_fixation session fixation] attacks. In the current code, the SID exists before the user logs in and is kept after he is logged in.
That part of the code then looks as follows:
{{{
#!python
@cherrypy.expose
def login(self, username=None, password=None, from_page="/"):
if username is None or password is None:
return self.get_loginform("", from_page=from_page)
error_msg = check_credentials(username, password)
if error_msg:
return self.get_loginform(username, error_msg, from_page)
else:
cherrypy.session.regenerate()
cherrypy.session[SESSION_KEY] = cherrypy.request.login = username
self.on_login(username)
raise cherrypy.HTTPRedirect(from_page or "/")
}}}
-- Bram Bonné
----
Redirecting to the login page for insufficient privileges is probably not what you want to happen, if someone has an idea on how to include the redirect as part of the conditions please share. For example you have a member of group condition and someone posts a group link in an open area, you don't want people getting a login loop attempting to click on it and not knowing whats happening.
-- Mark
----
For a simple CAS Authentication Client you can visit this page[http://tools.cherrypy.org/wiki/CASAuthentication].
--Marc
----
The example code contains XSS vulnerability: DONT USE IT!!!
/auth/login?from_page=" /><script>alert('XSS' + document.cookie);</script><
(URLencodet of course)
--spaceone
----
If I understand things correctly the XSS vulnerability mentioned above, and another one using "username", can be prevented e.g. by:
{{{
from cgi import escape
}}}
{{{
def get_loginform(self, username, msg="Enter login information", from_page="/"):
username=escape(username, True)
from_page=escape(from_page, True)
return """<html><body>
<form method="post" action="/auth/login">
<input type="hidden" name="from_page" value="%(from_page)s" />
%(msg)s<br />
Username: <input type="text" name="username" value="%(username)s" /><br />
Password: <input type="password" name="password" /><br />
<input type="submit" value="Log in" />
</body></html>""" % locals()
}}}
Please correct me if I'm wrong
--motoz