KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > methodhead > auth > LoginAction


1 /*
2  * Copyright (C) 2006 Methodhead Software LLC. All rights reserved.
3  *
4  * This file is part of TransferCM.
5  *
6  * TransferCM is free software; you can redistribute it and/or modify it under the
7  * terms of the GNU General Public License as published by the Free Software
8  * Foundation; either version 2 of the License, or (at your option) any later
9  * version.
10  *
11  * TransferCM is distributed in the hope that it will be useful, but WITHOUT ANY
12  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
13  * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
14  * details.
15  *
16  * You should have received a copy of the GNU General Public License along with
17  * TransferCM; if not, write to the Free Software Foundation, Inc., 51 Franklin St,
18  * Fifth Floor, Boston, MA 02110-1301 USA
19  */

20
21 package com.methodhead.auth;
22
23 import javax.servlet.http.HttpServletRequest JavaDoc;
24 import javax.servlet.http.HttpServletResponse JavaDoc;
25
26 import org.apache.log4j.Logger;
27
28 import org.apache.struts.Globals;
29 import org.apache.struts.action.Action;
30 import org.apache.struts.action.ActionError;
31 import org.apache.struts.action.ActionErrors;
32 import org.apache.struts.action.ActionForm;
33 import org.apache.struts.action.ActionForward;
34 import org.apache.struts.action.ActionMapping;
35 import org.apache.struts.action.DynaActionForm;
36 import com.methodhead.util.StrutsUtil;
37 import com.methodhead.util.OperationContext;
38 import javax.servlet.http.Cookie JavaDoc;
39 import org.apache.commons.lang.StringUtils;
40 import com.methodhead.sitecontext.SiteContext;
41
42 /**
43 <p>
44   Use <tt>LoginAction</tt> to build a web interface to handle logins.
45   This action will respond to the mappings <tt>/loginForm</tt>,
46   <tt>/login</tt>, and <tt>/logout</tt>, calling {@link #doLoginForm
47   doLoginForm()}, {@link #doLogin doLogin()}, and {@link #doLogout
48   doLogout()} respectively.
49 </p>
50 <p>
51   The following are example mappings:
52 </p>
53 <xmp>
54   <action
55     path ="/loginForm"
56     type ="com.methodhead.auth.LoginAction"
57     name ="loginForm"
58     scope ="request"
59     input ="/login.jsp"
60     validate="false">
61     <forward name="loginForm" path="/login.jsp"/>
62   </action>
63
64   <action
65     path ="/login"
66     type ="com.methodhead.auth.LoginAction"
67     parameter="com.methodhead.auth.DefaultUser"
68     name ="loginForm"
69     scope ="request"
70     input ="/login.jsp"
71     validate ="true">
72     <forward name="loggedIn" path="/index.jsp"/>
73   </action>
74
75   <action
76     path ="/logout"
77     type ="com.methodhead.auth.LoginAction"
78     name ="loginForm"
79     scope ="request"
80     input ="/login.jsp"
81     validate="false">
82     <forward name="loggedOut" path="/login.jsp"/>
83   </action>
84
85   <global-forwards>
86     <forward name="accessDenied" path="/accessdenied.jsp"/>
87     <forward name="loginForm" path="/loginForm.do"/>
88   </global-forwards>
89
90   <form-bean
91     name ="loginForm"
92     dynamic="true"
93     type ="org.apache.struts.action.DynaActionForm">
94
95     <form-property name="login" type="java.lang.String"/>
96     <form-property name="password" type="java.lang.String"/>
97     <form-property name="desturl" type="java.lang.String"/>
98   </form-bean>
99 </xmp>
100 <p>
101   The action will make use of the following message resources:
102 </p>
103 <xmp>
104   loginform.invalidlogin=Please enter a valid login and password.
105   loginform.missingloginpassword=Please enter a valid login and password.
106 </xmp>
107  */

108 public class LoginAction extends Action {
109
110   /**
111    * The action will initialize the <tt>desturl</tt> property of the login form
112    * with the contents of the <tt>AuthGlobals.URL_KEY</tt> request attribute if
113    * available (this attribute is set by {@link
114    * com.methodhead.auth.AuthAction AuthAction} when
115    */

116   protected ActionForward doLoginForm(
117     OperationContext op,
118     AuthPolicy policy )
119   throws
120     Exception JavaDoc {
121
122     //
123
// set the desturl if the attribute has been set
124
//
125
String JavaDoc desturl =
126       ( String JavaDoc )op.request.getAttribute( AuthGlobals.URL_KEY );
127
128     if ( desturl == null )
129       desturl = "";
130
131     op.form.set( "desturl", desturl );
132
133     //
134
// set remember me?
135
//
136
Cookie JavaDoc[] cookies = op.request.getCookies();
137
138     op.form.set( "rememberme", "" );
139
140     if ( cookies != null ) {
141       for ( int i = 0; i < cookies.length; i++ ) {
142         if ( cookies[ i ].getName().equals( "rememberme" ) ) {
143           op.form.set( "rememberme", "on" );
144           break;
145         }
146       }
147     }
148
149     return StrutsUtil.findForward( op.mapping, "loginForm" );
150   }
151
152   /**
153    * <p>
154    * The action will attempt to log in the user. An
155    * <tt>AuthUser</tt> is instantiated and used to load and authenticate the
156    * user. The concrete class to instantiate must be specified by the action
157    * mapping's <tt>parameter</tt> attribute.
158    * </p>
159    * <p>
160    * The user is considered authenticated if the user can be
161    * successfully loaded and {@link
162    * com.methodhead.auth.AuthUser#authenticate authenticate()}
163    * returns <tt>true</tt>. If the user is
164    * successfully authenticated, the user is added to the session
165    * using {@link com.methodhead.auth.AuthUtil#setUser
166    * AuthUtil.setUser()}. If the <tt>desturl</tt>
167    * parameter is available, a forward to that URL is returned,
168    * otherwise the <tt>loggedIn</tt> forward is returned.
169    * </p>
170    * <p>
171    * If the user is not successfully authenticated, the
172    * <tt>loginform.invalidlogin</tt> action error is added to the
173    * form and a forward to input is returned.
174    * </p>
175    */

176   protected ActionForward doLogin(
177     OperationContext op,
178     AuthPolicy policy )
179   throws
180     Exception JavaDoc {
181
182     if ( logger_.isDebugEnabled() ) {
183       logger_.debug( "Attempting to login " + op.form.get( "login" ) );
184     }
185
186     //
187
// instantiate AuthUser
188
//
189
AuthUser user = policy.newUser();
190
191
192     //
193
// load user
194
//
195
if ( user.loadForLogin( ( String JavaDoc )op.form.get( "login" ) ) ) {
196
197       if ( logger_.isDebugEnabled() ) {
198         logger_.debug( "Successfully loaded " + user );
199       }
200
201       //
202
// authenticate
203
//
204
if ( user.authenticate(
205              ( String JavaDoc )op.form.get( "password" ) ) ) {
206
207         if ( logger_.isDebugEnabled() ) {
208           logger_.debug( "Successfully authenticated " + user );
209         }
210
211         //
212
// remember me?
213
//
214
if ( StringUtils.isNotBlank( ( String JavaDoc )op.form.get( "rememberme" ) ) ) {
215           Cookie JavaDoc cookie =
216             new Cookie JavaDoc(
217               "rememberme", user.getLogin() + ":" + user.getPublicSecret() );
218           
219           cookie.setMaxAge( 365 * 24 * 60 * 60 ); // one year
220

221           op.response.addCookie( cookie );
222
223           if ( logger_.isDebugEnabled() ) {
224             logger_.debug( "Added rememberme cookie \"" + cookie.getValue() + "\"" );
225           }
226         }
227         else {
228           //
229
// "delete" the cookie
230
//
231
Cookie JavaDoc cookie = new Cookie JavaDoc( "rememberme", "" );
232           cookie.setMaxAge( 0 ); // a zero value deletes the cookie
233
op.response.addCookie( cookie );
234
235           if ( logger_.isDebugEnabled() ) {
236             logger_.debug( "Deleted rememberme cookie" );
237           }
238         }
239
240         //
241
// log in the user
242
//
243
AuthUtil.setUser( op.request, user );
244
245         //
246
// forward to appropriate destination
247
//
248
if ( !"".equals( op.form.get( "desturl" ) ) ) {
249
250           if ( logger_.isDebugEnabled() ) {
251             logger_.debug( "desturl set; forwarding to " + op.form.get( "desturl" ) );
252           }
253
254           return new ActionForward( ( String JavaDoc )op.form.get( "desturl" ), true );
255         }
256         else {
257           return StrutsUtil.findForward( op.mapping, "loggedIn" );
258         }
259       }
260     }
261
262     //
263
// authentication failed; forward back to input
264
//
265
ActionErrors errors = new ActionErrors();
266     errors.add(
267       ActionErrors.GLOBAL_ERROR,
268       new ActionError( "loginform.invalidlogin" ) );
269
270     op.request.setAttribute( Globals.ERROR_KEY, errors );
271
272     return new ActionForward( op.mapping.getInput() );
273   }
274
275   /**
276    * The action will attempt to logout the user. The user is removed
277    * from the session and the <tt>loggedOut</tt> forward is returned.
278    */

279   protected ActionForward doLogout(
280     OperationContext op,
281     AuthPolicy policy )
282   throws
283     Exception JavaDoc {
284
285     AuthUtil.setUser( op.request, null );
286     return StrutsUtil.findForward( op.mapping, "loggedOut" );
287   }
288
289   public ActionForward execute(
290     ActionMapping mapping,
291     ActionForm form,
292     HttpServletRequest JavaDoc request,
293     HttpServletResponse JavaDoc response )
294   throws
295     Exception JavaDoc {
296
297     //
298
// get policy
299
//
300
AuthPolicy policy =
301       ( AuthPolicy )Class.forName( mapping.getParameter() ).newInstance();
302
303     DynaActionForm loginForm = ( DynaActionForm )form;
304
305     OperationContext op =
306       new OperationContext(
307         mapping, loginForm, request, response, null );
308
309     if ( mapping.getPath().equals( "/loginForm" ) ) {
310       return doLoginForm( op, policy );
311     }
312
313     if ( mapping.getPath().equals( "/login" ) ) {
314       return doLogin( op, policy );
315     }
316
317     else if ( mapping.getPath().equals( "/logout" ) ) {
318       return doLogout( op, policy );
319     }
320
321     throw new Exception JavaDoc(
322       "Unexpected action mapping path " + mapping.getPath() );
323   }
324
325   private Logger logger_ = Logger.getLogger( LoginAction.class );
326 }
327
Popular Tags