KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > alfresco > web > app > servlet > NovellIChainsHTTPRequestAuthenticationFilter


1 /*
2  * Copyright (C) 2006 Alfresco, Inc.
3  *
4  * Licensed under the Mozilla Public License version 1.1
5  * with a permitted attribution clause. You may obtain a
6  * copy of the License at
7  *
8  * http://www.alfresco.org/legal/license.txt
9  *
10  * Unless required by applicable law or agreed to in writing,
11  * software distributed under the License is distributed on an
12  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
13  * either express or implied. See the License for the specific
14  * language governing permissions and limitations under the
15  * License.
16  */

17 package org.alfresco.web.app.servlet;
18
19 import java.io.IOException JavaDoc;
20 import java.util.List JavaDoc;
21 import java.util.Locale JavaDoc;
22
23 import javax.servlet.Filter JavaDoc;
24 import javax.servlet.FilterChain JavaDoc;
25 import javax.servlet.FilterConfig JavaDoc;
26 import javax.servlet.ServletContext JavaDoc;
27 import javax.servlet.ServletException JavaDoc;
28 import javax.servlet.ServletRequest JavaDoc;
29 import javax.servlet.ServletResponse JavaDoc;
30 import javax.servlet.http.HttpServletRequest JavaDoc;
31 import javax.servlet.http.HttpServletResponse JavaDoc;
32 import javax.servlet.http.HttpSession JavaDoc;
33 import javax.transaction.UserTransaction JavaDoc;
34
35 import org.alfresco.config.ConfigService;
36 import org.alfresco.i18n.I18NUtil;
37 import org.alfresco.model.ContentModel;
38 import org.alfresco.repo.security.authentication.AuthenticationComponent;
39 import org.alfresco.repo.security.authentication.AuthenticationException;
40 import org.alfresco.service.ServiceRegistry;
41 import org.alfresco.service.cmr.repository.NodeRef;
42 import org.alfresco.service.cmr.repository.NodeService;
43 import org.alfresco.service.cmr.security.AuthenticationService;
44 import org.alfresco.service.cmr.security.PersonService;
45 import org.alfresco.service.transaction.TransactionService;
46 import org.alfresco.web.app.Application;
47 import org.alfresco.web.bean.LoginBean;
48 import org.alfresco.web.bean.repository.User;
49 import org.alfresco.web.config.LanguagesConfigElement;
50 import org.apache.commons.logging.Log;
51 import org.apache.commons.logging.LogFactory;
52 import org.springframework.web.context.WebApplicationContext;
53 import org.springframework.web.context.support.WebApplicationContextUtils;
54
55 /**
56  * Sample authentication for Novell ICHAINS.
57  *
58  * @author Andy Hind
59  */

60 public class NovellIChainsHTTPRequestAuthenticationFilter extends AbstractAuthenticationFilter implements Filter JavaDoc
61 {
62     private static final String JavaDoc LOCALE = "locale";
63
64     public static final String JavaDoc MESSAGE_BUNDLE = "alfresco.messages.webclient";
65
66     private static Log logger = LogFactory.getLog(NovellIChainsHTTPRequestAuthenticationFilter.class);
67
68     private ServletContext JavaDoc context;
69
70     private String JavaDoc loginPage;
71
72     private AuthenticationComponent authComponent;
73
74     private AuthenticationService authService;
75
76     private TransactionService transactionService;
77
78     private PersonService personService;
79
80     private NodeService nodeService;
81
82     private List JavaDoc<String JavaDoc> m_languages;
83
84     public NovellIChainsHTTPRequestAuthenticationFilter()
85     {
86         super();
87     }
88
89     public void destroy()
90     {
91         // Nothing to do
92
}
93
94     /**
95      * Run the filter
96      *
97      * @param sreq
98      * ServletRequest
99      * @param sresp
100      * ServletResponse
101      * @param chain
102      * FilterChain
103      * @exception IOException
104      * @exception ServletException
105      */

106     public void doFilter(ServletRequest JavaDoc sreq, ServletResponse JavaDoc sresp, FilterChain JavaDoc chain) throws IOException JavaDoc,
107             ServletException JavaDoc
108     {
109         // Get the HTTP request/response/session
110

111         HttpServletRequest JavaDoc req = (HttpServletRequest JavaDoc) sreq;
112         HttpServletResponse JavaDoc resp = (HttpServletResponse JavaDoc) sresp;
113
114         HttpSession JavaDoc httpSess = req.getSession(true);
115
116         // Check for the ICHAINS header
117

118         String JavaDoc authHdr = req.getHeader("x-user");
119         if(logger.isDebugEnabled())
120         {
121             if(authHdr == null)
122             {
123                 logger.debug("x-user header not found.");
124             }
125             else
126             {
127                 logger.debug("x-user header is <" + authHdr + ">");
128             }
129         }
130         // Stet here to test.....
131
//authHdr = "DVShelley";
132
boolean reqAuth = false;
133
134         // Throw an error if we have an unknown authentication
135

136         if ((authHdr == null) || (authHdr.length() < 1))
137         {
138             resp.sendRedirect(req.getContextPath() + "/jsp/noaccess.jsp");
139             return;
140         }
141
142         // Get the user
143

144         String JavaDoc userName = authHdr;
145
146         if(logger.isDebugEnabled())
147         {
148             logger.debug("User = "+ userName);
149         }
150         
151         // See if there is a user in the session and test if it matches
152

153         User user = (User) httpSess.getAttribute(AuthenticationHelper.AUTHENTICATION_USER);
154
155         if (user != null)
156         {
157             try
158             {
159                 // Debug
160

161                 if (logger.isDebugEnabled())
162                     logger.debug("User " + user.getUserName() + " validate ticket");
163
164                 // Validate the user ticket
165

166                 if (user.getUserName().equals(userName))
167                 {
168
169                     // Set the current locale
170
authComponent.setCurrentUser(user.getUserName());
171                     I18NUtil.setLocale(Application.getLanguage(httpSess));
172                     chain.doFilter(sreq, sresp);
173                     return;
174                 }
175                 else
176                 {
177                     // No match
178
setAuthenticatedUser(req, httpSess, userName);
179                 }
180             }
181             catch (AuthenticationException ex)
182             {
183                 if (logger.isErrorEnabled())
184                     logger.error("Failed to validate user " + user.getUserName(), ex);
185
186                 reqAuth = true;
187             }
188         }
189
190         setAuthenticatedUser(req, httpSess, userName);
191
192         // Redirect the login page as it is never seen as we always login by name
193
if (req.getRequestURI().endsWith(getLoginPage()) == true)
194         {
195             if (logger.isDebugEnabled())
196                 logger.debug("Login page requested, chaining ...");
197
198             resp.sendRedirect(req.getContextPath() + "/faces/jsp/browse/browse.jsp");
199             return;
200         }
201         else
202         {
203             chain.doFilter(sreq, sresp);
204             return;
205         }
206     }
207
208     /**
209      * Set the authenticated user.
210      *
211      * It does not check that the user exists at the moment.
212      *
213      * @param req
214      * @param httpSess
215      * @param userName
216      */

217     private void setAuthenticatedUser(HttpServletRequest JavaDoc req, HttpSession JavaDoc httpSess, String JavaDoc userName)
218     {
219         // Set the authentication
220
authComponent.setCurrentUser(userName);
221
222         User user = new User(userName, authService.getCurrentTicket(), personService.getPerson(userName));
223
224         // Set up the user information
225
UserTransaction JavaDoc tx = transactionService.getUserTransaction();
226         NodeRef homeSpaceRef = null;
227
228         try
229         {
230             tx.begin();
231             homeSpaceRef = (NodeRef) nodeService.getProperty(personService.getPerson(userName),
232                     ContentModel.PROP_HOMEFOLDER);
233             user.setHomeSpaceId(homeSpaceRef.getId());
234             tx.commit();
235         }
236         catch (Throwable JavaDoc ex)
237         {
238             logger.error(ex);
239
240             try
241             {
242                 tx.rollback();
243             }
244             catch (Exception JavaDoc ex2)
245             {
246                 logger.error("Failed to rollback transaction", ex2);
247             }
248             
249             if(ex instanceof RuntimeException JavaDoc)
250             {
251                 throw (RuntimeException JavaDoc)ex;
252             }
253             else
254             {
255                 throw new RuntimeException JavaDoc("Failed to set authenticated user", ex);
256             }
257         }
258
259         // Store the user
260

261         httpSess.setAttribute(AuthenticationHelper.AUTHENTICATION_USER, user);
262         httpSess.setAttribute(LoginBean.LOGIN_EXTERNAL_AUTH, Boolean.TRUE);
263
264         // Set the current locale from the Accept-Lanaguage header if available
265

266         Locale JavaDoc userLocale = parseAcceptLanguageHeader(req, m_languages);
267
268         if (userLocale != null)
269         {
270             httpSess.setAttribute(LOCALE, userLocale);
271             httpSess.removeAttribute(MESSAGE_BUNDLE);
272         }
273
274         // Set the locale using the session
275

276         I18NUtil.setLocale(Application.getLanguage(httpSess));
277     }
278
279     public void init(FilterConfig JavaDoc config) throws ServletException JavaDoc
280     {
281         this.context = config.getServletContext();
282         WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(context);
283         ServiceRegistry serviceRegistry = (ServiceRegistry) ctx.getBean(ServiceRegistry.SERVICE_REGISTRY);
284         transactionService = serviceRegistry.getTransactionService();
285         nodeService = serviceRegistry.getNodeService();
286
287         authComponent = (AuthenticationComponent) ctx.getBean("authenticationComponent");
288         authService = (AuthenticationService) ctx.getBean("authenticationService");
289         personService = (PersonService) ctx.getBean("personService");
290
291         // Get a list of the available locales
292

293         ConfigService configServiceService = (ConfigService) ctx.getBean("webClientConfigService");
294         LanguagesConfigElement configElement = (LanguagesConfigElement) configServiceService.
295               getConfig("Languages").getConfigElement(LanguagesConfigElement.CONFIG_ELEMENT_ID);
296
297         m_languages = configElement.getLanguages();
298     }
299
300     /**
301      * Return the login page address
302      *
303      * @return String
304      */

305     private String JavaDoc getLoginPage()
306     {
307         if (loginPage == null)
308         {
309             loginPage = Application.getLoginPage(context);
310         }
311
312         return loginPage;
313     }
314
315 }
316
Popular Tags