Refactoring of name editor.
[taxeditor.git] / taxeditor-store / src / main / java / eu / etaxonomy / taxeditor / store / LoginManager.java
1 // $Id$
2 /**
3 * Copyright (C) 2007 EDIT
4 * European Distributed Institute of Taxonomy
5 * http://www.e-taxonomy.eu
6 *
7 * The contents of this file are subject to the Mozilla Public License Version 1.1
8 * See LICENSE.TXT at the top of this package for the full license terms.
9 */
10
11 package eu.etaxonomy.taxeditor.store;
12
13 import java.util.Observable;
14
15 import org.springframework.security.authentication.BadCredentialsException;
16 import org.springframework.security.authentication.LockedException;
17 import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
18 import org.springframework.security.core.Authentication;
19 import org.springframework.security.core.context.SecurityContextHolder;
20
21 import eu.etaxonomy.cdm.model.common.User;
22
23 /**
24 * <p>LoginManager class.</p>
25 *
26 * @author n.hoffmann
27 * @created 03.07.2009
28 * @version 1.0
29 */
30 public class LoginManager extends Observable{
31
32 /**
33 * <p>authenticate</p>
34 *
35 * @param token a {@link org.springframework.security.authentication.UsernamePasswordAuthenticationToken} object.
36 */
37 public void authenticate(String username, String password){
38 try{
39 UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);
40
41 SecurityContextHolder.clearContext();
42 Authentication authentication = CdmStore.getAuthenticationManager().authenticate(token);
43 SecurityContextHolder.getContext().setAuthentication(authentication);
44 }
45 catch(BadCredentialsException e){
46 StoreUtil.warningDialog("Could not authenticate", this, "Could not authenticate. Reason: Bad Credentials.");
47 }
48 catch(LockedException e){
49 StoreUtil.warningDialog("Could not authenticate", this, "Could not authenticate. Reason: Account is locked.");
50 }
51 catch(IllegalArgumentException e){
52 StoreUtil.warningDialog("Could not authenticate", this, "Could not authenticate. Reason: Username and/or Password empty.");
53 }
54 finally{
55 this.setChanged();
56 this.notifyObservers();
57 }
58 }
59
60 /**
61 * <p>getAuthenticatedUser</p>
62 *
63 * @return a {@link eu.etaxonomy.cdm.model.common.User} object.
64 */
65 public User getAuthenticatedUser(){
66 Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
67
68 if(authentication != null
69 && authentication.getPrincipal() != null
70 && authentication.getPrincipal() instanceof User){
71 return (User)authentication.getPrincipal();
72 }
73 return null;
74 }
75
76 public void logoutAll(){
77 SecurityContextHolder.clearContext();
78 notifyObservers();
79 }
80 }