Search in sources :

Example 6 with Role

use of com.twinsoft.convertigo.engine.AuthenticatedSessionManager.Role in project convertigo by convertigo.

the class Edit method getServiceResult.

protected void getServiceResult(HttpServletRequest request, Document document) throws Exception {
    String username = request.getParameter("username");
    String password = request.getParameter("password");
    String[] roles = request.getParameterValues("roles");
    String oldUsername = request.getParameter("oldUsername");
    Element root = document.getDocumentElement();
    Element response = document.createElement("response");
    if (roles == null) {
        roles = new String[] {};
    }
    try {
        Set<Role> set = new HashSet<Role>(roles.length);
        for (String role : roles) {
            set.add(Role.valueOf(role));
        }
        if (StringUtils.isBlank(password)) {
            password = Engine.authenticatedSessionManager.getPassword(oldUsername);
        } else {
            AuthenticatedSessionManager.validatePassword(password);
            password = DigestUtils.sha512Hex(password);
        }
        if (!username.equals(oldUsername)) {
            if (Engine.authenticatedSessionManager.hasUser(username)) {
                throw new IllegalArgumentException("User '" + username + "' already exists");
            }
            Engine.authenticatedSessionManager.setUser(username, password, set);
            Engine.authenticatedSessionManager.deleteUser(oldUsername);
        } else {
            Engine.authenticatedSessionManager.setUser(username, password, set);
        }
        response.setAttribute("state", "success");
        response.setAttribute("message", "User '" + username + "' have been successfully edited!");
    } catch (Exception e) {
        Engine.logAdmin.error("Error during editing the user!\n" + e.getMessage());
        response.setAttribute("state", "error");
        response.setAttribute("message", "Error during editing the user!\n" + e.getMessage());
    }
    root.appendChild(response);
}
Also used : Role(com.twinsoft.convertigo.engine.AuthenticatedSessionManager.Role) Element(org.w3c.dom.Element) HashSet(java.util.HashSet)

Example 7 with Role

use of com.twinsoft.convertigo.engine.AuthenticatedSessionManager.Role in project convertigo by convertigo.

the class Authenticate method getServiceResult.

@Override
protected void getServiceResult(HttpServletRequest request, Document document) throws Exception {
    boolean logIn = "login".equals(ServiceUtils.getRequiredParameter(request, "authType"));
    HttpSession httpSession = request.getSession(false);
    // Login
    if (logIn) {
        String authToken = request.getParameter("authToken");
        String user = null;
        String password = null;
        if (authToken != null) {
            try {
                Class.forName("com.twinsoft.convertigo.eclipse.actions.AdministrationAction").getMethod("checkAuthToken", String.class).invoke(null, authToken);
                user = EnginePropertiesManager.getProperty(PropertyName.ADMIN_USERNAME);
            } catch (Throwable t) {
                authToken = null;
            }
        }
        if (authToken == null) {
            user = ServiceUtils.getRequiredParameter(request, "authUserName");
            password = ServiceUtils.getRequiredParameter(request, "authPassword");
        }
        Engine.logAdmin.info("User '" + user + "' is trying to login");
        // Check authentication attempts
        AuthenticationAttempt authenticationAttempt = Authenticate.authenticationAttempts.get(user);
        if (authenticationAttempt != null && authenticationAttempt.accountBlockedUntil != 0) {
            long now = System.currentTimeMillis();
            if (now > authenticationAttempt.accountBlockedUntil) {
                // Unblock the account
                authenticationAttempt.accountBlockedUntil = 0;
                authenticationAttempt.numberOfFailedRequests = 0;
            } else {
                // Continue blocking the account
                Engine.logAdmin.warn("Detected possible brute force attack: user '" + user + "' has failed to login too many times; authentication request is blocked.");
                Engine.authenticatedSessionManager.removeAuthenticatedSession(httpSession);
                long secondsRemaining = (authenticationAttempt.accountBlockedUntil - now) / 1000;
                ServiceUtils.addMessage(document, document.getDocumentElement(), "The '" + user + "' account is blocked during " + secondsRemaining + " seconds, due to too many failed authentication attempts.\n\n" + "Please wait and retry it later.", "error", false);
                return;
            }
        }
        Set<Role> rolesSet;
        Role[] roles = null;
        // Legacy authentication
        if (authToken != null || (EnginePropertiesManager.getProperty(PropertyName.ADMIN_USERNAME).equals(user) && EnginePropertiesManager.checkProperty(PropertyName.ADMIN_PASSWORD, password))) {
            roles = AuthenticatedSessionManager.toRoles(Role.WEB_ADMIN, Role.TEST_PLATFORM, Role.AUTHENTICATED);
        } else if (EnginePropertiesManager.getProperty(PropertyName.TEST_PLATFORM_USERNAME).equals(user) && EnginePropertiesManager.checkProperty(PropertyName.TEST_PLATFORM_PASSWORD, password)) {
            roles = AuthenticatedSessionManager.toRoles(Role.TEST_PLATFORM, Role.AUTHENTICATED);
        } else if ((rolesSet = Engine.authenticatedSessionManager.checkUser(user, password)) != null) {
            roles = new Role[rolesSet.size() + 1];
            rolesSet.toArray(roles);
            roles[roles.length - 1] = Role.AUTHENTICATED;
        } else // Trial authentication
        {
            File hackTrial = new File(Engine.CONFIGURATION_PATH + "/hackTrial.txt");
            if (hackTrial.exists()) {
                try {
                    BufferedReader br = new BufferedReader(new FileReader(hackTrial));
                    String line = br.readLine();
                    br.close();
                    if (!"ok, you can deploy !!".equals(line)) {
                        Engine.logAdmin.error("Trial authentication failure: wrong internal data!");
                    } else if (user.matches(".+@.+\\.[a-z]+") && user.equals(SimpleCipher.decode(password))) {
                        roles = new Role[] { Role.TRIAL };
                    } else {
                        Engine.logAdmin.error("Trial authentication failure: wrong username/password");
                    }
                } catch (Exception e) {
                    Engine.logAdmin.error("Trial authentication failure: wrong internal data!", e);
                }
            }
        }
        if (roles == null) {
            if (authenticationAttempt == null) {
                // The AuthenticationAttempt object does not exist; we must create a new one
                authenticationAttempt = new AuthenticationAttempt();
                Authenticate.authenticationAttempts.put(user, authenticationAttempt);
            }
            Engine.logAdmin.error("Invalid password or user name '" + user + "' (attempt #" + authenticationAttempt.numberOfFailedRequests + ")");
            authenticationAttempt.numberOfFailedRequests++;
            Engine.authenticatedSessionManager.removeAuthenticatedSession(httpSession);
            if (authenticationAttempt.numberOfFailedRequests > Authenticate.MAX_NUMBER_OF_WRONG_AUTHENTICATION_ATTEMPTS) {
                Engine.logAdmin.warn("Detected possible brute force attack: user '" + user + "' has failed to login too many times; authentication request is blocked.");
                if (authenticationAttempt.accountBlockedUntil == 0) {
                    authenticationAttempt.accountBlockedUntil = System.currentTimeMillis() + Authenticate.AUTHENTICATION_DELAY * 1000;
                }
                long now = System.currentTimeMillis();
                long secondsRemaining = (authenticationAttempt.accountBlockedUntil - now) / 1000;
                ServiceUtils.addMessage(document, document.getDocumentElement(), "The '" + user + "' account is blocked during " + secondsRemaining + " seconds, due to too many failed authentication attempts.\n\n" + "Please wait and retry it later.", "error", false);
            } else {
                ServiceUtils.addMessage(document, document.getDocumentElement(), "Invalid authentication!\n\nPlease verify your user ID and/or your password.", "error", false);
            }
        } else {
            Authenticate.authenticationAttempts.remove(user);
            String token = null;
            if (httpSession != null) {
                token = SessionAttribute.xsrfToken.string(httpSession);
                httpSession.invalidate();
            }
            httpSession = request.getSession(true);
            if (token != null) {
                SessionAttribute.xsrfToken.set(httpSession, token);
            }
            httpSession.setAttribute(SessionKey.ADMIN_USER.toString(), user);
            Engine.authenticatedSessionManager.addAuthenticatedSession(httpSession, roles);
            ServiceUtils.addMessage(document, document.getDocumentElement(), "", "success");
            ServiceUtils.addMessage(document, document.getDocumentElement(), "" + httpSession.getAttribute(SessionKey.ADMIN_USER.toString()), "user", false);
            ServiceUtils.addRoleNodes(document.getDocumentElement(), roles);
            SessionAttribute.authenticatedUser.set(httpSession, "c8o:admin");
            Engine.logAdmin.info("User '" + user + "' has been successfully authenticated");
        }
    } else // Logout
    {
        Engine.authenticatedSessionManager.removeAuthenticatedSession(httpSession);
        SessionAttribute.authenticatedUser.remove(httpSession);
        ServiceUtils.addMessage(document, document.getDocumentElement(), "", "success");
    }
}
Also used : HttpSession(javax.servlet.http.HttpSession) Role(com.twinsoft.convertigo.engine.AuthenticatedSessionManager.Role) BufferedReader(java.io.BufferedReader) FileReader(java.io.FileReader) File(java.io.File)

Example 8 with Role

use of com.twinsoft.convertigo.engine.AuthenticatedSessionManager.Role in project convertigo by convertigo.

the class CheckAuthentication method getServiceResult.

@Override
protected void getServiceResult(HttpServletRequest request, Document document) throws Exception {
    HttpSession httpSession = request.getSession(false);
    // Handle anonymous access for test platform user
    if (EnginePropertiesManager.getProperty(PropertyName.TEST_PLATFORM_USERNAME).length() == 0) {
        if (httpSession == null) {
            httpSession = request.getSession(true);
        }
        if (!Engine.authenticatedSessionManager.isAuthenticated(httpSession)) {
            Engine.authenticatedSessionManager.addAuthenticatedSession(httpSession, new Role[] { Role.TEST_PLATFORM });
        }
    }
    boolean bAuthenticated = Engine.authenticatedSessionManager.isAuthenticated(httpSession);
    Role[] roles = Engine.authenticatedSessionManager.getRoles(httpSession);
    if (roles != null) {
        Engine.logAdmin.info("Added roles: " + Arrays.toString(roles));
        ServiceUtils.addRoleNodes(document.getDocumentElement(), roles);
    }
    if (bAuthenticated) {
        Engine.logAdmin.info("Check authentication success");
        ServiceUtils.addMessage(document, document.getDocumentElement(), "" + httpSession.getAttribute(SessionKey.ADMIN_USER.toString()), "user", false);
        ServiceUtils.addMessage(document, document.getDocumentElement(), "true", "authenticated", false);
    } else {
        Engine.logAdmin.info("Check authentication failed (no role defined)");
        ServiceUtils.addMessage(document, document.getDocumentElement(), "false", "authenticated", false);
    }
}
Also used : Role(com.twinsoft.convertigo.engine.AuthenticatedSessionManager.Role) HttpSession(javax.servlet.http.HttpSession)

Example 9 with Role

use of com.twinsoft.convertigo.engine.AuthenticatedSessionManager.Role in project convertigo by convertigo.

the class List method getServiceResult.

protected void getServiceResult(HttpServletRequest request, Document document) throws Exception {
    HttpSession currentSession = request.getSession();
    Element rootElement = document.getDocumentElement();
    Element connectionsListElement = document.createElement("connections");
    rootElement.appendChild(connectionsListElement);
    Element sessionsListElement = document.createElement("sessions");
    rootElement.appendChild(sessionsListElement);
    Element contextsInUseElement = document.createElement("contextsInUse");
    contextsInUseElement.setTextContent("" + Math.max(0, Engine.theApp.contextManager.getNumberOfContexts()));
    rootElement.appendChild(contextsInUseElement);
    Element contextsNumberElement = document.createElement("contextsNumber");
    contextsNumberElement.setTextContent("" + EnginePropertiesManager.getProperty(PropertyName.CONVERTIGO_MAX_CONTEXTS));
    rootElement.appendChild(contextsNumberElement);
    Element sessionsInUseElement = document.createElement("sessionsInUse");
    sessionsInUseElement.setTextContent("" + HttpSessionListener.countSessions());
    rootElement.appendChild(sessionsInUseElement);
    Element sessionsIsOverflowElement = document.createElement("sessionsIsOverflow");
    sessionsIsOverflowElement.setTextContent(KeyManager.isOverflow(Session.EmulIDSE) ? "true" : "false");
    rootElement.appendChild(sessionsIsOverflowElement);
    Element sessionsNumberElement = document.createElement("sessionsNumber");
    sessionsNumberElement.setTextContent("" + Math.max(0, KeyManager.getMaxCV(Session.EmulIDSE)));
    rootElement.appendChild(sessionsNumberElement);
    Element threadsInUseElement = document.createElement("threadsInUse");
    threadsInUseElement.setTextContent("" + Math.max(0, com.twinsoft.convertigo.beans.core.RequestableObject.nbCurrentWorkerThreads));
    rootElement.appendChild(threadsInUseElement);
    Element threadsNumberElement = document.createElement("threadsNumber");
    threadsNumberElement.setTextContent(EnginePropertiesManager.getProperty(PropertyName.DOCUMENT_THREADING_MAX_WORKER_THREADS));
    rootElement.appendChild(threadsNumberElement);
    Element httpTimeoutElement = document.createElement("httpTimeout");
    httpTimeoutElement.setTextContent(formatTime(currentSession.getMaxInactiveInterval()));
    rootElement.appendChild(httpTimeoutElement);
    long now = System.currentTimeMillis();
    Collection<Context> contexts = null;
    String sessionToFilter = request.getParameter("session");
    if (StringUtils.isNotBlank(sessionToFilter)) {
        HttpSession session = HttpSessionListener.getHttpSession(sessionToFilter);
        if (session != null) {
            contexts = Engine.theApp.contextManager.getContexts(session);
        }
    }
    if (contexts == null) {
        contexts = Engine.theApp.contextManager.getContexts();
    }
    for (Context context : contexts) {
        String authenticatedUser = null;
        try {
            authenticatedUser = context.getAuthenticatedUser();
        } catch (Exception e) {
            Engine.logAdmin.trace("connection.List failed to get the authenticated user: " + e);
        }
        com.twinsoft.api.Session apiSession = Engine.theApp.sessionManager.getSession(context.contextID);
        boolean bConnected = ((apiSession != null) && apiSession.isConnected());
        Element connectionElement = document.createElement("connection");
        connectionElement.setAttribute("connected", Boolean.toString(bConnected));
        connectionElement.setAttribute("contextName", context.contextID);
        connectionElement.setAttribute("project", context.projectName);
        connectionElement.setAttribute("connector", context.connectorName);
        connectionElement.setAttribute("requested", (context.requestedObject instanceof Transaction) ? context.transactionName : context.sequenceName);
        connectionElement.setAttribute("status", (context.requestedObject == null || context.requestedObject.runningThread == null ? "finished" : (context.requestedObject.runningThread.bContinue ? "in progress" : "finished")) + "(" + context.waitingRequests + ")");
        connectionElement.setAttribute("user", authenticatedUser == null ? "" : authenticatedUser);
        connectionElement.setAttribute("contextCreationDate", DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM).format(new Date(context.creationTime)));
        connectionElement.setAttribute("lastContextAccessDate", DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM).format(new Date(context.lastAccessTime)));
        try {
            connectionElement.setAttribute("contextInactivityTime", formatTime((now - context.lastAccessTime) / 1000) + " / " + formatTime(Engine.theApp.databaseObjectsManager.getOriginalProjectByName(context.projectName).getContextTimeout()));
        } catch (Exception e) {
        // TODO: document = DOMUtils.handleError(e); << USELESS
        }
        connectionElement.setAttribute("clientComputer", context.remoteHost + " (" + context.remoteAddr + "), " + context.userAgent);
        connectionsListElement.appendChild(connectionElement);
    }
    if (!"false".equals(request.getParameter("sessions"))) {
        for (HttpSession session : HttpSessionListener.getSessions()) {
            Element sessionElement = document.createElement("session");
            java.util.List<Context> ctxs = Engine.theApp.contextManager.getContexts(session);
            sessionElement.setAttribute("sessionID", session.getId());
            sessionElement.setAttribute("authenticatedUser", SessionAttribute.authenticatedUser.string(session));
            sessionElement.setAttribute("contexts", Integer.toString(ctxs == null ? 0 : ctxs.size()));
            sessionElement.setAttribute("clientIP", SessionAttribute.clientIP.string(session));
            sessionElement.setAttribute("deviceUUID", SessionAttribute.deviceUUID.string(session));
            sessionElement.setAttribute("lastSessionAccessDate", DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM).format(new Date(session.getLastAccessedTime())));
            sessionElement.setAttribute("sessionInactivityTime", formatTime((now - session.getLastAccessedTime()) / 1000) + " / " + formatTime(session.getMaxInactiveInterval()));
            Role[] r = (Role[]) session.getAttribute(SessionKey.ADMIN_ROLES.toString());
            sessionElement.setAttribute("adminRoles", Integer.toString(r == null ? 0 : r.length));
            if (session == currentSession) {
                sessionElement.setAttribute("isCurrentSession", "true");
            }
            Set<HttpServletRequest> set = SessionAttribute.fullSyncRequests.get(session);
            sessionElement.setAttribute("isFullSyncActive", Boolean.toString(set != null && !set.isEmpty()));
            sessionsListElement.appendChild(sessionElement);
        }
    }
}
Also used : Context(com.twinsoft.convertigo.engine.Context) Session(com.twinsoft.api.Session) HttpSession(javax.servlet.http.HttpSession) Element(org.w3c.dom.Element) Date(java.util.Date) Role(com.twinsoft.convertigo.engine.AuthenticatedSessionManager.Role) HttpServletRequest(javax.servlet.http.HttpServletRequest) Transaction(com.twinsoft.convertigo.beans.core.Transaction)

Aggregations

Role (com.twinsoft.convertigo.engine.AuthenticatedSessionManager.Role)9 Element (org.w3c.dom.Element)7 HttpSession (javax.servlet.http.HttpSession)3 PropertyName (com.twinsoft.convertigo.engine.EnginePropertiesManager.PropertyName)2 Document (org.w3c.dom.Document)2 NodeList (org.w3c.dom.NodeList)2 Session (com.twinsoft.api.Session)1 Transaction (com.twinsoft.convertigo.beans.core.Transaction)1 AuthenticationException (com.twinsoft.convertigo.engine.AuthenticationException)1 Context (com.twinsoft.convertigo.engine.Context)1 ComboEnum (com.twinsoft.convertigo.engine.EnginePropertiesManager.ComboEnum)1 PropertyCategory (com.twinsoft.convertigo.engine.EnginePropertiesManager.PropertyCategory)1 BufferedReader (java.io.BufferedReader)1 File (java.io.File)1 FileReader (java.io.FileReader)1 InvalidParameterException (java.security.InvalidParameterException)1 Date (java.util.Date)1 HashSet (java.util.HashSet)1 HttpServletRequest (javax.servlet.http.HttpServletRequest)1 Text (org.w3c.dom.Text)1