Advertisement
Guest User

Untitled

a guest
Jun 20th, 2016
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 15.23 KB | None | 0 0
  1. /*
  2. * Copyright (C) 2016 oskarmendel
  3. *
  4. * This program is free software; you can redistribute it and/or
  5. * modify it under the terms of the GNU General Public License
  6. * as published by the Free Software Foundation; either version 2
  7. * of the License, or (at your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program; if not, write to the Free Software
  16. * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
  17. */
  18. package tb.bmanager.main;
  19.  
  20. import java.io.Serializable;
  21. import javax.ejb.EJB;
  22. import javax.inject.Named;
  23. import javax.enterprise.context.RequestScoped;
  24. import javax.enterprise.context.SessionScoped;
  25. import javax.faces.application.FacesMessage;
  26. import javax.faces.context.FacesContext;
  27. import tb.bmanager.auth.AuthenticationActionBeanLocal;
  28. import tb.bmanager.entitymanager.UserEntityFacade;
  29. import tb.bmanager.util.validation.UserValidation;
  30.  
  31. /**
  32. * Controller for the login view.
  33. *
  34. * @author oskarmendel
  35. * @version 0.00.00
  36. * %name LoginManagedBean.java
  37. * %date 14:38:19 PM, Jun 18, 2016
  38. */
  39. @Named(value = "loginManagedBean")
  40. @SessionScoped
  41. public class LoginManagedBean implements Serializable{
  42.  
  43. @EJB
  44. private AuthenticationActionBeanLocal login;
  45.  
  46. @EJB
  47. private UserEntityFacade userFacade;
  48.  
  49. String username;
  50. String password;
  51.  
  52. private UserValidation userValidation;
  53.  
  54. /**
  55. * Creates a new instance of LoginManagedBean
  56. */
  57. public LoginManagedBean() {
  58. }
  59.  
  60. public void verifyLogin() {
  61. userValidation = UserValidation.getInstance();
  62.  
  63. //Check username is within length & if its taken or not
  64. if(!userValidation.validateUsername(username)) {
  65. String message = "Your specified username is too long or contains illegal characters.";
  66. FacesContext.getCurrentInstance().addMessage(null,
  67. new FacesMessage(FacesMessage.SEVERITY_WARN, message, null));
  68. }else if (userFacade.findByUsername(username) == null){
  69. String message = "User doesnt exists.";
  70. FacesContext.getCurrentInstance().addMessage(null,
  71. new FacesMessage(FacesMessage.SEVERITY_WARN, message, null));
  72. }
  73.  
  74. //Check if password is strong enough
  75. if(!userValidation.validatePassword(password)) {
  76. String message = "Your password needs to be longer than 4 characters.";
  77. FacesContext.getCurrentInstance().addMessage(null,
  78. new FacesMessage(FacesMessage.SEVERITY_WARN, message, null));
  79. }
  80.  
  81. login.preformAuthentication(username, password);
  82. }
  83.  
  84. /**
  85. *
  86. * @param username - the username of the user.
  87. */
  88. public void setUsername(String username) {
  89. this.username = username;
  90. }
  91.  
  92. /**
  93. *
  94. * @return the username of the user.
  95. */
  96. public String getUsername(){
  97. return this.username;
  98. }
  99.  
  100. /**
  101. *
  102. * @return the password of the user.
  103. */
  104. public String getPassword() {
  105. return password;
  106. }
  107.  
  108. /**
  109. *
  110. * @param password - the password for the user.
  111. */
  112. public void setPassword(String password) {
  113. this.password = password;
  114. }
  115. }
  116.  
  117. /*
  118. * Copyright (C) 2016 oskarmendel
  119. *
  120. * This program is free software; you can redistribute it and/or
  121. * modify it under the terms of the GNU General Public License
  122. * as published by the Free Software Foundation; either version 2
  123. * of the License, or (at your option) any later version.
  124. *
  125. * This program is distributed in the hope that it will be useful,
  126. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  127. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  128. * GNU General Public License for more details.
  129. *
  130. * You should have received a copy of the GNU General Public License
  131. * along with this program; if not, write to the Free Software
  132. * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
  133. */
  134. package tb.bmanager.auth;
  135.  
  136. import javax.ejb.EJB;
  137. import javax.ejb.Stateless;
  138. import javax.faces.application.FacesMessage;
  139. import javax.faces.context.FacesContext;
  140. import tb.bmanager.entity.UserEntity;
  141. import tb.bmanager.entitymanager.UserEntityFacade;
  142. import tb.bmanager.util.BCrypt;
  143.  
  144. /**
  145. * Preforms the authentication of users, creating a new session if success.
  146. *
  147. * @author oskarmendel
  148. * @version 0.00.00
  149. * %name AuthenticationActionBean.java
  150. * %date 17:23:53 PM, Jun 18, 2016
  151. */
  152. @Stateless
  153. public class AuthenticationActionBean implements AuthenticationActionBeanLocal {
  154.  
  155. @EJB
  156. private UserEntityFacade userFacade;
  157.  
  158. UserEntity user;
  159.  
  160. /**
  161. *
  162. * @param username
  163. * @param password
  164. */
  165. public void preformAuthentication(String username, String password) {
  166. FacesContext context = FacesContext.getCurrentInstance();
  167. System.out.println("Made it to perform Auth.");
  168.  
  169. user = userFacade.findByUsername(username);
  170.  
  171. if (user == null) {
  172. return;
  173. }
  174.  
  175. if (user.getUsername().equals(username)) {
  176. System.out.println("Username matches");
  177. if(BCrypt.checkpw(password, user.getPassword())) {
  178. context.getExternalContext().getSessionMap().put("USER", user);
  179. System.out.println("Password matches");
  180. } else {
  181. String message = "The user / password combination is wrong.";
  182. FacesContext.getCurrentInstance().addMessage(null,
  183. new FacesMessage(FacesMessage.SEVERITY_ERROR, message, null));
  184. }
  185. }
  186. }
  187. }
  188.  
  189. /*
  190. * Copyright (C) 2016 oskarmendel
  191. *
  192. * This program is free software; you can redistribute it and/or
  193. * modify it under the terms of the GNU General Public License
  194. * as published by the Free Software Foundation; either version 2
  195. * of the License, or (at your option) any later version.
  196. *
  197. * This program is distributed in the hope that it will be useful,
  198. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  199. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  200. * GNU General Public License for more details.
  201. *
  202. * You should have received a copy of the GNU General Public License
  203. * along with this program; if not, write to the Free Software
  204. * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
  205. */
  206. package tb.bmanager.auth.filter;
  207.  
  208. import java.io.IOException;
  209. import java.io.PrintStream;
  210. import java.io.PrintWriter;
  211. import java.io.StringWriter;
  212. import javax.faces.application.ResourceHandler;
  213. import javax.servlet.Filter;
  214. import javax.servlet.FilterChain;
  215. import javax.servlet.FilterConfig;
  216. import javax.servlet.ServletException;
  217. import javax.servlet.ServletRequest;
  218. import javax.servlet.ServletResponse;
  219. import javax.servlet.annotation.WebFilter;
  220. import javax.servlet.http.HttpServletRequest;
  221. import javax.servlet.http.HttpServletResponse;
  222. import javax.servlet.http.HttpSession;
  223.  
  224. /**
  225. *
  226. * @author oskarmendel
  227. */
  228. @WebFilter("/b/*")
  229. public class UserSessionFilter implements Filter {
  230.  
  231. private static final boolean debug = true;
  232.  
  233. // The filter configuration object we are associated with. If
  234. // this value is null, this filter instance is not currently
  235. // configured.
  236. private FilterConfig filterConfig = null;
  237.  
  238. private static final String AJAX_REDIRECT_XML = "<?xml version="1.0" encoding="UTF-8"?>"
  239. + "<partial-response><redirect url="%s"></redirect></partial-response>";
  240.  
  241.  
  242. public UserSessionFilter() {
  243. }
  244.  
  245. private void doBeforeProcessing(ServletRequest request, ServletResponse response)
  246. throws IOException, ServletException {
  247. if (debug) {
  248. log("UserSessionFilter:DoBeforeProcessing");
  249. }
  250.  
  251. // Write code here to process the request and/or response before
  252. // the rest of the filter chain is invoked.
  253. // For example, a logging filter might log items on the request object,
  254. // such as the parameters.
  255. /*
  256. for (Enumeration en = request.getParameterNames(); en.hasMoreElements(); ) {
  257. String name = (String)en.nextElement();
  258. String values[] = request.getParameterValues(name);
  259. int n = values.length;
  260. StringBuffer buf = new StringBuffer();
  261. buf.append(name);
  262. buf.append("=");
  263. for(int i=0; i < n; i++) {
  264. buf.append(values[i]);
  265. if (i < n-1)
  266. buf.append(",");
  267. }
  268. log(buf.toString());
  269. }
  270. */
  271. }
  272.  
  273. private void doAfterProcessing(ServletRequest request, ServletResponse response)
  274. throws IOException, ServletException {
  275. if (debug) {
  276. log("UserSessionFilter:DoAfterProcessing");
  277. }
  278.  
  279. // Write code here to process the request and/or response after
  280. // the rest of the filter chain is invoked.
  281. // For example, a logging filter might log the attributes on the
  282. // request object after the request has been processed.
  283. /*
  284. for (Enumeration en = request.getAttributeNames(); en.hasMoreElements(); ) {
  285. String name = (String)en.nextElement();
  286. Object value = request.getAttribute(name);
  287. log("attribute: " + name + "=" + value.toString());
  288.  
  289. }
  290. */
  291. // For example, a filter might append something to the response.
  292. /*
  293. PrintWriter respOut = new PrintWriter(response.getWriter());
  294. respOut.println("<P><B>This has been appended by an intrusive filter.</B>");
  295. */
  296. }
  297.  
  298. /**
  299. *
  300. * @param request The servlet request we are processing
  301. * @param response The servlet response we are creating
  302. * @param chain The filter chain we are processing
  303. *
  304. * @exception IOException if an input/output error occurs
  305. * @exception ServletException if a servlet error occurs
  306. */
  307. public void doFilter(ServletRequest request, ServletResponse response,
  308. FilterChain chain)
  309. throws IOException, ServletException {
  310.  
  311. if (debug) {
  312. log("UserSessionFilter:doFilter()");
  313. }
  314.  
  315. doBeforeProcessing(request, response);
  316.  
  317. HttpServletRequest req = (HttpServletRequest) request;
  318. HttpServletResponse res = (HttpServletResponse) response;
  319. HttpSession session = req.getSession(false);
  320. String loginURL = req.getContextPath() + "/login.xhtml";
  321.  
  322. boolean loggedIn = (session != null) && (session.getAttribute("USER") != null);
  323. boolean loginRequest = req.getRequestURI().equals(loginURL);
  324. boolean resourceRequest = req.getRequestURI().startsWith(req.getContextPath() + ResourceHandler.RESOURCE_IDENTIFIER + "/");
  325. boolean ajaxRequest = "partial/ajax".equals(req.getHeader("Faces-Request"));
  326.  
  327.  
  328. Throwable problem = null;
  329. try {
  330. if (loggedIn || resourceRequest) {
  331. if(!resourceRequest) {
  332. res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
  333. res.setHeader("Pragma", "no-cache"); // HTTP 1.0.
  334. res.setDateHeader("Expires", 0); // Proxies.
  335. }
  336. chain.doFilter(req, res);
  337. }else if (ajaxRequest) {
  338. res.setContentType("text/xml");
  339. res.setCharacterEncoding("UTF-8");
  340. res.getWriter().printf(AJAX_REDIRECT_XML, loginURL); // So, return special XML response instructing JSF ajax to send a redirect.
  341. }else {
  342. res.sendRedirect(loginURL); // So, just perform standard synchronous redirect.
  343. }
  344. } catch (Throwable t) {
  345. // If an exception is thrown somewhere down the filter chain,
  346. // we still want to execute our after processing, and then
  347. // rethrow the problem after that.
  348. problem = t;
  349. t.printStackTrace();
  350. }
  351.  
  352. doAfterProcessing(request, response);
  353.  
  354. // If there was a problem, we want to rethrow it if it is
  355. // a known type, otherwise log it.
  356. if (problem != null) {
  357. if (problem instanceof ServletException) {
  358. throw (ServletException) problem;
  359. }
  360. if (problem instanceof IOException) {
  361. throw (IOException) problem;
  362. }
  363. sendProcessingError(problem, response);
  364. }
  365. }
  366.  
  367. /**
  368. * Return the filter configuration object for this filter.
  369. */
  370. public FilterConfig getFilterConfig() {
  371. return (this.filterConfig);
  372. }
  373.  
  374. /**
  375. * Set the filter configuration object for this filter.
  376. *
  377. * @param filterConfig The filter configuration object
  378. */
  379. public void setFilterConfig(FilterConfig filterConfig) {
  380. this.filterConfig = filterConfig;
  381. }
  382.  
  383. /**
  384. * Destroy method for this filter
  385. */
  386. public void destroy() {
  387. }
  388.  
  389. /**
  390. * Init method for this filter
  391. */
  392. public void init(FilterConfig filterConfig) {
  393. this.filterConfig = filterConfig;
  394. if (filterConfig != null) {
  395. if (debug) {
  396. log("UserSessionFilter:Initializing filter");
  397. }
  398. }
  399. }
  400.  
  401. /**
  402. * Return a String representation of this object.
  403. */
  404. @Override
  405. public String toString() {
  406. if (filterConfig == null) {
  407. return ("UserSessionFilter()");
  408. }
  409. StringBuffer sb = new StringBuffer("UserSessionFilter(");
  410. sb.append(filterConfig);
  411. sb.append(")");
  412. return (sb.toString());
  413. }
  414.  
  415. private void sendProcessingError(Throwable t, ServletResponse response) {
  416. String stackTrace = getStackTrace(t);
  417.  
  418. if (stackTrace != null && !stackTrace.equals("")) {
  419. try {
  420. response.setContentType("text/html");
  421. PrintStream ps = new PrintStream(response.getOutputStream());
  422. PrintWriter pw = new PrintWriter(ps);
  423. pw.print("<html>n<head>n<title>Error</title>n</head>n<body>n"); //NOI18N
  424.  
  425. // PENDING! Localize this for next official release
  426. pw.print("<h1>The resource did not process correctly</h1>n<pre>n");
  427. pw.print(stackTrace);
  428. pw.print("</pre></body>n</html>"); //NOI18N
  429. pw.close();
  430. ps.close();
  431. response.getOutputStream().close();
  432. } catch (Exception ex) {
  433. }
  434. } else {
  435. try {
  436. PrintStream ps = new PrintStream(response.getOutputStream());
  437. t.printStackTrace(ps);
  438. ps.close();
  439. response.getOutputStream().close();
  440. } catch (Exception ex) {
  441. }
  442. }
  443. }
  444.  
  445. public static String getStackTrace(Throwable t) {
  446. String stackTrace = null;
  447. try {
  448. StringWriter sw = new StringWriter();
  449. PrintWriter pw = new PrintWriter(sw);
  450. t.printStackTrace(pw);
  451. pw.close();
  452. sw.close();
  453. stackTrace = sw.getBuffer().toString();
  454. } catch (Exception ex) {
  455. }
  456. return stackTrace;
  457. }
  458.  
  459. public void log(String msg) {
  460. filterConfig.getServletContext().log(msg);
  461. }
  462.  
  463. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement