KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > alfresco > web > bean > LoginBean


1 /*
2  * Copyright (C) 2005 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.bean;
18
19 import java.io.IOException JavaDoc;
20 import java.text.MessageFormat JavaDoc;
21 import java.util.List JavaDoc;
22 import java.util.Locale JavaDoc;
23 import java.util.Map JavaDoc;
24
25 import javax.faces.application.FacesMessage;
26 import javax.faces.component.UIComponent;
27 import javax.faces.context.FacesContext;
28 import javax.faces.model.SelectItem;
29 import javax.faces.validator.ValidatorException;
30 import javax.portlet.PortletRequest;
31 import javax.servlet.http.HttpServletRequest JavaDoc;
32
33 import org.alfresco.config.Config;
34 import org.alfresco.config.ConfigService;
35 import org.alfresco.model.ContentModel;
36 import org.alfresco.repo.security.authentication.AuthenticationException;
37 import org.alfresco.service.cmr.repository.InvalidNodeRefException;
38 import org.alfresco.service.cmr.repository.NodeRef;
39 import org.alfresco.service.cmr.repository.NodeService;
40 import org.alfresco.service.cmr.security.AuthenticationService;
41 import org.alfresco.service.cmr.security.PersonService;
42 import org.alfresco.web.app.Application;
43 import org.alfresco.web.app.servlet.AuthenticationHelper;
44 import org.alfresco.web.bean.repository.Repository;
45 import org.alfresco.web.bean.repository.User;
46 import org.alfresco.web.config.LanguagesConfigElement;
47 import org.alfresco.web.ui.common.Utils;
48 import org.apache.commons.logging.Log;
49 import org.apache.commons.logging.LogFactory;
50
51 /**
52  * JSF Managed Bean. Backs the "login.jsp" view to provide the form fields used
53  * to enter user data for login. Also contains bean methods to validate form
54  * fields and action event fired in response to the Login button being pressed.
55  *
56  * @author Kevin Roast
57  */

58 public class LoginBean
59 {
60    // ------------------------------------------------------------------------------
61
// Managed bean properties
62

63    /**
64     * @param authenticationService The AuthenticationService to set.
65     */

66    public void setAuthenticationService(AuthenticationService authenticationService)
67    {
68       this.authenticationService = authenticationService;
69    }
70
71    /**
72     * @param personService The personService to set.
73     */

74    public void setPersonService(PersonService personService)
75    {
76       this.personService = personService;
77    }
78
79    /**
80     * @param nodeService The nodeService to set.
81     */

82    public void setNodeService(NodeService nodeService)
83    {
84       this.nodeService = nodeService;
85    }
86
87    /**
88     * @param browseBean The BrowseBean to set.
89     */

90    public void setBrowseBean(BrowseBean browseBean)
91    {
92       this.browseBean = browseBean;
93    }
94    
95    /**
96     * @param navigator The NavigationBean to set.
97     */

98    public void setNavigator(NavigationBean navigator)
99    {
100       this.navigator = navigator;
101    }
102    
103    /**
104     * @return true if the default Alfresco authentication process is being used, else false
105     * if an external authorisation mechanism is present.
106     */

107    public boolean isAlfrescoAuth()
108    {
109       Map JavaDoc session = FacesContext.getCurrentInstance().getExternalContext().getSessionMap();
110       return (session.get(LOGIN_EXTERNAL_AUTH) == null);
111    }
112
113    /**
114     * @param val Username from login dialog
115     */

116    public void setUsername(String JavaDoc val)
117    {
118       this.username = val;
119    }
120
121    /**
122     * @return The username string from login dialog
123     */

124    public String JavaDoc getUsername()
125    {
126       // this value may have been set by a servlet filter via a cookie
127
// check for this by detecting a special value in the session
128
FacesContext context = FacesContext.getCurrentInstance();
129       Map JavaDoc session = context.getExternalContext().getSessionMap();
130       
131       String JavaDoc username = (String JavaDoc)session.get(AuthenticationHelper.SESSION_USERNAME);
132       if (username != null)
133       {
134          session.remove(AuthenticationHelper.SESSION_USERNAME);
135          this.username = username;
136       }
137       
138       return this.username;
139    }
140    
141    public String JavaDoc getUsernameInternal()
142    {
143       return this.username;
144    }
145
146    /**
147     * @param val Password from login dialog
148     */

149    public void setPassword(String JavaDoc val)
150    {
151       this.password = val;
152    }
153
154    /**
155     * @return The password string from login dialog
156     */

157    public String JavaDoc getPassword()
158    {
159       return this.password;
160    }
161
162    /**
163     * @return the available languages
164     */

165    public SelectItem[] getLanguages()
166    {
167       Config config = Application.getConfigService(FacesContext.getCurrentInstance()).getConfig("Languages");
168       LanguagesConfigElement langConfig = (LanguagesConfigElement)config.getConfigElement(
169             LanguagesConfigElement.CONFIG_ELEMENT_ID);
170       
171       List JavaDoc<String JavaDoc> languages = langConfig.getLanguages();
172       SelectItem[] items = new SelectItem[languages.size()];
173       int count = 0;
174       for (String JavaDoc locale : languages)
175       {
176          // get label associated to the locale
177
String JavaDoc label = langConfig.getLabelForLanguage(locale);
178
179          // set default selection
180
if (count == 0 && this.language == null)
181          {
182             // first try to get the language that the current user is using
183
Locale JavaDoc lastLocale = Application.getLanguage(FacesContext.getCurrentInstance());
184             if (lastLocale != null)
185             {
186                this.language = lastLocale.toString();
187             }
188             // else we default to the first item in the list
189
else
190             {
191                this.language = locale;
192             }
193          }
194          
195          items[count++] = new SelectItem(locale, label);
196       }
197       
198       return items;
199    }
200
201    /**
202     * @return Returns the language selection.
203     */

204    public String JavaDoc getLanguage()
205    {
206       return this.language;
207    }
208
209    /**
210     * @param language The language selection to set.
211     */

212    public void setLanguage(String JavaDoc language)
213    {
214       this.language = language;
215       Application.setLanguage(FacesContext.getCurrentInstance(), this.language);
216    }
217
218
219    // ------------------------------------------------------------------------------
220
// Validator methods
221

222    /**
223     * Validate password field data is acceptable
224     */

225    public void validatePassword(FacesContext context, UIComponent component, Object JavaDoc value)
226          throws ValidatorException
227    {
228       String JavaDoc pass = (String JavaDoc) value;
229       if (pass.length() < 3 || pass.length() > 32)
230       {
231          String JavaDoc err = MessageFormat.format(Application.getMessage(context, MSG_PASSWORD_LENGTH),
232                new Object JavaDoc[]{3, 32});
233          throw new ValidatorException(new FacesMessage(err));
234       }
235    }
236
237    /**
238     * Validate Username field data is acceptable
239     */

240    public void validateUsername(FacesContext context, UIComponent component, Object JavaDoc value)
241          throws ValidatorException
242    {
243       String JavaDoc name = (String JavaDoc) value;
244       if (name.length() < 3 || name.length() > 32)
245       {
246          String JavaDoc err = MessageFormat.format(Application.getMessage(context, MSG_USERNAME_LENGTH),
247                new Object JavaDoc[]{3, 32});
248          throw new ValidatorException(new FacesMessage(err));
249       }
250       if (name.indexOf('\'') != -1 || name.indexOf('"') != -1 || name.indexOf('\\') != -1)
251       {
252          String JavaDoc err = MessageFormat.format(Application.getMessage(context, MSG_USER_ERR),
253                new Object JavaDoc[]{"', \", \\"});
254          throw new ValidatorException(new FacesMessage(err));
255       }
256    }
257
258    
259    // ------------------------------------------------------------------------------
260
// Action event methods
261

262    /**
263     * Login action handler
264     *
265     * @return outcome view name
266     */

267    public String JavaDoc login()
268    {
269       String JavaDoc outcome = null;
270       
271       FacesContext fc = FacesContext.getCurrentInstance();
272       
273       if (this.username != null && this.username.length() != 0 &&
274           this.password != null && this.password.length() != 0)
275       {
276          try
277          {
278             Map JavaDoc session = fc.getExternalContext().getSessionMap();
279             
280             // Authenticate via the authentication service, then save the details of user in an object
281
// in the session - this is used by the servlet filter etc. on each page to check for login
282
this.authenticationService.authenticate(this.username, this.password.toCharArray());
283             
284             // remove the session invalidated flag (used to remove last username cookie by AuthenticationFilter)
285
session.remove(AuthenticationHelper.SESSION_INVALIDATED);
286             
287             // setup User object and Home space ID
288
User user = new User(
289                   this.authenticationService.getCurrentUserName(),
290                   this.authenticationService.getCurrentTicket(),
291                   personService.getPerson(this.username));
292             
293             NodeRef homeSpaceRef = (NodeRef) this.nodeService.getProperty(personService.getPerson(this.username), ContentModel.PROP_HOMEFOLDER);
294             
295             // check that the home space node exists - else user cannot login
296
if (this.nodeService.exists(homeSpaceRef) == false)
297             {
298                throw new InvalidNodeRefException(homeSpaceRef);
299             }
300             user.setHomeSpaceId(homeSpaceRef.getId());
301             
302             // put the User object in the Session - the authentication servlet will then allow
303
// the app to continue without redirecting to the login page
304
session.put(AuthenticationHelper.AUTHENTICATION_USER, user);
305             
306             // if a redirect URL has been provided then use that
307
// this allows servlets etc. to provide a URL to return too after a successful login
308
String JavaDoc redirectURL = (String JavaDoc)fc.getExternalContext().getSessionMap().get(LOGIN_REDIRECT_KEY);
309             if (redirectURL != null)
310             {
311                if (logger.isDebugEnabled())
312                   logger.debug("Redirect URL found: " + redirectURL);
313                
314                // remove redirect URL from session
315
fc.getExternalContext().getSessionMap().remove(LOGIN_REDIRECT_KEY);
316                
317                try
318                {
319                   fc.getExternalContext().redirect(redirectURL);
320                   fc.responseComplete();
321                   return null;
322                }
323                catch (IOException JavaDoc ioErr)
324                {
325                   logger.warn("Unable to redirect to url: " + redirectURL);
326                }
327             }
328             else
329             {
330                return "success";
331             }
332          }
333          catch (AuthenticationException aerr)
334          {
335             Utils.addErrorMessage(Application.getMessage(fc, MSG_ERROR_UNKNOWN_USER));
336          }
337          catch (InvalidNodeRefException refErr)
338          {
339             Utils.addErrorMessage(MessageFormat.format(Application.getMessage(fc,
340                   Repository.ERROR_NOHOME), refErr.getNodeRef().getId()));
341          }
342       }
343       else
344       {
345          Utils.addErrorMessage(Application.getMessage(fc, MSG_ERROR_MISSING));
346       }
347
348       return outcome;
349    }
350
351    /**
352     * Invalidate ticket and logout user
353     */

354    public String JavaDoc logout()
355    {
356       FacesContext context = FacesContext.getCurrentInstance();
357       
358       Map JavaDoc session = context.getExternalContext().getSessionMap();
359       User user = (User) session.get(AuthenticationHelper.AUTHENTICATION_USER);
360       
361       // need to capture this value before invalidating the session
362
boolean externalAuth = isAlfrescoAuth();
363       
364       // Invalidate Session for this user.
365
// This causes the sessionDestroyed() event to be processed by ContextListener
366
// which is responsible for invalidating the ticket and clearing the security context
367
if (Application.inPortalServer() == false)
368       {
369          HttpServletRequest JavaDoc request = (HttpServletRequest JavaDoc)FacesContext.getCurrentInstance().getExternalContext().getRequest();
370          request.getSession().invalidate();
371       }
372       else
373       {
374          PortletRequest request = (PortletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
375          request.getPortletSession().invalidate();
376       }
377       
378       // Request that the username cookie state is removed - this is not
379
// possible from JSF - so instead we setup a session variable
380
// which will be detected by the login.jsp/Portlet as appropriate.
381
session = context.getExternalContext().getSessionMap();
382       session.put(AuthenticationHelper.SESSION_INVALIDATED, true);
383       
384       // set language to last used
385
if (this.language != null && this.language.length() != 0)
386       {
387          Application.setLanguage(context, this.language);
388       }
389       
390       return externalAuth ? "logout" : "relogin";
391    }
392    
393    
394    // ------------------------------------------------------------------------------
395
// Private data
396

397    private static final Log logger = LogFactory.getLog(LoginBean.class);
398    
399    /** I18N messages */
400    private static final String JavaDoc MSG_ERROR_MISSING = "error_login_missing";
401    private static final String JavaDoc MSG_ERROR_UNKNOWN_USER = "error_login_user";
402    private static final String JavaDoc MSG_USERNAME_CHARS = "login_err_username_chars";
403    private static final String JavaDoc MSG_USERNAME_LENGTH = "login_err_username_length";
404    private static final String JavaDoc MSG_PASSWORD_CHARS = "login_err_password_chars";
405    private static final String JavaDoc MSG_PASSWORD_LENGTH = "login_err_password_length";
406    private static final String JavaDoc MSG_USER_ERR = "user_err_user_name";
407
408    public static final String JavaDoc LOGIN_REDIRECT_KEY = "_alfRedirect";
409    public static final String JavaDoc LOGIN_EXTERNAL_AUTH= "_alfExternalAuth";
410
411    /** user name */
412    private String JavaDoc username = null;
413
414    /** password */
415    private String JavaDoc password = null;
416
417    /** language locale selection */
418    private String JavaDoc language = null;
419
420    /** PersonService bean reference */
421    protected PersonService personService;
422    
423    /** AuthenticationService bean reference */
424    protected AuthenticationService authenticationService;
425
426    /** NodeService bean reference */
427    protected NodeService nodeService;
428
429    /** The BrowseBean reference */
430    protected BrowseBean browseBean;
431    
432    /** The NavigationBean bean reference */
433    protected NavigationBean navigator;
434 }
435
Popular Tags