Project

General

Profile

Download (6.37 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
package eu.etaxonomy.taxeditor.store;
10

    
11
import java.util.Observable;
12
import java.util.Set;
13

    
14
import org.apache.logging.log4j.LogManager;
15
import org.apache.logging.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.util.CdmUserHelper;
27
import eu.etaxonomy.cdm.api.util.RoleProberImpl;
28
import eu.etaxonomy.cdm.api.util.UserHelper;
29
import eu.etaxonomy.cdm.model.permission.Group;
30
import eu.etaxonomy.cdm.model.permission.User;
31
import eu.etaxonomy.cdm.persistence.permission.Role;
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
 */
41
public class LoginManager extends Observable implements IContextListener{
42

    
43
	public static final Logger logger = LogManager.getLogger();
44

    
45
	public static final String INCORRECT_CREDENTIALS_MESSAGE = "Login and/or Password incorrect";
46
	public static final String ACCOUNT_LOCKED_MESSAGE = "Account is locked";
47
	public static final String EMPTY_CREDENTIALS_MESSAGE = "Login and/or Password empty";
48

    
49

    
50
    private CdmUserHelper userHelper = null;
51

    
52
	public LoginManager(){
53
	    CdmStore.getContextManager().addContextListener(this);
54

    
55
	}
56

    
57
	private UserHelper userHelper() {
58

    
59
        if (userHelper == null){
60
            userHelper = new CdmUserHelper();
61
        }
62
        return userHelper;
63
	}
64

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

    
81
	public void doAuthenticate(String username, String password) throws CdmAuthenticationException {
82
	    try {
83
	        SecurityContextHolder.clearContext();
84
	        Authentication lastAuthentication = CdmStore.getCurrentAuthentiation();
85

    
86
	        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);
87
	        Authentication authentication = CdmStore.getAuthenticationManager().authenticate(token);
88

    
89
	        User user = (User) authentication.getPrincipal();
90
	        /* circumventing problem with hibernate not refreshing the transient collection authorities in this case,
91
	         * see http://dev.e-taxonomy.eu/trac/ticket/4053 */
92
	        user.initAuthorities();
93

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

    
106
	        authentication = new UsernamePasswordAuthenticationToken(user,password, authentication.getAuthorities());
107
	        SecurityContextHolder.getContext().setAuthentication(authentication);
108
	        CdmApplicationState.setCurrentSecurityContext(SecurityContextHolder.getContext());
109

    
110
	        if(!authentication.equals(lastAuthentication)){
111
	            this.setChanged();
112
	            this.notifyObservers();
113
	        }
114
	    } catch(BadCredentialsException e){
115
	        throw new CdmAuthenticationException(INCORRECT_CREDENTIALS_MESSAGE, e);
116
	    } catch(LockedException e){
117
	        throw new CdmAuthenticationException(ACCOUNT_LOCKED_MESSAGE, e);
118
	    } catch(IllegalArgumentException e){
119
	        e.printStackTrace();
120
	        throw new CdmAuthenticationException(EMPTY_CREDENTIALS_MESSAGE, e);
121
	    }
122
	}
123

    
124
	private void _logGrantedAuthotities(StringBuilder gaText, String indent,
125
			Set<GrantedAuthority> gaSet) {
126
		for(GrantedAuthority ga : gaSet){
127
			gaText.append(indent).append("ga[").append(ga.hashCode()).append("] ").append(ga.toString()).append("\n");
128
		}
129
	}
130

    
131
	public User getAuthenticatedUser(){
132
 		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
133

    
134
		if(authentication != null
135
				&& authentication.getPrincipal() != null
136
				&& authentication.getPrincipal() instanceof User){
137
			return (User)authentication.getPrincipal();
138
		}
139
		return null;
140
	}
141

    
142
	public void logoutAll(){
143
		SecurityContextHolder.clearContext();
144
		notifyObservers();
145
	}
146

    
147

    
148
	/**
149
	 * Whether the current user has the role admin
150
	 *
151
	 * @return
152
	 */
153
	public boolean isAdmin() {
154
	    boolean result = userHelper().userIs(new RoleProberImpl(Role.ROLE_ADMIN));
155
        return result;
156
	}
157

    
158
	/**
159
     * Whether the current user has the role user manager
160
     *
161
     * @return
162
     */
163
    public boolean isUserManager() {
164
        boolean result = userHelper().userIs(new RoleProberImpl(Role.ROLE_USER_MANAGER));
165
        return result;
166
    }
167

    
168
	@Override
169
	public void contextAboutToStop(IMemento memento, IProgressMonitor monitor) {
170

    
171
	}
172

    
173
	@Override
174
	public void contextStop(IMemento memento, IProgressMonitor monitor) {
175

    
176
	}
177

    
178
	@Override
179
	public void contextStart(IMemento memento, IProgressMonitor monitor){
180
	}
181

    
182
	@Override
183
	public void contextRefresh(IProgressMonitor monitor) {
184
	}
185

    
186
	@Override
187
	public void workbenchShutdown(IMemento memento, IProgressMonitor monitor) {
188

    
189
	}
190
}
(7-7/13)