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