Commit 41c409da authored by michada's avatar michada

Added login capabilities.

Access to any resource except index.html can be restricted enabling the
LoginFilter in the web.xml configuration file. It is currently disabled.

Old index.html moved to main.html and replaced with an index.html that
contains a login form.
parent 7e143670
...@@ -45,6 +45,12 @@ ...@@ -45,6 +45,12 @@
<artifactId>mysql-connector-java</artifactId> <artifactId>mysql-connector-java</artifactId>
<version>5.1.28</version> <version>5.1.28</version>
</dependency> </dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.9</version>
</dependency>
</dependencies> </dependencies>
<build> <build>
......
package es.uvigo.esei.daa;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import es.uvigo.esei.daa.dao.DAOException;
import es.uvigo.esei.daa.dao.UsersDAO;
public class LoginFilter implements Filter {
@Override
public void doFilter(
ServletRequest request,
ServletResponse response,
FilterChain chain
) throws IOException, ServletException {
final HttpServletRequest httpRequest = (HttpServletRequest) request;
final HttpServletResponse httpResponse = (HttpServletResponse) response;
if (isLogoutPath(httpRequest)) {
removeCookie(httpResponse);
redirectToIndex(httpRequest, httpResponse);
} else if (isIndexPath(httpRequest) ||
checkLogin(httpRequest, httpResponse) ||
checkToken(httpRequest)
) {
chain.doFilter(request, response);
} else {
redirectToIndex(httpRequest, httpResponse);
}
}
private void redirectToIndex(
HttpServletRequest httpRequest,
HttpServletResponse httpResponse
) throws IOException {
httpResponse.sendRedirect(httpRequest.getContextPath() + "/index.html");
}
private void removeCookie(HttpServletResponse httpResponse) {
final Cookie cookie = new Cookie("token", "");
cookie.setMaxAge(0);
httpResponse.addCookie(cookie);
}
private boolean isLogoutPath(HttpServletRequest httpRequest) {
return httpRequest.getServletPath().equals("/logout");
}
private boolean isIndexPath(HttpServletRequest httpRequest) {
return httpRequest.getServletPath().equals("/index.html");
}
private boolean checkLogin(HttpServletRequest httpRequest, HttpServletResponse response) {
final String login = httpRequest.getParameter("login");
final String password = httpRequest.getParameter("password");
if (login != null && password != null) {
try {
final UsersDAO dao = new UsersDAO();
final String token = dao.checkLogin(login, password);
if (token == null) {
return false;
} else {
response.addCookie(new Cookie("token", token));
return true;
}
} catch (DAOException e) {
e.printStackTrace();
return false;
}
} else {
return false;
}
}
private boolean checkToken(HttpServletRequest httpRequest) {
final Cookie[] cookies = httpRequest.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals("token")) {
try {
return new UsersDAO().checkToken(cookie.getValue()) != null;
} catch (DAOException e) {
e.printStackTrace();
return false;
}
}
}
}
return false;
}
@Override
public void init(FilterConfig config) throws ServletException {
}
@Override
public void destroy() {
}
}
package es.uvigo.esei.daa.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.commons.codec.digest.DigestUtils;
public class UsersDAO extends DAO {
public String checkLogin(String login, String password) throws DAOException {
final String shaPassword = DigestUtils.sha256Hex(password);
try (final Connection conn = this.getConnection()) {
final String query = "SELECT password FROM users WHERE login=?";
try (PreparedStatement statement = conn.prepareStatement(query)) {
statement.setString(1, login);
try (ResultSet result = statement.executeQuery()) {
if (result.next()) {
final String dbPassword = result.getString("password");
if (shaPassword.equals(dbPassword)) {
return DigestUtils.sha256Hex(login + dbPassword);
} else {
return null;
}
} else {
return null;
}
}
}
} catch (SQLException e) {
throw new DAOException(e);
}
}
public String checkToken(String token) throws DAOException {
try (final Connection conn = this.getConnection()) {
final String query = "SELECT login FROM users WHERE sha2(concat(login, password), 256)=?";
try (PreparedStatement statement = conn.prepareStatement(query)) {
statement.setString(1, token);
try (ResultSet result = statement.executeQuery()) {
if (result.next()) {
return result.getString("login");
} else {
return null;
}
}
}
} catch (SQLException e) {
throw new DAOException(e);
}
}
}
CREATE DATABASE `daaexample`;
CREATE TABLE `daaexample`.`people` (
`id` int NOT NULL AUTO_INCREMENT,
`name` varchar(50) DEFAULT NULL,
`surname` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`)
);
CREATE TABLE `daaexample`.`users` (
`login` varchar(100) NOT NULL,
`password` varbinary(64) DEFAULT NULL,
PRIMARY KEY (`login`)
);
GRANT ALL ON `daaexample`.* TO 'daa'@'localhost' IDENTIFIED BY 'daa';
INSERT INTO `daaexample`.`people` (`id`,`name`,`surname`) VALUES (0,'Antón','Pérez');
INSERT INTO `daaexample`.`people` (`id`,`name`,`surname`) VALUES (0,'Manuel','Martínez');
INSERT INTO `daaexample`.`people` (`id`,`name`,`surname`) VALUES (0,'Laura','Reboredo');
INSERT INTO `daaexample`.`people` (`id`,`name`,`surname`) VALUES (0,'Perico','Palotes');
INSERT INTO `daaexample`.`people` (`id`,`name`,`surname`) VALUES (0,'Ana','María');
INSERT INTO `daaexample`.`people` (`id`,`name`,`surname`) VALUES (0,'María','Nuevo');
INSERT INTO `daaexample`.`people` (`id`,`name`,`surname`) VALUES (0,'Alba','Fernández');
INSERT INTO `daaexample`.`people` (`id`,`name`,`surname`) VALUES (0,'Asunción','Jiménez');
INSERT INTO `daaexample`.`users` (`login`,`password`) VALUES ('mrjato', '59189332a4abf8ddf66fde068cad09eb563b4bd974f7663d97ff6852a7910a73');
CREATE DATABASE `daaexample`;
CREATE TABLE `daaexample`.`people` (
`id` int NOT NULL AUTO_INCREMENT,
`name` varchar(50) DEFAULT NULL,
`surname` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`)
);
CREATE TABLE `daaexample`.`users` (
`login` varchar(100) NOT NULL,
`password` varbinary(64) DEFAULT NULL,
PRIMARY KEY (`login`)
);
GRANT ALL ON `daaexample`.* TO 'daa'@'localhost' IDENTIFIED BY 'daa';
\ No newline at end of file
...@@ -3,7 +3,8 @@ ...@@ -3,7 +3,8 @@
xmlns="http://java.sun.com/xml/ns/javaee" xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0"> id="WebApp_ID" version="3.0">
<display-name>DAAExampleTMP</display-name> <display-name>DAAExample</display-name>
<welcome-file-list> <welcome-file-list>
<welcome-file>index.html</welcome-file> <welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file> <welcome-file>index.htm</welcome-file>
...@@ -12,15 +13,18 @@ ...@@ -12,15 +13,18 @@
<welcome-file>default.htm</welcome-file> <welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file> <welcome-file>default.jsp</welcome-file>
</welcome-file-list> </welcome-file-list>
<resource-ref> <resource-ref>
<description>DAA Example DB Connection</description> <description>DAA Example DB Connection</description>
<res-ref-name>jdbc/daaexample</res-ref-name> <res-ref-name>jdbc/daaexample</res-ref-name>
<res-type>javax.sql.DataSource</res-type> <res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth> <res-auth>Container</res-auth>
</resource-ref> </resource-ref>
<servlet> <servlet>
<servlet-name>javax.ws.rs.core.Application</servlet-name> <servlet-name>javax.ws.rs.core.Application</servlet-name>
<init-param> <init-param>
<!-- Activates JSON automatic conversion in JAX-RS -->
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name> <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value> <param-value>true</param-value>
</init-param> </init-param>
...@@ -30,10 +34,12 @@ ...@@ -30,10 +34,12 @@
<url-pattern>/rest/*</url-pattern> <url-pattern>/rest/*</url-pattern>
</servlet-mapping> </servlet-mapping>
<!-- servlet> <servlet-name>webdav</servlet-name> <servlet-class>org.apache.catalina.servlets.WebdavServlet</servlet-class> <!-- filter>
<init-param> <param-name>debug</param-name> <param-value>0</param-value> <filter-name>LoginFilter</filter-name>
</init-param> <init-param> <param-name>listings</param-name> <param-value>false</param-value> <filter-class>es.uvigo.esei.daa.LoginFilter</filter-class>
</init-param> <init-param> <param-name>readonly</param-name> <param-value>false</param-value> </filter>
</init-param> </servlet> <servlet-mapping> <servlet-name>webdav</servlet-name> <filter-mapping>
<url-pattern>/*</url-pattern> </servlet-mapping --> <filter-name>LoginFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping-->
</web-app> </web-app>
\ No newline at end of file
...@@ -2,21 +2,13 @@ ...@@ -2,21 +2,13 @@
<html> <html>
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<title>DAA Example</title> <title>DAA Example - Login</title>
</head> </head>
<body> <body>
<div id="people-container"> <form action="main.html" method="POST">
<h1>People</h1> <div>Login: <input name="login" type="text"/></div>
</div> <div>Password: <input name="password" type="password"/></div>
<div><input type="submit" value="Login"/></div>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.0.js"></script> </form>
<script type="text/javascript" src="js/view/people.js"></script>
<script type="text/javascript">
$(document).ready(function() {
insertPeopleForm($('#people-container'));
insertPeopleList($('#people-container'));
initPeople();
});
</script>
</body> </body>
</html> </html>
\ No newline at end of file
...@@ -50,6 +50,13 @@ function formToPerson() { ...@@ -50,6 +50,13 @@ function formToPerson() {
}; };
} }
function personToForm(person) {
var form = $(peopleFormQuery);
form.find('input[name="id"]').val(person.id);
form.find('input[name="name"]').val(person.name);
form.find('input[name="surname"]').val(person.surname);
}
function rowToPerson(id) { function rowToPerson(id) {
var row = $('#person-' + id); var row = $('#person-' + id);
...@@ -60,13 +67,6 @@ function rowToPerson(id) { ...@@ -60,13 +67,6 @@ function rowToPerson(id) {
}; };
} }
function personToForm(person) {
var form = $(peopleFormQuery);
form.find('input[name="id"]').val(person.id);
form.find('input[name="name"]').val(person.name);
form.find('input[name="surname"]').val(person.surname);
}
function isEditing() { function isEditing() {
return $(peopleFormQuery + ' input[name="id"]').val() != ""; return $(peopleFormQuery + ' input[name="id"]').val() != "";
} }
......
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>DAA Example</title>
</head>
<body>
<div id="people-container">
<h1>People</h1>
<a id="#logout" href="logout">Logout</a>
</div>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.0.js"></script>
<script type="text/javascript" src="js/view/people.js"></script>
<script type="text/javascript">
$(document).ready(function() {
insertPeopleForm($('#people-container'));
insertPeopleList($('#people-container'));
initPeople();
});
</script>
</body>
</html>
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment