Advertisement
Guest User

Untitled

a guest
Feb 4th, 2016
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 22.42 KB | None | 0 0
  1. table users:
  2. +----------+-------------+------+-----+---------+----------------+
  3. | Field | Type | Null | Key | Default | Extra |
  4. +----------+-------------+------+-----+---------+----------------+
  5. | userid | int(11) | NO | PRI | NULL | auto_increment |
  6. | username | varchar(45) | NO | UNI | NULL | |
  7. | password | varchar(32) | NO | | NULL | |
  8. | email | varchar(75) | NO | UNI | NULL | |
  9. +----------+-------------+------+-----+---------+----------------+
  10. table banbyip
  11. +--------+-------------+------+-----+---------+-------+
  12. | Field | Type | Null | Key | Default | Extra |
  13. +--------+-------------+------+-----+---------+-------+
  14. | ipAddr | varchar(45) | YES | | NULL | |
  15. +--------+-------------+------+-----+---------+-------+
  16. table banlist
  17. +--------+-------------+------+-----+---------+-------+
  18. | Field | Type | Null | Key | Default | Extra |
  19. +--------+-------------+------+-----+---------+-------+
  20. | ipAddr | varchar(45) | YES | | NULL | |
  21. +--------+-------------+------+-----+---------+-------+
  22. table loginattempts
  23. +----------+-------------+------+-----+---------+-------+
  24. | Field | Type | Null | Key | Default | Extra |
  25. +----------+-------------+------+-----+---------+-------+
  26. | ipaddr | varchar(45) | NO | | NULL | |
  27. | username | varchar(45) | NO | | NULL | |
  28. | count | int(11) | NO | | NULL | |
  29. +----------+-------------+------+-----+---------+-------+
  30.  
  31. <!-- jQuery library -->
  32. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
  33.  
  34. <!-- Latest compiled JavaScript -->
  35. <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
  36. <!-- End Bootstrap -->
  37. </head>
  38. <body>
  39. <nav class="navbar navbar-default" >
  40. <ul class="nav navbar-nav">
  41. <li class="active"><a href="index.html"> Home</a></li>
  42. <li><a href="login.jsp"> Login </a> </li>
  43. <li><a href="register.jsp"> Register </a> </li>
  44. </ul>
  45. </nav>
  46. </body>
  47. </html>
  48.  
  49. <%@page contentType="text/html" pageEncoding="UTF-8"%>
  50. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
  51. <!DOCTYPE html>
  52. <html>
  53. <head>
  54. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  55. <title>Login</title>
  56. <!-- Bootstrap -->
  57. <!-- Latest compiled and minified CSS -->
  58. <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
  59.  
  60. <!-- jQuery library -->
  61. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
  62.  
  63. <!-- Latest compiled JavaScript -->
  64. <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
  65. <!-- End Bootstrap -->
  66. </head>
  67. <body>
  68. <nav class="navbar navbar-default" >
  69. <ul class="nav navbar-nav">
  70. <li><a href="index.html"> Home</a></li>
  71. <li class="active"><a href="login.jsp"> Login </a> </li>
  72. <li><a href="register.jsp"> Register </a> </li>
  73. </ul>
  74. </nav>
  75. <form action="login" method="POST" role="form">
  76. <c:if test="${sessionScope.failed == 1}">
  77. <div class="form-group">
  78. <h3>Login failed</h3>
  79. </div>
  80. </c:if>
  81. <div class="form-group">
  82. <label for="username">Username:</label>
  83. <input type="text" class="form-control" id="username" name="username">
  84. </div>
  85. <div class="form-group">
  86. <label for="password">Password:</label>
  87. <input type="password" class="form-control" id="password" name="password">
  88. </div>
  89. <button type="submit" class="btn btn-default">Submit</button>
  90. </form>
  91. </body>
  92. </html>
  93.  
  94. <!-- jQuery library -->
  95. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
  96.  
  97. <!-- Latest compiled JavaScript -->
  98. <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
  99. <!-- End Bootstrap -->
  100. </head>
  101. <body>
  102. <nav class="navbar navbar-default" >
  103. <ul class="nav navbar-nav">
  104. <li><a href="index.html"> Home</a></li>
  105. <li><a href="login.jsp"> Login </a> </li>
  106. <li class="active"><a href="register.jsp"> Register </a> </li>
  107. </ul>
  108. </nav>
  109. <form action="register" method="POST" role="form">
  110. <div class="form-group">
  111. <c:if test="${sessionScope.Invalid_username == 1}">
  112. <h6> Invalid username </h6><br />
  113. <c:set var="Invalid_username" value="0" scope="session" />
  114. </c:if>
  115. <c:if test="${sessionScope.unameAlreadyRegistered == 1}">
  116. <h6> Username is already registered</h6><br />
  117. <c:set var="unameAlreadyRegistered" value="0" scope="session" />
  118. </c:if>
  119. <label for="username">Username:</label>
  120. <input type="text" class="form-control" id="username" name="username" placeholder="Username">
  121. </div>
  122. <div class="form-group">
  123. <c:if test="${sessionScope.mailAlreadyRegistered == 1}">
  124. <h6> E-mail is already registered</h6><br />
  125. <c:set var="mailAlreadyRegistered" value="0" scope="session" />
  126. </c:if>
  127. <c:if test="${sessionScope.Invalid_email == 1}">
  128. <h6> E-mail is invalid</h6><br />
  129. <c:set var="Invalid_email" value="0" scope="session" />
  130. </c:if>
  131. <label for="email">Email address:</label>
  132. <input type="email" class="form-control" id="email" name="email" placeholder="Email">
  133. </div>
  134. <div class="form-group">
  135. <c:if test="${sessionScope.Invalid_password == 1}">
  136. <h6> Password is invalid</h6><br />
  137. <c:set var="Invalid_password" value="0" scope="session" />
  138. </c:if>
  139. <c:if test="${sessionScope.passwordsDontMatch == 1}">
  140. <h6> Passwords don't match</h6><br />
  141. <c:set var="passwordsDontMatch" value="0" scope="session" />
  142. </c:if>
  143. <label for="password">Password:</label>
  144. <input type="password" class="form-control" id="password" name="password" placeholder="Password" >
  145. </div>
  146. <div class="form-group">
  147. <label for="passwordRepeat">Repeat password:</label>
  148. <input type="password" class="form-control" id="passwordRepeat" name="passwordRepeat" placeholder="Repeat password">
  149. </div>
  150. <button type="submit" class="btn btn-default">Submit</button>
  151. </form>
  152. </body>
  153. </html>
  154.  
  155. <!DOCTYPE html>
  156. <%@ page contentType="text/html;charset=windows-1251"%>
  157. <html>
  158. <head>
  159. <meta http-equiv="Content-Type" content="text/html; charset=windows-1251"/>
  160. <title>banned</title>
  161. </head>
  162. <body>
  163. You are banned
  164. </body>
  165. </html>
  166.  
  167. package loginsystem;
  168. import java.sql.Connection;
  169. import java.sql.DriverManager;
  170. import java.sql.PreparedStatement;
  171. import java.sql.ResultSet;
  172. import java.sql.SQLException;
  173.  
  174. public class DataBase {
  175.  
  176. private final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
  177. private final String DB_URL = "jdbc:mysql://localhost/loginsystem";
  178. private final String username = "root";
  179. private final String password = "123456";
  180.  
  181. private Connection connection;
  182. private PreparedStatement statement;
  183.  
  184. public DataBase() {
  185. try {
  186. Class.forName("com.mysql.jdbc.Driver");
  187. connection = DriverManager.getConnection(DB_URL, username, password);
  188. } catch (ClassNotFoundException e) {
  189. System.out.println("An exception occured: " + e.toString());
  190. } catch (SQLException e) {
  191. System.out.println("An exception occured: " + e.toString());
  192. }
  193. }
  194.  
  195. public Object[] createParams(Object... args) {
  196. Object params[] = new Object[args.length];
  197. for (int i = 0; i < args.length; i++) {
  198. params[i] = args[i];
  199. }
  200. return params;
  201. }
  202.  
  203. public ResultSet runSQL(String sql, Object[] params, boolean isUpdate) {
  204. if (!validateSQL(sql, params)) {
  205. return null;
  206. }
  207. try {
  208. statement = connection.prepareStatement(sql);
  209. for (int i = 0; i < params.length; i++) {
  210. int j = i + 1;
  211. statement.setObject(j, params[i]);
  212. }
  213. if (isUpdate) {
  214. statement.executeUpdate();
  215. return null;
  216. } else {
  217. return statement.executeQuery();
  218. }
  219. } catch (SQLException e) {
  220. System.out.println(e.toString());
  221. return null;
  222. }
  223. }
  224.  
  225. public int getUserId(String username) {
  226. String sql = "SELECT user_id FROM users WHERE username = ?;";
  227. int id;
  228. try {
  229. PreparedStatement ps = connection.prepareStatement(sql);
  230. ps.setString(1, username);
  231. ResultSet rs = ps.executeQuery();
  232. rs.next();
  233. id = rs.getInt("user_id");
  234. } catch (SQLException e) {
  235. System.out.print(e.toString());
  236. id = -1;
  237. }
  238. return id;
  239. }
  240.  
  241. private boolean validateSQL(String sql, Object[] params) {
  242. int objectsCount = params.length;
  243. int questionMarks = 0;
  244. for (int i = 0; i < sql.length(); i++) {
  245. if (sql.charAt(i) == '?') {
  246. questionMarks++;
  247. }
  248. }
  249. return objectsCount == questionMarks;
  250. }
  251.  
  252. }
  253.  
  254. package loginsystem;
  255.  
  256.  
  257. import java.sql.ResultSet;
  258. import java.sql.SQLException;
  259.  
  260. public class Logger {
  261.  
  262. private final String checkIfRecordExists = "SELECT ipaddr FROM loginattempts WHERE ipaddr = ?;";
  263. private final String clearRecord = "UPDATE loginattempts SET count = 0 WHERE ipaddr = ?;";
  264. private final String incrementRecord = "UPDATE loginattempts SET count = count + 1 WHERE ipaddr = ?";
  265. private final String addRecord = "INSERT INTO loginattempts(ipaddr, username, count) VALUES(?, ?, 0)";
  266. private final String getCountByUserName = "SELECT count FROM loginattempts WHERE username = ?";
  267. private final String getCountByIp = "SELECT count FROM loginattempts WHERE ipaddr = ?";
  268. private final String getCount = "SELECT count FROM loginattempts WHERE ipaddr = ? AND username = ?";
  269. private final DataBase db = new DataBase();
  270. public Logger() {
  271.  
  272. }
  273.  
  274. public boolean checkIfRecordExists(String IP) {
  275. boolean retVal = false;
  276. ResultSet rs;
  277. try {
  278. rs = db.runSQL(checkIfRecordExists, db.createParams(IP), false);
  279. retVal = rs.isBeforeFirst();
  280. } catch (SQLException e) {
  281. System.out.println(e.toString());
  282. }
  283. return retVal;
  284. }
  285.  
  286. public void clearRecord(String IP) {
  287. if (!checkIfRecordExists(IP)) {
  288. return;
  289. }
  290. db.runSQL(clearRecord, db.createParams(IP), true);
  291. }
  292.  
  293. public void incrementRecord(String IP, String username) {
  294. if (!checkIfRecordExists(IP)) {
  295. addRecord(IP, username);
  296. } else {
  297. db.runSQL(incrementRecord, db.createParams(IP), true);
  298. }
  299. }
  300.  
  301. public int getCountByUserName(String username) {
  302. int count = 0;
  303. try {
  304. ResultSet rs = db.runSQL(getCountByUserName, db.createParams(username), false);
  305. while (rs.next()) {
  306. count += rs.getInt("count");
  307. }
  308. } catch (SQLException e) {
  309. System.out.println(e.toString());
  310. }
  311. return count;
  312. }
  313.  
  314. public int getCountByIp(String IP) {
  315. int count = 0;
  316. try {
  317. ResultSet rs = db.runSQL(getCountByIp, db.createParams(IP), false);
  318. rs.beforeFirst();
  319. while (rs.next()) {
  320. count += rs.getInt("count");
  321. }
  322. rs.close();
  323. } catch (SQLException e) {
  324. System.out.println(e.toString());
  325. }
  326.  
  327. return count;
  328. }
  329.  
  330. public int getCount(String IP, String username) {
  331. int count = 0;
  332. try {
  333. ResultSet rs = db.runSQL(getCount, db.createParams(IP, username), false);
  334. rs.beforeFirst();
  335. while (rs.next()) {
  336. count += rs.getInt("count");
  337. }
  338. rs.close();
  339. } catch (SQLException e) {
  340. System.out.println(e.toString());
  341. }
  342.  
  343. return count;
  344. }
  345.  
  346. private void addRecord(String IP, String username) {
  347. db.runSQL(addRecord, db.createParams(IP, username), true);
  348. }
  349. }
  350.  
  351. package loginsystem;
  352.  
  353. import java.security.MessageDigest;
  354. import java.security.NoSuchAlgorithmException;
  355.  
  356. public class HashingMethod
  357. {
  358. private MessageDigest md5;
  359.  
  360. public HashingMethod(){
  361. try{
  362. md5 = MessageDigest.getInstance("MD5");
  363. }
  364. catch(NoSuchAlgorithmException e){
  365. System.out.println(e.toString());
  366. }
  367. }
  368.  
  369. public String hashPassword(String password){
  370. md5.update(password.getBytes());
  371. byte[] digest = md5.digest();
  372. StringBuffer strBuff = new StringBuffer();
  373. for (byte b : digest) {
  374. strBuff.append(String.format("%02x", b & 0xff));
  375. }
  376. return strBuff.toString();
  377. }
  378. }
  379.  
  380. package loginsystem;
  381.  
  382. import java.sql.ResultSet;
  383. import java.sql.SQLException;
  384.  
  385. public class BAN {
  386. private String addBanUser = "INSERT INTO banlist VALUES(?)";
  387. private String removeBanUser = "DELETE FROM banlist WHERE userId = ?";
  388. private String isBannedUser = "SELECT * FROM banlist WHERE userId = ?";
  389. private String addBanIP = "INSERT INTO banbyip VALUES(?)";
  390. private String removeBanIP = "DELETE FROM banbyip WHERE ipAddr = ?";
  391. private String isBannedIP = "SELECT * FROM banbyip WHERE iAddr = ?";
  392. private DataBase db = new DataBase();
  393. public BAN(){
  394.  
  395. }
  396. public void addBan(String param, boolean isIP){
  397. if(isIP)
  398. db.runSQL(addBanIP, db.createParams(db.getUserId(param)), false);
  399. else
  400. db.runSQL(addBanUser, db.createParams(db.getUserId(param)), false);
  401. }
  402. public void removeBan(String param, boolean isIP){
  403. if(isIP)
  404. db.runSQL(removeBanIP, db.createParams(db.getUserId(param)), false);
  405. else
  406. db.runSQL(removeBanUser, db.createParams(db.getUserId(param)), false);
  407. }
  408. public boolean isBanned(String param, boolean isIP){
  409. try{
  410. ResultSet rs;
  411. if(isIP)
  412. rs = db.runSQL(isBannedIP, db.createParams(db.getUserId(param)), true);
  413. else
  414. rs = db.runSQL(isBannedUser, db.createParams(db.getUserId(param)), true);
  415. return rs.isBeforeFirst();
  416. }catch(SQLException e){
  417. System.out.println(e.toString());
  418. return false;
  419. }
  420. }
  421. }
  422.  
  423. package loginsystem;
  424.  
  425. import java.io.IOError;
  426. import java.io.IOException;
  427. import java.io.PrintWriter;
  428. import java.sql.ResultSet;
  429. import java.sql.SQLException;
  430. import javax.servlet.ServletException;
  431. import javax.servlet.annotation.WebServlet;
  432. import javax.servlet.http.HttpServlet;
  433. import javax.servlet.http.HttpServletRequest;
  434. import javax.servlet.http.HttpServletResponse;
  435. import javax.servlet.ServletConfig;
  436.  
  437. @WebServlet(name = "Login", urlPatterns = { "/login" })
  438. public class Login extends HttpServlet {
  439. private final int MAX_LEN_USERNAME = 30;
  440. private final int MAX_LEN_PASSWORD = 32;
  441. private final String validateLogin = "SELECT password FROM users WHERE username = ?";
  442. private Logger logger;
  443. private BAN ban;
  444. private DataBase db;
  445. private HashingMethod hasher;
  446. private static final String CONTENT_TYPE = "text/html; charset=windows-1251";
  447.  
  448. public void init(ServletConfig config) throws ServletException {
  449. super.init(config);
  450. db = new DataBase();
  451. ban = new BAN();
  452. logger = new Logger();
  453. hasher = new HashingMethod();
  454. }
  455. private void failedAttempt(HttpServletRequest request, HttpServletResponse response) throws IOException{
  456. String username = request.getParameter("username");
  457. String IP = request.getRemoteAddr();
  458. logger.incrementRecord(IP,username);
  459. request.getSession().setAttribute("failed", 1);
  460. if(logger.getCountByUserName(username) > 10)
  461. ban.addBan(username, false);
  462. if(logger.getCountByIp(IP) > 10)
  463. ban.addBan(IP,true);
  464. response.sendRedirect("login.jsp");
  465. }
  466. private boolean validateData(String username, String password){
  467. if(username.equals("") || password.equals(""))
  468. return false;
  469. if(username.length() > MAX_LEN_USERNAME || password.length() > MAX_LEN_PASSWORD)
  470. return false;
  471. return true;
  472. }
  473. private boolean validateLogin(String username, String password){
  474. ResultSet rs;
  475. String passwordFromDb = "";
  476. try{
  477. rs = db.runSQL(validateLogin, db.createParams(username), false);
  478. rs.next();
  479. passwordFromDb = rs.getString("password");
  480. }catch(SQLException e){
  481. System.out.println(e.toString());
  482. }
  483. return passwordFromDb.equals(hasher.hashPassword(password));
  484. }
  485. private void succesullAttempt(HttpServletRequest request, HttpServletResponse response) throws IOException{
  486. response.sendRedirect("http://9gag.com");
  487. }
  488. @Override
  489. protected void doPost(HttpServletRequest request, HttpServletResponse response)
  490. throws ServletException, IOException {
  491. String username = request.getParameter("username");
  492. String password = request.getParameter("password");
  493. if(validateData(username, password)){
  494. if(ban.isBanned(username, false) || ban.isBanned(request.getRemoteAddr(), true))
  495. response.sendRedirect("banned.jsp");
  496. if(validateLogin(username, password)){
  497. succesullAttempt(request, response);
  498. }
  499. else{
  500. failedAttempt(request, response);
  501. }
  502. }
  503. else
  504. failedAttempt(request, response);
  505. }
  506. }
  507.  
  508. package loginsystem;
  509.  
  510. import java.io.IOException;
  511.  
  512. import java.sql.ResultSet;
  513. import java.sql.SQLException;
  514.  
  515. import java.util.regex.Matcher;
  516. import java.util.regex.Pattern;
  517.  
  518. import javax.servlet.*;
  519. import javax.servlet.annotation.WebServlet;
  520. import javax.servlet.http.*;
  521.  
  522. @WebServlet(name = "Register", urlPatterns = { "register" })
  523. public class Register extends HttpServlet {
  524. private static final String CONTENT_TYPE = "text/html; charset=windows-1251";
  525. private final String checkIfUserExists = "SELECT username FROM users WHERE username = ?";
  526. private final String checkIfEmailExists = "SELECT username FROM users WHERE email = ?";
  527. private final String inserUser = "INSERT INTO users(username, password, email) VALUES(?, ? ,?)";
  528. private DataBase db = new DataBase();
  529. private HashingMethod hasher = new HashingMethod();
  530.  
  531. public void init(ServletConfig config) throws ServletException {
  532. super.init(config);
  533. }
  534.  
  535. private boolean validateEmail(String email) {
  536. String EMAIL_PATTERN =
  537. "^[_A-Za-z0-9-\+]+(\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\.[A-Za-z0-9]+)*(\.[A-Za-z]{2,})$";
  538. Pattern pattern;
  539. pattern = Pattern.compile(EMAIL_PATTERN);
  540. Matcher matcher;
  541. matcher = pattern.matcher(email);
  542. return !matcher.matches();
  543. }
  544.  
  545. private boolean checkIfUserExists(String username) {
  546. ResultSet rs;
  547. rs = db.runSQL(checkIfUserExists, db.createParams(username), false);
  548. try {
  549. return rs.isBeforeFirst();
  550. } catch (SQLException e) {
  551. System.out.println(e.toString());
  552. return true;
  553. }
  554. }
  555.  
  556. private boolean checkIfEmailExists(String email) {
  557. ResultSet rs = db.runSQL(checkIfEmailExists, db.createParams(email), false);
  558. try {
  559. return rs.isBeforeFirst();
  560. } catch (SQLException e) {
  561. System.out.println(e.toString());
  562. return true;
  563. }
  564. }
  565.  
  566. private boolean validateInput(String username, String password, String repeatPassword, String email,
  567. HttpSession session) {
  568. // username
  569. if (username.equals("") || username.length() > 42) {
  570. session.setAttribute("Invalid_username", 1);
  571. return false;
  572. }
  573. if (checkIfUserExists(username)) {
  574. session.setAttribute("unameAlreadyRegistered", 1);
  575. return false;
  576. }
  577. // password
  578. if (password.equals("")) {
  579. session.setAttribute("Invalid_password", 1);
  580. return false;
  581. }
  582. if (!password.equals(repeatPassword)) {
  583. session.setAttribute("passwordsDontMatch", 1);
  584. return false;
  585. }
  586. // email
  587. if (email.equals("") || validateEmail(email)) {
  588. session.setAttribute("Invalid_email", 1);
  589. return false;
  590. }
  591. if (checkIfEmailExists(email)) {
  592. session.setAttribute("mailAlreadyRegistered", 1);
  593. return false;
  594. }
  595. //else
  596. return true;
  597. }
  598.  
  599. public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  600. String username = (request.getParameter("username") != null) ? request.getParameter("username") : "";
  601. String password = (request.getParameter("password") != null) ? request.getParameter("password") : "";
  602. String passwordRepeat =
  603. (request.getParameter("passwordRepeat") != null) ? request.getParameter("passwordRepeat") : "";
  604. String email = (request.getParameter("email") != null) ? request.getParameter("email") : "";
  605. if (validateInput(username, password, passwordRepeat, email, request.getSession())) {
  606. String hashedPassword = hasher.hashPassword(password);
  607. db.runSQL(inserUser, db.createParams(username, hashedPassword, email), true);
  608. response.sendRedirect("login.jsp");
  609. } else {
  610. response.sendRedirect("register.jsp");
  611. }
  612. }
  613. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement