Project

General

Profile

« Previous | Next » 

Revision 4080

Added by daigle almost 16 years ago

Merge 1.9 changes into Head

View differences:

AuthSession.java
32 32

  
33 33
import org.apache.log4j.Logger;
34 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

  
35 39
/**
36 40
 * A Class that implements session tracking for MetaCatServlet users.
37 41
 * User's login data are stored in the session object.
......
39 43
 */
40 44
public class AuthSession {
41 45

  
42
  private String authClass = null;
43
  private HttpSession session = null;
44
  private AuthInterface authService = null;
45
  private String statusMessage = null;
46
  private static Logger logMetacat = Logger.getLogger(AuthSession.class);
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);
47 51

  
48
  /**
49
   * Construct an AuthSession
50
   */
51
  public AuthSession() throws Exception {
52
    // Determine our session authentication method and
53
    // create an instance of the auth class
54
    MetaCatUtil util = new MetaCatUtil();
55
    this.authClass = util.getOption("authclass");
56
    this.authService = (AuthInterface)createObject(authClass);
57
  }
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
	}
58 61

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

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

  
81
        // getGroups returns groupname along with their description.
82
        // hence groups[] is generated from groupsWithDescription[][]
83
        String[][] groupsWithDescription =
84
            authService.getGroups(username,password,username);
85
        String groups[] = new String[groupsWithDescription.length];
86
        
87
        for(int i=0; i<groupsWithDescription.length; i++){
88
          groups[i] = groupsWithDescription[i][0];
89
        }
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];
90 88

  
91
        if(groups == null)
92
        {
93
          groups = new String[0];
94
        }
95
        
96
        String[] userInfo =
97
            authService.getUserInfo(username,password);
98
        
99
        
100
        this.session = createSession(request, username, password, groups, userInfo);
101
        String sessionId = session.getId();
102
        message = "Authentication successful for user: " + username;
103
        this.statusMessage = formatOutput("login", message, sessionId, username, groups, userInfo);
104
        return true;
105
      } else {
106
        message = "Authentication failed for user: " + username;
107
        this.statusMessage = formatOutput("unauth_login", message);
108
        return false;
109
      }
110
    } catch ( ConnectException ce ) {
111
      message = "Connection to the authentication service failed in " +
112
                "AuthSession.authenticate: " + ce.getMessage();
113
    } catch ( IllegalStateException ise ) {
114
      message = ise.getMessage();
115
    }
89
				for (int i = 0; i < groupsWithDescription.length; i++) {
90
					groups[i] = groupsWithDescription[i][0];
91
				}
116 92

  
117
    this.statusMessage = formatOutput("error_login", message);
118
    return false;
119
  }
93
				if (groups == null) {
94
					groups = new String[0];
95
				}
120 96

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

  
127
    // get the current session object, create one if necessary
128
    HttpSession session = request.getSession(true);
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
		}
129 117

  
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 : " +
134
                                session.getId());
135
      logMetacat.info("the old session username : " +
136
                                session.getAttribute("username"));
137
      session.invalidate();
138
      logMetacat.info("in session is not new");
139
      session = request.getSession(true);
140
    }
141
    // store the username, password, and groupname (the first only)
142
    // in the session obj for use on subsequent calls to Metacat servlet
143
    session.setMaxInactiveInterval(-1);
144
    session.setAttribute("username", username);
145
    session.setAttribute("password", password);
146
    
147
    if ( userInfo!=null & userInfo.length == 3 ) {
148
        session.setAttribute("name", userInfo[0]);
149
        session.setAttribute("organization", userInfo[1]);
150
        session.setAttribute("email", userInfo[2]);
151
    }
152
    
153
    if ( groups.length > 0 ) {
154
      session.setAttribute("groupnames", groups);
155
    }
156
     logMetacat.info("the new session id is : " +
157
                                session.getId());
158
     logMetacat.info("the new session username : " +
159
                                session.getAttribute("username"));
160
    return session;
161
  }
118
		this.statusMessage = formatOutput("error_login", message);
119
		return false;
120
	}
162 121

  
163
  /**
164
   * Get the message associated with authenticating this session. The
165
   * message is formatted in XML.
166
   */
167
  public String getMessage()
168
  {
169
    return this.statusMessage;
170
  }
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 {
171 126

  
172
  /**
173
   * Get all groups and users from authentication scheme.
174
   * The output is formatted in XML.
175
   * @param user the user which requests the information
176
   * @param password the user's password
177
   */
178
  public String getPrincipals(String user, String password)
179
                throws ConnectException
180
  {
181
    return authService.getPrincipals(user, password);
182
  }
127
		// get the current session object, create one if necessary
128
		HttpSession session = request.getSession(true);
183 129

  
184
  /*
185
   * format the output in xml for processing from client applications
186
   *
187
   * @param tag the root element tag for the message (error or success)
188
   * @param message the message content of the root element
189
   */
190
  private String formatOutput(String tag, String message)
191
  {
192
      return formatOutput(tag, message, null, null, null, null);
193
  }
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);
194 145

  
195
  /*
196
   * format the output in xml for processing from client applications
197
   *
198
   * @param tag the root element tag for the message (error or success)
199
   * @param message the message content of the root element
200
   * @param sessionId the session identifier for a successful login
201
   */
202
  private String formatOutput(String tag, String message, 
203
		  String sessionId, String username, String[] groups,
204
		  String userInfo[])
205
  {
206
    StringBuffer out = new StringBuffer();
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
		}
207 151

  
208
    out.append("<?xml version=\"1.0\"?>\n");
209
    out.append("<" + tag + ">");
210
    out.append("\n  <message>" + message + "</message>\n");
211
    if (sessionId != null) {
212
        out.append("\n  <sessionId>" + sessionId + "</sessionId>\n");
213
        
214
        if(userInfo != null && userInfo[0]!=null){
215
        	out.append("\n<name>\n");
216
        	out.append(userInfo[0]);
217
        	out.append("\n</name>\n");
218
        }
219
        
220
        // insert <isAdministrator> tag if the user is an administrator
221
        if(MetaCatUtil.isAdministrator(username,groups)){
222
            out.append("\n  <isAdministrator></isAdministrator>\n");
223
        }
224
        
225
        // insert <isModerator> tag if the user is a Moderator
226
        if(MetaCatUtil.isModerator(username,groups)){
227
            out.append("\n  <isModerator></isModerator>\n");
228
        }
229
    }
230
    out.append("</" + tag + ">");
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
	}
231 159

  
232
    return out.toString();
233
  }
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
	}
234 167

  
235
  /**
236
   * Instantiate a class using the name of the class at runtime
237
   *
238
   * @param className the fully qualified name of the class to instantiate
239
   */
240
  private static Object createObject(String className) throws Exception {
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
	}
241 177

  
242
    Object object = null;
243
    try {
244
      Class classDefinition = Class.forName(className);
245
      object = classDefinition.newInstance();
246
    } catch (InstantiationException e) {
247
      throw e;
248
    } catch (IllegalAccessException e) {
249
      throw e;
250
    } catch (ClassNotFoundException e) {
251
      throw e;
252
    }
253
    return object;
254
  }
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
	}
255 272
}

Also available in: Unified diff