Search in sources :

Example 86 with Principal

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

the class RestAuthenticator method doLogin.

@Override
public Principal doLogin(final HttpServletRequest request, final String emailOrUsername, final String password) throws AuthenticationException, FrameworkException {
    final PropertyKey<String> eMailKey = StructrApp.key(Principal.class, "eMail");
    final Principal user = AuthHelper.getPrincipalForPassword(eMailKey, emailOrUsername, password);
    SessionHelper.clearInvalidSessions(user);
    return user;
}
Also used : Principal(org.structr.core.entity.Principal)

Example 87 with Principal

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

the class RestAuthenticator method initializeAndExamineRequest.

// ~--- methods --------------------------------------------------------
/**
 * Examine request and try to find a user.
 *
 * First, check session id, then try external (OAuth) authentication,
 * finally, check standard login by credentials.
 *
 * @param request
 * @param response
 * @return security context
 * @throws FrameworkException
 */
@Override
public SecurityContext initializeAndExamineRequest(final HttpServletRequest request, final HttpServletResponse response) throws FrameworkException {
    SecurityContext securityContext;
    Principal user = SessionHelper.checkSessionAuthentication(request);
    if (user == null) {
        user = getUser(request, true);
    }
    if (user == null) {
        // If no user could be determined, assume frontend access
        securityContext = SecurityContext.getInstance(user, request, AccessMode.Frontend);
    } else {
        if (user instanceof SuperUser) {
            securityContext = SecurityContext.getSuperUserInstance(request);
        } else {
            securityContext = SecurityContext.getInstance(user, request, AccessMode.Backend);
            SessionHelper.clearInvalidSessions(user);
        }
    }
    securityContext.setAuthenticator(this);
    // Check CORS settings (Cross-origin resource sharing, see http://en.wikipedia.org/wiki/Cross-origin_resource_sharing)
    final String origin = request.getHeader("Origin");
    if (!StringUtils.isBlank(origin)) {
        final Services services = Services.getInstance();
        response.setHeader("Access-Control-Allow-Origin", origin);
        // allow cross site resource sharing (read only)
        final String maxAge = Settings.AccessControlMaxAge.getValue();
        if (StringUtils.isNotBlank(maxAge)) {
            response.setHeader("Access-Control-MaxAge", maxAge);
        }
        final String allowMethods = Settings.AccessControlAllowMethods.getValue();
        if (StringUtils.isNotBlank(allowMethods)) {
            response.setHeader("Access-Control-Allow-Methods", allowMethods);
        }
        final String allowHeaders = Settings.AccessControlAllowHeaders.getValue();
        if (StringUtils.isNotBlank(allowHeaders)) {
            response.setHeader("Access-Control-Allow-Headers", allowHeaders);
        }
        final String allowCredentials = Settings.AccessControlAllowCredentials.getValue();
        if (StringUtils.isNotBlank(allowCredentials)) {
            response.setHeader("Access-Control-Allow-Credentials", allowCredentials);
        }
        final String exposeHeaders = Settings.AccessControlExposeHeaders.getValue();
        if (StringUtils.isNotBlank(exposeHeaders)) {
            response.setHeader("Access-Control-Expose-Headers", exposeHeaders);
        }
    }
    examined = true;
    return securityContext;
}
Also used : Services(org.structr.core.Services) SecurityContext(org.structr.common.SecurityContext) SuperUser(org.structr.core.entity.SuperUser) Principal(org.structr.core.entity.Principal)

Example 88 with Principal

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

the class SessionHelper method checkSessionAuthentication.

public static synchronized Principal checkSessionAuthentication(final HttpServletRequest request) throws FrameworkException {
    String requestedSessionId = request.getRequestedSessionId();
    String sessionId = null;
    logger.debug("0. Requested session id: " + requestedSessionId + ", request says is valid? " + request.isRequestedSessionIdValid());
    HttpSession session = request.getSession(false);
    boolean isNotTimedOut = false;
    if (requestedSessionId == null) {
        logger.debug("1b. Empty requested session id, creating a new one.");
        // No session id requested => create new session
        SessionHelper.newSession(request);
        // Store info in request that session is new => saves us a lookup later
        request.setAttribute(SESSION_IS_NEW, true);
        // be a user with this session ID, so don't search.
        return null;
    } else {
        requestedSessionId = getShortSessionId(requestedSessionId);
        // Existing session id, check if we have an existing session
        if (session != null) {
            logger.debug("1a. Requested session id without worker id suffix: " + requestedSessionId);
            sessionId = session.getId();
            logger.debug("2a. Current session id: " + session.getId());
            if (sessionId.equals(requestedSessionId)) {
                logger.debug("3a. Current session id equals requested session id");
            } else {
                logger.debug("3b. Current session id does not equal requested session id.");
            }
        } else {
            logger.debug("2b. Current session is null.");
            // Try to find session in session cache
            session = getSessionBySessionId(requestedSessionId);
            if (session == null) {
                // Not found, create new
                SessionHelper.newSession(request);
                logger.debug("3a. Created new session");
                // remove session ID without session
                SessionHelper.clearSession(requestedSessionId);
                logger.debug("4. Cleared unknown session " + requestedSessionId);
                // be a user with this session ID, so don't search.
                return null;
            } else {
                logger.debug("3b. Session with requested id " + requestedSessionId + " found, continuing.");
            }
        }
        sessionId = session.getId();
        if (SessionHelper.isSessionTimedOut(session)) {
            isNotTimedOut = false;
            // invalidate session
            SessionHelper.invalidateSession(session);
            // remove invalid session ID
            SessionHelper.clearSession(sessionId);
            logger.debug("4a. Cleared timed-out session " + sessionId);
            SessionHelper.newSession(request);
            // be a user with this session ID, so don't search.
            return null;
        } else {
            logger.debug("4b. Session " + sessionId + " is not timed-out.");
            isNotTimedOut = true;
        }
    }
    if (isNotTimedOut) {
        final Principal user = AuthHelper.getPrincipalForSessionId(sessionId);
        logger.debug("Valid session found: {}, last accessed {}, authenticated with user {}", new Object[] { session, session.getLastAccessedTime(), user });
        return user;
    } else {
        final Principal user = AuthHelper.getPrincipalForSessionId(sessionId);
        if (user != null) {
            logger.info("Timed-out session: {}, last accessed {}, authenticated with user {}", new Object[] { session, (session != null ? session.getLastAccessedTime() : ""), user });
            logger.debug("Logging out user {}", new Object[] { user });
            AuthHelper.doLogout(request, user);
            try {
                request.logout();
            } catch (Throwable t) {
            }
        }
        SessionHelper.newSession(request);
        return null;
    }
}
Also used : HttpSession(javax.servlet.http.HttpSession) Principal(org.structr.core.entity.Principal)

Example 89 with Principal

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

the class SessionHelper method clearSession.

/**
 * Make sure the given sessionId is not set for any user.
 *
 * @param sessionId
 */
public static synchronized void clearSession(final String sessionId) {
    final App app = StructrApp.getInstance();
    final PropertyKey<String[]> sessionIdKey = StructrApp.key(Principal.class, "sessionIds");
    final Query<Principal> query = app.nodeQuery(Principal.class).and(sessionIdKey, new String[] { sessionId }).disableSorting();
    try {
        List<Principal> principals = query.getAsList();
        for (final Principal p : principals) {
            p.removeSessionId(sessionId);
        }
    } catch (FrameworkException fex) {
        logger.warn("Error while removing sessionId " + sessionId + " from all principals", fex);
    }
}
Also used : StructrApp(org.structr.core.app.StructrApp) App(org.structr.core.app.App) FrameworkException(org.structr.common.error.FrameworkException) Principal(org.structr.core.entity.Principal)

Example 90 with Principal

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

the class DeploymentTest method test22TemplateOwnershipAndGrants.

@Test
public void test22TemplateOwnershipAndGrants() {
    Principal user1 = null;
    Principal user2 = null;
    try (final Tx tx = app.tx()) {
        user1 = createTestNode(User.class, new NodeAttribute<>(AbstractNode.name, "user1"));
        user2 = createTestNode(User.class, new NodeAttribute<>(AbstractNode.name, "user2"));
        tx.success();
    } catch (FrameworkException ex) {
        fail("Unexpected exception.");
    }
    Assert.assertNotNull("User was not created, test cannot continue", user1);
    Assert.assertNotNull("User was not created, test cannot continue", user2);
    // setup
    try (final Tx tx = app.tx()) {
        // create first page
        final Page page1 = Page.createNewPage(securityContext, "test22_1");
        final Html html1 = createElement(page1, page1, "html");
        final Head head1 = createElement(page1, html1, "head");
        createElement(page1, head1, "title", "test22_1");
        final Body body1 = createElement(page1, html1, "body");
        final Div div1 = createElement(page1, body1, "div");
        createElement(page1, div1, "div", "test1");
        createElement(page1, div1, "div", "test1");
        final Div component = createComponent(div1);
        // create second page
        final Page page2 = Page.createNewPage(securityContext, "test22_2");
        final Html html2 = createElement(page2, page2, "html");
        final Head head2 = createElement(page2, html2, "head");
        createElement(page2, head2, "title", "test22_2");
        final Body body2 = createElement(page2, html2, "body");
        final Div div2 = createElement(page2, body2, "div");
        // re-use template from above
        final Div cloned = cloneComponent(component, div2);
        component.grant(Permission.read, user1);
        cloned.grant(Permission.read, user2);
        tx.success();
    } catch (FrameworkException fex) {
        fail("Unexpected exception.");
    }
    // test
    doImportExportRoundtrip(true, true, new Function() {

        @Override
        public Object apply(Object t) {
            try (final Tx tx = app.tx()) {
                createTestNode(User.class, new NodeAttribute<>(AbstractNode.name, "user1"));
                createTestNode(User.class, new NodeAttribute<>(AbstractNode.name, "user2"));
                tx.success();
            } catch (FrameworkException ex) {
                fail("Unexpected exception.");
            }
            return null;
        }
    });
}
Also used : NodeAttribute(org.structr.core.graph.NodeAttribute) Head(org.structr.web.entity.html.Head) User(org.structr.web.entity.User) Tx(org.structr.core.graph.Tx) FrameworkException(org.structr.common.error.FrameworkException) Html(org.structr.web.entity.html.Html) Page(org.structr.web.entity.dom.Page) Div(org.structr.web.entity.html.Div) Function(java.util.function.Function) GraphObject(org.structr.core.GraphObject) Body(org.structr.web.entity.html.Body) Principal(org.structr.core.entity.Principal) Test(org.junit.Test) StructrUiTest(org.structr.web.StructrUiTest)

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