Search in sources :

Example 46 with Principal

use of org.structr.core.entity.Principal in project structr by structr.

the class HtmlServlet method checkResetPassword.

/**
 * This method checks if the current request to reset a user password
 *
 * @param request
 * @param response
 * @param path
 * @return true if the registration was successful
 * @throws FrameworkException
 * @throws IOException
 */
private boolean checkResetPassword(final Authenticator auth, final HttpServletRequest request, final HttpServletResponse response, final String path) throws FrameworkException, IOException {
    logger.debug("Checking registration ...");
    String key = request.getParameter(CONFIRM_KEY_KEY);
    if (StringUtils.isEmpty(key)) {
        return false;
    }
    final PropertyKey<String> confirmationKeyKey = StructrApp.key(User.class, "confirmationKey");
    final String targetPage = filterMaliciousRedirects(request.getParameter(TARGET_PAGE_KEY));
    if (RESET_PASSWORD_PAGE.equals(path)) {
        final App app = StructrApp.getInstance();
        Result<Principal> results;
        try (final Tx tx = app.tx()) {
            results = app.nodeQuery(Principal.class).and(confirmationKeyKey, key).getResult();
            tx.success();
        }
        if (!results.isEmpty()) {
            final Principal user = results.get(0);
            try (final Tx tx = app.tx()) {
                // Clear confirmation key and set session id
                user.setProperty(confirmationKeyKey, null);
                if (Settings.RestUserAutologin.getValue()) {
                    AuthHelper.doLogin(request, user);
                }
                tx.success();
            }
        }
        // Redirect to target page
        if (StringUtils.isNotBlank(targetPage)) {
            response.sendRedirect(targetPage);
        }
        return true;
    }
    return false;
}
Also used : App(org.structr.core.app.App) StructrApp(org.structr.core.app.StructrApp) Tx(org.structr.core.graph.Tx) Principal(org.structr.core.entity.Principal)

Example 47 with Principal

use of org.structr.core.entity.Principal 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);
    }
}
Also used : Tx(org.structr.core.graph.Tx) ServletOutputStream(javax.servlet.ServletOutputStream) SecurityContext(org.structr.common.SecurityContext) IOException(java.io.IOException) URI(java.net.URI) UiAuthenticator(org.structr.web.auth.UiAuthenticator) Authenticator(org.structr.core.auth.Authenticator) Principal(org.structr.core.entity.Principal)

Example 48 with Principal

use of org.structr.core.entity.Principal 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);
        }
    }
}
Also used : UnlicensedException(org.structr.common.error.UnlicensedException) FrameworkException(org.structr.common.error.FrameworkException) AuthenticationException(org.structr.core.auth.exception.AuthenticationException) StructrWebSocket(org.structr.websocket.StructrWebSocket) Principal(org.structr.core.entity.Principal) Authenticator(org.structr.core.auth.Authenticator)

Example 49 with Principal

use of org.structr.core.entity.Principal in project structr by structr.

the class LogoutCommand method processMessage.

@Override
public void processMessage(final WebSocketMessage webSocketData) throws FrameworkException {
    final Principal user = getWebSocket().getCurrentUser();
    if (user != null) {
        final String sessionId = SessionHelper.getShortSessionId(webSocketData.getSessionId());
        if (sessionId != null) {
            SessionHelper.clearSession(sessionId);
            SessionHelper.invalidateSession(SessionHelper.getSessionBySessionId(sessionId));
        }
        AuthHelper.sendLogoutNotification(user);
        getWebSocket().setAuthenticated(null, null);
        getWebSocket().send(MessageBuilder.status().code(401).build(), true);
        getWebSocket().invalidateConsole();
    }
}
Also used : Principal(org.structr.core.entity.Principal)

Example 50 with Principal

use of org.structr.core.entity.Principal in project structr by structr.

the class FavoritesCommand method processMessage.

@Override
public void processMessage(final WebSocketMessage webSocketData) {
    final Map<String, Object> data = webSocketData.getNodeData();
    final String mode = (String) data.get("mode");
    final String favoritableId = (String) data.get("id");
    final Principal currentUser = webSocket.getCurrentUser();
    if (mode == null) {
        getWebSocket().send(MessageBuilder.status().code(422).message("Favorites Command: No mode given. Valid modes: add, remove").build(), true);
    } else if (favoritableId == null) {
        getWebSocket().send(MessageBuilder.status().code(422).message("Favorites Command: No favoritable id given").build(), true);
    } else {
        final App app = StructrApp.getInstance(webSocket.getSecurityContext());
        try (final Tx tx = app.tx()) {
            final Favoritable file = app.get(Favoritable.class, favoritableId);
            if (file != null) {
                final List<Favoritable> favorites = currentUser.getFavorites();
                switch(mode) {
                    case "add":
                        {
                            favorites.add((Favoritable) file);
                            break;
                        }
                    case "remove":
                        {
                            favorites.remove((Favoritable) file);
                            break;
                        }
                    default:
                        getWebSocket().send(MessageBuilder.status().code(422).message("Favorites Command: Invalid mode '" + mode + "'. Valid modes: add, remove").build(), true);
                        return;
                }
                currentUser.setFavorites(favorites);
                getWebSocket().send(MessageBuilder.finished().callback(callback).build(), true);
            } else {
                getWebSocket().send(MessageBuilder.status().code(422).message("Favorites Command: Favoritable with id '" + favoritableId + "'does not exist!").build(), true);
            }
            tx.success();
        } catch (FrameworkException fex) {
            getWebSocket().send(MessageBuilder.status().code(422).message("Favorites Command: Favoritable with id '" + favoritableId + "'does not exist!").build(), true);
        }
    }
}
Also used : StructrApp(org.structr.core.app.StructrApp) App(org.structr.core.app.App) Tx(org.structr.core.graph.Tx) FrameworkException(org.structr.common.error.FrameworkException) List(java.util.List) Principal(org.structr.core.entity.Principal) Favoritable(org.structr.core.entity.Favoritable)

Aggregations

Principal (org.structr.core.entity.Principal)112 FrameworkException (org.structr.common.error.FrameworkException)68 Tx (org.structr.core.graph.Tx)65 Test (org.junit.Test)41 App (org.structr.core.app.App)31 StructrApp (org.structr.core.app.StructrApp)31 TestOne (org.structr.core.entity.TestOne)16 Group (org.structr.core.entity.Group)14 NodeAttribute (org.structr.core.graph.NodeAttribute)13 PropertyMap (org.structr.core.property.PropertyMap)13 SecurityContext (org.structr.common.SecurityContext)10 LinkedList (java.util.LinkedList)9 Result (org.structr.core.Result)8 User (org.structr.web.entity.User)8 AbstractNode (org.structr.core.entity.AbstractNode)7 SuperUser (org.structr.core.entity.SuperUser)7 StructrUiTest (org.structr.web.StructrUiTest)7 Page (org.structr.web.entity.dom.Page)7 IOException (java.io.IOException)6 List (java.util.List)6