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
 *
8
 *   '$Author: jones $'
9
 *     '$Date: 2006-11-10 10:25:38 -0800 (Fri, 10 Nov 2006) $'
10
 * '$Revision: 3077 $'
11
 *
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
 */
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
import org.apache.log4j.Logger;
34

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

    
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
  }
58

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

    
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) ) {
80

    
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
        }
90

    
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
    }
116

    
117
    this.statusMessage = formatOutput("error_login", message);
118
    return false;
119
  }
120

    
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 {
126

    
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
      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
  }
162

    
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
  }
171

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

    
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();
207

    
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 + ">");
231

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

    
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
  }
255
}
(12-12/66)