KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > ofbiz > securityext > login > LoginEvents


1 /*
2  * $Id: LoginEvents.java 6695 2006-02-06 22:35:58Z jonesde $
3  *
4  * Copyright (c) 2001-2005 The Open For Business Project - www.ofbiz.org
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a
7  * copy of this software and associated documentation files (the "Software"),
8  * to deal in the Software without restriction, including without limitation
9  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10  * and/or sell copies of the Software, and to permit persons to whom the
11  * Software is furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included
14  * in all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
17  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19  * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
20  * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
21  * OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
22  * THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23  */

24 package org.ofbiz.securityext.login;
25
26 import java.util.Iterator JavaDoc;
27 import java.util.List JavaDoc;
28 import java.util.Map JavaDoc;
29
30 import javax.servlet.ServletContext JavaDoc;
31 import javax.servlet.http.Cookie JavaDoc;
32 import javax.servlet.http.HttpServletRequest JavaDoc;
33 import javax.servlet.http.HttpServletResponse JavaDoc;
34 import javax.servlet.http.HttpSession JavaDoc;
35
36 import javolution.util.FastList;
37 import javolution.util.FastMap;
38
39 import org.ofbiz.base.component.ComponentConfig;
40 import org.ofbiz.base.util.Debug;
41 import org.ofbiz.base.util.UtilFormatOut;
42 import org.ofbiz.base.util.UtilHttp;
43 import org.ofbiz.base.util.UtilMisc;
44 import org.ofbiz.base.util.UtilProperties;
45 import org.ofbiz.base.util.UtilValidate;
46 import org.ofbiz.entity.GenericDelegator;
47 import org.ofbiz.entity.GenericEntityException;
48 import org.ofbiz.entity.GenericValue;
49 import org.ofbiz.party.contact.ContactHelper;
50 import org.ofbiz.product.product.ProductEvents;
51 import org.ofbiz.product.store.ProductStoreWorker;
52 import org.ofbiz.security.Security;
53 import org.ofbiz.service.GenericServiceException;
54 import org.ofbiz.service.LocalDispatcher;
55 import org.ofbiz.service.ModelService;
56 import org.ofbiz.webapp.control.LoginWorker;
57 import org.ofbiz.webapp.control.RequestHandler;
58 import org.ofbiz.webapp.stats.VisitHandler;
59
60 /**
61  * LoginEvents - Events for UserLogin and Security handling.
62  *
63  * @author <a HREF="mailto:jaz@ofbiz.org">Andy Zeneski</a>
64  * @author <a HREF="mailto:jonesde@ofbiz.org">David E. Jones</a>
65  * @author <a HREF="">Dustin Caldwell</a>
66  * @author <a HREF="mailto:therrick@yahoo.com">Tom Herrick</a>
67  * @version $Rev: 6695 $
68  * @since 2.0
69  */

70 public class LoginEvents {
71
72     public static final String JavaDoc module = LoginEvents.class.getName();
73     public static final String JavaDoc resource = "SecurityextUiLabels";
74
75     /**
76      * Save USERNAME and PASSWORD for use by auth pages even if we start in non-auth pages.
77      *
78      * @param request The HTTP request object for the current JSP or Servlet request.
79      * @param response The HTTP response object for the current JSP or Servlet request.
80      * @return String
81      */

82     public static String JavaDoc saveEntryParams(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
83         GenericValue userLogin = (GenericValue) request.getSession().getAttribute("userLogin");
84         HttpSession JavaDoc session = request.getSession();
85
86         // save entry login parameters if we don't have a valid login object
87
if (userLogin == null) {
88
89             String JavaDoc username = request.getParameter("USERNAME");
90             String JavaDoc password = request.getParameter("PASSWORD");
91
92             if ((username != null) && ("true".equalsIgnoreCase(UtilProperties.getPropertyValue("security.properties", "username.lowercase")))) {
93                 username = username.toLowerCase();
94             }
95             if ((password != null) && ("true".equalsIgnoreCase(UtilProperties.getPropertyValue("security.properties", "password.lowercase")))) {
96                 password = password.toLowerCase();
97             }
98
99             // save parameters into the session - so they can be used later, if needed
100
if (username != null) session.setAttribute("USERNAME", username);
101             if (password != null) session.setAttribute("PASSWORD", password);
102
103         } else {
104             // if the login object is valid, remove attributes
105
session.removeAttribute("USERNAME");
106             session.removeAttribute("PASSWORD");
107         }
108
109         return "success";
110     }
111
112     /**
113      * An HTTP WebEvent handler that checks to see is a userLogin is logged in.
114      * If not, the user is forwarded to the login page.
115      *
116      * @param request The HTTP request object for the current JSP or Servlet request.
117      * @param response The HTTP response object for the current JSP or Servlet request.
118      * @return String
119      */

120     public static String JavaDoc checkLogin(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
121         GenericValue userLogin = (GenericValue) request.getSession().getAttribute("userLogin");
122         HttpSession JavaDoc session = request.getSession();
123
124         // anonymous shoppers are not logged in
125
if (userLogin != null && "anonymous".equals(userLogin.getString("userLoginId"))) {
126             userLogin = null;
127         }
128
129         // user is logged in; check to see if they have globally logged out if not
130
// check if they have permission for this login attempt; if not log them out
131
if (userLogin != null) {
132             if (!hasBasePermission(userLogin, request) || isFlaggedLoggedOut(userLogin)) {
133                 Debug.logInfo("User does not have permission or is flagged as logged out", module);
134                 doBasicLogout(userLogin, request);
135                 userLogin = null;
136
137                 // have to reget this because the old session object will be invalid
138
session = request.getSession();
139             }
140         }
141
142         String JavaDoc username = null;
143         String JavaDoc password = null;
144
145         if (userLogin == null) {
146             // check parameters
147
if (username == null) username = request.getParameter("USERNAME");
148             if (password == null) password = request.getParameter("PASSWORD");
149             // check session attributes
150
if (username == null) username = (String JavaDoc) session.getAttribute("USERNAME");
151             if (password == null) password = (String JavaDoc) session.getAttribute("PASSWORD");
152
153             if ((username != null) && ("true".equalsIgnoreCase(UtilProperties.getPropertyValue("security.properties", "username.lowercase")))) {
154                 username = username.toLowerCase();
155             }
156             if ((password != null) && ("true".equalsIgnoreCase(UtilProperties.getPropertyValue("security.properties", "password.lowercase")))) {
157                 password = password.toLowerCase();
158             }
159
160             // in this condition log them in if not already; if not logged in or can't log in, save parameters and return error
161
if ((username == null) || (password == null) || ("error".equals(login(request, response)))) {
162                 Map JavaDoc reqParams = UtilHttp.getParameterMap(request);
163                 String JavaDoc queryString = UtilHttp.urlEncodeArgs(reqParams);
164                 Debug.logInfo("reqParams Map: " + reqParams, module);
165                 Debug.logInfo("queryString: " + queryString, module);
166
167                 session.setAttribute("_PREVIOUS_REQUEST_", request.getPathInfo());
168                 if (queryString != null && queryString.length() > 0) {
169                     session.setAttribute("_PREVIOUS_PARAMS_", queryString);
170                 }
171
172                 if (Debug.infoOn()) Debug.logInfo("checkLogin: queryString=" + queryString, module);
173                 if (Debug.infoOn()) Debug.logInfo("checkLogin: PathInfo=" + request.getPathInfo(), module);
174
175                 return "error";
176             }
177         }
178
179         return "success";
180     }
181
182     /**
183      * An HTTP WebEvent handler that logs in a userLogin. This should run before the security check.
184      *
185      * @param request The HTTP request object for the current JSP or Servlet request.
186      * @param response The HTTP response object for the current JSP or Servlet request.
187      * @return Return a boolean which specifies whether or not the calling Servlet or
188      * JSP should generate its own content. This allows an event to override the default content.
189      */

190     public static String JavaDoc login(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
191         HttpSession JavaDoc session = request.getSession();
192
193         String JavaDoc username = request.getParameter("USERNAME");
194         String JavaDoc password = request.getParameter("PASSWORD");
195
196         if (username == null) username = (String JavaDoc) session.getAttribute("USERNAME");
197         if (password == null) password = (String JavaDoc) session.getAttribute("PASSWORD");
198         
199         // allow a username and/or password in a request attribute to override the request parameter or the session attribute; this way a preprocessor can play with these a bit...
200
if (UtilValidate.isNotEmpty((String JavaDoc) request.getAttribute("USERNAME"))) {
201             username = (String JavaDoc) request.getAttribute("USERNAME");
202         }
203         if (UtilValidate.isNotEmpty((String JavaDoc) request.getAttribute("PASSWORD"))) {
204             password = (String JavaDoc) request.getAttribute("PASSWORD");
205         }
206
207         List JavaDoc unpwErrMsgList = FastList.newInstance();
208         if (UtilValidate.isEmpty(username)) {
209             unpwErrMsgList.add(UtilProperties.getMessage(resource, "loginevents.username_was_empty_reenter", UtilHttp.getLocale(request)));
210         }
211         if (UtilValidate.isEmpty(password)) {
212             unpwErrMsgList.add(UtilProperties.getMessage(resource, "loginevents.password_was_empty_reenter", UtilHttp.getLocale(request)));
213         }
214         if (!unpwErrMsgList.isEmpty()) {
215             request.setAttribute("_ERROR_MESSAGE_LIST_", unpwErrMsgList);
216             return "error";
217         }
218         
219
220         if ((username != null) && ("true".equalsIgnoreCase(UtilProperties.getPropertyValue("security.properties", "username.lowercase")))) {
221             username = username.toLowerCase();
222         }
223         if ((password != null) && ("true".equalsIgnoreCase(UtilProperties.getPropertyValue("security.properties", "password.lowercase")))) {
224             password = password.toLowerCase();
225         }
226
227         // get the visit id to pass to the userLogin for history
228
String JavaDoc visitId = VisitHandler.getVisitId(session);
229
230         LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
231         Map JavaDoc result = null;
232
233         try {
234             result = dispatcher.runSync("userLogin", UtilMisc.toMap("login.username", username, "login.password", password, "visitId", visitId, "locale", UtilHttp.getLocale(request)));
235         } catch (GenericServiceException e) {
236             Debug.logError(e, "Error calling userLogin service", module);
237             Map JavaDoc messageMap = UtilMisc.toMap("errorMessage", e.getMessage());
238             String JavaDoc errMsg = UtilProperties.getMessage(resource, "loginevents.following_error_occurred_during_login", messageMap, UtilHttp.getLocale(request));
239             request.setAttribute("_ERROR_MESSAGE_", errMsg);
240             return "error";
241         }
242
243         if (ModelService.RESPOND_SUCCESS.equals(result.get(ModelService.RESPONSE_MESSAGE))) {
244             GenericValue userLogin = (GenericValue) result.get("userLogin");
245             Map JavaDoc userLoginSession = (Map JavaDoc) result.get("userLoginSession");
246
247             if (userLogin != null && hasBasePermission(userLogin, request)) {
248                 doBasicLogin(userLogin, request);
249             } else {
250                 String JavaDoc errMsg = UtilProperties.getMessage(resource, "loginevents.unable_to_login_this_application", UtilHttp.getLocale(request));
251                 request.setAttribute("_ERROR_MESSAGE_", errMsg);
252                 return "error";
253             }
254
255             if (userLoginSession != null) {
256                 session.setAttribute("userLoginSession", userLoginSession);
257             }
258         } else {
259             Map JavaDoc messageMap = UtilMisc.toMap("errorMessage", (String JavaDoc) result.get(ModelService.ERROR_MESSAGE));
260             String JavaDoc errMsg = UtilProperties.getMessage(resource, "loginevents.following_error_occurred_during_login", messageMap, UtilHttp.getLocale(request));
261             request.setAttribute("_ERROR_MESSAGE_", errMsg);
262             return "error";
263         }
264
265         request.setAttribute("_LOGIN_PASSED_", "TRUE");
266
267         // run the after-login events
268
RequestHandler rh = RequestHandler.getRequestHandler(request.getSession().getServletContext());
269         rh.runAfterLoginEvents(request, response);
270
271         // make sure the autoUserLogin is set to the same and that the client cookie has the correct userLoginId
272
return autoLoginSet(request, response);
273     }
274
275     public static void doBasicLogin(GenericValue userLogin, HttpServletRequest JavaDoc request) {
276         HttpSession JavaDoc session = request.getSession();
277         session.setAttribute("userLogin", userLogin);
278
279         try {
280             GenericValue person = userLogin.getRelatedOne("Person");
281             GenericValue partyGroup = userLogin.getRelatedOne("PartyGroup");
282             if (person != null) session.setAttribute("person", person);
283             if (partyGroup != null) session.setAttribute("partyGroup", partyGroup);
284         } catch (GenericEntityException e) {
285             Debug.logError(e, "Error getting person/partyGroup info for session, ignoring...", module);
286         }
287
288         // let the visit know who the user is
289
VisitHandler.setUserLogin(session, userLogin, false);
290     }
291
292     /**
293      * An HTTP WebEvent handler that logs out a userLogin by clearing the session.
294      *
295      * @param request The HTTP request object for the current request.
296      * @param response The HTTP response object for the current request.
297      * @return Return a boolean which specifies whether or not the calling request
298      * should generate its own content. This allows an event to override the default content.
299      */

300     public static String JavaDoc logout(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
301         // run the before-logout events
302
RequestHandler rh = RequestHandler.getRequestHandler(request.getSession().getServletContext());
303         rh.runBeforeLogoutEvents(request, response);
304
305
306         // invalidate the security group list cache
307
GenericValue userLogin = (GenericValue) request.getSession().getAttribute("userLogin");
308
309         doBasicLogout(userLogin, request);
310
311         if (request.getAttribute("_AUTO_LOGIN_LOGOUT_") == null) {
312             return autoLoginCheck(request, response);
313         }
314         return "success";
315     }
316
317     public static void doBasicLogout(GenericValue userLogin, HttpServletRequest JavaDoc request) {
318         HttpSession JavaDoc session = request.getSession();
319
320         GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator");
321         Security security = (Security) request.getAttribute("security");
322
323         if (security != null && userLogin != null) {
324             Security.userLoginSecurityGroupByUserLoginId.remove(userLogin.getString("userLoginId"));
325         }
326
327         // set the logged out flag
328
LoginWorker.setLoggedOut(userLogin.getString("userLoginId"), delegator);
329
330         // this is a setting we don't want to lose, although it would be good to have a more general solution here...
331
String JavaDoc currCatalog = (String JavaDoc) session.getAttribute("CURRENT_CATALOG_ID");
332         // also make sure the delegatorName is preserved, especially so that a new Visit can be created
333
String JavaDoc delegatorName = (String JavaDoc) session.getAttribute("delegatorName");
334         // also save the shopping cart if we have one
335
// DON'T save the cart, causes too many problems: security issues with things done in cart to easy to miss, especially bad on public systems; was put in here because of the "not me" link for auto-login stuff, but that is a small problem compared to what it causes
336
//ShoppingCart shoppingCart = (ShoppingCart) session.getAttribute("shoppingCart");
337

338         session.invalidate();
339         session = request.getSession(true);
340
341         if (currCatalog != null) session.setAttribute("CURRENT_CATALOG_ID", currCatalog);
342         if (delegatorName != null) session.setAttribute("delegatorName", delegatorName);
343         // DON'T save the cart, causes too many problems: if (shoppingCart != null) session.setAttribute("shoppingCart", new WebShoppingCart(shoppingCart, session));
344
}
345
346     /**
347      * The user forgot his/her password. This will either call showPasswordHint or emailPassword.
348      *
349      * @param request The HTTPRequest object for the current request
350      * @param response The HTTPResponse object for the current request
351      * @return String specifying the exit status of this event
352      */

353     public static String JavaDoc forgotPassword(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
354         if ((UtilValidate.isNotEmpty(request.getParameter("GET_PASSWORD_HINT"))) || (UtilValidate.isNotEmpty(request.getParameter("GET_PASSWORD_HINT.x")))) {
355             return showPasswordHint(request, response);
356         } else {
357             return emailPassword(request, response);
358         }
359     }
360
361     /** Show the password hint for the userLoginId specified in the request object.
362      *@param request The HTTPRequest object for the current request
363      *@param response The HTTPResponse object for the current request
364      *@return String specifying the exit status of this event
365      */

366     public static String JavaDoc showPasswordHint(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
367         GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator");
368
369         String JavaDoc userLoginId = request.getParameter("USERNAME");
370         String JavaDoc errMsg = null;
371
372         if ((userLoginId != null) && ("true".equals(UtilProperties.getPropertyValue("security.properties", "username.lowercase")))) {
373             userLoginId = userLoginId.toLowerCase();
374         }
375
376         if (!UtilValidate.isNotEmpty(userLoginId)) {
377             // the password was incomplete
378
errMsg = UtilProperties.getMessage(resource, "loginevents.username_was_empty_reenter", UtilHttp.getLocale(request));
379             request.setAttribute("_ERROR_MESSAGE_", errMsg);
380             return "error";
381         }
382
383         GenericValue supposedUserLogin = null;
384
385         try {
386             supposedUserLogin = delegator.findByPrimaryKey("UserLogin", UtilMisc.toMap("userLoginId", userLoginId));
387         } catch (GenericEntityException gee) {
388             Debug.logWarning(gee, "", module);
389         }
390         if (supposedUserLogin == null) {
391             // the Username was not found
392
errMsg = UtilProperties.getMessage(resource, "loginevents.username_not_found_reenter", UtilHttp.getLocale(request));
393             request.setAttribute("_ERROR_MESSAGE_", errMsg);
394             return "error";
395         }
396
397         String JavaDoc passwordHint = supposedUserLogin.getString("passwordHint");
398
399         if (!UtilValidate.isNotEmpty(passwordHint)) {
400             // the Username was not found
401
errMsg = UtilProperties.getMessage(resource, "loginevents.no_password_hint_specified_try_password_emailed", UtilHttp.getLocale(request));
402             request.setAttribute("_ERROR_MESSAGE_", errMsg);
403             return "error";
404         }
405
406         Map JavaDoc messageMap = UtilMisc.toMap("passwordHint", passwordHint);
407         errMsg = UtilProperties.getMessage(resource, "loginevents.password_hint_is", messageMap, UtilHttp.getLocale(request));
408         request.setAttribute("_ERROR_MESSAGE_", errMsg);
409         return "success";
410     }
411
412     /**
413      * Email the password for the userLoginId specified in the request object.
414      *
415      * @param request The HTTPRequest object for the current request
416      * @param response The HTTPResponse object for the current request
417      * @return String specifying the exit status of this event
418      */

419     public static String JavaDoc emailPassword(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
420         String JavaDoc defaultScreenLocation = "component://securityext/widget/EmailSecurityScreens.xml#PasswordEmail";
421         
422         GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator");
423         LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
424         String JavaDoc productStoreId = ProductStoreWorker.getProductStoreId(request);
425         
426         String JavaDoc errMsg = null;
427
428         Map JavaDoc subjectData = FastMap.newInstance();
429         subjectData.put("productStoreId", productStoreId);
430
431         boolean useEncryption = "true".equals(UtilProperties.getPropertyValue("security.properties", "password.encrypt"));
432
433         String JavaDoc userLoginId = request.getParameter("USERNAME");
434         subjectData.put("userLoginId", userLoginId);
435
436         if ((userLoginId != null) && ("true".equals(UtilProperties.getPropertyValue("security.properties", "username.lowercase")))) {
437             userLoginId = userLoginId.toLowerCase();
438         }
439
440         if (!UtilValidate.isNotEmpty(userLoginId)) {
441             // the password was incomplete
442
errMsg = UtilProperties.getMessage(resource, "loginevents.username_was_empty_reenter", UtilHttp.getLocale(request));
443             request.setAttribute("_ERROR_MESSAGE_", errMsg);
444             return "error";
445         }
446
447         GenericValue supposedUserLogin = null;
448         String JavaDoc passwordToSend = null;
449
450         try {
451             supposedUserLogin = delegator.findByPrimaryKey("UserLogin", UtilMisc.toMap("userLoginId", userLoginId));
452             if (supposedUserLogin == null) {
453                 // the Username was not found
454
errMsg = UtilProperties.getMessage(resource, "loginevents.username_not_found_reenter", UtilHttp.getLocale(request));
455                 request.setAttribute("_ERROR_MESSAGE_", errMsg);
456                 return "error";
457             }
458             if (useEncryption) {
459                 // password encrypted, can't send, generate new password and email to user
460
double randNum = Math.random();
461
462                 // multiply by 100,000 to usually make a 5 digit number
463
passwordToSend = "auto" + ((long) (randNum * 100000));
464                 supposedUserLogin.set("currentPassword", LoginServices.getPasswordHash(passwordToSend));
465                 supposedUserLogin.set("passwordHint", "Auto-Generated Password");
466             } else {
467                 passwordToSend = supposedUserLogin.getString("currentPassword");
468             }
469         } catch (GenericEntityException e) {
470             Debug.logWarning(e, "", module);
471             Map JavaDoc messageMap = UtilMisc.toMap("errorMessage", e.toString());
472             errMsg = UtilProperties.getMessage(resource, "loginevents.error_accessing_password", messageMap, UtilHttp.getLocale(request));
473             request.setAttribute("_ERROR_MESSAGE_", errMsg);
474             return "error";
475         }
476         if (supposedUserLogin == null) {
477             // the Username was not found
478
Map JavaDoc messageMap = UtilMisc.toMap("userLoginId", userLoginId);
479             errMsg = UtilProperties.getMessage(resource, "loginevents.user_with_the_username_not_found", messageMap, UtilHttp.getLocale(request));
480             request.setAttribute("_ERROR_MESSAGE_", errMsg);
481             return "error";
482         }
483
484         StringBuffer JavaDoc emails = new StringBuffer JavaDoc();
485         GenericValue party = null;
486
487         try {
488             party = supposedUserLogin.getRelatedOne("Party");
489         } catch (GenericEntityException e) {
490             Debug.logWarning(e, "", module);
491             party = null;
492         }
493         if (party != null) {
494             Iterator JavaDoc emailIter = UtilMisc.toIterator(ContactHelper.getContactMechByPurpose(party, "PRIMARY_EMAIL", false));
495             while (emailIter != null && emailIter.hasNext()) {
496                 GenericValue email = (GenericValue) emailIter.next();
497                 emails.append(emails.length() > 0 ? "," : "").append(email.getString("infoString"));
498             }
499         }
500
501         if (!UtilValidate.isNotEmpty(emails.toString())) {
502             // the Username was not found
503
errMsg = UtilProperties.getMessage(resource, "loginevents.no_primary_email_address_set_contact_customer_service", UtilHttp.getLocale(request));
504             request.setAttribute("_ERROR_MESSAGE_", errMsg);
505             return "error";
506         }
507
508         // get the ProductStore email settings
509
GenericValue productStoreEmail = null;
510         try {
511             productStoreEmail = delegator.findByPrimaryKey("ProductStoreEmailSetting", UtilMisc.toMap("productStoreId", productStoreId, "emailType", "PRDS_PWD_RETRIEVE"));
512         } catch (GenericEntityException e) {
513             Debug.logError(e, "Problem getting ProductStoreEmailSetting", module);
514         }
515
516         if (productStoreEmail == null) {
517             errMsg = UtilProperties.getMessage(resource, "loginevents.problems_with_configuration_contact_customer_service", UtilHttp.getLocale(request));
518             request.setAttribute("_ERROR_MESSAGE_", errMsg);
519             return "error";
520         }
521
522         String JavaDoc bodyScreenLocation = productStoreEmail.getString("bodyScreenLocation");
523         if (UtilValidate.isEmpty(bodyScreenLocation)) {
524             bodyScreenLocation = defaultScreenLocation;
525         }
526         
527         // set the needed variables in new context
528
Map JavaDoc bodyParameters = FastMap.newInstance();
529         bodyParameters.put("useEncryption", new Boolean JavaDoc(useEncryption));
530         bodyParameters.put("password", UtilFormatOut.checkNull(passwordToSend));
531         bodyParameters.put("locale", UtilHttp.getLocale(request));
532         bodyParameters.put("userLogin", supposedUserLogin);
533
534         Map JavaDoc serviceContext = FastMap.newInstance();
535         serviceContext.put("bodyScreenUri", bodyScreenLocation);
536         serviceContext.put("bodyParameters", bodyParameters);
537         serviceContext.put("subject", productStoreEmail.getString("subject"));
538         serviceContext.put("sendFrom", productStoreEmail.get("fromAddress"));
539         serviceContext.put("sendCc", productStoreEmail.get("ccAddress"));
540         serviceContext.put("sendBcc", productStoreEmail.get("bccAddress"));
541         serviceContext.put("contentType", productStoreEmail.get("contentType"));
542         serviceContext.put("sendTo", emails.toString());
543
544         try {
545             Map JavaDoc result = dispatcher.runSync("sendMailFromScreen", serviceContext);
546
547             if (ModelService.RESPOND_ERROR.equals((String JavaDoc) result.get(ModelService.RESPONSE_MESSAGE))) {
548                 Map JavaDoc messageMap = UtilMisc.toMap("errorMessage", result.get(ModelService.ERROR_MESSAGE));
549                 errMsg = UtilProperties.getMessage(resource, "loginevents.error_unable_email_password_contact_customer_service_errorwas", messageMap, UtilHttp.getLocale(request));
550                 request.setAttribute("_ERROR_MESSAGE_", errMsg);
551                 return "error";
552             }
553         } catch (GenericServiceException e) {
554             Debug.logWarning(e, "", module);
555             errMsg = UtilProperties.getMessage(resource, "loginevents.error_unable_email_password_contact_customer_service", UtilHttp.getLocale(request));
556             request.setAttribute("_ERROR_MESSAGE_", errMsg);
557             return "error";
558         }
559
560         // don't save password until after it has been sent
561
if (useEncryption) {
562             try {
563                 supposedUserLogin.store();
564             } catch (GenericEntityException e) {
565                 Debug.logWarning(e, "", module);
566                 Map JavaDoc messageMap = UtilMisc.toMap("errorMessage", e.toString());
567                 errMsg = UtilProperties.getMessage(resource, "loginevents.error_saving_new_password_email_not_correct_password", messageMap, UtilHttp.getLocale(request));
568                 request.setAttribute("_ERROR_MESSAGE_", errMsg);
569                 return "error";
570             }
571         }
572
573         if (useEncryption) {
574             errMsg = UtilProperties.getMessage(resource, "loginevents.new_password_createdandsent_check_email", UtilHttp.getLocale(request));
575             request.setAttribute("_EVENT_MESSAGE_", errMsg);
576         } else {
577             errMsg = UtilProperties.getMessage(resource, "loginevents.new_password_sent_check_email", UtilHttp.getLocale(request));
578             request.setAttribute("_EVENT_MESSAGE_", errMsg);
579         }
580         return "success";
581     }
582
583     protected static String JavaDoc getAutoLoginCookieName(HttpServletRequest JavaDoc request) {
584         return UtilHttp.getApplicationName(request) + ".autoUserLoginId";
585     }
586
587     public static String JavaDoc getAutoUserLoginId(HttpServletRequest JavaDoc request) {
588         String JavaDoc autoUserLoginId = null;
589         Cookie JavaDoc[] cookies = request.getCookies();
590         if (Debug.verboseOn()) Debug.logVerbose("Cookies:" + cookies, module);
591         if (cookies != null) {
592             for (int i = 0; i < cookies.length; i++) {
593                 if (cookies[i].getName().equals(getAutoLoginCookieName(request))) {
594                     autoUserLoginId = cookies[i].getValue();
595                     break;
596                 }
597             }
598         }
599         return autoUserLoginId;
600     }
601
602     public static String JavaDoc autoLoginCheck(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
603         GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator");
604         HttpSession JavaDoc session = request.getSession();
605
606         return autoLoginCheck(delegator, session, getAutoUserLoginId(request));
607     }
608
609     private static String JavaDoc autoLoginCheck(GenericDelegator delegator, HttpSession JavaDoc session, String JavaDoc autoUserLoginId) {
610         if (autoUserLoginId != null) {
611             Debug.logInfo("Running autoLogin check.", module);
612             try {
613                 GenericValue autoUserLogin = delegator.findByPrimaryKey("UserLogin", UtilMisc.toMap("userLoginId", autoUserLoginId));
614                 GenericValue person = null;
615                 GenericValue group = null;
616                 if (autoUserLogin != null) {
617                     person = delegator.findByPrimaryKey("Person", UtilMisc.toMap("partyId", autoUserLogin.getString("partyId")));
618                     group = delegator.findByPrimaryKey("PartyGroup", UtilMisc.toMap("partyId", autoUserLogin.getString("partyId")));
619                     session.setAttribute("autoUserLogin", autoUserLogin);
620                 }
621                 if (person != null) {
622                     session.setAttribute("autoName", person.getString("firstName") + " " + person.getString("lastName"));
623                 } else if (group != null) {
624                     session.setAttribute("autoName", group.getString("groupName"));
625                 }
626             } catch (GenericEntityException e) {
627                 Debug.logError(e, "Cannot get autoUserLogin information: " + e.getMessage(), module);
628             }
629         }
630         return "success";
631     }
632
633     public static String JavaDoc autoLoginSet(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
634         GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator");
635         HttpSession JavaDoc session = request.getSession();
636         GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");
637         if (userLogin != null) {
638             Cookie JavaDoc autoLoginCookie = new Cookie JavaDoc(getAutoLoginCookieName(request), userLogin.getString("userLoginId"));
639             autoLoginCookie.setMaxAge(60 * 60 * 24 * 365);
640             autoLoginCookie.setPath("/");
641             response.addCookie(autoLoginCookie);
642             return autoLoginCheck(delegator, session, userLogin.getString("userLoginId"));
643         } else {
644             return "success";
645         }
646     }
647
648     public static String JavaDoc autoLoginRemove(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
649         HttpSession JavaDoc session = request.getSession();
650         GenericValue userLogin = (GenericValue) session.getAttribute("autoUserLogin");
651
652         // remove the cookie
653
if (userLogin != null) {
654             Cookie JavaDoc autoLoginCookie = new Cookie JavaDoc(getAutoLoginCookieName(request), userLogin.getString("userLoginId"));
655             autoLoginCookie.setMaxAge(0);
656             autoLoginCookie.setPath("/");
657             response.addCookie(autoLoginCookie);
658         }
659         // remove the session attributes
660
session.removeAttribute("autoUserLogin");
661         session.removeAttribute("autoName");
662         // logout the user if logged in.
663
if (session.getAttribute("userLogin") != null) {
664             request.setAttribute("_AUTO_LOGIN_LOGOUT_", new Boolean JavaDoc(true));
665             return logout(request, response);
666         }
667         return "success";
668     }
669
670     public static String JavaDoc checkExternalLoginKey(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
671         HttpSession JavaDoc session = request.getSession();
672
673         String JavaDoc externalKey = request.getParameter(LoginWorker.EXTERNAL_LOGIN_KEY_ATTR);
674         if (externalKey == null) return "success";
675
676         GenericValue userLogin = (GenericValue) LoginWorker.externalLoginKeys.get(externalKey);
677         if (userLogin != null) {
678             // found userLogin, do the external login...
679

680             // if the user is already logged in and the login is different, logout the other user
681
GenericValue currentUserLogin = (GenericValue) session.getAttribute("userLogin");
682             if (currentUserLogin != null) {
683                 if (currentUserLogin.getString("userLoginId").equals(userLogin.getString("userLoginId"))) {
684                     // is the same user, just carry on...
685
return "success";
686                 }
687
688                 // logout the current user and login the new user...
689
logout(request, response);
690                 // ignore the return value; even if the operation failed we want to set the new UserLogin
691
}
692
693             doBasicLogin(userLogin, request);
694         } else {
695             Debug.logWarning("Could not find userLogin for external login key: " + externalKey, module);
696         }
697
698         return "success";
699     }
700
701     public static boolean isFlaggedLoggedOut(GenericValue userLogin) {
702         if ("true".equalsIgnoreCase(UtilProperties.getPropertyValue("security.properties", "login.disable.global.logout"))) {
703             return false;
704         }
705         if (userLogin == null || userLogin.get("userLoginId") == null) {
706             return true;
707         }
708         // refresh the login object -- maybe cache this?
709
try {
710             userLogin.refreshFromCache();
711         } catch (GenericEntityException e) {
712             Debug.logWarning(e, "Unable to refresh UserLogin", module);
713         }
714         return (userLogin.get("hasLoggedOut") != null ?
715                 "Y".equalsIgnoreCase(userLogin.getString("hasLoggedOut")) : false);
716     }
717
718     protected static boolean hasBasePermission(GenericValue userLogin, HttpServletRequest JavaDoc request) {
719         ServletContext JavaDoc context = (ServletContext JavaDoc) request.getAttribute("servletContext");
720         Security security = (Security) request.getAttribute("security");
721
722         String JavaDoc serverId = (String JavaDoc) context.getAttribute("_serverId");
723         String JavaDoc contextPath = request.getContextPath();
724
725         ComponentConfig.WebappInfo info = ComponentConfig.getWebAppInfo(serverId, contextPath);
726         if (security != null) {
727             if (info != null) {
728                 String JavaDoc[] permissions = info.getBasePermission();
729                 for (int i = 0; i < permissions.length; i++) {
730                     if (!"NONE".equals(permissions[i]) && !security.hasEntityPermission(permissions[i], "_VIEW", userLogin)) {
731                         return false;
732                     }
733                 }
734             } else {
735                 Debug.logInfo("No webapp configuration found for : " + serverId + " / " + contextPath, module);
736             }
737         } else {
738             Debug.logWarning("Received a null Security object from HttpServletRequest", module);
739         }
740
741         return true;
742     }
743
744     public static String JavaDoc storeCheckLogin(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
745         String JavaDoc responseString = LoginEvents.checkLogin(request, response);
746         if ("error".equals(responseString)) {
747             return responseString;
748         }
749         // if we are logged in okay, do the check store customer role
750
return ProductEvents.checkStoreCustomerRole(request, response);
751     }
752
753     public static String JavaDoc storeLogin(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
754         String JavaDoc responseString = LoginEvents.login(request, response);
755         if ("error".equals(responseString)) {
756             return responseString;
757         }
758         // if we logged in okay, do the check store customer role
759
return ProductEvents.checkStoreCustomerRole(request, response);
760     }
761 }
762
Popular Tags