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: daigle $'
9
 *     '$Date: 2008-11-19 15:23:42 -0800 (Wed, 19 Nov 2008) $'
10
 * '$Revision: 4588 $'
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.service.PropertyService;
39
import edu.ucsb.nceas.metacat.util.AuthUtil;
40
import edu.ucsb.nceas.metacat.util.UtilException;
41

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

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

    
55
	/**
56
	 * Construct an AuthSession
57
	 */
58
	public AuthSession() throws Exception {
59
		// Determine our session authentication method and
60
		// create an instance of the auth class
61
		this.authClass = PropertyService.getProperty("auth.class");
62
		this.authService = (AuthInterface) createObject(authClass);
63
	}
64

    
65
	/**
66
	 * Get the new session
67
	 */
68
	public HttpSession getSessions() {
69
		return this.session;
70
	}
71

    
72
	/**
73
	 * determine if the credentials for this session are valid by
74
	 * authenticating them using the authService configured for this session.
75
	 *
76
	 * @param request the request made from the client
77
	 * @param username the username entered when login
78
	 * @param password the password entered when login
79
	 */
80
	public boolean authenticate(HttpServletRequest request, String username,
81
			String password) {
82
		String message = null;
83
		try {
84
			if (authService.authenticate(username, password)) {
85

    
86
				// getGroups returns groupname along with their description.
87
				// hence groups[] is generated from groupsWithDescription[][]
88
				String[][] groupsWithDescription = authService.getGroups(username,
89
						password, username);
90
				String groups[] = new String[groupsWithDescription.length];
91

    
92
				for (int i = 0; i < groupsWithDescription.length; i++) {
93
					groups[i] = groupsWithDescription[i][0];
94
				}
95

    
96
				if (groups == null) {
97
					groups = new String[0];
98
				}
99

    
100
				String[] userInfo = authService.getUserInfo(username, password);
101

    
102
				this.session = createSession(request, username, password, groups,
103
						userInfo);
104
				String sessionId = session.getId();
105
				message = "Authentication successful for user: " + username;
106
				this.statusMessage = formatOutput("login", message, sessionId, username,
107
						groups, userInfo);
108
				return true;
109
			} else {
110
				message = "Authentication failed for user: " + username;
111
				this.statusMessage = formatOutput("unauth_login", message);
112
				return false;
113
			}
114
		} catch (ConnectException ce) {
115
			message = "Connection to the authentication service failed in "
116
					+ "AuthSession.authenticate: " + ce.getMessage();
117
		} catch (IllegalStateException ise) {
118
			message = ise.getMessage();
119
		}
120

    
121
		this.statusMessage = formatOutput("error_login", message);
122
		return false;
123
	}
124

    
125
	/** Get new HttpSession and store username & password in it */
126
	private HttpSession createSession(HttpServletRequest request, String username,
127
			String password, String[] groups, String[] userInfo)
128
			throws IllegalStateException {
129

    
130
		// get the current session object, create one if necessary
131
		HttpSession session = request.getSession(true);
132

    
133
		// if it is still in use invalidate and get a new one
134
		if (!session.isNew()) {
135
			logMetacat.info("in session is not new");
136
			logMetacat.info("the old session id is : " + session.getId());
137
			logMetacat.info("the old session username : "
138
					+ session.getAttribute("username"));
139
			session.invalidate();
140
			logMetacat.info("in session is not new");
141
			session = request.getSession(true);
142
		}
143
		// store the username, password, and groupname (the first only)
144
		// in the session obj for use on subsequent calls to Metacat servlet
145
		session.setMaxInactiveInterval(-1);
146
		session.setAttribute("username", username);
147
		session.setAttribute("password", password);
148

    
149
		if (userInfo != null & userInfo.length == 3) {
150
			session.setAttribute("name", userInfo[0]);
151
			session.setAttribute("organization", userInfo[1]);
152
			session.setAttribute("email", userInfo[2]);
153
		}
154

    
155
		if (groups.length > 0) {
156
			session.setAttribute("groupnames", groups);
157
		}
158
		logMetacat.info("the new session id is : " + session.getId());
159
		logMetacat.info("the new session username : " + session.getAttribute("username"));
160
		return session;
161
	}
162

    
163
	/**
164
	 * Get the message associated with authenticating this session. The
165
	 * message is formatted in XML.
166
	 */
167
	public String getMessage() {
168
		return this.statusMessage;
169
	}
170

    
171
	/**
172
	 * Get all groups and users from authentication scheme.
173
	 * The output is formatted in XML.
174
	 * @param user the user which requests the information
175
	 * @param password the user's password
176
	 */
177
	public String getPrincipals(String user, String password) throws ConnectException {
178
		return authService.getPrincipals(user, password);
179
	}
180
	
181
	/**
182
	 * Get attributes describing a user or group
183
	 * 
184
	 * @param foruser
185
	 *            the user for which the attribute list is requested
186
	 * @returns HashMap a map of attribute name to a Vector of values
187
	 */
188
	public HashMap<String, Vector<String>> getAttributes(String foruser)
189
			throws ConnectException {
190
		return authService.getAttributes(foruser);
191
	}
192

    
193
	/*
194
	 * format the output in xml for processing from client applications
195
	 * 
196
	 * @param tag the root element tag for the message (error or success) @param
197
	 * message the message content of the root element
198
	 */
199
	private String formatOutput(String tag, String message) {
200
		return formatOutput(tag, message, null, null, null, null);
201
	}
202

    
203
	/*
204
	 * format the output in xml for processing from client applications
205
	 *
206
	 * @param tag the root element tag for the message (error or success)
207
	 * @param message the message content of the root element
208
	 * @param sessionId the session identifier for a successful login
209
	 */
210
	private String formatOutput(String tag, String message, String sessionId,
211
			String username, String[] groups, String userInfo[]) {
212
		StringBuffer out = new StringBuffer();
213

    
214
		out.append("<?xml version=\"1.0\"?>\n");
215
		out.append("<" + tag + ">");
216
		out.append("\n  <message>" + message + "</message>\n");
217
		if (sessionId != null) {
218
			out.append("\n  <sessionId>" + sessionId + "</sessionId>\n");
219

    
220
			if (userInfo != null && userInfo[0] != null) {
221
				out.append("\n<name>\n");
222
				out.append(userInfo[0]);
223
				out.append("\n</name>\n");
224
			}
225

    
226
			try {
227
				// insert <isAdministrator> tag if the user is an administrator
228
				if (AuthUtil.isAdministrator(username, groups)) {
229
					out.append("\n  <isAdministrator></isAdministrator>\n");
230
				}
231
			} catch (UtilException ue) {
232
				logMetacat.error("Could not determine if user is administrator. "
233
						+ "Omitting from xml output: " + ue.getMessage());
234
			}
235

    
236
			// insert <isModerator> tag if the user is a Moderator
237
			if (AuthUtil.isModerator(username, groups)) {
238
				out.append("\n  <isModerator></isModerator>\n");
239
			}
240
		}
241
		out.append("</" + tag + ">");
242

    
243
		return out.toString();
244
	}
245

    
246
	/**
247
	 * Instantiate a class using the name of the class at runtime
248
	 *
249
	 * @param className the fully qualified name of the class to instantiate
250
	 */
251
	private static Object createObject(String className) throws Exception {
252

    
253
		Object object = null;
254
		try {
255
			Class classDefinition = Class.forName(className);
256
			object = classDefinition.newInstance();
257
		} catch (InstantiationException e) {
258
			throw e;
259
		} catch (IllegalAccessException e) {
260
			throw e;
261
		} catch (ClassNotFoundException e) {
262
			throw e;
263
		}
264
		return object;
265
	}
266
	
267
	/**
268
	 * Instantiate a class using the name of the class at runtime
269
	 *
270
	 * @param className the fully qualified name of the class to instantiate
271
	 */
272
	private static Object createObject(String className, String orgName) throws Exception {
273

    
274
		Object object = null;
275
		try {
276
			Class classDefinition = Class.forName(className);
277
			object = classDefinition.newInstance();
278
		} catch (InstantiationException e) {
279
			throw e;
280
		} catch (IllegalAccessException e) {
281
			throw e;
282
		} catch (ClassNotFoundException e) {
283
			throw e;
284
		}
285
		return object;
286
	}
287
}
(11-11/68)