+++ /dev/null
-package com.prueba.api.persistence;
-
-public class Account {
- private final String code;
- private final String name;
- private final String surname;
- private final String password;
- private final String role;
-
- public Account() {
- this.code = null;
- this.name = null;
- this.surname = null;
- this.password = null;
- this.role = null;
- }
-
- public Account(String code, String name, String surname, String password, String role) {
- this.code = code;
- this.name = name;
- this.surname = surname;
- this.password = password;
- this.role = role;
- }
-
- public String getCode() {
- return code;
- }
-
- public String getName() {
- return name;
- }
-
- public String getSurname() {
- return surname;
- }
-
- public String getPassword() {
- return password;
- }
-
- public String getRole() {
- return role;
- }
-
-}
+++ /dev/null
-package com.prueba.authorization.persistence.dao;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import javax.sql.DataSource;
-
-import com.prueba.core.context.integration.database.impl.DataBaseAccessImpl;
-import com.prueba.core.context.web.application.ApplicationWebContext;
-
-public class ApplicationResourceDao {
- public static final String URL_PATTERN = "URL_PATTERN";
- public static final String HTTP_METHOD = "HTTP_METHOD";
-
- public List<Map<String, String>> findURLsByUserName(String userName) {
- final DataSource dataSource = ApplicationWebContext.getInstance().getDataSource();
- final DataBaseAccessImpl dataBaseAccess = new DataBaseAccessImpl(dataSource);
-
- return dataBaseAccess.executeQuery(""
- + "SELECT APP_RES.URL_PATTERN, APP_RES.HTTP_METHOD FROM APPLICATION_ROLE APP_ROLE "
- + "INNER JOIN APPLICATION_RESOURCE_APPLICATION_ROLE APP_RES_APP_ROLE ON APP_ROLE.CODE = APP_RES_APP_ROLE.APPLICATION_ROLE_CODE "
- + "INNER JOIN APPLICATION_RESOURCE APP_RES ON APP_RES.URL_PATTERN = APP_RES_APP_ROLE.APPLICATION_RESOURCE_URL_PATTERN "
- + "INNER JOIN ACCOUNT ACC ON ACC.APPLICATION_ROLE_CODE = APP_ROLE.CODE "
- + "WHERE ACC.CODE = ? ",
- answer ->
- {
- final List<Map<String, String>> result = new ArrayList<>();
- while (answer.next()) {
- final Map<String, String> row = new HashMap<>();
- String urlPatternValue = answer.getString(URL_PATTERN);
- String httpMethodValue = answer.getString(HTTP_METHOD);
- row.put(URL_PATTERN, urlPatternValue);
- row.put(HTTP_METHOD, httpMethodValue);
- result.add(row);
- }
-
- return result;
- },
- preparedStatement -> {
- preparedStatement.setString(1, userName);
- });
- }
-}
-
+++ /dev/null
-package com.prueba.authorization.services.impl;
-
-import java.util.List;
-import java.util.Map;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.prueba.authorization.persistence.dao.ApplicationResourceDao;
-import com.prueba.core.context.util.AntPathMatcher;
-
-public class AuthorizationServicesImpl {
- private static final Logger LOGGER = LoggerFactory.getLogger(AuthorizationServicesImpl.class);
-
- private static final String USER_NAME_PARAM = "username";
- private static final String API_URL_PATTERN = "/app/api/users/{" + USER_NAME_PARAM + "}";
-
- public boolean isAuthorized(String httpMethod, String uri, String userName) {
- final String userNameParam = this.getSafeUserNameParam(uri);
-
- final ApplicationResourceDao dao = new ApplicationResourceDao();
-
- final List<Map<String, String>> urls = dao.findURLsByUserName(userName);
-
- return urls.stream().anyMatch(urlMap ->
- {
- final String urlPatternValue = urlMap.get(ApplicationResourceDao.URL_PATTERN);
- final String urlReplacedPatternValue = urlPatternValue.replace("{" + USER_NAME_PARAM + "}", userNameParam);
-
- final String httpMethodValue = urlMap.get(ApplicationResourceDao.HTTP_METHOD);
-
- return urlReplacedPatternValue.equals(uri) && httpMethodValue.equals(httpMethod);
- });
-
- }
-
- protected String getSafeUserNameParam(String uri) {
- final AntPathMatcher pathMatcher = new AntPathMatcher();
-
- String userNameParam = "";
- try {
- final Map<String, String> variables = pathMatcher.extractUriTemplateVariables(API_URL_PATTERN, uri);
- userNameParam = variables.get(USER_NAME_PARAM);
- } catch (IllegalStateException exception) {
-
- LOGGER.warn("AntPathMatcher: ", exception);
- }
-
- return userNameParam;
- }
-}
--- /dev/null
+package com.prueba.controllers.rest;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.charset.Charset;
+import java.util.Map;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.prueba.core.context.util.AntPathMatcher;
+import com.prueba.core.web.controller.Controller;
+import com.prueba.persistence.domain.AccountResource;
+import com.prueba.services.impl.ApiServiceImpl;
+import com.sun.net.httpserver.Headers;
+import com.sun.net.httpserver.HttpExchange;
+
+public class ApiController implements Controller {
+ private static final String CONTENT_TYPE_JSON = "application/json";
+ private static final String CONTENT_TYPE_HEADER = "Content-Type";
+ private static final Logger LOGGER = LoggerFactory.getLogger(ApiController.class);
+ private static final String USER_NAME_PARAM = "username";
+ private static final String API_URL_PATTERN = "/app/api/users/{" + USER_NAME_PARAM + "}";
+
+ // Both are thread safe :)
+ private final ApiServiceImpl apiService = new ApiServiceImpl();
+ private final ObjectMapper mapper = new ObjectMapper();
+
+ @Override
+ public void handle(HttpExchange httpExchange) throws IOException {
+ final String requestMethod = httpExchange.getRequestMethod();
+
+ switch (requestMethod) {
+ case "GET":
+ this.processGet(httpExchange);
+
+ break;
+ case "POST":
+
+ if (this.isJSONContentType(httpExchange)) {
+ this.processPost(httpExchange);
+ } else {
+ httpExchange.sendResponseHeaders(415, 0);
+ }
+
+ break;
+ case "DELETE":
+ this.processDelete(httpExchange);
+
+ break;
+ default:
+ // Not found
+ httpExchange.sendResponseHeaders(404, 0);
+ break;
+ }
+ }
+
+ protected String getBody (HttpExchange httpExchange) throws IOException {
+ try(final InputStream inputStream = httpExchange.getRequestBody();
+ final ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream()) {
+
+ final int bufferSize = 1024;
+ final byte[] buffer = new byte[bufferSize];
+
+ int len = 0;
+ while ((len = inputStream.read(buffer)) != -1) {
+ byteBuffer.write(buffer, 0, len);
+ }
+
+ return new String(byteBuffer.toByteArray(), Charset.forName("UTF-8"));
+ }
+ }
+
+ protected void processGet(HttpExchange httpExchange) throws IOException {
+ int statusCode = 404;
+ final String userNameParam = this.getSafeUserNameParam(httpExchange);
+
+ AccountResource account = apiService.findAccountByCode(userNameParam);
+ String bodyResponse = "";
+ if (account != null) {
+ statusCode = 200;
+ bodyResponse = mapper.writeValueAsString(account);
+ }
+
+ this.setJSONContentType(httpExchange);
+ httpExchange.sendResponseHeaders(statusCode, bodyResponse.length());
+
+ try (final OutputStream os = httpExchange.getResponseBody()) {
+ os.write(bodyResponse.getBytes());
+ }
+ }
+
+ protected void processPost(HttpExchange httpExchange) throws IOException {
+ final String bodyRequest = getBody(httpExchange);
+ final AccountResource accountRequest = mapper.readValue(bodyRequest, AccountResource.class);
+
+ apiService.createAccount(accountRequest);
+
+ this.setJSONContentType(httpExchange);
+
+ httpExchange.sendResponseHeaders(200, 0);
+
+ try (final OutputStream os = httpExchange.getResponseBody()) {
+ os.write(bodyRequest.getBytes());
+ }
+ }
+
+ protected void processDelete(HttpExchange httpExchange) throws IOException {
+ final String userNameParam = getSafeUserNameParam(httpExchange);
+
+ apiService.deleteAccountByCode(userNameParam);
+
+ httpExchange.sendResponseHeaders(204, 0);
+ }
+
+ protected void setJSONContentType(HttpExchange httpExchange) {
+ final Headers headers = httpExchange.getResponseHeaders();
+
+ headers.remove(CONTENT_TYPE_HEADER);
+ headers.set(CONTENT_TYPE_HEADER, CONTENT_TYPE_JSON);
+ }
+
+ protected boolean isJSONContentType(HttpExchange httpExchange) {
+ final Headers headers = httpExchange.getRequestHeaders();
+ final String contentType = headers.getFirst(CONTENT_TYPE_HEADER);
+
+ return null != contentType && contentType.equals(CONTENT_TYPE_JSON);
+ }
+
+ protected String getSafeUserNameParam(HttpExchange httpExchange) {
+ final String uri = httpExchange.getRequestURI().toString();
+ final AntPathMatcher pathMatcher = new AntPathMatcher();
+
+ String userNameParam = "";
+ try {
+ final Map<String, String> variables = pathMatcher.extractUriTemplateVariables(API_URL_PATTERN, uri);
+ userNameParam = variables.get(USER_NAME_PARAM);
+ } catch (IllegalStateException exception) {
+
+ LOGGER.warn("AntPathMatcher: ", exception);
+ }
+
+ return userNameParam;
+ }
+}
--- /dev/null
+package com.prueba.controllers.rest;
+
+import java.io.IOException;
+
+import com.prueba.core.web.controller.Controller;
+import com.prueba.services.impl.LoginServiceImpl;
+import com.sun.net.httpserver.HttpExchange;
+
+public class LoginController implements Controller {
+
+ @Override
+ public void handle(HttpExchange httpExchange) throws IOException {
+ final LoginServiceImpl loginService = new LoginServiceImpl();
+ final String requestedURI = httpExchange.getRequestURI().toString();
+
+ if (requestedURI.startsWith("/app/login/login.html")) {
+
+ final String requestMethod = httpExchange.getRequestMethod();
+
+ switch (requestMethod) {
+ case "GET":
+ loginService.processLoginGet(httpExchange);
+ break;
+ case "POST":
+ loginService.processLoginPost(httpExchange);
+ break;
+ default:
+ httpExchange.sendResponseHeaders(404, 0);
+ break;
+ }
+
+ } else if (requestedURI.startsWith("/app/login/logout.html")) {
+ loginService.processLogoutGet(httpExchange);
+ } else {
+ httpExchange.sendResponseHeaders(404, 0);
+ }
+
+ }
+
+
+
+}
--- /dev/null
+package com.prueba.controllers.rest;
+
+import java.io.IOException;
+import java.io.OutputStream;
+
+import com.prueba.core.context.security.persistence.SessionInfo;
+import com.prueba.core.context.security.persistence.context.SessionContext;
+import com.prueba.core.web.controller.Controller;
+import com.prueba.view.login.PageImpl;
+import com.sun.net.httpserver.HttpExchange;
+
+public class PagesController implements Controller {
+
+ @Override
+ public void handle(HttpExchange httpExchange) throws IOException {
+ final String requestMethod = httpExchange.getRequestMethod();
+
+ switch (requestMethod) {
+ case "GET":
+ this.processPages(httpExchange);
+ break;
+ default:
+ httpExchange.sendResponseHeaders(404, 0);
+ break;
+ }
+
+ }
+
+ protected void processPages(HttpExchange httpExchange) throws IOException {
+ final String requestedURI = httpExchange.getRequestURI().toString();
+ final PageImpl pageImpl = new PageImpl();
+
+ int responseStatus = 200;
+ String html = "";
+ switch (requestedURI) {
+ case "/app/pages/page_1.html":
+ html = pageImpl.doPage(1, getSafeUserName());
+ break;
+ case "/app/pages/page_2.html":
+ html = pageImpl.doPage(2, getSafeUserName());
+ break;
+ case "/app/pages/page_3.html":
+ html = pageImpl.doPage(3, getSafeUserName());
+ break;
+ default:
+ responseStatus = 404;
+ break;
+ }
+
+ httpExchange.sendResponseHeaders(responseStatus, html.length());
+ try (final OutputStream os = httpExchange.getResponseBody()) {
+ os.write(html.getBytes());
+ }
+ }
+
+ protected String getSafeUserName() {
+ SessionInfo sessionInfo = SessionContext.getSession();
+ String userName = "";
+
+ if (sessionInfo != null) {
+ userName = sessionInfo.getUsername();
+ }
+
+ return userName;
+ }
+
+}
List<Map<String, String>> executeQuery(
final String query, final ExecuteResultSet<ResultSet> executeResultSet, FillPreparedStatement fillStatement);
+
+
+ void executeUpdate(String query, FillPreparedStatement fillStatement);
}
}
+ @Override
public void executeUpdate(String query, FillPreparedStatement fillStatement) {
try {
this.executeUpdateThrowable(query, fillStatement);
} catch (SQLException exception) {
- LOGGER.error("Query error: ", exception);
+ LOGGER.error("Update error: ", exception);
- throw new IllegalStateException("Querry error", exception);
+ throw new IllegalStateException("Update error", exception);
}
}
pool.setPassword(PASSWORD);
pool.setDriverClass(DRIVER_CLASS);
pool.setJdbcUrl(JDBC_URL);
- pool.setInitialPoolSize(5);
+ pool.setInitialPoolSize(10);
pool.setMaxPoolSize(35);
pool.setMinPoolSize(10);
pool.setAcquireIncrement(1);
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.prueba.authorization.services.impl.AuthorizationServicesImpl;
+import com.prueba.controllers.rest.ApiController;
import com.prueba.core.context.security.authenticator.persistence.AuthenticationInfo;
import com.prueba.core.context.security.persistence.context.BasicAuthenticationContext;
-import com.prueba.resources.rest.controllers.ApiController;
+import com.prueba.services.impl.AuthorizationServicesImpl;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.prueba.resources.rest.controllers.LoginController;
+import com.prueba.controllers.rest.LoginController;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.prueba.authorization.services.impl.AuthorizationServicesImpl;
+import com.prueba.controllers.rest.PagesController;
import com.prueba.core.context.security.persistence.SessionInfo;
import com.prueba.core.context.security.persistence.Sessions;
import com.prueba.core.context.security.persistence.context.SessionContext;
-import com.prueba.resources.rest.controllers.PagesController;
+import com.prueba.services.impl.AuthorizationServicesImpl;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.prueba.core.context.integration.liquibase.impl.LiquibaseContext;
import com.prueba.core.context.security.handle.ApiHandler;
import com.prueba.core.context.security.handle.LoginHandler;
-import com.prueba.core.context.security.handle.SessionHandler;
-import com.prueba.resources.rest.controllers.LoginController;
import com.prueba.core.context.security.handle.PagesHandler;
+import com.prueba.core.context.security.handle.SessionHandler;
import com.sun.net.httpserver.HttpHandler;
import javax.sql.DataSource;
-import com.prueba.api.persistence.Account;
+import com.prueba.core.context.integration.database.DataBaseAccess;
import com.prueba.core.context.integration.database.impl.DataBaseAccessImpl;
import com.prueba.core.context.web.application.ApplicationWebContext;
+import com.prueba.persistence.domain.AccountResource;
public class AccountDao {
private static final String CODE = "CODE";
private static final String PASSWORD = "PASSWORD";
private static final String APP_ROLE_CODE = "APPLICATION_ROLE_CODE";
- public Account findByCode(String accountCode) {
+ public AccountResource findByCode(String accountCode) {
final DataSource dataSource = ApplicationWebContext.getInstance().getDataSource();
- final DataBaseAccessImpl dataBaseAccess = new DataBaseAccessImpl(dataSource);
+ final DataBaseAccess dataBaseAccess = new DataBaseAccessImpl(dataSource);
final List<Map<String, String>> results =
dataBaseAccess.executeQuery("SELECT * FROM ACCOUNT WHERE CODE = ?",
preparedStatement.setString(1, accountCode);
});
- Account account = null;
+ AccountResource account = null;
if (!results.isEmpty()) {
final Map<String, String> row = results.get(0);
- account = new Account(row.get(CODE), row.get(NAME),
+ account = new AccountResource(row.get(CODE), row.get(NAME),
row.get(SURNAME), null, row.get(APP_ROLE_CODE));
}
return account;
}
- public void create(Account account) {
+ public void create(AccountResource account) {
final DataSource dataSource = ApplicationWebContext.getInstance().getDataSource();
final DataBaseAccessImpl dataBaseAccess = new DataBaseAccessImpl(dataSource);
}
- public Account findByCodeAndPassword(String username, String password) {
+ public AccountResource findByCodeAndPassword(String username, String password) {
final DataSource dataSource = ApplicationWebContext.getInstance().getDataSource();
final DataBaseAccessImpl dataBaseAccess = new DataBaseAccessImpl(dataSource);
preparedStatement.setString(2, password);
});
- Account account = null;
+ AccountResource account = null;
if (!results.isEmpty()) {
final Map<String, String> row = results.get(0);
- account = new Account(row.get(CODE), row.get(NAME),
+ account = new AccountResource(row.get(CODE), row.get(NAME),
row.get(SURNAME), null, row.get(APP_ROLE_CODE));
}
--- /dev/null
+package com.prueba.persistence.dao;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import javax.sql.DataSource;
+
+import com.prueba.core.context.integration.database.impl.DataBaseAccessImpl;
+import com.prueba.core.context.web.application.ApplicationWebContext;
+
+public class ApplicationResourceDao {
+ public static final String URL_PATTERN = "URL_PATTERN";
+ public static final String HTTP_METHOD = "HTTP_METHOD";
+
+ public List<Map<String, String>> findURLsByUserName(String userName) {
+ final DataSource dataSource = ApplicationWebContext.getInstance().getDataSource();
+ final DataBaseAccessImpl dataBaseAccess = new DataBaseAccessImpl(dataSource);
+
+ return dataBaseAccess.executeQuery(""
+ + "SELECT APP_RES.URL_PATTERN, APP_RES.HTTP_METHOD FROM APPLICATION_ROLE APP_ROLE "
+ + "INNER JOIN APPLICATION_RESOURCE_APPLICATION_ROLE APP_RES_APP_ROLE ON APP_ROLE.CODE = APP_RES_APP_ROLE.APPLICATION_ROLE_CODE "
+ + "INNER JOIN APPLICATION_RESOURCE APP_RES ON APP_RES.URL_PATTERN = APP_RES_APP_ROLE.APPLICATION_RESOURCE_URL_PATTERN "
+ + "INNER JOIN ACCOUNT ACC ON ACC.APPLICATION_ROLE_CODE = APP_ROLE.CODE "
+ + "WHERE ACC.CODE = ? ",
+ answer ->
+ {
+ final List<Map<String, String>> result = new ArrayList<>();
+ while (answer.next()) {
+ final Map<String, String> row = new HashMap<>();
+ String urlPatternValue = answer.getString(URL_PATTERN);
+ String httpMethodValue = answer.getString(HTTP_METHOD);
+ row.put(URL_PATTERN, urlPatternValue);
+ row.put(HTTP_METHOD, httpMethodValue);
+ result.add(row);
+ }
+
+ return result;
+ },
+ preparedStatement -> {
+ preparedStatement.setString(1, userName);
+ });
+ }
+}
+
--- /dev/null
+package com.prueba.persistence.domain;
+
+public class AccountResource {
+ private final String code;
+ private final String name;
+ private final String surname;
+ private final String password;
+ private final String role;
+
+ public AccountResource() {
+ this.code = null;
+ this.name = null;
+ this.surname = null;
+ this.password = null;
+ this.role = null;
+ }
+
+ public AccountResource(String code, String name, String surname, String password, String role) {
+ this.code = code;
+ this.name = name;
+ this.surname = surname;
+ this.password = password;
+ this.role = role;
+ }
+
+ public String getCode() {
+ return code;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public String getSurname() {
+ return surname;
+ }
+
+ public String getPassword() {
+ return password;
+ }
+
+ public String getRole() {
+ return role;
+ }
+
+}
+++ /dev/null
-package com.prueba.resources.rest.controllers;
-
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.nio.charset.Charset;
-import java.util.Map;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.prueba.api.persistence.Account;
-import com.prueba.core.context.util.AntPathMatcher;
-import com.prueba.core.web.controller.Controller;
-import com.prueba.services.impl.ApiServiceImpl;
-import com.sun.net.httpserver.Headers;
-import com.sun.net.httpserver.HttpExchange;
-
-public class ApiController implements Controller {
- private static final String CONTENT_TYPE_JSON = "application/json";
- private static final String CONTENT_TYPE_HEADER = "Content-Type";
- private static final Logger LOGGER = LoggerFactory.getLogger(ApiController.class);
- private static final String USER_NAME_PARAM = "username";
- private static final String API_URL_PATTERN = "/app/api/users/{" + USER_NAME_PARAM + "}";
-
- // Both are thread safe :)
- private final ApiServiceImpl apiService = new ApiServiceImpl();
- private final ObjectMapper mapper = new ObjectMapper();
-
- @Override
- public void handle(HttpExchange httpExchange) throws IOException {
- final String requestMethod = httpExchange.getRequestMethod();
-
- switch (requestMethod) {
- case "GET":
- this.processGet(httpExchange);
-
- break;
- case "POST":
-
- if (this.isJSONContentType(httpExchange)) {
- this.processPost(httpExchange);
- } else {
- httpExchange.sendResponseHeaders(415, 0);
- }
-
- break;
- case "DELETE":
- this.processDelete(httpExchange);
-
- break;
- default:
- // Not found
- httpExchange.sendResponseHeaders(404, 0);
- break;
- }
- }
-
- protected String getBody (HttpExchange httpExchange) throws IOException {
- try(final InputStream inputStream = httpExchange.getRequestBody();
- final ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream()) {
-
- final int bufferSize = 1024;
- final byte[] buffer = new byte[bufferSize];
-
- int len = 0;
- while ((len = inputStream.read(buffer)) != -1) {
- byteBuffer.write(buffer, 0, len);
- }
-
- return new String(byteBuffer.toByteArray(), Charset.forName("UTF-8"));
- }
- }
-
- protected void processGet(HttpExchange httpExchange) throws IOException {
- int statusCode = 404;
- final String userNameParam = this.getSafeUserNameParam(httpExchange);
-
- Account account = apiService.findAccountByCode(userNameParam);
- String bodyResponse = "";
- if (account != null) {
- statusCode = 200;
- bodyResponse = mapper.writeValueAsString(account);
- }
-
- this.setJSONContentType(httpExchange);
- httpExchange.sendResponseHeaders(statusCode, bodyResponse.length());
-
- try (final OutputStream os = httpExchange.getResponseBody()) {
- os.write(bodyResponse.getBytes());
- }
- }
-
- protected void processPost(HttpExchange httpExchange) throws IOException {
- final String bodyRequest = getBody(httpExchange);
- final Account accountRequest = mapper.readValue(bodyRequest, Account.class);
-
- apiService.createAccount(accountRequest);
-
- this.setJSONContentType(httpExchange);
-
- httpExchange.sendResponseHeaders(200, 0);
-
- try (final OutputStream os = httpExchange.getResponseBody()) {
- os.write(bodyRequest.getBytes());
- }
- }
-
- protected void processDelete(HttpExchange httpExchange) throws IOException {
- final String userNameParam = getSafeUserNameParam(httpExchange);
-
- apiService.deleteAccountByCode(userNameParam);
-
- httpExchange.sendResponseHeaders(204, 0);
- }
-
- protected void setJSONContentType(HttpExchange httpExchange) {
- final Headers headers = httpExchange.getResponseHeaders();
-
- headers.remove(CONTENT_TYPE_HEADER);
- headers.set(CONTENT_TYPE_HEADER, CONTENT_TYPE_JSON);
- }
-
- protected boolean isJSONContentType(HttpExchange httpExchange) {
- final Headers headers = httpExchange.getRequestHeaders();
- final String contentType = headers.getFirst(CONTENT_TYPE_HEADER);
-
- return null != contentType && contentType.equals(CONTENT_TYPE_JSON);
- }
-
- protected String getSafeUserNameParam(HttpExchange httpExchange) {
- final String uri = httpExchange.getRequestURI().toString();
- final AntPathMatcher pathMatcher = new AntPathMatcher();
-
- String userNameParam = "";
- try {
- final Map<String, String> variables = pathMatcher.extractUriTemplateVariables(API_URL_PATTERN, uri);
- userNameParam = variables.get(USER_NAME_PARAM);
- } catch (IllegalStateException exception) {
-
- LOGGER.warn("AntPathMatcher: ", exception);
- }
-
- return userNameParam;
- }
-}
+++ /dev/null
-package com.prueba.resources.rest.controllers;
-
-import java.io.IOException;
-
-import com.prueba.core.web.controller.Controller;
-import com.prueba.services.impl.LoginServiceImpl;
-import com.sun.net.httpserver.HttpExchange;
-
-public class LoginController implements Controller {
-
- @Override
- public void handle(HttpExchange httpExchange) throws IOException {
- final LoginServiceImpl loginService = new LoginServiceImpl();
- final String requestedURI = httpExchange.getRequestURI().toString();
-
- if (requestedURI.startsWith("/app/login/login.html")) {
-
- final String requestMethod = httpExchange.getRequestMethod();
-
- switch (requestMethod) {
- case "GET":
- loginService.processLoginGet(httpExchange);
- break;
- case "POST":
- loginService.processLoginPost(httpExchange);
- break;
- default:
- httpExchange.sendResponseHeaders(404, 0);
- break;
- }
-
- } else if (requestedURI.startsWith("/app/login/logout.html")) {
- loginService.processLogoutGet(httpExchange);
- } else {
- httpExchange.sendResponseHeaders(404, 0);
- }
-
- }
-
-
-
-}
+++ /dev/null
-package com.prueba.resources.rest.controllers;
-
-import java.io.IOException;
-import java.io.OutputStream;
-
-import com.prueba.core.context.security.persistence.SessionInfo;
-import com.prueba.core.context.security.persistence.context.SessionContext;
-import com.prueba.core.web.controller.Controller;
-import com.prueba.view.login.PageImpl;
-import com.sun.net.httpserver.HttpExchange;
-
-public class PagesController implements Controller {
-
- @Override
- public void handle(HttpExchange httpExchange) throws IOException {
- final String requestMethod = httpExchange.getRequestMethod();
-
- switch (requestMethod) {
- case "GET":
- this.processPages(httpExchange);
- break;
- default:
- httpExchange.sendResponseHeaders(404, 0);
- break;
- }
-
- }
-
- protected void processPages(HttpExchange httpExchange) throws IOException {
- final String requestedURI = httpExchange.getRequestURI().toString();
- final PageImpl pageImpl = new PageImpl();
-
- int responseStatus = 200;
- String html = "";
- switch (requestedURI) {
- case "/app/pages/page_1.html":
- html = pageImpl.doPage(1, getSafeUserName());
- break;
- case "/app/pages/page_2.html":
- html = pageImpl.doPage(2, getSafeUserName());
- break;
- case "/app/pages/page_3.html":
- html = pageImpl.doPage(3, getSafeUserName());
- break;
- default:
- responseStatus = 404;
- break;
- }
-
- httpExchange.sendResponseHeaders(responseStatus, html.length());
- try (final OutputStream os = httpExchange.getResponseBody()) {
- os.write(html.getBytes());
- }
- }
-
- protected String getSafeUserName() {
- SessionInfo sessionInfo = SessionContext.getSession();
- String userName = "";
-
- if (sessionInfo != null) {
- userName = sessionInfo.getUsername();
- }
-
- return userName;
- }
-
-}
package com.prueba.services.impl;
-import com.prueba.api.persistence.Account;
import com.prueba.persistence.dao.AccountDao;
+import com.prueba.persistence.domain.AccountResource;
public class ApiServiceImpl {
- public Account findAccountByCode(String accountCode) {
+ public AccountResource findAccountByCode(String accountCode) {
AccountDao accountDao = new AccountDao();
return accountDao.findByCode(accountCode);
}
- public void createAccount(Account account) {
+ public void createAccount(AccountResource account) {
AccountDao accountDao = new AccountDao();
accountDao.create(account);
--- /dev/null
+package com.prueba.services.impl;
+
+import java.util.List;
+import java.util.Map;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.prueba.core.context.util.AntPathMatcher;
+import com.prueba.persistence.dao.ApplicationResourceDao;
+
+public class AuthorizationServicesImpl {
+ private static final Logger LOGGER = LoggerFactory.getLogger(AuthorizationServicesImpl.class);
+
+ private static final String USER_NAME_PARAM = "username";
+ private static final String API_URL_PATTERN = "/app/api/users/{" + USER_NAME_PARAM + "}";
+
+ public boolean isAuthorized(String httpMethod, String uri, String userName) {
+ final String userNameParam = this.getSafeUserNameParam(uri);
+
+ final ApplicationResourceDao dao = new ApplicationResourceDao();
+
+ final List<Map<String, String>> urls = dao.findURLsByUserName(userName);
+
+ return urls.stream().anyMatch(urlMap ->
+ {
+ final String urlPatternValue = urlMap.get(ApplicationResourceDao.URL_PATTERN);
+ final String urlReplacedPatternValue = urlPatternValue.replace("{" + USER_NAME_PARAM + "}", userNameParam);
+
+ final String httpMethodValue = urlMap.get(ApplicationResourceDao.HTTP_METHOD);
+
+ return urlReplacedPatternValue.equals(uri) && httpMethodValue.equals(httpMethod);
+ });
+
+ }
+
+ protected String getSafeUserNameParam(String uri) {
+ final AntPathMatcher pathMatcher = new AntPathMatcher();
+
+ String userNameParam = "";
+ try {
+ final Map<String, String> variables = pathMatcher.extractUriTemplateVariables(API_URL_PATTERN, uri);
+ userNameParam = variables.get(USER_NAME_PARAM);
+ } catch (IllegalStateException exception) {
+
+ LOGGER.warn("AntPathMatcher: ", exception);
+ }
+
+ return userNameParam;
+ }
+}
import org.junit.Before;
import org.junit.Test;
-import com.prueba.api.persistence.Account;
import com.prueba.core.context.integration.datasource.impl.DoDataSourceContext;
import com.prueba.core.context.integration.liquibase.impl.LiquibaseContext;
+import com.prueba.persistence.domain.AccountResource;
public class AccountDaoIntegrationTest {
private AccountDao accountDao;
@Test
public void whenFindAccountByCodeAndPasswordThenRetrieveAccount() {
- Account expectedAccount = doAccount();
+ AccountResource expectedAccount = doAccount();
- Account account = accountDao.findByCodeAndPassword(
+ AccountResource account = accountDao.findByCodeAndPassword(
expectedAccount.getCode(), expectedAccount.getPassword());
assertNotNull(account);
@Test
public void whenCreateNewAccountThenRetrieveNewAccount() {
- Account expectedAccount = doSampleAccount();
+ AccountResource expectedAccount = doSampleAccount();
accountDao.create(expectedAccount);
- Account account = accountDao.findByCode(expectedAccount.getCode());
+ AccountResource account = accountDao.findByCode(expectedAccount.getCode());
assertNotNull(account);
assertEquals(expectedAccount.getCode(), account.getCode());
@Test
public void whenDeleteAccountThenDoNotRetrieveAgainAccount() {
- Account expectedAccount = doOtherSampleAccount();
+ AccountResource expectedAccount = doOtherSampleAccount();
accountDao.create(expectedAccount);
- Account account = accountDao.findByCode(expectedAccount.getCode());
+ AccountResource account = accountDao.findByCode(expectedAccount.getCode());
assertNotNull(account);
assertEquals(expectedAccount.getCode(), account.getCode());
assertNull(account);
}
- private Account doAccount() {
+ private AccountResource doAccount() {
final String expectedCode = "GUMARTIN";
final String expectedName = "Gustavo";
final String expectedSurname = "Martin Morcuende";
final String expectedPassword = "lame";
final String expectedAppRoleCode = "ROLE_APP_ADMIN";
- return new Account(expectedCode, expectedName, expectedSurname, expectedPassword, expectedAppRoleCode);
+ return new AccountResource(expectedCode, expectedName, expectedSurname, expectedPassword, expectedAppRoleCode);
}
- private Account doSampleAccount() {
+ private AccountResource doSampleAccount() {
final String expectedCode = "PRUEBA";
final String expectedName = "Gustavo";
final String expectedSurname = "Martin Morcuende";
final String expectedPassword = "lame";
final String expectedAppRoleCode = "ROLE_APP_ADMIN";
- return new Account(expectedCode, expectedName, expectedSurname, expectedPassword, expectedAppRoleCode);
+ return new AccountResource(expectedCode, expectedName, expectedSurname, expectedPassword, expectedAppRoleCode);
}
- private Account doOtherSampleAccount() {
+ private AccountResource doOtherSampleAccount() {
final String expectedCode = "OTRAPRUEBA";
final String expectedName = "Gustavo";
final String expectedSurname = "Martin Morcuende";
final String expectedPassword = "lame";
final String expectedAppRoleCode = "ROLE_APP_ADMIN";
- return new Account(expectedCode, expectedName, expectedSurname, expectedPassword, expectedAppRoleCode);
+ return new AccountResource(expectedCode, expectedName, expectedSurname, expectedPassword, expectedAppRoleCode);
}
}