use of org.structr.core.auth.Authenticator in project structr by structr.
the class ProxyServlet method doGet.
@Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response) {
final PropertyKey<String> proxyUrlKey = StructrApp.key(User.class, "proxyUrl");
final PropertyKey<String> proxyUsernameKey = StructrApp.key(User.class, "proxyUsernameKey");
final PropertyKey<String> proxyPasswordKey = StructrApp.key(User.class, "proxyPasswordKey");
final Authenticator auth = getConfig().getAuthenticator();
SecurityContext securityContext;
String content;
if (auth == null) {
final String errorMessage = "No authenticator class found. Check log for 'Missing authenticator key " + this.getClass().getSimpleName() + ".authenticator'";
logger.error(errorMessage);
try {
final ServletOutputStream out = response.getOutputStream();
content = errorPage(new Throwable(errorMessage));
IOUtils.write(content, out);
} catch (IOException ex) {
logger.error("Could not write to response", ex);
}
return;
}
try {
// isolate request authentication in a transaction
try (final Tx tx = StructrApp.getInstance().tx()) {
securityContext = auth.initializeAndExamineRequest(request, response);
tx.success();
}
// Ensure access mode is frontend
securityContext.setAccessMode(AccessMode.Frontend);
String address = request.getParameter("url");
final URI url = URI.create(address);
String proxyUrl = request.getParameter("proxyUrl");
String proxyUsername = request.getParameter("proxyUsername");
String proxyPassword = request.getParameter("proxyPassword");
String authUsername = request.getParameter("authUsername");
String authPassword = request.getParameter("authPassword");
String cookie = request.getParameter("cookie");
final Principal user = securityContext.getCachedUser();
if (user != null && StringUtils.isBlank(proxyUrl)) {
proxyUrl = user.getProperty(proxyUrlKey);
proxyUsername = user.getProperty(proxyUsernameKey);
proxyPassword = user.getProperty(proxyPasswordKey);
}
content = HttpHelper.get(address, authUsername, authPassword, proxyUrl, proxyUsername, proxyPassword, cookie, Collections.EMPTY_MAP).replace("<head>", "<head>\n <base href=\"" + url + "\">");
} catch (Throwable t) {
logger.error("Exception while processing request", t);
content = errorPage(t);
}
try {
final ServletOutputStream out = response.getOutputStream();
IOUtils.write(content, out, "utf-8");
} catch (IOException ex) {
logger.error("Could not write to response", ex);
}
}
use of org.structr.core.auth.Authenticator in project structr by structr.
the class LoginCommand method processMessage.
// ~--- methods --------------------------------------------------------
@Override
public void processMessage(final WebSocketMessage webSocketData) {
final String username = (String) webSocketData.getNodeData().get("username");
final String password = (String) webSocketData.getNodeData().get("password");
Principal user;
if ((username != null) && (password != null)) {
try {
StructrWebSocket socket = this.getWebSocket();
Authenticator auth = socket.getAuthenticator();
user = auth.doLogin(socket.getRequest(), username, password);
if (user != null) {
String sessionId = webSocketData.getSessionId();
if (sessionId == null) {
logger.debug("Unable to login {}: No sessionId found", new Object[] { username, password });
getWebSocket().send(MessageBuilder.status().code(403).build(), true);
return;
}
sessionId = SessionHelper.getShortSessionId(sessionId);
try {
Actions.call(Actions.NOTIFICATION_LOGIN, user);
} catch (UnlicensedException ex) {
ex.log(logger);
}
// Clear possible existing sessions
SessionHelper.clearSession(sessionId);
user.addSessionId(sessionId);
// store token in response data
webSocketData.getNodeData().clear();
webSocketData.setSessionId(sessionId);
webSocketData.getNodeData().put("username", user.getProperty(AbstractNode.name));
// authenticate socket
socket.setAuthenticated(sessionId, user);
// send data..
socket.send(webSocketData, false);
}
} catch (AuthenticationException e) {
logger.info("Unable to login {}, probably wrong password", username);
getWebSocket().send(MessageBuilder.status().code(403).build(), true);
} catch (FrameworkException fex) {
logger.warn("Unable to execute command", fex);
}
}
}
use of org.structr.core.auth.Authenticator in project structr by structr.
the class GraphQLServlet method handleGraphQLRequest.
// ----- private methods -----
private void handleGraphQLRequest(final HttpServletRequest request, final HttpServletResponse response, final String query) throws IOException, FrameworkException {
final SecurityContext securityContext;
final Authenticator authenticator;
try {
// isolate request authentication in a transaction
try (final Tx tx = StructrApp.getInstance().tx()) {
authenticator = config.getAuthenticator();
securityContext = authenticator.initializeAndExamineRequest(request, response);
tx.success();
}
final App app = StructrApp.getInstance(securityContext);
if (securityContext != null) {
// isolate write output
try (final Tx tx = app.tx()) {
final Document doc = GraphQLRequest.parse(new Parser(), query);
if (doc != null) {
final List<ValidationError> errors = new Validator().validateDocument(SchemaService.getGraphQLSchema(), doc);
if (errors.isEmpty()) {
// no validation errors in query, do request
final GraphQLWriter graphQLWriter = new GraphQLWriter(true);
// no trailing semicolon so we dont trip MimeTypes.getContentTypeWithoutCharset
response.setContentType("application/json; charset=utf-8");
final Writer writer = response.getWriter();
graphQLWriter.stream(securityContext, writer, new GraphQLRequest(securityContext, doc, query));
// useful newline
writer.append("\n");
} else {
final Map<String, Object> map = new LinkedHashMap<>();
final Writer writer = response.getWriter();
final Gson gson = getGson();
map.put("errors", errors);
gson.toJson(map, writer);
// useful newline
writer.append("\n");
// send 422 status
response.setStatus(422);
}
}
tx.success();
}
}
} catch (FrameworkException frameworkException) {
// set status & write JSON output
response.setStatus(frameworkException.getStatus());
getGson().toJson(frameworkException, response.getWriter());
response.getWriter().println();
} catch (IllegalStateException | IllegalArgumentException iex) {
final Map<String, Object> map = new LinkedHashMap<>();
map.put("code", 422);
map.put("message", iex.getMessage());
// set status & write JSON output
response.setStatus(422);
getGson().toJson(map, response.getWriter());
response.getWriter().println();
} catch (UnsupportedOperationException uoe) {
logger.warn("POST not supported");
int code = HttpServletResponse.SC_BAD_REQUEST;
response.setStatus(code);
response.getWriter().append(RestMethodResult.jsonError(code, "POST not supported: " + uoe.getMessage()));
} catch (Throwable t) {
logger.warn("Exception in POST", t);
int code = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
response.setStatus(code);
response.getWriter().append(RestMethodResult.jsonError(code, "JsonSyntaxException in POST: " + t.getMessage()));
} finally {
try {
// response.getWriter().flush();
response.getWriter().close();
} catch (Throwable t) {
logger.warn("Unable to flush and close response: {}", t.getMessage());
}
}
}
use of org.structr.core.auth.Authenticator in project structr by structr.
the class JsonRestServlet method doDelete.
// <editor-fold defaultstate="collapsed" desc="DELETE">
@Override
protected void doDelete(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
SecurityContext securityContext = null;
Authenticator authenticator = null;
RestMethodResult result = null;
Resource resource = null;
try {
assertInitialized();
// first thing to do!
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8");
// isolate request authentication in a transaction
try (final Tx tx = StructrApp.getInstance().tx()) {
authenticator = config.getAuthenticator();
securityContext = authenticator.initializeAndExamineRequest(request, response);
tx.success();
}
final App app = StructrApp.getInstance(securityContext);
// isolate resource authentication
try (final Tx tx = app.tx()) {
resource = ResourceHelper.optimizeNestedResourceChain(securityContext, request, resourceMap, propertyView);
authenticator.checkResourceAccess(securityContext, request, resource.getResourceSignature(), propertyView.get(securityContext));
tx.success();
}
// isolate doDelete
boolean retry = true;
while (retry) {
try {
result = resource.doDelete();
retry = false;
} catch (RetryException ddex) {
retry = true;
}
}
// isolate write output
try (final Tx tx = app.tx()) {
result.commitResponse(gson.get(), response);
tx.success();
}
} catch (FrameworkException frameworkException) {
// set status & write JSON output
response.setStatus(frameworkException.getStatus());
gson.get().toJson(frameworkException, response.getWriter());
response.getWriter().println();
} catch (JsonSyntaxException jsex) {
logger.warn("JsonSyntaxException in DELETE", jsex);
int code = HttpServletResponse.SC_BAD_REQUEST;
response.setStatus(code);
response.getWriter().append(RestMethodResult.jsonError(code, "JsonSyntaxException in DELETE: " + jsex.getMessage()));
} catch (JsonParseException jpex) {
logger.warn("JsonParseException in DELETE", jpex);
int code = HttpServletResponse.SC_BAD_REQUEST;
response.setStatus(code);
response.getWriter().append(RestMethodResult.jsonError(code, "JsonSyntaxException in DELETE: " + jpex.getMessage()));
} catch (Throwable t) {
logger.warn("Exception in DELETE", t);
int code = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
response.setStatus(code);
response.getWriter().append(RestMethodResult.jsonError(code, "JsonSyntaxException in DELETE: " + t.getMessage()));
} finally {
try {
// response.getWriter().flush();
response.getWriter().close();
} catch (IOException t) {
logger.warn("Unable to flush and close response: {}", t.getMessage());
}
}
}
use of org.structr.core.auth.Authenticator in project structr by structr.
the class JsonRestServlet method doPut.
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="PUT">
@Override
protected void doPut(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
final SecurityContext securityContext;
final Authenticator authenticator;
final Resource resource;
RestMethodResult result = new RestMethodResult(HttpServletResponse.SC_BAD_REQUEST);
try {
assertInitialized();
// first thing to do!
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8");
// get reader before initalizing security context
final String input = IOUtils.toString(request.getReader());
// isolate request authentication in a transaction
try (final Tx tx = StructrApp.getInstance().tx()) {
authenticator = config.getAuthenticator();
securityContext = authenticator.initializeAndExamineRequest(request, response);
tx.success();
}
final App app = StructrApp.getInstance(securityContext);
final IJsonInput jsonInput = cleanAndParseJsonString(app, input);
if (securityContext != null) {
// isolate resource authentication
try (final Tx tx = app.tx()) {
// evaluate constraint chain
resource = ResourceHelper.applyViewTransformation(request, securityContext, ResourceHelper.optimizeNestedResourceChain(securityContext, request, resourceMap, propertyView), propertyView);
authenticator.checkResourceAccess(securityContext, request, resource.getResourceSignature(), propertyView.get(securityContext));
tx.success();
}
// isolate doPut
boolean retry = true;
while (retry) {
try (final Tx tx = app.tx()) {
result = resource.doPut(convertPropertySetToMap(jsonInput.getJsonInputs().get(0)));
tx.success();
retry = false;
} catch (RetryException ddex) {
retry = true;
}
}
// isolate write output
try (final Tx tx = app.tx()) {
result.commitResponse(gson.get(), response);
tx.success();
}
} else {
// isolate write output
try (final Tx tx = app.tx()) {
result = new RestMethodResult(HttpServletResponse.SC_FORBIDDEN);
result.commitResponse(gson.get(), response);
tx.success();
}
}
} catch (FrameworkException frameworkException) {
// set status & write JSON output
response.setStatus(frameworkException.getStatus());
gson.get().toJson(frameworkException, response.getWriter());
response.getWriter().println();
} catch (JsonSyntaxException jsex) {
logger.warn("PUT: Invalid JSON syntax", jsex.getMessage());
int code = HttpServletResponse.SC_BAD_REQUEST;
response.setStatus(code);
response.getWriter().append(RestMethodResult.jsonError(code, "JsonSyntaxException in PUT: " + jsex.getMessage()));
} catch (JsonParseException jpex) {
logger.warn("PUT: Unable to parse JSON string", jpex.getMessage());
int code = HttpServletResponse.SC_BAD_REQUEST;
response.setStatus(code);
response.getWriter().append(RestMethodResult.jsonError(code, "JsonSyntaxException in PUT: " + jpex.getMessage()));
} catch (Throwable t) {
logger.warn("Exception in PUT", t);
logger.warn("", t);
int code = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
response.setStatus(code);
response.getWriter().append(RestMethodResult.jsonError(code, "JsonSyntaxException in PUT: " + t.getMessage()));
} finally {
try {
// response.getWriter().flush();
response.getWriter().close();
} catch (Throwable t) {
logger.warn("Unable to flush and close response: {}", t.getMessage());
}
}
}
Aggregations