Project

General

Profile

1 503 bojilova
/**
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$'
9
 *     '$Date$'
10
 * '$Revision$'
11 669 jones
 *
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 503 bojilova
 */
26
27
package edu.ucsb.nceas.metacat;
28
29
import java.net.ConnectException;
30 4588 daigle
import java.util.HashMap;
31
import java.util.Vector;
32
33 503 bojilova
import javax.servlet.http.HttpSession;
34
import javax.servlet.http.HttpServletRequest;
35
36 2663 sgarg
import org.apache.log4j.Logger;
37
38 5030 daigle
import edu.ucsb.nceas.metacat.properties.PropertyService;
39 5015 daigle
import edu.ucsb.nceas.metacat.shared.MetacatUtilException;
40 4588 daigle
import edu.ucsb.nceas.metacat.util.AuthUtil;
41 6932 jones
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
42 4080 daigle
43 503 bojilova
/**
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 4080 daigle
	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 2058 sgarg
56 4080 daigle
	/**
57
	 * Construct an AuthSession
58 6932 jones
	 * @throws ClassNotFoundException
59
	 * @throws IllegalAccessException
60
	 * @throws InstantiationException
61 4080 daigle
	 */
62 6932 jones
	public AuthSession() throws InstantiationException, IllegalAccessException, ClassNotFoundException {
63 4080 daigle
		// Determine our session authentication method and
64
		// create an instance of the auth class
65 6932 jones
		try {
66
            this.authClass = PropertyService.getProperty("auth.class");
67
        } catch (PropertyNotFoundException e) {
68
            // TODO Auto-generated catch block
69
            e.printStackTrace();
70
        }
71 4080 daigle
		this.authService = (AuthInterface) createObject(authClass);
72
	}
73 2058 sgarg
74 4080 daigle
	/**
75
	 * Get the new session
76
	 */
77
	public HttpSession getSessions() {
78
		return this.session;
79
	}
80 503 bojilova
81 4080 daigle
	/**
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 2058 sgarg
95 4080 daigle
				// 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[] = new String[groupsWithDescription.length];
100 2058 sgarg
101 4080 daigle
				for (int i = 0; i < groupsWithDescription.length; i++) {
102
					groups[i] = groupsWithDescription[i][0];
103
				}
104 2058 sgarg
105 4080 daigle
				if (groups == null) {
106
					groups = new String[0];
107
				}
108 503 bojilova
109 4080 daigle
				String[] userInfo = authService.getUserInfo(username, password);
110 509 bojilova
111 4080 daigle
				this.session = createSession(request, username, password, groups,
112
						userInfo);
113
				String sessionId = session.getId();
114
				message = "Authentication successful for user: " + username;
115
				this.statusMessage = formatOutput("login", message, sessionId, username,
116
						groups, userInfo);
117
				return true;
118
			} else {
119
				message = "Authentication failed for user: " + username;
120
				this.statusMessage = formatOutput("unauth_login", message);
121
				return false;
122
			}
123
		} catch (ConnectException ce) {
124
			message = "Connection to the authentication service failed in "
125
					+ "AuthSession.authenticate: " + ce.getMessage();
126
		} catch (IllegalStateException ise) {
127
			message = ise.getMessage();
128
		}
129 509 bojilova
130 4080 daigle
		this.statusMessage = formatOutput("error_login", message);
131
		return false;
132
	}
133 509 bojilova
134 4080 daigle
	/** Get new HttpSession and store username & password in it */
135
	private HttpSession createSession(HttpServletRequest request, String username,
136
			String password, String[] groups, String[] userInfo)
137
			throws IllegalStateException {
138 503 bojilova
139 4080 daigle
		// get the current session object, create one if necessary
140
		HttpSession session = request.getSession(true);
141 503 bojilova
142 4080 daigle
		// if it is still in use invalidate and get a new one
143
		if (!session.isNew()) {
144
			logMetacat.info("in session is not new");
145
			logMetacat.info("the old session id is : " + session.getId());
146
			logMetacat.info("the old session username : "
147
					+ session.getAttribute("username"));
148
			session.invalidate();
149
			logMetacat.info("in session is not new");
150
			session = request.getSession(true);
151
		}
152
		// store the username, password, and groupname (the first only)
153
		// in the session obj for use on subsequent calls to Metacat servlet
154
		session.setMaxInactiveInterval(-1);
155
		session.setAttribute("username", username);
156
		session.setAttribute("password", password);
157 1822 jones
158 4080 daigle
		if (userInfo != null & userInfo.length == 3) {
159
			session.setAttribute("name", userInfo[0]);
160
			session.setAttribute("organization", userInfo[1]);
161
			session.setAttribute("email", userInfo[2]);
162
		}
163 2058 sgarg
164 4080 daigle
		if (groups.length > 0) {
165
			session.setAttribute("groupnames", groups);
166
		}
167
		logMetacat.info("the new session id is : " + session.getId());
168
		logMetacat.info("the new session username : " + session.getAttribute("username"));
169
		return session;
170
	}
171 2058 sgarg
172 4080 daigle
	/**
173
	 * Get the message associated with authenticating this session. The
174
	 * message is formatted in XML.
175
	 */
176
	public String getMessage() {
177
		return this.statusMessage;
178
	}
179 503 bojilova
180 4080 daigle
	/**
181
	 * Get all groups and users from authentication scheme.
182
	 * The output is formatted in XML.
183
	 * @param user the user which requests the information
184
	 * @param password the user's password
185
	 */
186
	public String getPrincipals(String user, String password) throws ConnectException {
187
		return authService.getPrincipals(user, password);
188
	}
189 4588 daigle
190
	/**
191
	 * Get attributes describing a user or group
192
	 *
193
	 * @param foruser
194
	 *            the user for which the attribute list is requested
195
	 * @returns HashMap a map of attribute name to a Vector of values
196
	 */
197
	public HashMap<String, Vector<String>> getAttributes(String foruser)
198
			throws ConnectException {
199
		return authService.getAttributes(foruser);
200
	}
201 2058 sgarg
202 4080 daigle
	/*
203
	 * format the output in xml for processing from client applications
204 4588 daigle
	 *
205
	 * @param tag the root element tag for the message (error or success) @param
206
	 * message the message content of the root element
207 4080 daigle
	 */
208
	private String formatOutput(String tag, String message) {
209
		return formatOutput(tag, message, null, null, null, null);
210
	}
211
212
	/*
213
	 * format the output in xml for processing from client applications
214
	 *
215
	 * @param tag the root element tag for the message (error or success)
216
	 * @param message the message content of the root element
217
	 * @param sessionId the session identifier for a successful login
218
	 */
219
	private String formatOutput(String tag, String message, String sessionId,
220
			String username, String[] groups, String userInfo[]) {
221
		StringBuffer out = new StringBuffer();
222
223
		out.append("<?xml version=\"1.0\"?>\n");
224
		out.append("<" + tag + ">");
225
		out.append("\n  <message>" + message + "</message>\n");
226
		if (sessionId != null) {
227
			out.append("\n  <sessionId>" + sessionId + "</sessionId>\n");
228
229
			if (userInfo != null && userInfo[0] != null) {
230
				out.append("\n<name>\n");
231
				out.append(userInfo[0]);
232
				out.append("\n</name>\n");
233
			}
234 4936 cjones
235
			if(userInfo != null && userInfo[1]!=null){
236
				out.append("\n<organization>\n");
237
				out.append(userInfo[1]);
238
				out.append("\n</organization>\n");
239
			}
240
241
			if(userInfo != null && userInfo[2]!=null){
242
				out.append("\n<email>\n");
243
				out.append(userInfo[2]);
244
				out.append("\n</email>\n");
245
			}
246 4080 daigle
247
			try {
248
				// insert <isAdministrator> tag if the user is an administrator
249 4588 daigle
				if (AuthUtil.isAdministrator(username, groups)) {
250 4080 daigle
					out.append("\n  <isAdministrator></isAdministrator>\n");
251
				}
252 4854 daigle
			} catch (MetacatUtilException ue) {
253 4080 daigle
				logMetacat.error("Could not determine if user is administrator. "
254
						+ "Omitting from xml output: " + ue.getMessage());
255
			}
256 4627 daigle
257
			try {
258
				// insert <isModerator> tag if the user is a Moderator
259
				if (AuthUtil.isModerator(username, groups)) {
260
					out.append("\n  <isModerator></isModerator>\n");
261
				}
262 4854 daigle
			} catch (MetacatUtilException ue) {
263 4627 daigle
				logMetacat.error("Could not determine if user is moderator. "
264
						+ "Omitting from xml output: " + ue.getMessage());
265 4080 daigle
			}
266
		}
267
		out.append("</" + tag + ">");
268
269
		return out.toString();
270
	}
271
272
	/**
273
	 * Instantiate a class using the name of the class at runtime
274
	 *
275
	 * @param className the fully qualified name of the class to instantiate
276
	 */
277 6932 jones
	private static Object createObject(String className) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
278 4080 daigle
279
		Object object = null;
280 6932 jones
//		try {
281 4080 daigle
			Class classDefinition = Class.forName(className);
282
			object = classDefinition.newInstance();
283 6932 jones
//		} catch (InstantiationException e) {
284
//			throw e;
285
//		} catch (IllegalAccessException e) {
286
//			throw e;
287
//		} catch (ClassNotFoundException e) {
288
//			throw e;
289
//		}
290 4080 daigle
		return object;
291
	}
292
293
	/**
294
	 * Instantiate a class using the name of the class at runtime
295
	 *
296
	 * @param className the fully qualified name of the class to instantiate
297
	 */
298
	private static Object createObject(String className, String orgName) throws Exception {
299
300
		Object object = null;
301
		try {
302
			Class classDefinition = Class.forName(className);
303
			object = classDefinition.newInstance();
304
		} catch (InstantiationException e) {
305
			throw e;
306
		} catch (IllegalAccessException e) {
307
			throw e;
308
		} catch (ClassNotFoundException e) {
309
			throw e;
310
		}
311
		return object;
312
	}
313 503 bojilova
}