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-07-06 21:25:34 -0700 (Sun, 06 Jul 2008) $'
10
 * '$Revision: 4080 $'
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 javax.servlet.http.HttpSession;
31
import javax.servlet.http.HttpServletRequest;
32

    
33
import org.apache.log4j.Logger;
34

    
35
import edu.ucsb.nceas.metacat.service.PropertyService;
36
import edu.ucsb.nceas.metacat.util.LDAPUtil;
37
import edu.ucsb.nceas.metacat.util.UtilException;
38

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

    
46
	private String authClass = null;
47
	private HttpSession session = null;
48
	private AuthInterface authService = null;
49
	private String statusMessage = null;
50
	private static Logger logMetacat = Logger.getLogger(AuthSession.class);
51

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

    
62
	/**
63
	 * Get the new session
64
	 */
65
	public HttpSession getSessions() {
66
		return this.session;
67
	}
68

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

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

    
89
				for (int i = 0; i < groupsWithDescription.length; i++) {
90
					groups[i] = groupsWithDescription[i][0];
91
				}
92

    
93
				if (groups == null) {
94
					groups = new String[0];
95
				}
96

    
97
				String[] userInfo = authService.getUserInfo(username, password);
98

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

    
118
		this.statusMessage = formatOutput("error_login", message);
119
		return false;
120
	}
121

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

    
127
		// get the current session object, create one if necessary
128
		HttpSession session = request.getSession(true);
129

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

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

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

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

    
168
	/**
169
	 * Get all groups and users from authentication scheme.
170
	 * The output is formatted in XML.
171
	 * @param user the user which requests the information
172
	 * @param password the user's password
173
	 */
174
	public String getPrincipals(String user, String password) throws ConnectException {
175
		return authService.getPrincipals(user, password);
176
	}
177

    
178
	/*
179
	 * format the output in xml for processing from client applications
180
	 *
181
	 * @param tag the root element tag for the message (error or success)
182
	 * @param message the message content of the root element
183
	 */
184
	private String formatOutput(String tag, String message) {
185
		return formatOutput(tag, message, null, null, null, null);
186
	}
187

    
188
	/*
189
	 * format the output in xml for processing from client applications
190
	 *
191
	 * @param tag the root element tag for the message (error or success)
192
	 * @param message the message content of the root element
193
	 * @param sessionId the session identifier for a successful login
194
	 */
195
	private String formatOutput(String tag, String message, String sessionId,
196
			String username, String[] groups, String userInfo[]) {
197
		StringBuffer out = new StringBuffer();
198

    
199
		out.append("<?xml version=\"1.0\"?>\n");
200
		out.append("<" + tag + ">");
201
		out.append("\n  <message>" + message + "</message>\n");
202
		if (sessionId != null) {
203
			out.append("\n  <sessionId>" + sessionId + "</sessionId>\n");
204

    
205
			if (userInfo != null && userInfo[0] != null) {
206
				out.append("\n<name>\n");
207
				out.append(userInfo[0]);
208
				out.append("\n</name>\n");
209
			}
210

    
211
			try {
212
				// insert <isAdministrator> tag if the user is an administrator
213
				if (LDAPUtil.isAdministrator(username, groups)) {
214
					out.append("\n  <isAdministrator></isAdministrator>\n");
215
				}
216
			} catch (UtilException ue) {
217
				logMetacat.error("Could not determine if user is administrator. "
218
						+ "Omitting from xml output: " + ue.getMessage());
219
			}
220

    
221
			// insert <isModerator> tag if the user is a Moderator
222
			if (LDAPUtil.isModerator(username, groups)) {
223
				out.append("\n  <isModerator></isModerator>\n");
224
			}
225
		}
226
		out.append("</" + tag + ">");
227

    
228
		return out.toString();
229
	}
230

    
231
	/**
232
	 * Instantiate a class using the name of the class at runtime
233
	 *
234
	 * @param className the fully qualified name of the class to instantiate
235
	 */
236
	private static Object createObject(String className) throws Exception {
237

    
238
		Object object = null;
239
		try {
240
			Class classDefinition = Class.forName(className);
241
			object = classDefinition.newInstance();
242
		} catch (InstantiationException e) {
243
			throw e;
244
		} catch (IllegalAccessException e) {
245
			throw e;
246
		} catch (ClassNotFoundException e) {
247
			throw e;
248
		}
249
		return object;
250
	}
251
	
252
	/**
253
	 * Instantiate a class using the name of the class at runtime
254
	 *
255
	 * @param className the fully qualified name of the class to instantiate
256
	 */
257
	private static Object createObject(String className, String orgName) throws Exception {
258

    
259
		Object object = null;
260
		try {
261
			Class classDefinition = Class.forName(className);
262
			object = classDefinition.newInstance();
263
		} catch (InstantiationException e) {
264
			throw e;
265
		} catch (IllegalAccessException e) {
266
			throw e;
267
		} catch (ClassNotFoundException e) {
268
			throw e;
269
		}
270
		return object;
271
	}
272
}
(11-11/67)