~jhullu/pyshot/current

« back to all changes in this revision

Viewing changes to trunk/src/pyshot_server/pyshot/multiauth/filter.py

  • Committer: Jacques HULLU
  • Date: 2010-11-29 22:28:24 UTC
  • Revision ID: jacques@hullu.fr-20101129222824-317nrpjt6vks87dg
fix some bugs

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
import cherrypy
 
2
from cherrypy.lib.filter.basefilter import BaseFilter
 
3
from multiauth.auth import SecureResource
 
4
 
 
5
def loginScreen(targetPage, message=None):
 
6
    cherrypy.response.body = """
 
7
    <html>
 
8
    <head><title>Login</title></head>
 
9
    <body>
 
10
    <form action="%s" method="POST">
 
11
    Username: <input type="text" name="ma_username" /><br />
 
12
    Password: <input type="password" name="ma_password" /><br />
 
13
    <input value="Login" type="submit" />
 
14
    </form>
 
15
    </body>
 
16
    </html>
 
17
    """ % (targetPage,)
 
18
 
 
19
class MultiAuthFilter(BaseFilter):
 
20
    def __init__(self, unauthorizedPath, backend, frontend=loginScreen, 
 
21
                 username_arg='ma_username', password_arg='ma_password'):
 
22
        self.backend = backend
 
23
        self.frontend = frontend
 
24
        self.unauthorizedPath = unauthorizedPath
 
25
        self.username_arg = username_arg
 
26
        self.password_arg = password_arg
 
27
 
 
28
    def beforeMain(self):
 
29
        if (cherrypy.request.paramMap.has_key(self.username_arg) \
 
30
            and cherrypy.request.paramMap.has_key(self.password_arg)):
 
31
            # the user is trying to login
 
32
            username = cherrypy.request.paramMap.get(self.username_arg)
 
33
            password = cherrypy.request.paramMap.get(self.password_arg)
 
34
            authenticated, roles = self.backend.authenticate(username, password)
 
35
            if authenticated:
 
36
                cherrypy.session['roles'] = roles + [username, 'loggedIn']
 
37
            del cherrypy.request.paramMap[self.username_arg]
 
38
            del cherrypy.request.paramMap[self.password_arg]
 
39
                           
 
40
 
 
41
    def beforeFinalize(self):
 
42
        if isinstance(cherrypy.response.body, SecureResource):
 
43
            rsrc = cherrypy.response.body
 
44
            if not cherrypy.session.get('roles'):
 
45
                self.frontend(cherrypy.request.path)
 
46
                return
 
47
            matches = [role for role in rsrc.roles if role in cherrypy.session['roles']]
 
48
            if not matches:
 
49
                raise cherrypy.HTTPRedirect(self.unauthorizedPath)
 
50
            else:
 
51
                cherrypy.response.body = rsrc.callable(rsrc.instance,
 
52
                                                       *rsrc.callable_args,
 
53
                                                       **rsrc.callable_kwargs)
 
54
                
 
 
b'\\ No newline at end of file'