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-20 11:32:41 -0700 (Thu, 20 Oct 2005) $'
11
 * '$Revision: 2680 $'
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
        
97
        String[] userInfo =
98
            authService.getUserInfo(username,password);
99
        
100
        
101
        this.session = createSession(request, username, password, groups, userInfo);
102
        String sessionId = session.getId();
103
        message = "Authentication successful for user: " + username;
104
        this.statusMessage = formatOutput("login", message, sessionId, username, 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,
124
                                 String username, String password,
125
                                 String[] groups, String[] userInfo)
126
                      throws IllegalStateException {
127

    
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
      logMetacat.info("in session is not new");
134
      logMetacat.info("the old session id is : " +
135
                                session.getId());
136
      logMetacat.info("the old session username : " +
137
                                session.getAttribute("username"));
138
      session.invalidate();
139
      logMetacat.info("in session is not new");
140
      session = request.getSession(true);
141
    }
142
    // store the username, password, and groupname (the first only)
143
    // in the session obj for use on subsequent calls to Metacat servlet
144
    session.setMaxInactiveInterval(-1);
145
    session.setAttribute("username", username);
146
    session.setAttribute("password", password);
147
    
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
    if ( groups.length > 0 ) {
155
      session.setAttribute("groupnames", groups);
156
    }
157
     logMetacat.info("the new session id is : " +
158
                                session.getId());
159
     logMetacat.info("the new session username : " +
160
                                session.getAttribute("username"));
161
    return session;
162
  }
163

    
164
  /**
165
   * Get the message associated with authenticating this session. The
166
   * message is formatted in XML.
167
   */
168
  public String getMessage()
169
  {
170
    return this.statusMessage;
171
  }
172

    
173
  /**
174
   * Get all groups and users from authentication scheme.
175
   * The output is formatted in XML.
176
   * @param user the user which requests the information
177
   * @param password the user's password
178
   */
179
  public String getPrincipals(String user, String password)
180
                throws ConnectException
181
  {
182
    return authService.getPrincipals(user, password);
183
  }
184

    
185
  /*
186
   * 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
  private String formatOutput(String tag, String message)
192
  {
193
      return formatOutput(tag, message, null, null, null, null);
194
  }
195

    
196
  /*
197
   * 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
  private String formatOutput(String tag, String message, 
204
		  String sessionId, String username, String[] groups,
205
		  String userInfo[])
206
  {
207
    StringBuffer out = new StringBuffer();
208

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

    
233
    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
  private static Object createObject(String className) throws Exception {
242

    
243
    Object object = null;
244
    try {
245
      Class classDefinition = Class.forName(className);
246
      object = classDefinition.newInstance();
247
    } catch (InstantiationException e) {
248
      throw e;
249
    } catch (IllegalAccessException e) {
250
      throw e;
251
    } catch (ClassNotFoundException e) {
252
      throw e;
253
    }
254
    return object;
255
  }
256
}
(13-13/65)