Merge branch 'develop' of wp5.e-taxonomy.eu:/var/git/taxeditor into remoting-4.0
[taxeditor.git] / eu.etaxonomy.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 import java.util.Set;
15
16 import org.apache.log4j.Logger;
17 import org.eclipse.core.runtime.IProgressMonitor;
18 import org.eclipse.ui.IMemento;
19 import org.springframework.security.authentication.BadCredentialsException;
20 import org.springframework.security.authentication.LockedException;
21 import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
22 import org.springframework.security.core.Authentication;
23 import org.springframework.security.core.GrantedAuthority;
24 import org.springframework.security.core.context.SecurityContextHolder;
25
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.AbstractUtility;
32 import eu.etaxonomy.taxeditor.model.IContextListener;
33 import eu.etaxonomy.taxeditor.model.MessagingUtils;
34
35 /**
36 * <p>LoginManager class.</p>
37 *
38 * @author n.hoffmann
39 * @created 03.07.2009
40 * @version 1.0
41 */
42 public class LoginManager extends Observable implements IConversationEnabled, IContextListener{
43
44 public static final Logger logger = Logger.getLogger(LoginManager.class);
45
46 private ConversationHolder conversation;
47
48 public LoginManager(){
49 CdmStore.getContextManager().addContextListener(this);
50 }
51
52 /**
53 * <p>authenticate</p>
54 *
55 * @param token a {@link org.springframework.security.authentication.UsernamePasswordAuthenticationToken} object.
56 * @return true if the login attempt was successful even if the authentication has changed or not
57 */
58 public boolean authenticate(String username, String password){
59
60 // close all open editors
61 if(!AbstractUtility.closeAll()){
62 return false;
63 }
64
65
66 try{
67 SecurityContextHolder.clearContext();
68
69 Authentication lastAuthentication = CdmStore.getCurrentAuthentiation();
70
71 UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);
72 Authentication authentication = CdmStore.getAuthenticationManager().authenticate(token);
73
74 User user = (User) authentication.getPrincipal();
75 /* circumventing problem with hibernate not refreshing the transient collection authorities in this case,
76 * see http://dev.e-taxonomy.eu/trac/ticket/4053 */
77 user.initAuthorities();
78
79 if(logger.isDebugEnabled()){
80 StringBuilder gaText = new StringBuilder();
81 String indent = " ";
82 Set<GrantedAuthority> gaSet = user.getGrantedAuthorities();
83 _logGrantedAuthotities(gaText, indent, gaSet);
84 for(Group gr : user.getGroups()){
85 gaText.append(indent).append("gr[").append(gr.hashCode()).append("] \"").append(gr.getName()).append("\" ").append(gr.toString()).append("\n");
86 _logGrantedAuthotities(gaText, indent + indent, gr.getGrantedAuthorities());
87 }
88 logger.debug("User authenticated: " + user.getUsername() + "\n" + gaText.toString());
89 }
90
91 authentication = new UsernamePasswordAuthenticationToken(username,password, authentication.getAuthorities());
92 SecurityContextHolder.getContext().setAuthentication(authentication);
93
94 if(!authentication.equals(lastAuthentication)){
95 this.setChanged();
96 this.notifyObservers();
97 }
98 return true;
99 }
100 catch(BadCredentialsException e){
101 MessagingUtils.warningDialog("Could not authenticate", this, "Could not authenticate. Reason: Bad Credentials.");
102 }
103 catch(LockedException e){
104 MessagingUtils.warningDialog("Could not authenticate", this, "Could not authenticate. Reason: Account is locked.");
105 }
106 catch(IllegalArgumentException e){
107 MessagingUtils.warningDialog("Could not authenticate", this, "Could not authenticate. Reason: Username and/or Password empty.");
108 }
109 return false;
110 }
111
112 private void _logGrantedAuthotities(StringBuilder gaText, String indent,
113 Set<GrantedAuthority> gaSet) {
114 for(GrantedAuthority ga : gaSet){
115 gaText.append(indent).append("ga[").append(ga.hashCode()).append("] ").append(ga.toString()).append("\n");
116 }
117 }
118
119 /**
120 * <p>getAuthenticatedUser</p>
121 *
122 * @return a {@link eu.etaxonomy.cdm.model.common.User} object.
123 */
124 public User getAuthenticatedUser(){
125 Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
126
127 if(authentication != null
128 && authentication.getPrincipal() != null
129 && authentication.getPrincipal() instanceof User){
130 return (User)authentication.getPrincipal();
131 }
132 return null;
133 }
134
135 public void logoutAll(){
136 SecurityContextHolder.clearContext();
137 notifyObservers();
138 }
139
140 /* (non-Javadoc)
141 * @see eu.etaxonomy.cdm.persistence.hibernate.ICdmPostDataChangeObserver#update(eu.etaxonomy.cdm.persistence.hibernate.CdmDataChangeMap)
142 */
143 @Override
144 public void update(CdmDataChangeMap arg) {}
145
146 /* (non-Javadoc)
147 * @see eu.etaxonomy.cdm.api.conversation.IConversationEnabled#getConversationHolder()
148 */
149 @Override
150 public ConversationHolder getConversationHolder() {
151 if(conversation == null){
152 conversation = CdmStore.createConversation();
153 }
154 return conversation;
155 }
156
157 /**
158 * Whether the current user has the role admin
159 *
160 * @return
161 */
162 public boolean isAdmin() {
163 // FIXME until we have rights implemented properly we do this
164 // by a simple string check. This has to change
165
166 return "admin".equals(getAuthenticatedUser().getUsername());
167 }
168
169 @Override
170 public void contextAboutToStop(IMemento memento, IProgressMonitor monitor) {
171
172 }
173
174 @Override
175 public void contextStop(IMemento memento, IProgressMonitor monitor) {
176
177 }
178
179 @Override
180 public void contextStart(IMemento memento, IProgressMonitor monitor){
181 conversation = CdmStore.createConversation();
182 }
183
184 @Override
185 public void contextRefresh(IProgressMonitor monitor) {
186 conversation = CdmStore.createConversation();
187 }
188
189 @Override
190 public void workbenchShutdown(IMemento memento, IProgressMonitor monitor) {
191
192 }
193 }