Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *    Purpose: A Class that tracks sessions for MetaCatServlet users.
4
 *  Copyright: 2000 Regents of the University of California and the
5
 *             National Center for Ecological Analysis and Synthesis
6
 *    Authors: Matt Jones
7
 *
8
 *   '$Author: tao $'
9
 *     '$Date: 2014-01-13 13:39:43 -0800 (Mon, 13 Jan 2014) $'
10
 * '$Revision: 8492 $'
11
 *
12
 * This program is free software; you can redistribute it and/or modify
13
 * it under the terms of the GNU General Public License as published by
14
 * the Free Software Foundation; either version 2 of the License, or
15
 * (at your option) any later version.
16
 *
17
 * This program is distributed in the hope that it will be useful,
18
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
 * GNU General Public License for more details.
21
 *
22
 * You should have received a copy of the GNU General Public License
23
 * along with this program; if not, write to the Free Software
24
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
25
 */
26

    
27
package edu.ucsb.nceas.metacat;
28

    
29
import java.net.ConnectException;
30
import java.util.HashMap;
31
import java.util.Vector;
32

    
33
import javax.servlet.http.HttpSession;
34
import javax.servlet.http.HttpServletRequest;
35

    
36
import org.apache.log4j.Logger;
37

    
38
import edu.ucsb.nceas.metacat.properties.PropertyService;
39
import edu.ucsb.nceas.metacat.shared.MetacatUtilException;
40
import edu.ucsb.nceas.metacat.util.AuthUtil;
41
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
42

    
43
/**
44
 * A Class that implements session tracking for MetaCatServlet users.
45
 * User's login data are stored in the session object.
46
 * User authentication is done through a dynamically determined AuthInterface.
47
 */
48
public class AuthSession {
49

    
50
	private String authClass = null;
51
	private HttpSession session = null;
52
	private AuthInterface authService = null;
53
	private String statusMessage = null;
54
	private static Logger logMetacat = Logger.getLogger(AuthSession.class);
55

    
56
	/**
57
	 * Construct an AuthSession
58
	 * @throws ClassNotFoundException 
59
	 * @throws IllegalAccessException 
60
	 * @throws InstantiationException 
61
	 */
62
	public AuthSession() throws InstantiationException, IllegalAccessException, ClassNotFoundException {
63
		// Determine our session authentication method and
64
		// create an instance of the auth class
65
		try {
66
            this.authClass = PropertyService.getProperty("auth.class");
67
        } catch (PropertyNotFoundException e) {
68
            // TODO Auto-generated catch block
69
            e.printStackTrace();
70
        }
71
		this.authService = (AuthInterface) createObject(authClass);
72
	}
73

    
74
	/**
75
	 * Get the new session
76
	 */
77
	public HttpSession getSessions() {
78
		return this.session;
79
	}
80

    
81
	/**
82
	 * determine if the credentials for this session are valid by
83
	 * authenticating them using the authService configured for this session.
84
	 *
85
	 * @param request the request made from the client
86
	 * @param username the username entered when login
87
	 * @param password the password entered when login
88
	 */
89
	public boolean authenticate(HttpServletRequest request, String username,
90
			String password) {
91
		String message = null;
92
		try {
93
			if (authService.authenticate(username, password)) {
94

    
95
				// getGroups returns groupname along with their description.
96
				// hence groups[] is generated from groupsWithDescription[][]
97
				String[][] groupsWithDescription = authService.getGroups(username,
98
						password, username);
99
				String groups[] = null;
100
				if(groupsWithDescription != null) {
101
				    groups = new String[groupsWithDescription.length];
102

    
103
	                for (int i = 0; i < groupsWithDescription.length; i++) {
104
	                    groups[i] = groupsWithDescription[i][0];
105
	                }
106

    
107
				}
108
				
109
				if (groups == null) {
110
                    groups = new String[0];
111
                }
112

    
113
				String[] userInfo = authService.getUserInfo(username, password);
114

    
115
				this.session = createSession(request, username, password, groups,
116
						userInfo);
117
				String sessionId = session.getId();
118
				message = "Authentication successful for user: " + username;
119
				this.statusMessage = formatOutput("login", message, sessionId, username,
120
						groups, userInfo);
121
				return true;
122
			} else {
123
				message = "Authentication failed for user: " + username;
124
				this.statusMessage = formatOutput("unauth_login", message);
125
				return false;
126
			}
127
		} catch (ConnectException ce) {
128
			message = "Connection to the authentication service failed in "
129
					+ "AuthSession.authenticate: " + ce.getMessage();
130
		} catch (IllegalStateException ise) {
131
			message = ise.getMessage();
132
		}
133

    
134
		this.statusMessage = formatOutput("error_login", message);
135
		return false;
136
	}
137

    
138
	/** Get new HttpSession and store username & password in it */
139
	private HttpSession createSession(HttpServletRequest request, String username,
140
			String password, String[] groups, String[] userInfo)
141
			throws IllegalStateException {
142

    
143
		// get the current session object, create one if necessary
144
		HttpSession session = request.getSession(true);
145

    
146
		// if it is still in use invalidate and get a new one
147
		if (!session.isNew()) {
148
			logMetacat.info("in session is not new");
149
			logMetacat.info("the old session id is : " + session.getId());
150
			logMetacat.info("the old session username : "
151
					+ session.getAttribute("username"));
152
			session.invalidate();
153
			logMetacat.info("in session is not new");
154
			session = request.getSession(true);
155
		}
156
		// store the username, password, and groupname (the first only)
157
		// in the session obj for use on subsequent calls to Metacat servlet
158
		session.setMaxInactiveInterval(-1);
159
		session.setAttribute("username", username);
160
		session.setAttribute("password", password);
161

    
162
		if (userInfo != null & userInfo.length == 3) {
163
			session.setAttribute("name", userInfo[0]);
164
			session.setAttribute("organization", userInfo[1]);
165
			session.setAttribute("email", userInfo[2]);
166
		}
167

    
168
		if (groups.length > 0) {
169
			session.setAttribute("groupnames", groups);
170
		}
171
		logMetacat.info("the new session id is : " + session.getId());
172
		logMetacat.info("the new session username : " + session.getAttribute("username"));
173
		return session;
174
	}
175

    
176
	/**
177
	 * Get the message associated with authenticating this session. The
178
	 * message is formatted in XML.
179
	 */
180
	public String getMessage() {
181
		return this.statusMessage;
182
	}
183

    
184
	/**
185
	 * Get all groups and users from authentication scheme.
186
	 * The output is formatted in XML.
187
	 * @param user the user which requests the information
188
	 * @param password the user's password
189
	 */
190
	public String getPrincipals(String user, String password) throws ConnectException {
191
		return authService.getPrincipals(user, password);
192
	}
193
	
194
	/**
195
	 * Get attributes describing a user or group
196
	 * 
197
	 * @param foruser
198
	 *            the user for which the attribute list is requested
199
	 * @returns HashMap a map of attribute name to a Vector of values
200
	 */
201
	public HashMap<String, Vector<String>> getAttributes(String foruser)
202
			throws ConnectException {
203
		return authService.getAttributes(foruser);
204
	}
205

    
206
	/*
207
	 * format the output in xml for processing from client applications
208
	 * 
209
	 * @param tag the root element tag for the message (error or success) @param
210
	 * message the message content of the root element
211
	 */
212
	private String formatOutput(String tag, String message) {
213
		return formatOutput(tag, message, null, null, null, null);
214
	}
215

    
216
	/*
217
	 * format the output in xml for processing from client applications
218
	 *
219
	 * @param tag the root element tag for the message (error or success)
220
	 * @param message the message content of the root element
221
	 * @param sessionId the session identifier for a successful login
222
	 */
223
	private String formatOutput(String tag, String message, String sessionId,
224
			String username, String[] groups, String userInfo[]) {
225
		StringBuffer out = new StringBuffer();
226

    
227
		out.append("<?xml version=\"1.0\"?>\n");
228
		out.append("<" + tag + ">");
229
		out.append("\n  <message>" + message + "</message>\n");
230
		if (sessionId != null) {
231
			out.append("\n  <sessionId>" + sessionId + "</sessionId>\n");
232

    
233
			if (userInfo != null && userInfo[0] != null) {
234
				out.append("\n<name>\n");
235
				out.append(userInfo[0]);
236
				out.append("\n</name>\n");
237
			}
238
      
239
			if(userInfo != null && userInfo[1]!=null){
240
				out.append("\n<organization>\n");
241
				out.append(userInfo[1]);
242
				out.append("\n</organization>\n");
243
			}
244
      
245
			if(userInfo != null && userInfo[2]!=null){
246
				out.append("\n<email>\n");
247
				out.append(userInfo[2]);
248
				out.append("\n</email>\n");
249
			}
250

    
251
			try {
252
				// insert <isAdministrator> tag if the user is an administrator
253
				if (AuthUtil.isAdministrator(username, groups)) {
254
					out.append("\n  <isAdministrator></isAdministrator>\n");
255
				}
256
			} catch (MetacatUtilException ue) {
257
				logMetacat.error("Could not determine if user is administrator. "
258
						+ "Omitting from xml output: " + ue.getMessage());
259
			}
260
			
261
			try {
262
				// insert <isModerator> tag if the user is a Moderator
263
				if (AuthUtil.isModerator(username, groups)) {
264
					out.append("\n  <isModerator></isModerator>\n");
265
				}
266
			} catch (MetacatUtilException ue) {
267
				logMetacat.error("Could not determine if user is moderator. "
268
						+ "Omitting from xml output: " + ue.getMessage());
269
			}
270
		}
271
		out.append("</" + tag + ">");
272

    
273
		return out.toString();
274
	}
275

    
276
	/**
277
	 * Instantiate a class using the name of the class at runtime
278
	 *
279
	 * @param className the fully qualified name of the class to instantiate
280
	 */
281
	private static Object createObject(String className) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
282

    
283
		Object object = null;
284
//		try {
285
			Class classDefinition = Class.forName(className);
286
			object = classDefinition.newInstance();
287
//		} catch (InstantiationException e) {
288
//			throw e;
289
//		} catch (IllegalAccessException e) {
290
//			throw e;
291
//		} catch (ClassNotFoundException e) {
292
//			throw e;
293
//		}
294
		return object;
295
	}
296
	
297
	/**
298
	 * Instantiate a class using the name of the class at runtime
299
	 *
300
	 * @param className the fully qualified name of the class to instantiate
301
	 */
302
	private static Object createObject(String className, String orgName) throws Exception {
303

    
304
		Object object = null;
305
		try {
306
			Class classDefinition = Class.forName(className);
307
			object = classDefinition.newInstance();
308
		} catch (InstantiationException e) {
309
			throw e;
310
		} catch (IllegalAccessException e) {
311
			throw e;
312
		} catch (ClassNotFoundException e) {
313
			throw e;
314
		}
315
		return object;
316
	}
317
}
(7-7/63)