Project

General

Profile

Download (7.29 KB) Statistics
| Branch: | Tag: | Revision:
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.api.utility.CdmUserHelper;
29
import eu.etaxonomy.cdm.api.utility.RoleProber;
30
import eu.etaxonomy.cdm.api.utility.UserHelper;
31
import eu.etaxonomy.cdm.model.permission.Group;
32
import eu.etaxonomy.cdm.model.permission.User;
33
import eu.etaxonomy.cdm.persistence.hibernate.CdmDataChangeMap;
34
import eu.etaxonomy.cdm.persistence.permission.Role;
35
import eu.etaxonomy.taxeditor.model.IContextListener;
36
import eu.etaxonomy.taxeditor.model.MessagingUtils;
37

    
38
/**
39
 * <p>LoginManager class.</p>
40
 *
41
 * @author n.hoffmann
42
 * @created 03.07.2009
43
 * @version 1.0
44
 */
45
public class LoginManager extends Observable implements IConversationEnabled, IContextListener{
46

    
47
	public static final Logger logger = Logger.getLogger(LoginManager.class);
48

    
49
	private ConversationHolder conversation;
50

    
51
	public static final String INCORRECT_CREDENTIALS_MESSAGE = "Login and/or Password incorrect";
52
	public static final String ACCOUNT_LOCKED_MESSAGE = "Account is locked";
53
	public static final String EMPTY_CREDENTIALS_MESSAGE = "Login and/or Password empty";
54

    
55

    
56
    private CdmUserHelper userHelper = null;
57

    
58
	public LoginManager(){
59
	    CdmStore.getContextManager().addContextListener(this);
60

    
61
	}
62

    
63
	private UserHelper userHelper() {
64

    
65
        if (userHelper == null){
66
            userHelper = new CdmUserHelper();
67
        }
68
        return userHelper;
69
	}
70

    
71
	/**
72
	 * <p>authenticate</p>
73
	 *
74
	 * @param token a {@link org.springframework.security.authentication.UsernamePasswordAuthenticationToken} object.
75
	 * @return true if the login attempt was successful even if the authentication has changed or not
76
	 */
77
	public boolean authenticate(String username, String password){
78
	    try{
79
	        doAuthenticate(username, password);
80
	    } catch (CdmAuthenticationException e) {
81
	        MessagingUtils.warningDialog("Could not authenticate", this, e.getMessage());
82
	        return false;
83
        }
84
	    return true;
85
	}
86

    
87
	public void doAuthenticate(String username, String password) throws CdmAuthenticationException {
88
	    try {
89
	        SecurityContextHolder.clearContext();
90
	        Authentication lastAuthentication = CdmStore.getCurrentAuthentiation();
91

    
92
	        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);
93
	        Authentication authentication = CdmStore.getAuthenticationManager().authenticate(token);
94

    
95
	        User user = (User) authentication.getPrincipal();
96
	        /* circumventing problem with hibernate not refreshing the transient collection authorities in this case,
97
	         * see http://dev.e-taxonomy.eu/trac/ticket/4053 */
98
	        user.initAuthorities();
99

    
100
	        if(logger.isDebugEnabled()){
101
	            StringBuilder gaText = new StringBuilder();
102
	            String indent = "    ";
103
	            Set<GrantedAuthority> gaSet = user.getGrantedAuthorities();
104
	            _logGrantedAuthotities(gaText, indent, gaSet);
105
	            for(Group gr : user.getGroups()){
106
	                gaText.append(indent).append("gr[").append(gr.hashCode()).append("] \"").append(gr.getName()).append("\" ").append(gr.toString()).append("\n");
107
	                _logGrantedAuthotities(gaText, indent + indent, gr.getGrantedAuthorities());
108
	            }
109
	            logger.debug("User authenticated: " + user.getUsername() + "\n" + gaText.toString());
110
	        }
111

    
112
	        authentication = new UsernamePasswordAuthenticationToken(user,password, authentication.getAuthorities());
113
	        SecurityContextHolder.getContext().setAuthentication(authentication);
114
	        CdmApplicationState.setCurrentSecurityContext(SecurityContextHolder.getContext());
115

    
116
	        if(!authentication.equals(lastAuthentication)){
117
	            this.setChanged();
118
	            this.notifyObservers();
119
	        }
120
	    } catch(BadCredentialsException e){
121
	        throw new CdmAuthenticationException(INCORRECT_CREDENTIALS_MESSAGE, e);
122
	    } catch(LockedException e){
123
	        throw new CdmAuthenticationException(ACCOUNT_LOCKED_MESSAGE, e);
124
	    } catch(IllegalArgumentException e){
125
	        e.printStackTrace();
126
	        throw new CdmAuthenticationException(EMPTY_CREDENTIALS_MESSAGE, e);
127
	    }
128

    
129
	}
130

    
131

    
132
	private void _logGrantedAuthotities(StringBuilder gaText, String indent,
133
			Set<GrantedAuthority> gaSet) {
134
		for(GrantedAuthority ga : gaSet){
135
			gaText.append(indent).append("ga[").append(ga.hashCode()).append("] ").append(ga.toString()).append("\n");
136
		}
137
	}
138

    
139
	/**
140
	 * <p>getAuthenticatedUser</p>
141
	 *
142
	 * @return a {@link eu.etaxonomy.cdm.model.common.User} object.
143
	 */
144
	public User getAuthenticatedUser(){
145
 		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
146

    
147
		if(authentication != null
148
				&& authentication.getPrincipal() != null
149
				&& authentication.getPrincipal() instanceof User){
150
			return (User)authentication.getPrincipal();
151
		}
152
		return null;
153
	}
154

    
155
	public void logoutAll(){
156
		SecurityContextHolder.clearContext();
157
		notifyObservers();
158
	}
159

    
160
	/* (non-Javadoc)
161
	 * @see eu.etaxonomy.cdm.persistence.hibernate.ICdmPostDataChangeObserver#update(eu.etaxonomy.cdm.persistence.hibernate.CdmDataChangeMap)
162
	 */
163
	@Override
164
	public void update(CdmDataChangeMap arg) {}
165

    
166
	/* (non-Javadoc)
167
	 * @see eu.etaxonomy.cdm.api.conversation.IConversationEnabled#getConversationHolder()
168
	 */
169
	@Override
170
	public ConversationHolder getConversationHolder() {
171
		if(conversation == null){
172
			conversation = CdmStore.createConversation();
173
		}
174
		return conversation;
175
	}
176

    
177
	/**
178
	 * Whether the current user has the role admin
179
	 *
180
	 * @return
181
	 */
182
	public boolean isAdmin() {
183
	    boolean result = userHelper().userIs(new RoleProber(Role.ROLE_ADMIN));
184
        return result;
185
	}
186

    
187
	/**
188
     * Whether the current user has the role user manager
189
     *
190
     * @return
191
     */
192
    public boolean isUserManager() {
193
        boolean result = userHelper().userIs(new RoleProber(Role.ROLE_USER_MANAGER));
194
        return result;
195
    }
196

    
197
	@Override
198
	public void contextAboutToStop(IMemento memento, IProgressMonitor monitor) {
199

    
200
	}
201

    
202
	@Override
203
	public void contextStop(IMemento memento, IProgressMonitor monitor) {
204

    
205
	}
206

    
207
	@Override
208
	public void contextStart(IMemento memento, IProgressMonitor monitor){
209
		conversation = CdmStore.createConversation();
210
	}
211

    
212
	@Override
213
	public void contextRefresh(IProgressMonitor monitor) {
214
		conversation = CdmStore.createConversation();
215
	}
216

    
217
	@Override
218
	public void workbenchShutdown(IMemento memento, IProgressMonitor monitor) {
219

    
220
	}
221
}
(7-7/13)