ref #8045: further implementation for default/explicit value selection preference...
[taxeditor.git] / eu.etaxonomy.taxeditor.store / src / main / java / eu / etaxonomy / taxeditor / store / LoginManager.java
1 /**
2 * Copyright (C) 2007 EDIT
3 * European Distributed Institute of Taxonomy
4 * http://www.e-taxonomy.eu
5 *
6 * The contents of this file are subject to the Mozilla Public License Version 1.1
7 * See LICENSE.TXT at the top of this package for the full license terms.
8 */
9
10 package eu.etaxonomy.taxeditor.store;
11
12 import java.util.Observable;
13 import java.util.Set;
14
15 import org.apache.log4j.Logger;
16 import org.eclipse.core.runtime.IProgressMonitor;
17 import org.eclipse.ui.IMemento;
18 import org.springframework.security.authentication.BadCredentialsException;
19 import org.springframework.security.authentication.LockedException;
20 import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
21 import org.springframework.security.core.Authentication;
22 import org.springframework.security.core.GrantedAuthority;
23 import org.springframework.security.core.context.SecurityContextHolder;
24
25 import eu.etaxonomy.cdm.api.application.CdmApplicationState;
26 import eu.etaxonomy.cdm.api.conversation.ConversationHolder;
27 import eu.etaxonomy.cdm.api.conversation.IConversationEnabled;
28 import eu.etaxonomy.cdm.model.common.Group;
29 import eu.etaxonomy.cdm.model.common.User;
30 import eu.etaxonomy.cdm.persistence.hibernate.CdmDataChangeMap;
31 import eu.etaxonomy.taxeditor.model.IContextListener;
32 import eu.etaxonomy.taxeditor.model.MessagingUtils;
33
34 /**
35 * <p>LoginManager class.</p>
36 *
37 * @author n.hoffmann
38 * @created 03.07.2009
39 * @version 1.0
40 */
41 public class LoginManager extends Observable implements IConversationEnabled, IContextListener{
42
43 public static final Logger logger = Logger.getLogger(LoginManager.class);
44
45 private ConversationHolder conversation;
46
47 public static final String INCORRECT_CREDENTIALS_MESSAGE = "Login and/or Password incorrect";
48 public static final String ACCOUNT_LOCKED_MESSAGE = "Account is locked";
49 public static final String EMPTY_CREDENTIALS_MESSAGE = "Login and/or Password empty";
50
51 public LoginManager(){
52 CdmStore.getContextManager().addContextListener(this);
53 }
54
55 /**
56 * <p>authenticate</p>
57 *
58 * @param token a {@link org.springframework.security.authentication.UsernamePasswordAuthenticationToken} object.
59 * @return true if the login attempt was successful even if the authentication has changed or not
60 */
61 public boolean authenticate(String username, String password){
62 try{
63 doAuthenticate(username, password);
64 } catch (CdmAuthenticationException e) {
65 MessagingUtils.warningDialog("Could not authenticate", this, e.getMessage());
66 return false;
67 }
68 return true;
69 }
70
71 public void doAuthenticate(String username, String password) throws CdmAuthenticationException {
72 try {
73 SecurityContextHolder.clearContext();
74 Authentication lastAuthentication = CdmStore.getCurrentAuthentiation();
75
76 UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);
77 Authentication authentication = CdmStore.getAuthenticationManager().authenticate(token);
78
79 User user = (User) authentication.getPrincipal();
80 /* circumventing problem with hibernate not refreshing the transient collection authorities in this case,
81 * see http://dev.e-taxonomy.eu/trac/ticket/4053 */
82 user.initAuthorities();
83
84 if(logger.isDebugEnabled()){
85 StringBuilder gaText = new StringBuilder();
86 String indent = " ";
87 Set<GrantedAuthority> gaSet = user.getGrantedAuthorities();
88 _logGrantedAuthotities(gaText, indent, gaSet);
89 for(Group gr : user.getGroups()){
90 gaText.append(indent).append("gr[").append(gr.hashCode()).append("] \"").append(gr.getName()).append("\" ").append(gr.toString()).append("\n");
91 _logGrantedAuthotities(gaText, indent + indent, gr.getGrantedAuthorities());
92 }
93 logger.debug("User authenticated: " + user.getUsername() + "\n" + gaText.toString());
94 }
95
96 authentication = new UsernamePasswordAuthenticationToken(user,password, authentication.getAuthorities());
97 SecurityContextHolder.getContext().setAuthentication(authentication);
98 CdmApplicationState.setCurrentSecurityContext(SecurityContextHolder.getContext());
99
100 if(!authentication.equals(lastAuthentication)){
101 this.setChanged();
102 this.notifyObservers();
103 }
104 } catch(BadCredentialsException e){
105 throw new CdmAuthenticationException(INCORRECT_CREDENTIALS_MESSAGE, e);
106 } catch(LockedException e){
107 throw new CdmAuthenticationException(ACCOUNT_LOCKED_MESSAGE, e);
108 } catch(IllegalArgumentException e){
109 throw new CdmAuthenticationException(EMPTY_CREDENTIALS_MESSAGE, e);
110 }
111
112 }
113
114
115 private void _logGrantedAuthotities(StringBuilder gaText, String indent,
116 Set<GrantedAuthority> gaSet) {
117 for(GrantedAuthority ga : gaSet){
118 gaText.append(indent).append("ga[").append(ga.hashCode()).append("] ").append(ga.toString()).append("\n");
119 }
120 }
121
122 /**
123 * <p>getAuthenticatedUser</p>
124 *
125 * @return a {@link eu.etaxonomy.cdm.model.common.User} object.
126 */
127 public User getAuthenticatedUser(){
128 Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
129
130 if(authentication != null
131 && authentication.getPrincipal() != null
132 && authentication.getPrincipal() instanceof User){
133 return (User)authentication.getPrincipal();
134 }
135 return null;
136 }
137
138 public void logoutAll(){
139 SecurityContextHolder.clearContext();
140 notifyObservers();
141 }
142
143 /* (non-Javadoc)
144 * @see eu.etaxonomy.cdm.persistence.hibernate.ICdmPostDataChangeObserver#update(eu.etaxonomy.cdm.persistence.hibernate.CdmDataChangeMap)
145 */
146 @Override
147 public void update(CdmDataChangeMap arg) {}
148
149 /* (non-Javadoc)
150 * @see eu.etaxonomy.cdm.api.conversation.IConversationEnabled#getConversationHolder()
151 */
152 @Override
153 public ConversationHolder getConversationHolder() {
154 if(conversation == null){
155 conversation = CdmStore.createConversation();
156 }
157 return conversation;
158 }
159
160 /**
161 * Whether the current user has the role admin
162 *
163 * @return
164 */
165 public boolean isAdmin() {
166 // FIXME until we have rights implemented properly we do this
167 // by a simple string check. This has to change
168
169 return "admin".equals(getAuthenticatedUser().getUsername());
170 }
171
172 @Override
173 public void contextAboutToStop(IMemento memento, IProgressMonitor monitor) {
174
175 }
176
177 @Override
178 public void contextStop(IMemento memento, IProgressMonitor monitor) {
179
180 }
181
182 @Override
183 public void contextStart(IMemento memento, IProgressMonitor monitor){
184 conversation = CdmStore.createConversation();
185 }
186
187 @Override
188 public void contextRefresh(IProgressMonitor monitor) {
189 conversation = CdmStore.createConversation();
190 }
191
192 @Override
193 public void workbenchShutdown(IMemento memento, IProgressMonitor monitor) {
194
195 }
196 }