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
import javax.servlet.http.HttpSession;
31
import javax.servlet.http.HttpServletRequest;
32
33 2663 sgarg
import org.apache.log4j.Logger;
34
35 503 bojilova
/**
36
 * A Class that implements session tracking for MetaCatServlet users.
37
 * User's login data are stored in the session object.
38
 * User authentication is done through a dynamically determined AuthInterface.
39
 */
40
public class AuthSession {
41
42
  private String authClass = null;
43
  private HttpSession session = null;
44
  private AuthInterface authService = null;
45
  private String statusMessage = null;
46 2663 sgarg
  private static Logger logMetacat = Logger.getLogger(AuthSession.class);
47 2058 sgarg
48
  /**
49 503 bojilova
   * Construct an AuthSession
50
   */
51 509 bojilova
  public AuthSession() throws Exception {
52 503 bojilova
    // Determine our session authentication method and
53
    // create an instance of the auth class
54
    MetaCatUtil util = new MetaCatUtil();
55 728 bojilova
    this.authClass = util.getOption("authclass");
56
    this.authService = (AuthInterface)createObject(authClass);
57 503 bojilova
  }
58 2058 sgarg
59 2045 tao
  /**
60
   * Get the new session
61
   */
62
  public HttpSession getSessions()
63
  {
64
    return this.session;
65
  }
66 503 bojilova
67 2058 sgarg
  /**
68
   * determine if the credentials for this session are valid by
69 503 bojilova
   * authenticating them using the authService configured for this session.
70 509 bojilova
   *
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 503 bojilova
   */
75 2058 sgarg
  public boolean authenticate(HttpServletRequest request,
76
                              String username, String password)  {
77 509 bojilova
    String message = null;
78 2058 sgarg
    try {
79 503 bojilova
      if ( authService.authenticate(username, password) ) {
80 2058 sgarg
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 2679 sgarg
87 2058 sgarg
        for(int i=0; i<groupsWithDescription.length; i++){
88
          groups[i] = groupsWithDescription[i][0];
89
        }
90
91 888 berkley
        if(groups == null)
92
        {
93
          groups = new String[0];
94
        }
95 2679 sgarg
96
        String[] userInfo =
97
            authService.getUserInfo(username,password);
98
99
100
        this.session = createSession(request, username, password, groups, userInfo);
101 1822 jones
        String sessionId = session.getId();
102 510 bojilova
        message = "Authentication successful for user: " + username;
103 2679 sgarg
        this.statusMessage = formatOutput("login", message, sessionId, username, groups, userInfo);
104 509 bojilova
        return true;
105 2058 sgarg
      } else {
106 509 bojilova
        message = "Authentication failed for user: " + username;
107 510 bojilova
        this.statusMessage = formatOutput("unauth_login", message);
108
        return false;
109 2058 sgarg
      }
110 503 bojilova
    } catch ( ConnectException ce ) {
111 675 berkley
      message = "Connection to the authentication service failed in " +
112
                "AuthSession.authenticate: " + ce.getMessage();
113 509 bojilova
    } catch ( IllegalStateException ise ) {
114
      message = ise.getMessage();
115 503 bojilova
    }
116 2058 sgarg
117 510 bojilova
    this.statusMessage = formatOutput("error_login", message);
118 509 bojilova
    return false;
119 503 bojilova
  }
120
121 509 bojilova
  /** Get new HttpSession and store username & password in it */
122 2058 sgarg
  private HttpSession createSession(HttpServletRequest request,
123 725 bojilova
                                 String username, String password,
124 2679 sgarg
                                 String[] groups, String[] userInfo)
125 725 bojilova
                      throws IllegalStateException {
126 509 bojilova
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 2663 sgarg
      logMetacat.info("in session is not new");
133
      logMetacat.info("the old session id is : " +
134 2589 sgarg
                                session.getId());
135 2663 sgarg
      logMetacat.info("the old session username : " +
136 2589 sgarg
                                session.getAttribute("username"));
137 509 bojilova
      session.invalidate();
138 2663 sgarg
      logMetacat.info("in session is not new");
139 509 bojilova
      session = request.getSession(true);
140
    }
141 725 bojilova
    // store the username, password, and groupname (the first only)
142
    // in the session obj for use on subsequent calls to Metacat servlet
143 509 bojilova
    session.setMaxInactiveInterval(-1);
144
    session.setAttribute("username", username);
145
    session.setAttribute("password", password);
146 2679 sgarg
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 725 bojilova
    if ( groups.length > 0 ) {
154 802 bojilova
      session.setAttribute("groupnames", groups);
155 725 bojilova
    }
156 2663 sgarg
     logMetacat.info("the new session id is : " +
157 2589 sgarg
                                session.getId());
158 2663 sgarg
     logMetacat.info("the new session username : " +
159 2589 sgarg
                                session.getAttribute("username"));
160 509 bojilova
    return session;
161
  }
162
163 503 bojilova
  /**
164
   * Get the message associated with authenticating this session. The
165
   * message is formatted in XML.
166
   */
167 2058 sgarg
  public String getMessage()
168 503 bojilova
  {
169
    return this.statusMessage;
170
  }
171
172
  /**
173 730 bojilova
   * Get all groups and users from authentication scheme.
174 725 bojilova
   * The output is formatted in XML.
175 730 bojilova
   * @param user the user which requests the information
176
   * @param password the user's password
177 503 bojilova
   */
178 725 bojilova
  public String getPrincipals(String user, String password)
179
                throws ConnectException
180 503 bojilova
  {
181 730 bojilova
    return authService.getPrincipals(user, password);
182 503 bojilova
  }
183
184 2058 sgarg
  /*
185 503 bojilova
   * 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 2058 sgarg
  private String formatOutput(String tag, String message)
191 1822 jones
  {
192 2679 sgarg
      return formatOutput(tag, message, null, null, null, null);
193 1822 jones
  }
194
195 2058 sgarg
  /*
196 1822 jones
   * 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 2679 sgarg
  private String formatOutput(String tag, String message,
203
		  String sessionId, String username, String[] groups,
204
		  String userInfo[])
205 1822 jones
  {
206 503 bojilova
    StringBuffer out = new StringBuffer();
207 2058 sgarg
208 503 bojilova
    out.append("<?xml version=\"1.0\"?>\n");
209
    out.append("<" + tag + ">");
210 510 bojilova
    out.append("\n  <message>" + message + "</message>\n");
211 1822 jones
    if (sessionId != null) {
212 1825 jones
        out.append("\n  <sessionId>" + sessionId + "</sessionId>\n");
213 2679 sgarg
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 2680 sgarg
220
        // insert <isAdministrator> tag if the user is an administrator
221 2679 sgarg
        if(MetaCatUtil.isAdministrator(username,groups)){
222
            out.append("\n  <isAdministrator></isAdministrator>\n");
223
        }
224 2680 sgarg
225
        // insert <isModerator> tag if the user is a Moderator
226 2679 sgarg
        if(MetaCatUtil.isModerator(username,groups)){
227
            out.append("\n  <isModerator></isModerator>\n");
228
        }
229 1822 jones
    }
230 503 bojilova
    out.append("</" + tag + ">");
231 2058 sgarg
232 503 bojilova
    return out.toString();
233
  }
234
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 509 bojilova
  private static Object createObject(String className) throws Exception {
241 2058 sgarg
242 503 bojilova
    Object object = null;
243
    try {
244
      Class classDefinition = Class.forName(className);
245
      object = classDefinition.newInstance();
246
    } catch (InstantiationException e) {
247 509 bojilova
      throw e;
248 503 bojilova
    } catch (IllegalAccessException e) {
249 509 bojilova
      throw e;
250 503 bojilova
    } catch (ClassNotFoundException e) {
251 509 bojilova
      throw e;
252 503 bojilova
    }
253
    return object;
254
  }
255
}