Source Code Cross Referenced for LoginEvents.java in  » ERP-CRM-Financial » SourceTap-CRM » org » ofbiz » securityext » login » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » ERP CRM Financial » SourceTap CRM » org.ofbiz.securityext.login 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


001:        /*
002:         * $Id: LoginEvents.java,v 1.10 2004/01/28 21:34:12 ajzeneski Exp $
003:         *
004:         *  Copyright (c) 2001, 2002 The Open For Business Project - www.ofbiz.org
005:         *
006:         *  Permission is hereby granted, free of charge, to any person obtaining a
007:         *  copy of this software and associated documentation files (the "Software"),
008:         *  to deal in the Software without restriction, including without limitation
009:         *  the rights to use, copy, modify, merge, publish, distribute, sublicense,
010:         *  and/or sell copies of the Software, and to permit persons to whom the
011:         *  Software is furnished to do so, subject to the following conditions:
012:         *
013:         *  The above copyright notice and this permission notice shall be included
014:         *  in all copies or substantial portions of the Software.
015:         *
016:         *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
017:         *  OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
018:         *  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
019:         *  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
020:         *  CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
021:         *  OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
022:         *  THE USE OR OTHER DEALINGS IN THE SOFTWARE.
023:         */
024:        package org.ofbiz.securityext.login;
025:
026:        import java.util.HashMap;
027:        import java.util.Iterator;
028:        import java.util.Map;
029:
030:        import javax.servlet.http.Cookie;
031:        import javax.servlet.http.HttpServletRequest;
032:        import javax.servlet.http.HttpServletResponse;
033:        import javax.servlet.http.HttpSession;
034:        import javax.servlet.ServletContext;
035:
036:        import org.ofbiz.base.util.Debug;
037:        import org.ofbiz.base.util.FlexibleStringExpander;
038:        import org.ofbiz.base.util.UtilFormatOut;
039:        import org.ofbiz.base.util.UtilHttp;
040:        import org.ofbiz.base.util.UtilMisc;
041:        import org.ofbiz.base.util.UtilProperties;
042:        import org.ofbiz.base.util.UtilValidate;
043:        import org.ofbiz.base.component.ComponentConfig;
044:        import org.ofbiz.content.stats.VisitHandler;
045:        import org.ofbiz.entity.GenericDelegator;
046:        import org.ofbiz.entity.GenericEntityException;
047:        import org.ofbiz.entity.GenericValue;
048:        import org.ofbiz.order.shoppingcart.ShoppingCart;
049:        import org.ofbiz.order.shoppingcart.WebShoppingCart;
050:        import org.ofbiz.party.contact.ContactHelper;
051:        import org.ofbiz.product.store.ProductStoreWorker;
052:        import org.ofbiz.security.Security;
053:        import org.ofbiz.service.GenericServiceException;
054:        import org.ofbiz.service.LocalDispatcher;
055:        import org.ofbiz.service.ModelService;
056:
057:        /**
058:         * LoginEvents - Events for UserLogin and Security handling.
059:         *
060:         * @author     <a href="mailto:jaz@ofbiz.org">Andy Zeneski</a>
061:         * @author     <a href="mailto:jonesde@ofbiz.org">David E. Jones</a>
062:         * @author     <a href="">Dustin Caldwell</a>
063:         * @author     <a href="mailto:therrick@yahoo.com">Tom Herrick</a>
064:         * @version    $Revision: 1.10 $
065:         * @since      2.0
066:         */
067:        public class LoginEvents {
068:
069:            public static final String module = LoginEvents.class.getName();
070:
071:            public static final String EXTERNAL_LOGIN_KEY_ATTR = "externalLoginKey";
072:
073:            /** This Map is keyed by the randomly generated externalLoginKey and the value is a UserLogin GenericValue object */
074:            public static Map externalLoginKeys = new HashMap();
075:
076:            /** This Map is keyed by userLoginId and the value is another Map keyed by the webappName and the value is the sessionId.
077:             * When a user logs in an entry in this Map will be populated for the given user, webapp and session.
078:             * When checking security this Map will be checked if the user is logged in to see if we should log them out automatically; this implements the universal logout.
079:             * When a user logs out this Map will be cleared so the user will be logged out automatically on subsequent requests.
080:             */
081:            public static Map loggedInSessions = new HashMap();
082:
083:            /**
084:             * Save USERNAME and PASSWORD for use by auth pages even if we start in non-auth pages.
085:             *
086:             * @param request The HTTP request object for the current JSP or Servlet request.
087:             * @param response The HTTP response object for the current JSP or Servlet request.
088:             * @return
089:             */
090:            public static String saveEntryParams(HttpServletRequest request,
091:                    HttpServletResponse response) {
092:                GenericValue userLogin = (GenericValue) request.getSession()
093:                        .getAttribute("userLogin");
094:                HttpSession session = request.getSession();
095:
096:                // save entry login parameters if we don't have a valid login object
097:                if (userLogin == null) {
098:
099:                    String username = request.getParameter("USERNAME");
100:                    String password = request.getParameter("PASSWORD");
101:
102:                    if ((username != null)
103:                            && ("true".equals(UtilProperties
104:                                    .getPropertyValue("security.properties",
105:                                            "username.lowercase")))) {
106:                        username = username.toLowerCase();
107:                    }
108:                    if ((password != null)
109:                            && ("true".equals(UtilProperties
110:                                    .getPropertyValue("security.properties",
111:                                            "password.lowercase")))) {
112:                        password = password.toLowerCase();
113:                    }
114:
115:                    // save parameters into the session - so they can be used later, if needed
116:                    if (username != null)
117:                        session.setAttribute("USERNAME", username);
118:                    if (password != null)
119:                        session.setAttribute("PASSWORD", password);
120:
121:                } else {
122:                    // if the login object is valid, remove attributes
123:                    session.removeAttribute("USERNAME");
124:                    session.removeAttribute("PASSWORD");
125:                }
126:
127:                return "success";
128:            }
129:
130:            /**
131:             * An HTTP WebEvent handler that checks to see is a userLogin is logged in.
132:             * If not, the user is forwarded to the /login.jsp page.
133:             *
134:             * @param request The HTTP request object for the current JSP or Servlet request.
135:             * @param response The HTTP response object for the current JSP or Servlet request.
136:             * @return
137:             */
138:            public static String checkLogin(HttpServletRequest request,
139:                    HttpServletResponse response) {
140:                GenericValue userLogin = (GenericValue) request.getSession()
141:                        .getAttribute("userLogin");
142:                HttpSession session = request.getSession();
143:
144:                // anonymous shoppers are not logged in
145:                if (userLogin != null
146:                        && "anonymous".equals(userLogin
147:                                .getString("userLoginId"))) {
148:                    userLogin = null;
149:                }
150:
151:                // user is logged in; check to see if there is an entry in the loggedInSessions Map, if not log out this user
152:                // also check if they have permission for this login attempt; if not log them out as well.
153:                if (userLogin != null) {
154:                    boolean loggedInSession = isLoggedInSession(userLogin,
155:                            request);
156:                    boolean hasBasePermission = hasBasePermission(userLogin,
157:                            request);
158:                    if (!loggedInSession || !hasBasePermission) {
159:                        doBasicLogout(userLogin, request);
160:                        userLogin = null;
161:                        // have to reget this because the old session object will be invalid
162:                        session = request.getSession();
163:                    }
164:                }
165:
166:                String username = null;
167:                String password = null;
168:
169:                if (userLogin == null) {
170:                    // check parameters
171:                    if (username == null)
172:                        username = request.getParameter("USERNAME");
173:                    if (password == null)
174:                        password = request.getParameter("PASSWORD");
175:                    // check session attributes
176:                    if (username == null)
177:                        username = (String) session.getAttribute("USERNAME");
178:                    if (password == null)
179:                        password = (String) session.getAttribute("PASSWORD");
180:
181:                    if ((username != null)
182:                            && ("true".equals(UtilProperties
183:                                    .getPropertyValue("security.properties",
184:                                            "username.lowercase")))) {
185:                        username = username.toLowerCase();
186:                    }
187:                    if ((password != null)
188:                            && ("true".equals(UtilProperties
189:                                    .getPropertyValue("security.properties",
190:                                            "password.lowercase")))) {
191:                        password = password.toLowerCase();
192:                    }
193:
194:                    // in this condition log them in if not already; if not logged in or can't log in, save parameters and return error
195:                    if ((username == null) || (password == null)
196:                            || ("error".equals(login(request, response)))) {
197:                        Map reqParams = UtilHttp.getParameterMap(request);
198:                        String queryString = UtilHttp.urlEncodeArgs(reqParams);
199:                        Debug.logInfo("reqParams Map: " + reqParams, module);
200:                        Debug.logInfo("queryString: " + queryString, module);
201:
202:                        session.setAttribute("_PREVIOUS_REQUEST_", request
203:                                .getPathInfo());
204:                        if (queryString != null && queryString.length() > 0) {
205:                            session.setAttribute("_PREVIOUS_PARAMS_",
206:                                    queryString);
207:                        }
208:
209:                        if (Debug.infoOn())
210:                            Debug.logInfo("checkLogin: queryString="
211:                                    + queryString, module);
212:                        if (Debug.infoOn())
213:                            Debug.logInfo("checkLogin: PathInfo="
214:                                    + request.getPathInfo(), module);
215:
216:                        return "error";
217:                    }
218:                }
219:
220:                return "success";
221:            }
222:
223:            /**
224:             * An HTTP WebEvent handler that logs in a userLogin. This should run before the security check.
225:             *
226:             * @param request The HTTP request object for the current JSP or Servlet request.
227:             * @param response The HTTP response object for the current JSP or Servlet request.
228:             * @return Return a boolean which specifies whether or not the calling Servlet or
229:             *         JSP should generate its own content. This allows an event to override the default content.
230:             */
231:            public static String login(HttpServletRequest request,
232:                    HttpServletResponse response) {
233:                HttpSession session = request.getSession();
234:
235:                String username = request.getParameter("USERNAME");
236:                String password = request.getParameter("PASSWORD");
237:
238:                if (username == null)
239:                    username = (String) session.getAttribute("USERNAME");
240:                if (password == null)
241:                    password = (String) session.getAttribute("PASSWORD");
242:
243:                if ((username != null)
244:                        && ("true".equalsIgnoreCase(UtilProperties
245:                                .getPropertyValue("security.properties",
246:                                        "username.lowercase")))) {
247:                    username = username.toLowerCase();
248:                }
249:                if ((password != null)
250:                        && ("true".equalsIgnoreCase(UtilProperties
251:                                .getPropertyValue("security.properties",
252:                                        "password.lowercase")))) {
253:                    password = password.toLowerCase();
254:                }
255:
256:                if ("true".equalsIgnoreCase(UtilProperties.getPropertyValue(
257:                        "security.properties", "login.lock.active"))) {
258:                    boolean userIdLoggedIn = isLoggedInSession(username,
259:                            request, false);
260:                    boolean this UserLoggedIn = isLoggedInSession(username,
261:                            request, true);
262:                    if (userIdLoggedIn && !this UserLoggedIn) {
263:                        request.setAttribute("_ERROR_MESSAGE_",
264:                                "<b>This user is already logged in.</b><br>");
265:                        return "error";
266:                    }
267:                }
268:
269:                // get the visit id to pass to the userLogin for history
270:                String visitId = VisitHandler.getVisitId(session);
271:
272:                LocalDispatcher dispatcher = (LocalDispatcher) request
273:                        .getAttribute("dispatcher");
274:                Map result = null;
275:
276:                try {
277:                    result = dispatcher.runSync("userLogin", UtilMisc.toMap(
278:                            "login.username", username, "login.password",
279:                            password, "visitId", visitId));
280:                } catch (GenericServiceException e) {
281:                    Debug
282:                            .logError(e, "Error calling userLogin service",
283:                                    module);
284:                    request.setAttribute("_ERROR_MESSAGE_",
285:                            "<b>The following error occurred during login:</b><br>"
286:                                    + e.getMessage());
287:                    return "error";
288:                }
289:
290:                if (ModelService.RESPOND_SUCCESS.equals(result
291:                        .get(ModelService.RESPONSE_MESSAGE))) {
292:                    GenericValue userLogin = (GenericValue) result
293:                            .get("userLogin");
294:                    Map userLoginSession = (Map) result.get("userLoginSession");
295:
296:                    if (userLogin != null
297:                            && hasBasePermission(userLogin, request)) {
298:                        doBasicLogin(userLogin, request);
299:                    } else {
300:                        request
301:                                .setAttribute("_ERROR_MESSAGE_",
302:                                        "<b>Unable to login in to this application.</b><br>");
303:                        return "error";
304:                    }
305:
306:                    if (userLoginSession != null) {
307:                        session.setAttribute("userLoginSession",
308:                                userLoginSession);
309:                    }
310:                } else {
311:                    String errMsg = (String) result
312:                            .get(ModelService.ERROR_MESSAGE);
313:
314:                    errMsg = "<b>The following error occurred during login:</b><br>"
315:                            + errMsg;
316:                    request.setAttribute("_ERROR_MESSAGE_", errMsg);
317:                    return "error";
318:                }
319:
320:                request.setAttribute("_LOGIN_PASSED_", "TRUE");
321:                // make sure the autoUserLogin is set to the same and that the client cookie has the correct userLoginId
322:                return autoLoginSet(request, response);
323:            }
324:
325:            public static void doBasicLogin(GenericValue userLogin,
326:                    HttpServletRequest request) {
327:                HttpSession session = request.getSession();
328:                session.setAttribute("userLogin", userLogin);
329:                // let the visit know who the user is
330:                VisitHandler.setUserLogin(session, userLogin, false);
331:                loginToSession(userLogin, request);
332:            }
333:
334:            /**
335:             * An HTTP WebEvent handler that logs out a userLogin by clearing the session.
336:             *
337:             * @param request The HTTP request object for the current JSP or Servlet request.
338:             * @param response The HTTP response object for the current JSP or Servlet request.
339:             * @return Return a boolean which specifies whether or not the calling Servlet or
340:             *        JSP should generate its own content. This allows an event to override the default content.
341:             */
342:            public static String logout(HttpServletRequest request,
343:                    HttpServletResponse response) {
344:                // invalidate the security group list cache
345:                GenericValue userLogin = (GenericValue) request.getSession()
346:                        .getAttribute("userLogin");
347:
348:                // log out from all other sessions too; do this here so that it is only done when a user explicitly logs out
349:                logoutFromAllSessions(userLogin);
350:
351:                doBasicLogout(userLogin, request);
352:
353:                if (request.getAttribute("_AUTO_LOGIN_LOGOUT_") == null) {
354:                    return autoLoginCheck(request, response);
355:                }
356:                return "success";
357:            }
358:
359:            public static void doBasicLogout(GenericValue userLogin,
360:                    HttpServletRequest request) {
361:                HttpSession session = request.getSession();
362:
363:                Security security = (Security) request.getAttribute("security");
364:
365:                if (security != null && userLogin != null) {
366:                    Security.userLoginSecurityGroupByUserLoginId
367:                            .remove(userLogin.getString("userLoginId"));
368:                }
369:
370:                // this is a setting we don't want to lose, although it would be good to have a more general solution here...
371:                String currCatalog = (String) session
372:                        .getAttribute("CURRENT_CATALOG_ID");
373:                // also make sure the delegatorName is preserved, especially so that a new Visit can be created
374:                String delegatorName = (String) session
375:                        .getAttribute("delegatorName");
376:                // also save the shopping cart if we have one
377:                // 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
378:                //ShoppingCart shoppingCart = (ShoppingCart) session.getAttribute("shoppingCart");
379:
380:                session.invalidate();
381:                session = request.getSession(true);
382:
383:                if (currCatalog != null)
384:                    session.setAttribute("CURRENT_CATALOG_ID", currCatalog);
385:                if (delegatorName != null)
386:                    session.setAttribute("delegatorName", delegatorName);
387:                // DON'T save the cart, causes too many problems: if (shoppingCart != null) session.setAttribute("shoppingCart", new WebShoppingCart(shoppingCart, session));
388:            }
389:
390:            /**
391:             * The user forgot his/her password.  This will either call showPasswordHint or emailPassword.
392:             *
393:             * @param request The HTTPRequest object for the current request
394:             * @param response The HTTPResponse object for the current request
395:             * @return String specifying the exit status of this event
396:             */
397:            public static String forgotPassword(HttpServletRequest request,
398:                    HttpServletResponse response) {
399:                if ((UtilValidate.isNotEmpty(request
400:                        .getParameter("GET_PASSWORD_HINT")))
401:                        || (UtilValidate.isNotEmpty(request
402:                                .getParameter("GET_PASSWORD_HINT.x")))) {
403:                    return showPasswordHint(request, response);
404:                } else {
405:                    return emailPassword(request, response);
406:                }
407:            }
408:
409:            /** Show the password hint for the userLoginId specified in the request object.
410:             *@param request The HTTPRequest object for the current request
411:             *@param response The HTTPResponse object for the current request
412:             *@return String specifying the exit status of this event
413:             */
414:            public static String showPasswordHint(HttpServletRequest request,
415:                    HttpServletResponse response) {
416:                GenericDelegator delegator = (GenericDelegator) request
417:                        .getAttribute("delegator");
418:
419:                String userLoginId = request.getParameter("USERNAME");
420:
421:                if ((userLoginId != null)
422:                        && ("true".equals(UtilProperties.getPropertyValue(
423:                                "security.properties", "username.lowercase")))) {
424:                    userLoginId = userLoginId.toLowerCase();
425:                }
426:
427:                if (!UtilValidate.isNotEmpty(userLoginId)) {
428:                    // the password was incomplete
429:                    request.setAttribute("_ERROR_MESSAGE_",
430:                            "<li>The Username was empty, please re-enter.");
431:                    return "error";
432:                }
433:
434:                GenericValue supposedUserLogin = null;
435:
436:                try {
437:                    supposedUserLogin = delegator.findByPrimaryKey("UserLogin",
438:                            UtilMisc.toMap("userLoginId", userLoginId));
439:                } catch (GenericEntityException gee) {
440:                    Debug.logWarning(gee, "", module);
441:                }
442:                if (supposedUserLogin == null) {
443:                    // the Username was not found
444:                    request.setAttribute("_ERROR_MESSAGE_",
445:                            "<li>The Username was not found, please re-enter.");
446:                    return "error";
447:                }
448:
449:                String passwordHint = supposedUserLogin
450:                        .getString("passwordHint");
451:
452:                if (!UtilValidate.isNotEmpty(passwordHint)) {
453:                    // the Username was not found
454:                    request
455:                            .setAttribute("_ERROR_MESSAGE_",
456:                                    "<li>No password hint was specified, try having the password emailed instead.");
457:                    return "error";
458:                }
459:
460:                request.setAttribute("_EVENT_MESSAGE_",
461:                        "The Password Hint is: " + passwordHint);
462:                return "success";
463:            }
464:
465:            /**
466:             *  Email the password for the userLoginId specified in the request object.
467:             *
468:             * @param request The HTTPRequest object for the current request
469:             * @param response The HTTPResponse object for the current request
470:             * @return String specifying the exit status of this event
471:             */
472:            public static String emailPassword(HttpServletRequest request,
473:                    HttpServletResponse response) {
474:                GenericDelegator delegator = (GenericDelegator) request
475:                        .getAttribute("delegator");
476:                LocalDispatcher dispatcher = (LocalDispatcher) request
477:                        .getAttribute("dispatcher");
478:                String productStoreId = ProductStoreWorker
479:                        .getProductStoreId(request);
480:
481:                Map subjectData = new HashMap();
482:                subjectData.put("productStoreId", productStoreId);
483:
484:                boolean useEncryption = "true".equals(UtilProperties
485:                        .getPropertyValue("security.properties",
486:                                "password.encrypt"));
487:
488:                String userLoginId = request.getParameter("USERNAME");
489:                subjectData.put("userLoginId", userLoginId);
490:
491:                if ((userLoginId != null)
492:                        && ("true".equals(UtilProperties.getPropertyValue(
493:                                "security.properties", "username.lowercase")))) {
494:                    userLoginId = userLoginId.toLowerCase();
495:                }
496:
497:                if (!UtilValidate.isNotEmpty(userLoginId)) {
498:                    // the password was incomplete
499:                    request.setAttribute("_ERROR_MESSAGE_",
500:                            "<li>The Username was empty, please re-enter.");
501:                    return "error";
502:                }
503:
504:                GenericValue supposedUserLogin = null;
505:                String passwordToSend = null;
506:
507:                try {
508:                    supposedUserLogin = delegator.findByPrimaryKey("UserLogin",
509:                            UtilMisc.toMap("userLoginId", userLoginId));
510:                    if (supposedUserLogin == null) {
511:                        // the Username was not found
512:                        request
513:                                .setAttribute("_ERROR_MESSAGE_",
514:                                        "<li>The Username was not found, please re-enter.");
515:                        return "error";
516:                    }
517:                    if (useEncryption) {
518:                        // password encrypted, can't send, generate new password and email to user
519:                        double randNum = Math.random();
520:
521:                        // multiply by 100,000 to usually make a 5 digit number
522:                        passwordToSend = "auto" + ((long) (randNum * 100000));
523:                        supposedUserLogin.set("currentPassword", HashEncrypt
524:                                .getHash(passwordToSend));
525:                        supposedUserLogin.set("passwordHint",
526:                                "Auto-Generated Password");
527:                    } else {
528:                        passwordToSend = supposedUserLogin
529:                                .getString("currentPassword");
530:                    }
531:                } catch (GenericEntityException e) {
532:                    Debug.logWarning(e, "", module);
533:                    request.setAttribute("_ERROR_MESSAGE_",
534:                            "<li>Error accessing password: " + e.toString());
535:                    return "error";
536:                }
537:                if (supposedUserLogin == null) {
538:                    // the Username was not found
539:                    request.setAttribute("_ERROR_MESSAGE_",
540:                            "<li>A user with the username \"" + userLoginId
541:                                    + "\" was not found, please re-enter.");
542:                    return "error";
543:                }
544:
545:                StringBuffer emails = new StringBuffer();
546:                GenericValue party = null;
547:
548:                try {
549:                    party = supposedUserLogin.getRelatedOne("Party");
550:                } catch (GenericEntityException e) {
551:                    Debug.logWarning(e, "", module);
552:                    party = null;
553:                }
554:                if (party != null) {
555:                    Iterator emailIter = UtilMisc.toIterator(ContactHelper
556:                            .getContactMechByPurpose(party, "PRIMARY_EMAIL",
557:                                    false));
558:                    while (emailIter != null && emailIter.hasNext()) {
559:                        GenericValue email = (GenericValue) emailIter.next();
560:                        emails.append(emails.length() > 0 ? "," : "").append(
561:                                email.getString("infoString"));
562:                    }
563:                }
564:
565:                if (!UtilValidate.isNotEmpty(emails.toString())) {
566:                    // the Username was not found
567:                    request
568:                            .setAttribute("_ERROR_MESSAGE_",
569:                                    "<li>No Primary Email Address has been set, please contact customer service.");
570:                    return "error";
571:                }
572:
573:                // get the ProductStore email settings
574:                GenericValue productStoreEmail = null;
575:                try {
576:                    productStoreEmail = delegator.findByPrimaryKey(
577:                            "ProductStoreEmailSetting", UtilMisc.toMap(
578:                                    "productStoreId", productStoreId,
579:                                    "emailType", "PRDS_PWD_RETRIEVE"));
580:                } catch (GenericEntityException e) {
581:                    Debug.logError(e,
582:                            "Problem getting ProductStoreEmailSetting", module);
583:                }
584:
585:                if (productStoreEmail == null) {
586:                    request
587:                            .setAttribute("_ERROR_MESSAGE_",
588:                                    "<li>Problems with configuration; please contact customer service.");
589:                    return "error";
590:                }
591:
592:                // need OFBIZ_HOME for processing
593:                String ofbizHome = System.getProperty("ofbiz.home");
594:
595:                // set the needed variables in new context
596:                Map templateData = new HashMap();
597:                templateData.put("useEncryption", new Boolean(useEncryption));
598:                templateData.put("password", UtilFormatOut
599:                        .checkNull(passwordToSend));
600:
601:                // prepare the parsed subject
602:                String subjectString = productStoreEmail.getString("subject");
603:                subjectString = FlexibleStringExpander.expandString(
604:                        subjectString, subjectData);
605:
606:                Map serviceContext = new HashMap();
607:                serviceContext.put("templateName", ofbizHome
608:                        + productStoreEmail.get("templatePath"));
609:                serviceContext.put("templateData", templateData);
610:                serviceContext.put("subject", subjectString);
611:                serviceContext.put("sendFrom", productStoreEmail
612:                        .get("fromAddress"));
613:                serviceContext
614:                        .put("sendCc", productStoreEmail.get("ccAddress"));
615:                serviceContext.put("sendBcc", productStoreEmail
616:                        .get("ccAddress"));
617:                serviceContext.put("contentType", productStoreEmail
618:                        .get("contentType"));
619:                serviceContext.put("sendTo", emails.toString());
620:
621:                try {
622:                    Map result = dispatcher.runSync(
623:                            "sendGenericNotificationEmail", serviceContext);
624:
625:                    if (ModelService.RESPOND_ERROR.equals((String) result
626:                            .get(ModelService.RESPONSE_MESSAGE))) {
627:                        request
628:                                .setAttribute(
629:                                        "_ERROR_MESSAGE_",
630:                                        "Error occurred: unable to email password.  Please try again later or contact customer service. (error was: "
631:                                                + result
632:                                                        .get(ModelService.ERROR_MESSAGE)
633:                                                + ")");
634:                        return "error";
635:                    }
636:                } catch (GenericServiceException e) {
637:                    Debug.logWarning(e, "", module);
638:                    request
639:                            .setAttribute(
640:                                    "_ERROR_MESSAGE_",
641:                                    "Error occurred: unable to email password.  Please try again later or contact customer service.");
642:                    return "error";
643:                }
644:
645:                // don't save password until after it has been sent
646:                if (useEncryption) {
647:                    try {
648:                        supposedUserLogin.store();
649:                    } catch (GenericEntityException e) {
650:                        Debug.logWarning(e, "", module);
651:                        request
652:                                .setAttribute(
653:                                        "_ERROR_MESSAGE_",
654:                                        "<li>Error saving new password, the email that you receive will not have the correct password in it, your old password is still being used: "
655:                                                + e.toString());
656:                        return "error";
657:                    }
658:                }
659:
660:                if (useEncryption) {
661:                    request
662:                            .setAttribute("_EVENT_MESSAGE_",
663:                                    "A new password has been created and sent to you.  Please check your Email.");
664:                } else {
665:                    request
666:                            .setAttribute("_EVENT_MESSAGE_",
667:                                    "Your password has been sent to you.  Please check your Email.");
668:                }
669:                return "success";
670:            }
671:
672:            protected static String getAutoLoginCookieName(
673:                    HttpServletRequest request) {
674:                return UtilHttp.getApplicationName(request)
675:                        + ".autoUserLoginId";
676:            }
677:
678:            public static String getAutoUserLoginId(HttpServletRequest request) {
679:                String autoUserLoginId = null;
680:                Cookie[] cookies = request.getCookies();
681:                if (Debug.verboseOn())
682:                    Debug.logVerbose("Cookies:" + cookies, module);
683:                if (cookies != null) {
684:                    for (int i = 0; i < cookies.length; i++) {
685:                        if (cookies[i].getName().equals(
686:                                getAutoLoginCookieName(request))) {
687:                            autoUserLoginId = cookies[i].getValue();
688:                            break;
689:                        }
690:                    }
691:                }
692:                return autoUserLoginId;
693:            }
694:
695:            public static String autoLoginCheck(HttpServletRequest request,
696:                    HttpServletResponse response) {
697:                GenericDelegator delegator = (GenericDelegator) request
698:                        .getAttribute("delegator");
699:                HttpSession session = request.getSession();
700:
701:                return autoLoginCheck(delegator, session,
702:                        getAutoUserLoginId(request));
703:            }
704:
705:            private static String autoLoginCheck(GenericDelegator delegator,
706:                    HttpSession session, String autoUserLoginId) {
707:                if (autoUserLoginId != null) {
708:                    Debug.logInfo("Running autoLogin check.", module);
709:                    try {
710:                        GenericValue autoUserLogin = delegator
711:                                .findByPrimaryKey("UserLogin", UtilMisc.toMap(
712:                                        "userLoginId", autoUserLoginId));
713:                        GenericValue person = null;
714:                        GenericValue group = null;
715:                        if (autoUserLogin != null) {
716:                            person = delegator.findByPrimaryKey("Person",
717:                                    UtilMisc.toMap("partyId", autoUserLogin
718:                                            .getString("partyId")));
719:                            group = delegator.findByPrimaryKey("PartyGroup",
720:                                    UtilMisc.toMap("partyId", autoUserLogin
721:                                            .getString("partyId")));
722:                            session
723:                                    .setAttribute("autoUserLogin",
724:                                            autoUserLogin);
725:                        }
726:                        if (person != null) {
727:                            session.setAttribute("autoName", person
728:                                    .getString("firstName")
729:                                    + " " + person.getString("lastName"));
730:                        } else if (group != null) {
731:                            session.setAttribute("autoName", group
732:                                    .getString("groupName"));
733:                        }
734:                    } catch (GenericEntityException e) {
735:                        Debug.logError(e,
736:                                "Cannot get autoUserLogin information: "
737:                                        + e.getMessage(), module);
738:                    }
739:                }
740:                return "success";
741:            }
742:
743:            public static String autoLoginSet(HttpServletRequest request,
744:                    HttpServletResponse response) {
745:                GenericDelegator delegator = (GenericDelegator) request
746:                        .getAttribute("delegator");
747:                HttpSession session = request.getSession();
748:                GenericValue userLogin = (GenericValue) session
749:                        .getAttribute("userLogin");
750:                Cookie autoLoginCookie = new Cookie(
751:                        getAutoLoginCookieName(request), userLogin
752:                                .getString("userLoginId"));
753:                autoLoginCookie.setMaxAge(60 * 60 * 24 * 365);
754:                autoLoginCookie.setPath("/");
755:                response.addCookie(autoLoginCookie);
756:                return autoLoginCheck(delegator, session, userLogin
757:                        .getString("userLoginId"));
758:            }
759:
760:            public static String autoLoginRemove(HttpServletRequest request,
761:                    HttpServletResponse response) throws java.io.IOException {
762:                HttpSession session = request.getSession();
763:                GenericValue userLogin = (GenericValue) session
764:                        .getAttribute("autoUserLogin");
765:
766:                // remove the cookie
767:                if (userLogin != null) {
768:                    Cookie autoLoginCookie = new Cookie(
769:                            getAutoLoginCookieName(request), userLogin
770:                                    .getString("userLoginId"));
771:                    autoLoginCookie.setMaxAge(0);
772:                    autoLoginCookie.setPath("/");
773:                    response.addCookie(autoLoginCookie);
774:                }
775:                // remove the session attributes
776:                session.removeAttribute("autoUserLogin");
777:                session.removeAttribute("autoName");
778:                // logout the user if logged in.
779:                if (session.getAttribute("userLogin") != null) {
780:                    request.setAttribute("_AUTO_LOGIN_LOGOUT_", new Boolean(
781:                            true));
782:                    return logout(request, response);
783:                }
784:                return "success";
785:            }
786:
787:            /**
788:             * Gets (and creates if necessary) a key to be used for an external login parameter
789:             */
790:            public static String getExternalLoginKey(HttpServletRequest request) {
791:                Debug.logInfo(
792:                        "Running getExternalLoginKey, externalLoginKeys.size="
793:                                + externalLoginKeys.size(), module);
794:                GenericValue userLogin = (GenericValue) request
795:                        .getAttribute("userLogin");
796:
797:                String externalKey = (String) request
798:                        .getAttribute(EXTERNAL_LOGIN_KEY_ATTR);
799:                if (externalKey != null)
800:                    return externalKey;
801:
802:                HttpSession session = request.getSession();
803:                synchronized (session) {
804:                    // if the session has a previous key in place, remove it from the master list
805:                    String sesExtKey = (String) session
806:                            .getAttribute(EXTERNAL_LOGIN_KEY_ATTR);
807:                    if (sesExtKey != null) {
808:                        externalLoginKeys.remove(sesExtKey);
809:                    }
810:
811:                    //check the userLogin here, after the old session setting is set so that it will always be cleared
812:                    if (userLogin == null)
813:                        return "";
814:
815:                    //no key made yet for this request, create one
816:                    while (externalKey == null
817:                            || externalLoginKeys.containsKey(externalKey)) {
818:                        externalKey = "EL"
819:                                + Long.toString(Math
820:                                        .round(Math.random() * 1000000))
821:                                + Long.toString(Math
822:                                        .round(Math.random() * 1000000));
823:                    }
824:
825:                    request.setAttribute(EXTERNAL_LOGIN_KEY_ATTR, externalKey);
826:                    session.setAttribute(EXTERNAL_LOGIN_KEY_ATTR, externalKey);
827:                    externalLoginKeys.put(externalKey, userLogin);
828:                    return externalKey;
829:                }
830:            }
831:
832:            public static String checkExternalLoginKey(
833:                    HttpServletRequest request, HttpServletResponse response) {
834:                HttpSession session = request.getSession();
835:
836:                String externalKey = request
837:                        .getParameter(EXTERNAL_LOGIN_KEY_ATTR);
838:                if (externalKey == null)
839:                    return "success";
840:
841:                GenericValue userLogin = (GenericValue) externalLoginKeys
842:                        .get(externalKey);
843:                if (userLogin != null) {
844:                    // found userLogin, do the external login...
845:
846:                    // if the user is already logged in and the login is different, logout the other user
847:                    GenericValue currentUserLogin = (GenericValue) session
848:                            .getAttribute("userLogin");
849:                    if (currentUserLogin != null) {
850:                        if (currentUserLogin.getString("userLoginId").equals(
851:                                userLogin.getString("userLoginId"))) {
852:                            // is the same user, just carry on...
853:                            return "success";
854:                        }
855:
856:                        // logout the current user and login the new user...
857:                        String logoutRetVal = logout(request, response);
858:                        // ignore the return value; even if the operation failed we want to set the new UserLogin
859:                    }
860:
861:                    if ("true".equalsIgnoreCase(UtilProperties
862:                            .getPropertyValue("security.properties",
863:                                    "login.lock.active"))) {
864:                        String username = userLogin.getString("userLoginId");
865:                        boolean userIdLoggedIn = isLoggedInSession(username,
866:                                request, false);
867:                        boolean this UserLoggedIn = isLoggedInSession(username,
868:                                request, true);
869:                        if (userIdLoggedIn && !this UserLoggedIn) {
870:                            request
871:                                    .setAttribute("_ERROR_MESSAGE_",
872:                                            "<b>This user is already logged in.</b><br>");
873:                            return "error";
874:                        }
875:                    }
876:
877:                    doBasicLogin(userLogin, request);
878:                } else {
879:                    Debug.logWarning(
880:                            "Could not find userLogin for external login key: "
881:                                    + externalKey, module);
882:                }
883:
884:                return "success";
885:            }
886:
887:            public static void cleanupExternalLoginKey(HttpSession session) {
888:                String sesExtKey = (String) session
889:                        .getAttribute(EXTERNAL_LOGIN_KEY_ATTR);
890:                if (sesExtKey != null) {
891:                    externalLoginKeys.remove(sesExtKey);
892:                }
893:            }
894:
895:            public static boolean isLoggedInSession(GenericValue userLogin,
896:                    HttpServletRequest request) {
897:                return isLoggedInSession(userLogin.getString("userLoginId"),
898:                        request, true);
899:            }
900:
901:            public static boolean isLoggedInSession(String userLoginId,
902:                    HttpServletRequest request, boolean checkSessionId) {
903:                if (userLoginId != null) {
904:                    Map webappMap = (Map) loggedInSessions.get(userLoginId);
905:                    if (webappMap == null) {
906:                        return false;
907:                    } else {
908:                        String sessionId = (String) webappMap.get(UtilHttp
909:                                .getApplicationName(request));
910:                        if (!checkSessionId) {
911:                            if (sessionId == null) {
912:                                return false;
913:                            }
914:                        } else {
915:                            if (sessionId == null
916:                                    || !sessionId.equals(request.getSession()
917:                                            .getId())) {
918:                                return false;
919:                            }
920:                        }
921:                    }
922:                    return true;
923:                } else {
924:                    return false;
925:                }
926:            }
927:
928:            public static void loginToSession(GenericValue userLogin,
929:                    HttpServletRequest request) {
930:                if (userLogin != null) {
931:                    Map webappMap = (Map) loggedInSessions.get(userLogin
932:                            .get("userLoginId"));
933:                    if (webappMap == null) {
934:                        webappMap = new HashMap();
935:                        loggedInSessions.put(userLogin.get("userLoginId"),
936:                                webappMap);
937:                    }
938:
939:                    String webappName = UtilHttp.getApplicationName(request);
940:                    webappMap.put(webappName, request.getSession().getId());
941:                }
942:            }
943:
944:            public static void logoutFromAllSessions(GenericValue userLogin) {
945:                if (userLogin != null) {
946:                    loggedInSessions.remove(userLogin.get("userLoginId"));
947:                }
948:            }
949:
950:            protected static boolean hasBasePermission(GenericValue userLogin,
951:                    HttpServletRequest request) {
952:                ServletContext context = (ServletContext) request
953:                        .getAttribute("servletContext");
954:                Security security = (Security) request.getAttribute("security");
955:                HttpSession session = request.getSession();
956:
957:                String serverId = (String) context.getAttribute("_serverId");
958:                String contextPath = request.getContextPath();
959:
960:                ComponentConfig.WebappInfo info = ComponentConfig
961:                        .getWebAppInfo(serverId, contextPath);
962:                if (security != null) {
963:                    if (info != null) {
964:                        String permission = info.getBasePermission();
965:                        if (!"NONE".equals(permission)
966:                                && !security.hasEntityPermission(permission,
967:                                        "_VIEW", userLogin)) {
968:                            return false;
969:                        }
970:                    } else {
971:                        Debug.logInfo("No webapp configuration found for : "
972:                                + serverId + " / " + contextPath, module);
973:                    }
974:                } else {
975:                    Debug
976:                            .logWarning(
977:                                    "Received a null Security object from HttpServletRequest",
978:                                    module);
979:                }
980:
981:                return true;
982:
983:            }
984:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.