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
 *    Release: @release@
8
 *
9
 *   '$Author: sgarg $'
10
 *     '$Date: 2005-10-10 11:06:55 -0700 (Mon, 10 Oct 2005) $'
11
 * '$Revision: 2663 $'
12
 *
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
 */
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
import org.apache.log4j.Logger;
35

    
36
/**
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
  private static Logger logMetacat = Logger.getLogger(AuthSession.class);
48

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

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

    
68
  /**
69
   * determine if the credentials for this session are valid by
70
   * authenticating them using the authService configured for this session.
71
   *
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
   */
76
  public boolean authenticate(HttpServletRequest request,
77
                              String username, String password)  {
78
    String message = null;
79
    try {
80
      if ( authService.authenticate(username, password) ) {
81

    
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

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

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

    
113
    this.statusMessage = formatOutput("error_login", message);
114
    return false;
115
  }
116

    
117
  /** Get new HttpSession and store username & password in it */
118
  private HttpSession createSession(HttpServletRequest request,
119
                                 String username, String password,
120
                                 String[] groups)
121
                      throws IllegalStateException {
122

    
123
    // get the current session object, create one if necessary
124
    HttpSession session = request.getSession(true);
125

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

    
152
  /**
153
   * Get the message associated with authenticating this session. The
154
   * message is formatted in XML.
155
   */
156
  public String getMessage()
157
  {
158
    return this.statusMessage;
159
  }
160

    
161
  /**
162
   * Get all groups and users from authentication scheme.
163
   * The output is formatted in XML.
164
   * @param user the user which requests the information
165
   * @param password the user's password
166
   */
167
  public String getPrincipals(String user, String password)
168
                throws ConnectException
169
  {
170
    return authService.getPrincipals(user, password);
171
  }
172

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

    
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
   * @param sessionId the session identifier for a successful login
190
   */
191
  private String formatOutput(String tag, String message, String sessionId)
192
  {
193
    StringBuffer out = new StringBuffer();
194

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

    
203
    return out.toString();
204
  }
205

    
206
  /**
207
   * Instantiate a class using the name of the class at runtime
208
   *
209
   * @param className the fully qualified name of the class to instantiate
210
   */
211
  private static Object createObject(String className) throws Exception {
212

    
213
    Object object = null;
214
    try {
215
      Class classDefinition = Class.forName(className);
216
      object = classDefinition.newInstance();
217
    } catch (InstantiationException e) {
218
      throw e;
219
    } catch (IllegalAccessException e) {
220
      throw e;
221
    } catch (ClassNotFoundException e) {
222
      throw e;
223
    }
224
    return object;
225
  }
226
}
(13-13/63)