Download Install Tutorial Docs FAQ Tools WikiLicense Team IRC Planet Involvement Shop Book

root/branches/cherrypy-2.1/cherrypy/lib/csauthenticate.py

Revision 465 (checked in by fumanchu, 3 years ago)

Fixes for ticket #226.

Line 
1 """
2 Copyright (c) 2004, CherryPy Team (team@cherrypy.org)
3 All rights reserved.
4
5 Redistribution and use in source and binary forms, with or without modification,
6 are permitted provided that the following conditions are met:
7
8     * Redistributions of source code must retain the above copyright notice,
9       this list of conditions and the following disclaimer.
10     * Redistributions in binary form must reproduce the above copyright notice,
11       this list of conditions and the following disclaimer in the documentation
12       and/or other materials provided with the distribution.
13     * Neither the name of the CherryPy Team nor the names of its contributors
14       may be used to endorse or promote products derived from this software
15       without specific prior written permission.
16
17 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
18 ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
20 DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
21 FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
23 SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
24 CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
25 OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 """
28
29 import time, random
30 import cherrypy
31
32 from aspect import Aspect, STOP, CONTINUE
33
34 import warnings
35 warnings.warn("The CSAuthenticate module is deprecated. You can use the sessionauthenticate filter instead",
36       DeprecationWarning)
37
38 class CSAuthenticate(Aspect):
39     timeoutMessage = "Session timed out"
40     wrongLoginPasswordMessage = "Wrong login/password"
41     noCookieMessage = "No cookie"
42     logoutMessage = "You have been logged out"
43     sessionIdCookieName = "CherrySessionId"
44     timeout = 60 # in minutes
45
46     def notLoggedIn(self, message):
47         return STOP, self.loginScreen(message, cherrypy.request.browserUrl)
48
49     def _before(self, methodName, method):
50         # If the method is not exposed, don't do anything
51         if not getattr(method, 'exposed', None):
52             return CONTINUE, None
53
54         cherrypy.request.login = ''
55         # If the method is one of these 4, do not try to find out who is logged in
56         if methodName in ["loginScreen", "logoutScreen", "doLogin", "doLogout", "notLoggedIn"]:
57             return CONTINUE, None
58
59         # Check if a user is logged in:
60         #   - If they are, set request.login with the right value
61         #   - If not, return the login screen
62         if not cherrypy.request.simpleCookie.has_key(self.sessionIdCookieName):
63             # return STOP, self.loginScreen(self.noCookieMessage, cherrypy.request.browserUrl)
64             return self.notLoggedIn(self.noCookieMessage)
65         sessionId = cherrypy.request.simpleCookie[self.sessionIdCookieName].value
66         now=time.time()
67
68         # Check that session exists and hasn't timed out
69         timeout=0
70         if not cherrypy.request.sessionMap.has_key(sessionId):
71             # return STOP, self.loginScreen(self.noCookieMessage, cherrypy.request.browserUrl)
72             return self.notLoggedIn(self.noCookieMessage)
73         else:
74             login, expire = cherrypy.request.sessionMap[sessionId]
75             if expire < now: timeout=1
76             else:
77                 expire = now + self.timeout*60
78                 cherrypy.request.sessionMap[sessionId] = login, expire
79
80         if timeout:
81             # return STOP, self.loginScreen(self.timeoutMessage, cherrypy.request.browserUrl)
82             return self.notLoggedIn(self.timeoutMessage)
83
84         cherrypy.request.login = login
85         return CONTINUE, None
86
87     def checkLoginAndPassword(self, login, password):
88         if (login,password) == ('login','password'): return ''
89         return 'Wrong login/password'
90
91     def generateSessionId(self, sessionIdList):
92         choice="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
93         while 1:
94             sessionId=""
95             for dummy in range(20): sessionId += random.choice(choice)
96             if sessionId not in sessionIdList: return sessionId
97
98     def doLogin(self, login, password, fromPage):
99         # Check that login/password match
100         errorMsg = self.checkLoginAndPassword(login, password)
101         if errorMsg:
102             cherrypy.request.login = ''
103             return self.loginScreen(errorMsg, fromPage, login)
104         cherrypy.request.login = login
105         # Set session
106         newSessionId = self.generateSessionId(cherrypy.request.sessionMap.keys())
107         cherrypy.request.sessionMap[newSessionId] = login, time.time()+self.timeout*60
108        
109         cherrypy.response.simpleCookie[self.sessionIdCookieName] = newSessionId
110         cherrypy.response.simpleCookie[self.sessionIdCookieName]['path'] = '/'
111         cherrypy.response.simpleCookie[self.sessionIdCookieName]['max-age'] = 31536000
112         cherrypy.response.simpleCookie[self.sessionIdCookieName]['version'] = 1
113         cherrypy.response.status = "302 Found"
114         cherrypy.response.headerMap['Location'] = fromPage
115         return ""
116     doLogin.exposed = True
117
118     def doLogout(self):
119         try:
120             sessionId = cherrypy.request.simpleCookie[self.sessionIdCookieName].value
121             del cherrypy.request.sessionMap[sessionId]
122         except: pass
123        
124         cherrypy.response.simpleCookie[self.sessionIdCookieName] = ""
125         cherrypy.response.simpleCookie[self.sessionIdCookieName]['path'] = '/'
126         cherrypy.response.simpleCookie[self.sessionIdCookieName]['max-age'] = 0
127         cherrypy.response.simpleCookie[self.sessionIdCookieName]['version'] = 1
128         cherrypy.request.login = ''
129         cherrypy.response.status = "302 Found"
130         cherrypy.response.headerMap['Location'] = 'logoutScreen'
131         return ""
132     doLogout.exposed = True
133
134     def logoutScreen(self):
135         return self.loginScreen(self.logoutMessage, '/index') # TBC
136     logoutScreen.exposed = True
137
138     def loginScreen(self, message, fromPage, login=''):
139         return """
140         <html><body>
141             Message: %s
142             <form method="post" action="doLogin">
143                 Login: <input type=text name=login value="%s" size=10/><br/>
144                 Password: <input type=password name=password size=10/><br/>
145                 <input type=hidden name=fromPage value="%s"/><br/>
146                 <input type=submit/>
147             </form>
148         </body></html>
149         """ % (message, login, fromPage)
150     loginScreen.exposed = True
Note: See TracBrowser for help on using the browser.

Hosted by WebFaction

Log in as guest/cpguest to create tickets