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
 *    Release: @release@
8
 *
9
 *   '$Author$'
10
 *     '$Date$'
11
 * '$Revision$'
12 669 jones
 *
13
 * This program is free software; you can redistribute it and/or modify
14
 * it under the terms of the GNU General Public License as published by
15
 * the Free Software Foundation; either version 2 of the License, or
16
 * (at your option) any later version.
17
 *
18
 * This program is distributed in the hope that it will be useful,
19
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21
 * GNU General Public License for more details.
22
 *
23
 * You should have received a copy of the GNU General Public License
24
 * along with this program; if not, write to the Free Software
25
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
26 503 bojilova
 */
27
28
package edu.ucsb.nceas.metacat;
29
30
import java.net.ConnectException;
31
import javax.servlet.http.HttpSession;
32
import javax.servlet.http.HttpServletRequest;
33
34 2663 sgarg
import org.apache.log4j.Logger;
35
36 503 bojilova
/**
37
 * A Class that implements session tracking for MetaCatServlet users.
38
 * User's login data are stored in the session object.
39
 * User authentication is done through a dynamically determined AuthInterface.
40
 */
41
public class AuthSession {
42
43
  private String authClass = null;
44
  private HttpSession session = null;
45
  private AuthInterface authService = null;
46
  private String statusMessage = null;
47 2663 sgarg
  private static Logger logMetacat = Logger.getLogger(AuthSession.class);
48 2058 sgarg
49
  /**
50 503 bojilova
   * Construct an AuthSession
51
   */
52 509 bojilova
  public AuthSession() throws Exception {
53 503 bojilova
    // Determine our session authentication method and
54
    // create an instance of the auth class
55
    MetaCatUtil util = new MetaCatUtil();
56 728 bojilova
    this.authClass = util.getOption("authclass");
57
    this.authService = (AuthInterface)createObject(authClass);
58 503 bojilova
  }
59 2058 sgarg
60 2045 tao
  /**
61
   * Get the new session
62
   */
63
  public HttpSession getSessions()
64
  {
65
    return this.session;
66
  }
67 503 bojilova
68 2058 sgarg
  /**
69
   * determine if the credentials for this session are valid by
70 503 bojilova
   * authenticating them using the authService configured for this session.
71 509 bojilova
   *
72
   * @param request the request made from the client
73
   * @param username the username entered when login
74
   * @param password the password entered when login
75 503 bojilova
   */
76 2058 sgarg
  public boolean authenticate(HttpServletRequest request,
77
                              String username, String password)  {
78 509 bojilova
    String message = null;
79 2058 sgarg
    try {
80 503 bojilova
      if ( authService.authenticate(username, password) ) {
81 2058 sgarg
82
        // getGroups returns groupname along with their description.
83
        // hence groups[] is generated from groupsWithDescription[][]
84
        String[][] groupsWithDescription =
85
            authService.getGroups(username,password,username);
86
        String groups[] = new String[groupsWithDescription.length];
87 2679 sgarg
88 2058 sgarg
        for(int i=0; i<groupsWithDescription.length; i++){
89
          groups[i] = groupsWithDescription[i][0];
90
        }
91
92 888 berkley
        if(groups == null)
93
        {
94
          groups = new String[0];
95
        }
96 2679 sgarg
97
        String[] userInfo =
98
            authService.getUserInfo(username,password);
99
100
101
        this.session = createSession(request, username, password, groups, userInfo);
102 1822 jones
        String sessionId = session.getId();
103 510 bojilova
        message = "Authentication successful for user: " + username;
104 2679 sgarg
        this.statusMessage = formatOutput("login", message, sessionId, username, groups, userInfo);
105 509 bojilova
        return true;
106 2058 sgarg
      } else {
107 509 bojilova
        message = "Authentication failed for user: " + username;
108 510 bojilova
        this.statusMessage = formatOutput("unauth_login", message);
109
        return false;
110 2058 sgarg
      }
111 503 bojilova
    } catch ( ConnectException ce ) {
112 675 berkley
      message = "Connection to the authentication service failed in " +
113
                "AuthSession.authenticate: " + ce.getMessage();
114 509 bojilova
    } catch ( IllegalStateException ise ) {
115
      message = ise.getMessage();
116 503 bojilova
    }
117 2058 sgarg
118 510 bojilova
    this.statusMessage = formatOutput("error_login", message);
119 509 bojilova
    return false;
120 503 bojilova
  }
121
122 509 bojilova
  /** Get new HttpSession and store username & password in it */
123 2058 sgarg
  private HttpSession createSession(HttpServletRequest request,
124 725 bojilova
                                 String username, String password,
125 2679 sgarg
                                 String[] groups, String[] userInfo)
126 725 bojilova
                      throws IllegalStateException {
127 509 bojilova
128
    // get the current session object, create one if necessary
129
    HttpSession session = request.getSession(true);
130
131
    // if it is still in use invalidate and get a new one
132
    if ( !session.isNew() ) {
133 2663 sgarg
      logMetacat.info("in session is not new");
134
      logMetacat.info("the old session id is : " +
135 2589 sgarg
                                session.getId());
136 2663 sgarg
      logMetacat.info("the old session username : " +
137 2589 sgarg
                                session.getAttribute("username"));
138 509 bojilova
      session.invalidate();
139 2663 sgarg
      logMetacat.info("in session is not new");
140 509 bojilova
      session = request.getSession(true);
141
    }
142 725 bojilova
    // store the username, password, and groupname (the first only)
143
    // in the session obj for use on subsequent calls to Metacat servlet
144 509 bojilova
    session.setMaxInactiveInterval(-1);
145
    session.setAttribute("username", username);
146
    session.setAttribute("password", password);
147 2679 sgarg
148
    if ( userInfo!=null & userInfo.length == 3 ) {
149
        session.setAttribute("name", userInfo[0]);
150
        session.setAttribute("organization", userInfo[1]);
151
        session.setAttribute("email", userInfo[2]);
152
    }
153
154 725 bojilova
    if ( groups.length > 0 ) {
155 802 bojilova
      session.setAttribute("groupnames", groups);
156 725 bojilova
    }
157 2663 sgarg
     logMetacat.info("the new session id is : " +
158 2589 sgarg
                                session.getId());
159 2663 sgarg
     logMetacat.info("the new session username : " +
160 2589 sgarg
                                session.getAttribute("username"));
161 509 bojilova
    return session;
162
  }
163
164 503 bojilova
  /**
165
   * Get the message associated with authenticating this session. The
166
   * message is formatted in XML.
167
   */
168 2058 sgarg
  public String getMessage()
169 503 bojilova
  {
170
    return this.statusMessage;
171
  }
172
173
  /**
174 730 bojilova
   * Get all groups and users from authentication scheme.
175 725 bojilova
   * The output is formatted in XML.
176 730 bojilova
   * @param user the user which requests the information
177
   * @param password the user's password
178 503 bojilova
   */
179 725 bojilova
  public String getPrincipals(String user, String password)
180
                throws ConnectException
181 503 bojilova
  {
182 730 bojilova
    return authService.getPrincipals(user, password);
183 503 bojilova
  }
184
185 2058 sgarg
  /*
186 503 bojilova
   * format the output in xml for processing from client applications
187
   *
188
   * @param tag the root element tag for the message (error or success)
189
   * @param message the message content of the root element
190
   */
191 2058 sgarg
  private String formatOutput(String tag, String message)
192 1822 jones
  {
193 2679 sgarg
      return formatOutput(tag, message, null, null, null, null);
194 1822 jones
  }
195
196 2058 sgarg
  /*
197 1822 jones
   * format the output in xml for processing from client applications
198
   *
199
   * @param tag the root element tag for the message (error or success)
200
   * @param message the message content of the root element
201
   * @param sessionId the session identifier for a successful login
202
   */
203 2679 sgarg
  private String formatOutput(String tag, String message,
204
		  String sessionId, String username, String[] groups,
205
		  String userInfo[])
206 1822 jones
  {
207 503 bojilova
    StringBuffer out = new StringBuffer();
208 2058 sgarg
209 503 bojilova
    out.append("<?xml version=\"1.0\"?>\n");
210
    out.append("<" + tag + ">");
211 510 bojilova
    out.append("\n  <message>" + message + "</message>\n");
212 1822 jones
    if (sessionId != null) {
213 1825 jones
        out.append("\n  <sessionId>" + sessionId + "</sessionId>\n");
214 2679 sgarg
215
        if(userInfo != null && userInfo[0]!=null){
216
        	out.append("\n<name>\n");
217
        	out.append(userInfo[0]);
218
        	out.append("\n</name>\n");
219
        }
220 2680 sgarg
221
        // insert <isAdministrator> tag if the user is an administrator
222 2679 sgarg
        if(MetaCatUtil.isAdministrator(username,groups)){
223
            out.append("\n  <isAdministrator></isAdministrator>\n");
224
        }
225 2680 sgarg
226
        // insert <isModerator> tag if the user is a Moderator
227 2679 sgarg
        if(MetaCatUtil.isModerator(username,groups)){
228
            out.append("\n  <isModerator></isModerator>\n");
229
        }
230 1822 jones
    }
231 503 bojilova
    out.append("</" + tag + ">");
232 2058 sgarg
233 503 bojilova
    return out.toString();
234
  }
235
236
  /**
237
   * Instantiate a class using the name of the class at runtime
238
   *
239
   * @param className the fully qualified name of the class to instantiate
240
   */
241 509 bojilova
  private static Object createObject(String className) throws Exception {
242 2058 sgarg
243 503 bojilova
    Object object = null;
244
    try {
245
      Class classDefinition = Class.forName(className);
246
      object = classDefinition.newInstance();
247
    } catch (InstantiationException e) {
248 509 bojilova
      throw e;
249 503 bojilova
    } catch (IllegalAccessException e) {
250 509 bojilova
      throw e;
251 503 bojilova
    } catch (ClassNotFoundException e) {
252 509 bojilova
      throw e;
253 503 bojilova
    }
254
    return object;
255
  }
256
}