KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > atlassian > seraph > auth > DefaultAuthenticator


1 /*
2  * Created by IntelliJ IDEA.
3  * User: Administrator
4  * Date: 26/02/2002
5  * Time: 10:27:07
6  * To change template for new class use
7  * Code Style | Class Templates options (Tools | IDE Options).
8  */

9 package com.atlassian.seraph.auth;
10
11 import com.atlassian.seraph.config.SecurityConfig;
12 import com.atlassian.seraph.config.SecurityConfigFactory;
13 import com.atlassian.seraph.util.CookieUtils;
14 import com.atlassian.seraph.interceptor.LogoutInterceptor;
15 import com.opensymphony.user.UserManager;
16 import com.opensymphony.user.EntityNotFoundException;
17 import com.opensymphony.user.User;
18 import org.apache.log4j.Category;
19
20 import javax.servlet.http.Cookie JavaDoc;
21 import javax.servlet.http.HttpServletRequest JavaDoc;
22 import javax.servlet.http.HttpServletResponse JavaDoc;
23 import java.util.List JavaDoc;
24 import java.util.Iterator JavaDoc;
25 import java.util.Map JavaDoc;
26 import java.util.LinkedList JavaDoc;
27 import java.security.Principal JavaDoc;
28
29 /**
30  * This authenticator stores the currently logged in user in the session as OSUser User objects.
31  *
32  * It also provides for cookie logins and creates cookies if needed.
33  *
34  * Includes code from Jive 1.2.4 (released under the Apache license)
35  */

36 public class DefaultAuthenticator extends AbstractAuthenticator
37 {
38     private String JavaDoc loginCookieKey;
39
40     private static final Category log = Category.getInstance(DefaultAuthenticator.class);
41
42     /**
43      * The key used to store the user object in the session
44      */

45     public static String JavaDoc LOGGED_IN_KEY = "seraph_defaultauthenticator_user";
46
47     /**
48      * The key used to indicate that the user has logged out and session regarding of it containing a cookie is not
49      * logged in.
50      */

51     public static String JavaDoc LOGGED_OUT_KEY = "seraph_defaultauthenticator_logged_out_user";
52
53     // the age of the autologin cookie - default = 1 year (in seconds)
54
private static int AUTOLOGIN_COOKIE_AGE = 365 * 24 * 60 * 60;
55
56     public void init(Map JavaDoc params, SecurityConfig config)
57     {
58         log.debug(this.getClass().getName()+" $Revision: 1.11 $ initializing");
59         super.init(params, config);
60         this.loginCookieKey = config.getLoginCookieKey();
61     }
62
63     /** @deprecated Use {@link RoleMapper} directly */
64     public boolean isUserInRole(HttpServletRequest JavaDoc request, String JavaDoc role)
65     {
66         return getRoleMapper().hasRole(getUser(request), request, role);
67     }
68
69     /**
70      * Tries to authenticate a user (via OSUser). If successful, sets a session attribute and cookie indicating
71      * their logged-in status.
72      * @return Whether the user was authenticated. This base implementation returns false if any errors occur, rather
73      * than throw an exception.
74      */

75     public boolean login(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response, String JavaDoc username, String JavaDoc password, boolean cookie) throws AuthenticatorException
76     {
77         Principal JavaDoc user = getUser(username);
78
79         // check that they can login (they have the USE permission or ADMINISTER permission)
80
if (user == null)
81         {
82             log.info("Cannot login user '" + username + "' as they do not exist.");
83         }
84         else
85         {
86             boolean authenticated = authenticate(user, password);
87             if (authenticated)
88             {
89                 request.getSession().setAttribute(LOGGED_IN_KEY, user);
90                 request.getSession().setAttribute(LOGGED_OUT_KEY, null);
91
92                 if (getRoleMapper().canLogin(user, request))
93                 {
94                     if (cookie && response != null)
95                     {
96                         CookieUtils.setCookie(request, response, getLoginCookieKey(), CookieUtils.encodePasswordCookie(username, password, getConfig().getCookieEncoding()), AUTOLOGIN_COOKIE_AGE, getCookiePath(request));
97                     }
98                     return true;
99                 }
100                 else
101                 {
102                     request.getSession().removeAttribute(LOGGED_IN_KEY);
103                 }
104             }
105             else
106             {
107                 log.info("Cannot login user '" + username + "' as they used an incorrect password");
108             }
109         }
110
111
112         if (response != null && CookieUtils.getCookie(request, getLoginCookieKey()) != null)
113         {
114             log.warn("User: " + username + " tried to login but they do not have USE permission or weren't found. Deleting cookie.");
115
116             try
117             {
118                 CookieUtils.invalidateCookie(request, response, getLoginCookieKey(), getCookiePath(request));
119             }
120             catch (Exception JavaDoc e)
121             {
122                 log.error("Could not invalidate cookie: " + e, e);
123             }
124         }
125
126         return false;
127     }
128
129     // override this method if you need to retrieve the role mapper from elsewhere than the singleton-factory (injected depency for instance)
130
protected RoleMapper getRoleMapper() {
131         return SecurityConfigFactory.getInstance().getRoleMapper();
132     }
133
134     // The following two methods are the only OSUser-specific parts of this class
135

136     /** Uses OSUser to retrieve a Principal for a given username. Returns null if no user exists. */
137     protected Principal JavaDoc getUser(String JavaDoc username)
138     {
139         try
140         {
141             return UserManager.getInstance().getUser(username);
142         }
143         catch (EntityNotFoundException e)
144         {
145             log.debug("Could not find user who tried to login: " + e);
146         }
147         return null;
148     }
149
150     /** Uses OSUser's authenticate() to authenticate a user. */
151     protected boolean authenticate(Principal JavaDoc user, String JavaDoc password)
152     {
153         return ((User)user).authenticate(password);
154     }
155
156     public boolean logout(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) throws AuthenticatorException
157     {
158         List JavaDoc interceptors = getLogoutInterceptors();
159
160         for (Iterator JavaDoc iterator = interceptors.iterator(); iterator.hasNext();)
161         {
162             LogoutInterceptor interceptor = (LogoutInterceptor) iterator.next();
163             interceptor.beforeLogout(request, response);
164         }
165
166         request.getSession().setAttribute(LOGGED_IN_KEY, null);
167         request.getSession().setAttribute(LOGGED_OUT_KEY, Boolean.TRUE);
168
169         try
170         {
171             CookieUtils.invalidateCookie(request, response, getLoginCookieKey(), getCookiePath(request));
172         }
173         catch (Exception JavaDoc e)
174         {
175             log.error("Could not invalidate cookie: " + e, e);
176         }
177
178         for (Iterator JavaDoc iterator = interceptors.iterator(); iterator.hasNext();)
179         {
180             LogoutInterceptor interceptor = (LogoutInterceptor) iterator.next();
181             interceptor.afterLogout(request, response);
182         }
183
184         return true;
185     }
186
187     /**
188      * Returns the currently logged in user.
189      *
190      * Warning this method does not necessarily authenticate the user
191      */

192     public Principal JavaDoc getUser(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response)
193     {
194         Principal JavaDoc user = null;
195
196         try
197         {
198             //when running tests, a request may not neccessarily have a session
199
if (request.getSession() != null && request.getSession().getAttribute(LOGGED_OUT_KEY) != null)
200             {
201                 log.debug("Session found; user already logged in");
202                 user = null;
203             }
204             else if(request.getSession() != null && request.getSession().getAttribute(LOGGED_IN_KEY) != null)
205             {
206                 log.debug("Session found; user already logged in");
207                 user = (Principal JavaDoc) request.getSession().getAttribute(LOGGED_IN_KEY);
208             }
209             else
210             {
211                 // otherwise look for a cookie
212
Cookie JavaDoc cookie = CookieUtils.getCookie(request, getLoginCookieKey());
213
214                 if (cookie != null)
215                 {
216                     String JavaDoc[] values = CookieUtils.decodePasswordCookie(cookie.getValue(), SecurityConfigFactory.getInstance().getCookieEncoding());
217
218                     if (values != null)
219                     {
220                         String JavaDoc username = values[0];
221                         String JavaDoc password = values[1];
222
223                         if (login(request, response, username, password, false))
224                         {
225                             log.debug("Logged user in via a cookie");
226                             return getUser(request);
227                         }
228                     }
229
230                     log.debug("Cannot log user in via a cookie");
231                 }
232             }
233         }
234         catch (Exception JavaDoc e) // catch class cast exceptions
235
{
236             log.warn("Exception: " + e, e);
237         }
238
239         return user;
240     }
241
242     /**
243      * Root the login cookie at the same location as the webapp.
244      *
245      * Anyone wanting a different cookie path policy can override the authenticator and
246      * provide one.
247      */

248     protected String JavaDoc getCookiePath(HttpServletRequest JavaDoc request)
249     {
250         String JavaDoc path = request.getContextPath();
251         if (path == null || path.equals(""))
252             return "/";
253
254         // The spec says this should never happen, but just to be sure...
255
if (!path.startsWith("/"))
256             return "/" + path;
257
258         return path;
259     }
260
261     protected String JavaDoc getLoginCookieKey() {
262         return loginCookieKey;
263     }
264
265     protected List JavaDoc getLogoutInterceptors() {
266         return getConfig().getInterceptors(LogoutInterceptor.class);
267     }
268 }
269
Popular Tags