Source Code Cross Referenced for UserAction.java in  » Forum » JForum-2.1.8 » net » jforum » view » forum » 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 » Forum » JForum 2.1.8 » net.jforum.view.forum 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


001:        /*
002:         * Copyright (c) JForum Team
003:         * All rights reserved.
004:         * 
005:         * Redistribution and use in source and binary forms, 
006:         * with or without modification, are permitted provided 
007:         * that the following conditions are met:
008:         * 
009:         * 1) Redistributions of source code must retain the above 
010:         * copyright notice, this list of conditions and the 
011:         * following  disclaimer.
012:         * 2)  Redistributions in binary form must reproduce the 
013:         * above copyright notice, this list of conditions and 
014:         * the following disclaimer in the documentation and/or 
015:         * other materials provided with the distribution.
016:         * 3) Neither the name of "Rafael Steil" nor 
017:         * the names of its contributors may be used to endorse 
018:         * or promote products derived from this software without 
019:         * specific prior written permission.
020:         * 
021:         * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 
022:         * HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
023:         * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, 
024:         * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
025:         * MERCHANTABILITY AND FITNESS FOR A PARTICULAR 
026:         * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL 
027:         * THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE 
028:         * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 
029:         * EXEMPLARY, OR CONSEQUENTIAL DAMAGES 
030:         * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
031:         * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
032:         * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 
033:         * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER 
034:         * IN CONTRACT, STRICT LIABILITY, OR TORT 
035:         * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 
036:         * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF 
037:         * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE
038:         * 
039:         * This file creation date: May 12, 2003 / 8:31:25 PM
040:         * The JForum Project
041:         * http://www.jforum.net
042:         */
043:        package net.jforum.view.forum;
044:
045:        import java.io.BufferedReader;
046:        import java.io.File;
047:        import java.io.FileNotFoundException;
048:        import java.io.FileReader;
049:        import java.io.IOException;
050:        import java.util.Date;
051:        import java.util.HashMap;
052:        import java.util.Iterator;
053:        import java.util.List;
054:
055:        import net.jforum.Command;
056:        import net.jforum.ControllerUtils;
057:        import net.jforum.JForumExecutionContext;
058:        import net.jforum.SessionFacade;
059:        import net.jforum.context.RequestContext;
060:        import net.jforum.dao.DataAccessDriver;
061:        import net.jforum.dao.UserDAO;
062:        import net.jforum.dao.UserSessionDAO;
063:        import net.jforum.entities.Bookmark;
064:        import net.jforum.entities.User;
065:        import net.jforum.entities.UserSession;
066:        import net.jforum.exceptions.ForumException;
067:        import net.jforum.repository.ForumRepository;
068:        import net.jforum.repository.RankingRepository;
069:        import net.jforum.repository.SecurityRepository;
070:        import net.jforum.security.SecurityConstants;
071:        import net.jforum.util.I18n;
072:        import net.jforum.util.MD5;
073:        import net.jforum.util.concurrent.Executor;
074:        import net.jforum.util.mail.ActivationKeySpammer;
075:        import net.jforum.util.mail.EmailSenderTask;
076:        import net.jforum.util.mail.LostPasswordSpammer;
077:        import net.jforum.util.preferences.ConfigKeys;
078:        import net.jforum.util.preferences.SystemGlobals;
079:        import net.jforum.util.preferences.TemplateKeys;
080:        import net.jforum.view.forum.common.UserCommon;
081:        import net.jforum.view.forum.common.ViewCommon;
082:
083:        import org.apache.log4j.Logger;
084:
085:        /**
086:         * @author Rafael Steil
087:         * @version $Id: UserAction.java,v 1.94 2007/09/21 17:26:09 rafaelsteil Exp $
088:         */
089:        public class UserAction extends Command {
090:            private static final Logger logger = Logger
091:                    .getLogger(UserAction.class);
092:
093:            private boolean canEdit() {
094:                int tmpId = SessionFacade.getUserSession().getUserId();
095:                boolean canEdit = SessionFacade.isLogged()
096:                        && tmpId == this .request.getIntParameter("user_id");
097:
098:                if (!canEdit) {
099:                    this .profile();
100:                }
101:
102:                return canEdit;
103:            }
104:
105:            public void edit() {
106:                if (this .canEdit()) {
107:                    int userId = this .request.getIntParameter("user_id");
108:                    UserDAO um = DataAccessDriver.getInstance().newUserDAO();
109:                    User u = um.selectById(userId);
110:
111:                    this .context.put("u", u);
112:                    this .context.put("action", "editSave");
113:                    this .context.put("pageTitle", I18n
114:                            .getMessage("UserProfile.profileFor")
115:                            + " " + u.getUsername());
116:                    this .context
117:                            .put(
118:                                    "avatarAllowExternalUrl",
119:                                    SystemGlobals
120:                                            .getBoolValue(ConfigKeys.AVATAR_ALLOW_EXTERNAL_URL));
121:                    this .setTemplateName(TemplateKeys.USER_EDIT);
122:                }
123:            }
124:
125:            public void editDone() {
126:                this .context.put("editDone", true);
127:                this .edit();
128:            }
129:
130:            public void editSave() {
131:                if (this .canEdit()) {
132:                    int userId = this .request.getIntParameter("user_id");
133:                    List warns = UserCommon.saveUser(userId);
134:
135:                    if (warns.size() > 0) {
136:                        this .context.put("warns", warns);
137:                        this .edit();
138:                    } else {
139:                        JForumExecutionContext
140:                                .setRedirect(this .request.getContextPath()
141:                                        + "/user/editDone/"
142:                                        + userId
143:                                        + SystemGlobals
144:                                                .getValue(ConfigKeys.SERVLET_EXTENSION));
145:                    }
146:                }
147:            }
148:
149:            private void registrationDisabled() {
150:                this .setTemplateName(TemplateKeys.USER_REGISTRATION_DISABLED);
151:                this .context.put("message", I18n
152:                        .getMessage("User.registrationDisabled"));
153:            }
154:
155:            private void insert(boolean hasErrors) {
156:                int userId = SessionFacade.getUserSession().getUserId();
157:
158:                if ((!SystemGlobals
159:                        .getBoolValue(ConfigKeys.REGISTRATION_ENABLED) && !SecurityRepository
160:                        .get(userId).canAccess(
161:                                SecurityConstants.PERM_ADMINISTRATION))
162:                        || ConfigKeys.TYPE_SSO.equals(SystemGlobals
163:                                .getValue(ConfigKeys.AUTHENTICATION_TYPE))) {
164:                    this .registrationDisabled();
165:                    return;
166:                }
167:
168:                if (!hasErrors
169:                        && SystemGlobals
170:                                .getBoolValue(ConfigKeys.AGREEMENT_SHOW)
171:                        && !this .agreementAccepted()) {
172:                    this .setTemplateName(TemplateKeys.AGREEMENT_LIST);
173:                    this .context.put("agreementContents", this 
174:                            .agreementContents());
175:                    return;
176:                }
177:
178:                this .setTemplateName(TemplateKeys.USER_INSERT);
179:                this .context.put("action", "insertSave");
180:                this .context.put("username", this .request
181:                        .getParameter("username"));
182:                this .context.put("email", this .request.getParameter("email"));
183:                this .context.put("pageTitle", I18n
184:                        .getMessage("ForumBase.register"));
185:
186:                if (SystemGlobals.getBoolValue(ConfigKeys.CAPTCHA_REGISTRATION)) {
187:                    // Create a new image captcha
188:                    SessionFacade.getUserSession().createNewCaptcha();
189:                    this .context.put("captcha_reg", true);
190:                }
191:
192:                SessionFacade.removeAttribute(ConfigKeys.AGREEMENT_ACCEPTED);
193:            }
194:
195:            public void insert() {
196:                this .insert(false);
197:            }
198:
199:            public void acceptAgreement() {
200:                SessionFacade.setAttribute(ConfigKeys.AGREEMENT_ACCEPTED, "1");
201:                JForumExecutionContext.setRedirect(this .request
202:                        .getContextPath()
203:                        + "/user/insert"
204:                        + SystemGlobals.getValue(ConfigKeys.SERVLET_EXTENSION));
205:            }
206:
207:            private String agreementContents() {
208:                StringBuffer contents = new StringBuffer();
209:
210:                BufferedReader reader = null;
211:                FileReader fileReader = null;
212:
213:                try {
214:                    String directory = new StringBuffer().append(
215:                            SystemGlobals.getApplicationPath()).append(
216:                            SystemGlobals
217:                                    .getValue(ConfigKeys.AGREEMENT_FILES_PATH))
218:                            .append('/').toString();
219:
220:                    String filename = "terms_"
221:                            + SystemGlobals.getValue(ConfigKeys.I18N_DEFAULT)
222:                            + ".txt";
223:
224:                    File file = new File(directory + filename);
225:
226:                    if (!file.exists()) {
227:                        filename = SystemGlobals
228:                                .getValue(ConfigKeys.AGREEMENT_DEFAULT_FILE);
229:                        file = new File(directory + filename);
230:
231:                        if (!file.exists()) {
232:                            throw new FileNotFoundException(
233:                                    "Could not locate any terms agreement file");
234:                        }
235:                    }
236:
237:                    fileReader = new FileReader(file);
238:                    reader = new BufferedReader(fileReader);
239:
240:                    char[] buffer = new char[2048];
241:                    int c = 0;
242:
243:                    while ((c = reader.read(buffer, 0, buffer.length)) > -1) {
244:                        contents.append(buffer, 0, c);
245:                    }
246:                } catch (Exception e) {
247:                    logger.warn("Failed to read agreement data: " + e, e);
248:                    contents = new StringBuffer(I18n
249:                            .getMessage("User.agreement.noAgreement"));
250:                } finally {
251:                    if (fileReader != null) {
252:                        try {
253:                            fileReader.close();
254:                        } catch (Exception e) {
255:                        }
256:                    }
257:                    if (reader != null) {
258:                        try {
259:                            reader.close();
260:                        } catch (Exception e) {
261:                        }
262:                    }
263:                }
264:
265:                return contents.toString();
266:            }
267:
268:            private boolean agreementAccepted() {
269:                return "1".equals(SessionFacade
270:                        .getAttribute(ConfigKeys.AGREEMENT_ACCEPTED));
271:            }
272:
273:            public void insertSave() {
274:                UserSession userSession = SessionFacade.getUserSession();
275:                int userId = userSession.getUserId();
276:
277:                if ((!SystemGlobals
278:                        .getBoolValue(ConfigKeys.REGISTRATION_ENABLED) && !SecurityRepository
279:                        .get(userId).canAccess(
280:                                SecurityConstants.PERM_ADMINISTRATION))
281:                        || ConfigKeys.TYPE_SSO.equals(SystemGlobals
282:                                .getValue(ConfigKeys.AUTHENTICATION_TYPE))) {
283:                    this .registrationDisabled();
284:                    return;
285:                }
286:
287:                User u = new User();
288:                UserDAO dao = DataAccessDriver.getInstance().newUserDAO();
289:
290:                String username = this .request.getParameter("username");
291:                String password = this .request.getParameter("password");
292:                String email = this .request.getParameter("email");
293:                String captchaResponse = this .request
294:                        .getParameter("captchaResponse");
295:
296:                boolean error = false;
297:                if (username == null || username.trim().equals("")
298:                        || password == null || password.trim().equals("")) {
299:                    this .context.put("error", I18n
300:                            .getMessage("UsernamePasswordCannotBeNull"));
301:                    error = true;
302:                }
303:
304:                if (username != null) {
305:                    username = username.trim();
306:                }
307:
308:                if (!error
309:                        && username.length() > SystemGlobals
310:                                .getIntValue(ConfigKeys.USERNAME_MAX_LENGTH)) {
311:                    this .context.put("error", I18n
312:                            .getMessage("User.usernameTooBig"));
313:                    error = true;
314:                }
315:
316:                if (!error && username.indexOf('<') > -1
317:                        || username.indexOf('>') > -1) {
318:                    this .context.put("error", I18n
319:                            .getMessage("User.usernameInvalidChars"));
320:                    error = true;
321:                }
322:
323:                if (!error && dao.isUsernameRegistered(username)) {
324:                    this .context
325:                            .put("error", I18n.getMessage("UsernameExists"));
326:                    error = true;
327:                }
328:
329:                if (!error && dao.findByEmail(email) != null) {
330:                    this .context.put("error", I18n.getMessage(
331:                            "User.emailExists", new String[] { email }));
332:                    error = true;
333:                }
334:
335:                if (!error
336:                        && !userSession
337:                                .validateCaptchaResponse(captchaResponse)) {
338:                    this .context.put("error", I18n
339:                            .getMessage("CaptchaResponseFails"));
340:                    error = true;
341:                }
342:
343:                if (error) {
344:                    this .insert(true);
345:                    return;
346:                }
347:
348:                u.setUsername(username);
349:                u.setPassword(MD5.crypt(password));
350:                u.setEmail(email);
351:
352:                boolean requiresMailActivation = SystemGlobals
353:                        .getBoolValue(ConfigKeys.MAIL_USER_EMAIL_AUTH);
354:
355:                if (requiresMailActivation) {
356:                    u.setActivationKey(MD5.crypt(username
357:                            + System.currentTimeMillis()));
358:                }
359:
360:                int newUserId = dao.addNew(u);
361:
362:                if (requiresMailActivation) {
363:                    Executor.execute(new EmailSenderTask(
364:                            new ActivationKeySpammer(u)));
365:
366:                    this 
367:                            .setTemplateName(TemplateKeys.USER_INSERT_ACTIVATE_MAIL);
368:                    this .context.put("message", I18n
369:                            .getMessage("User.GoActivateAccountMessage"));
370:                } else if (SecurityRepository.get(userId).canAccess(
371:                        SecurityConstants.PERM_ADMINISTRATION)) {
372:                    JForumExecutionContext.setRedirect(this .request
373:                            .getContextPath()
374:                            + "/adminUsers/list"
375:                            + SystemGlobals
376:                                    .getValue(ConfigKeys.SERVLET_EXTENSION));
377:                } else {
378:                    this .logNewRegisteredUserIn(newUserId, u);
379:                }
380:
381:                if (!requiresMailActivation) {
382:                    dao.writeUserActive(newUserId);
383:                }
384:            }
385:
386:            public void activateAccount() {
387:                String hash = this .request.getParameter("hash");
388:                int userId = (new Integer(this .request.getParameter("user_id")))
389:                        .intValue();
390:
391:                UserDAO um = DataAccessDriver.getInstance().newUserDAO();
392:                User u = um.selectById(userId);
393:
394:                boolean isValid = um.validateActivationKeyHash(userId, hash);
395:
396:                if (isValid) {
397:                    // Activate the account
398:                    um.writeUserActive(userId);
399:                    this .logNewRegisteredUserIn(userId, u);
400:                } else {
401:                    this .setTemplateName(TemplateKeys.USER_INVALID_ACTIVATION);
402:                    this .context
403:                            .put(
404:                                    "message",
405:                                    I18n
406:                                            .getMessage(
407:                                                    "User.invalidActivationKey",
408:                                                    new Object[] { this .request
409:                                                            .getContextPath()
410:                                                            + "/user/activateManual"
411:                                                            + SystemGlobals
412:                                                                    .getValue(ConfigKeys.SERVLET_EXTENSION) }));
413:                }
414:
415:            }
416:
417:            public void activateManual() {
418:                this .setTemplateName(TemplateKeys.ACTIVATE_ACCOUNT_MANUAL);
419:            }
420:
421:            private void logNewRegisteredUserIn(int userId, User u) {
422:                SessionFacade.makeLogged();
423:
424:                UserSession userSession = new UserSession();
425:                userSession.setAutoLogin(true);
426:                userSession.setUserId(userId);
427:                userSession.setUsername(u.getUsername());
428:                userSession.setLastVisit(new Date(System.currentTimeMillis()));
429:                userSession.setStartTime(new Date(System.currentTimeMillis()));
430:
431:                SessionFacade.add(userSession);
432:
433:                // Finalizing.. show to user the congrats page
434:                JForumExecutionContext.setRedirect(this .request
435:                        .getContextPath()
436:                        + "/user/registrationComplete"
437:                        + SystemGlobals.getValue(ConfigKeys.SERVLET_EXTENSION));
438:            }
439:
440:            public void registrationComplete() {
441:                int userId = SessionFacade.getUserSession().getUserId();
442:
443:                ForumRepository.setLastRegisteredUser(DataAccessDriver
444:                        .getInstance().newUserDAO().selectById(userId));
445:                ForumRepository.incrementTotalUsers();
446:
447:                String profilePage = JForumExecutionContext.getForumContext()
448:                        .encodeURL("/user/edit/" + userId);
449:                String homePage = JForumExecutionContext.getForumContext()
450:                        .encodeURL("/forums/list");
451:
452:                String message = I18n.getMessage(
453:                        "User.RegistrationCompleteMessage", new Object[] {
454:                                profilePage, homePage });
455:                this .context.put("message", message);
456:                this .setTemplateName(TemplateKeys.USER_REGISTRATION_COMPLETE);
457:            }
458:
459:            public void validateLogin() {
460:                String password;
461:                String username;
462:
463:                if (parseBasicAuthentication()) {
464:                    username = (String) this .request.getAttribute("username");
465:                    password = (String) this .request.getAttribute("password");
466:                } else {
467:                    username = this .request.getParameter("username");
468:                    password = this .request.getParameter("password");
469:                }
470:
471:                boolean validInfo = false;
472:
473:                if (password.length() > 0) {
474:                    User user = this .validateLogin(username, password);
475:
476:                    if (user != null) {
477:                        // Note: here we only want to set the redirect location if it hasn't already been
478:                        // set. This will give the LoginAuthenticator a chance to set the redirect location.
479:                        this .buildSucessfulLoginRedirect();
480:
481:                        SessionFacade.makeLogged();
482:
483:                        String sessionId = SessionFacade.isUserInSession(user
484:                                .getId());
485:                        UserSession userSession = new UserSession(SessionFacade
486:                                .getUserSession());
487:
488:                        // Remove the "guest" session
489:                        SessionFacade.remove(userSession.getSessionId());
490:
491:                        userSession.dataToUser(user);
492:
493:                        UserSession currentUs = SessionFacade
494:                                .getUserSession(sessionId);
495:
496:                        // Check if the user is returning to the system
497:                        // before its last session has expired ( hypothesis )
498:                        UserSession tmpUs;
499:                        if (sessionId != null && currentUs != null) {
500:                            // Write its old session data
501:                            SessionFacade.storeSessionData(sessionId,
502:                                    JForumExecutionContext.getConnection());
503:                            tmpUs = new UserSession(currentUs);
504:                            SessionFacade.remove(sessionId);
505:                        } else {
506:                            UserSessionDAO sm = DataAccessDriver.getInstance()
507:                                    .newUserSessionDAO();
508:                            tmpUs = sm.selectById(userSession,
509:                                    JForumExecutionContext.getConnection());
510:                        }
511:
512:                        I18n.load(user.getLang());
513:
514:                        // Autologin
515:                        if (this .request.getParameter("autologin") != null
516:                                && SystemGlobals
517:                                        .getBoolValue(ConfigKeys.AUTO_LOGIN_ENABLED)) {
518:                            userSession.setAutoLogin(true);
519:
520:                            // Generate the user-specific hash
521:                            String systemHash = MD5.crypt(SystemGlobals
522:                                    .getValue(ConfigKeys.USER_HASH_SEQUENCE)
523:                                    + user.getId());
524:                            String userHash = MD5.crypt(System
525:                                    .currentTimeMillis()
526:                                    + systemHash);
527:
528:                            // Persist the user hash
529:                            UserDAO dao = DataAccessDriver.getInstance()
530:                                    .newUserDAO();
531:                            dao.saveUserAuthHash(user.getId(), userHash);
532:
533:                            systemHash = MD5.crypt(userHash);
534:
535:                            ControllerUtils.addCookie(SystemGlobals
536:                                    .getValue(ConfigKeys.COOKIE_AUTO_LOGIN),
537:                                    "1");
538:                            ControllerUtils.addCookie(SystemGlobals
539:                                    .getValue(ConfigKeys.COOKIE_USER_HASH),
540:                                    systemHash);
541:                        } else {
542:                            // Remove cookies for safety
543:                            ControllerUtils.addCookie(SystemGlobals
544:                                    .getValue(ConfigKeys.COOKIE_USER_HASH),
545:                                    null);
546:                            ControllerUtils.addCookie(SystemGlobals
547:                                    .getValue(ConfigKeys.COOKIE_AUTO_LOGIN),
548:                                    null);
549:                        }
550:
551:                        if (tmpUs == null) {
552:                            userSession.setLastVisit(new Date(System
553:                                    .currentTimeMillis()));
554:                        } else {
555:                            // Update last visit and session start time
556:                            userSession.setLastVisit(new Date(tmpUs
557:                                    .getStartTime().getTime()
558:                                    + tmpUs.getSessionTime()));
559:                        }
560:
561:                        SessionFacade.add(userSession);
562:                        SessionFacade.setAttribute(ConfigKeys.TOPICS_READ_TIME,
563:                                new HashMap());
564:                        ControllerUtils.addCookie(SystemGlobals
565:                                .getValue(ConfigKeys.COOKIE_NAME_DATA), Integer
566:                                .toString(user.getId()));
567:
568:                        SecurityRepository.load(user.getId(), true);
569:                        validInfo = true;
570:                    }
571:                }
572:
573:                // Invalid login
574:                if (!validInfo) {
575:                    this .context.put("invalidLogin", "1");
576:                    this .setTemplateName(TemplateKeys.USER_VALIDATE_LOGIN);
577:
578:                    if (this .request.getParameter("returnPath") != null) {
579:                        this .context.put("returnPath", this .request
580:                                .getParameter("returnPath"));
581:                    }
582:                } else if (this .request.getParameter("returnPath") != null) {
583:                    JForumExecutionContext.setRedirect(this .request
584:                            .getParameter("returnPath"));
585:                }
586:            }
587:
588:            private void buildSucessfulLoginRedirect() {
589:                if (JForumExecutionContext.getRedirectTo() == null) {
590:                    String forwaredHost = request.getHeader("X-Forwarded-Host");
591:
592:                    if (forwaredHost == null
593:                            || SystemGlobals
594:                                    .getBoolValue(ConfigKeys.LOGIN_IGNORE_XFORWARDEDHOST)) {
595:                        JForumExecutionContext
596:                                .setRedirect(this .request.getContextPath()
597:                                        + "/forums/list"
598:                                        + SystemGlobals
599:                                                .getValue(ConfigKeys.SERVLET_EXTENSION));
600:                    } else {
601:                        JForumExecutionContext
602:                                .setRedirect(this .request.getScheme()
603:                                        + "://"
604:                                        + forwaredHost
605:                                        + this .request.getContextPath()
606:                                        + "/forums/list"
607:                                        + SystemGlobals
608:                                                .getValue(ConfigKeys.SERVLET_EXTENSION));
609:                    }
610:                }
611:            }
612:
613:            public void validateLogin(RequestContext request) {
614:                this .request = request;
615:                validateLogin();
616:            }
617:
618:            public static boolean hasBasicAuthentication(RequestContext request) {
619:                String auth = request.getHeader("Authorization");
620:                return (auth != null && auth.startsWith("Basic "));
621:            }
622:
623:            private boolean parseBasicAuthentication() {
624:                if (hasBasicAuthentication(request)) {
625:                    String auth = request.getHeader("Authorization");
626:                    String decoded;
627:
628:                    try {
629:                        decoded = new String(new sun.misc.BASE64Decoder()
630:                                .decodeBuffer(auth.substring(6)));
631:                    } catch (IOException e) {
632:                        throw new ForumException(e);
633:                    }
634:
635:                    int p = decoded.indexOf(':');
636:
637:                    if (p != -1) {
638:                        request.setAttribute("username", decoded
639:                                .substring(0, p));
640:                        request.setAttribute("password", decoded
641:                                .substring(p + 1));
642:                        return true;
643:                    }
644:                }
645:                return false;
646:            }
647:
648:            private User validateLogin(String name, String password) {
649:                UserDAO um = DataAccessDriver.getInstance().newUserDAO();
650:                return um.validateLogin(name, password);
651:            }
652:
653:            public void profile() {
654:                DataAccessDriver da = DataAccessDriver.getInstance();
655:                UserDAO udao = da.newUserDAO();
656:
657:                User u = udao.selectById(this .request
658:                        .getIntParameter("user_id"));
659:
660:                if (u.getId() == 0) {
661:                    this .userNotFound();
662:                } else {
663:                    this .setTemplateName(TemplateKeys.USER_PROFILE);
664:                    this .context.put("karmaEnabled", SecurityRepository
665:                            .canAccess(SecurityConstants.PERM_KARMA_ENABLED));
666:                    this .context.put("rank", new RankingRepository());
667:                    this .context.put("u", u);
668:                    this .context
669:                            .put(
670:                                    "avatarAllowExternalUrl",
671:                                    SystemGlobals
672:                                            .getBoolValue(ConfigKeys.AVATAR_ALLOW_EXTERNAL_URL));
673:
674:                    int loggedId = SessionFacade.getUserSession().getUserId();
675:                    int count = 0;
676:
677:                    List bookmarks = da.newBookmarkDAO()
678:                            .selectByUser(u.getId());
679:                    for (Iterator iter = bookmarks.iterator(); iter.hasNext();) {
680:                        Bookmark b = (Bookmark) iter.next();
681:
682:                        if (b.isPublicVisible() || loggedId == u.getId()) {
683:                            count++;
684:                        }
685:                    }
686:
687:                    this .context.put("pageTitle", I18n
688:                            .getMessage("UserProfile.allAbout")
689:                            + " " + u.getUsername());
690:                    this .context.put("nbookmarks", new Integer(count));
691:                    this .context.put("ntopics", new Integer(da.newTopicDAO()
692:                            .countUserTopics(u.getId())));
693:                    this .context.put("nposts", new Integer(da.newPostDAO()
694:                            .countUserPosts(u.getId())));
695:                }
696:            }
697:
698:            private void userNotFound() {
699:                this .context.put("message", I18n.getMessage("User.notFound"));
700:                this .setTemplateName(TemplateKeys.USER_NOT_FOUND);
701:            }
702:
703:            public void logout() {
704:                JForumExecutionContext.setRedirect(this .request
705:                        .getContextPath()
706:                        + "/forums/list"
707:                        + SystemGlobals.getValue(ConfigKeys.SERVLET_EXTENSION));
708:
709:                UserSession userSession = SessionFacade.getUserSession();
710:                SessionFacade.storeSessionData(userSession.getSessionId(),
711:                        JForumExecutionContext.getConnection());
712:
713:                SessionFacade.makeUnlogged();
714:                SessionFacade.remove(userSession.getSessionId());
715:
716:                // Disable auto login
717:                userSession.setAutoLogin(false);
718:                userSession.makeAnonymous();
719:
720:                SessionFacade.add(userSession);
721:            }
722:
723:            public void login() {
724:                if (ConfigKeys.TYPE_SSO.equals(SystemGlobals
725:                        .getValue(ConfigKeys.AUTHENTICATION_TYPE))) {
726:                    this .registrationDisabled();
727:                    return;
728:                }
729:
730:                if (this .request.getParameter("returnPath") != null) {
731:                    this .context.put("returnPath", this .request
732:                            .getParameter("returnPath"));
733:                } else if (!SystemGlobals
734:                        .getBoolValue(ConfigKeys.LOGIN_IGNORE_REFERER)) {
735:                    String referer = this .request.getHeader("Referer");
736:
737:                    if (referer != null) {
738:                        this .context.put("returnPath", referer);
739:                    }
740:                }
741:
742:                this .context.put("pageTitle", I18n
743:                        .getMessage("ForumBase.login"));
744:                this .setTemplateName(TemplateKeys.USER_LOGIN);
745:            }
746:
747:            // Lost password form
748:            public void lostPassword() {
749:                this .setTemplateName(TemplateKeys.USER_LOSTPASSWORD);
750:                this .context.put("pageTitle", I18n
751:                        .getMessage("PasswordRecovery.title"));
752:            }
753:
754:            public User prepareLostPassword(String username, String email) {
755:                User user = null;
756:                UserDAO um = DataAccessDriver.getInstance().newUserDAO();
757:
758:                if (email != null && !email.trim().equals("")) {
759:                    username = um.getUsernameByEmail(email);
760:                }
761:
762:                if (username != null && !username.trim().equals("")) {
763:                    List l = um.findByName(username, true);
764:                    if (l.size() > 0) {
765:                        user = (User) l.get(0);
766:                    }
767:                }
768:
769:                if (user == null) {
770:                    return null;
771:                }
772:
773:                String hash = MD5.crypt(user.getEmail()
774:                        + System.currentTimeMillis());
775:                um.writeLostPasswordHash(user.getEmail(), hash);
776:
777:                user.setActivationKey(hash);
778:
779:                return user;
780:            }
781:
782:            // Send lost password email
783:            public void lostPasswordSend() {
784:                String email = this .request.getParameter("email");
785:                String username = this .request.getParameter("username");
786:
787:                User user = this .prepareLostPassword(username, email);
788:                if (user == null) {
789:                    // user could not be found
790:                    this .context.put("message", I18n
791:                            .getMessage("PasswordRecovery.invalidUserEmail"));
792:                    this .lostPassword();
793:                    return;
794:                }
795:
796:                Executor
797:                        .execute(new EmailSenderTask(
798:                                new LostPasswordSpammer(
799:                                        user,
800:                                        SystemGlobals
801:                                                .getValue(ConfigKeys.MAIL_LOST_PASSWORD_SUBJECT))));
802:
803:                this .setTemplateName(TemplateKeys.USER_LOSTPASSWORD_SEND);
804:                this .context
805:                        .put(
806:                                "message",
807:                                I18n
808:                                        .getMessage(
809:                                                "PasswordRecovery.emailSent",
810:                                                new String[] { this .request
811:                                                        .getContextPath()
812:                                                        + "/user/login"
813:                                                        + SystemGlobals
814:                                                                .getValue(ConfigKeys.SERVLET_EXTENSION) }));
815:            }
816:
817:            // Recover user password ( aka, ask him a new one )
818:            public void recoverPassword() {
819:                String hash = this .request.getParameter("hash");
820:
821:                this .setTemplateName(TemplateKeys.USER_RECOVERPASSWORD);
822:                this .context.put("recoverHash", hash);
823:            }
824:
825:            public void recoverPasswordValidate() {
826:                String hash = this .request.getParameter("recoverHash");
827:                String email = this .request.getParameter("email");
828:
829:                String message;
830:                boolean isOk = DataAccessDriver.getInstance().newUserDAO()
831:                        .validateLostPasswordHash(email, hash);
832:
833:                if (isOk) {
834:                    String password = this .request.getParameter("newPassword");
835:                    DataAccessDriver.getInstance().newUserDAO()
836:                            .saveNewPassword(MD5.crypt(password), email);
837:
838:                    message = I18n
839:                            .getMessage(
840:                                    "PasswordRecovery.ok",
841:                                    new String[] { this .request
842:                                            .getContextPath()
843:                                            + "/user/login"
844:                                            + SystemGlobals
845:                                                    .getValue(ConfigKeys.SERVLET_EXTENSION) });
846:                } else {
847:                    message = I18n.getMessage("PasswordRecovery.invalidData");
848:                }
849:
850:                this 
851:                        .setTemplateName(TemplateKeys.USER_RECOVERPASSWORD_VALIDATE);
852:                this .context.put("message", message);
853:            }
854:
855:            public void list() {
856:                int start = this .preparePagination(DataAccessDriver
857:                        .getInstance().newUserDAO().getTotalUsers());
858:                int usersPerPage = SystemGlobals
859:                        .getIntValue(ConfigKeys.USERS_PER_PAGE);
860:
861:                List users = DataAccessDriver.getInstance().newUserDAO()
862:                        .selectAll(start, usersPerPage);
863:                this .context.put("users", users);
864:                this .context.put("pageTitle", I18n
865:                        .getMessage("ForumBase.usersList"));
866:                this .setTemplateName(TemplateKeys.USER_LIST);
867:            }
868:
869:            public void listGroup() {
870:                int groupId = this .request.getIntParameter("group_id");
871:
872:                int start = this .preparePagination(DataAccessDriver
873:                        .getInstance().newUserDAO().getTotalUsersByGroup(
874:                                groupId));
875:                int usersPerPage = SystemGlobals
876:                        .getIntValue(ConfigKeys.USERS_PER_PAGE);
877:
878:                List users = DataAccessDriver.getInstance().newUserDAO()
879:                        .selectAllByGroup(groupId, start, usersPerPage);
880:
881:                this .context.put("users", users);
882:                this .setTemplateName(TemplateKeys.USER_LIST);
883:            }
884:
885:            /**
886:             * @deprecated probably will be removed. Use KarmaAction to load Karma
887:             */
888:            public void searchKarma() {
889:                int start = this .preparePagination(DataAccessDriver
890:                        .getInstance().newUserDAO().getTotalUsers());
891:                int usersPerPage = SystemGlobals
892:                        .getIntValue(ConfigKeys.USERS_PER_PAGE);
893:
894:                //Load all users with your karma
895:                List users = DataAccessDriver.getInstance().newUserDAO()
896:                        .selectAllWithKarma(start, usersPerPage);
897:                this .context.put("users", users);
898:                this .setTemplateName(TemplateKeys.USER_SEARCH_KARMA);
899:            }
900:
901:            private int preparePagination(int totalUsers) {
902:                int start = ViewCommon.getStartPage();
903:                int usersPerPage = SystemGlobals
904:                        .getIntValue(ConfigKeys.USERS_PER_PAGE);
905:
906:                ViewCommon.contextToPagination(start, totalUsers, usersPerPage);
907:
908:                return start;
909:            }
910:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.