Search in sources :

Example 1 with SuperUser

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

the class StructrCMISServicesFactory method checkAuthentication.

// ----- private methods -----
private SecurityContext checkAuthentication(final CallContext callContext) {
    final App app = StructrApp.getInstance();
    try (final Tx tx = app.tx()) {
        final String username = callContext.getUsername();
        final String password = callContext.getPassword();
        final Principal principal = AuthHelper.getPrincipalForPassword(Principal.name, username, password);
        SecurityContext securityContext = null;
        if (principal != null) {
            if (principal instanceof SuperUser) {
                securityContext = SecurityContext.getSuperUserInstance();
            } else {
                securityContext = SecurityContext.getInstance(principal, AccessMode.Backend);
            }
        }
        tx.success();
        if (securityContext != null) {
            return securityContext;
        }
    } catch (AuthenticationException aex) {
        throw new CmisUnauthorizedException(aex.getMessage());
    } catch (FrameworkException fex) {
        logger.warn("", fex);
    }
    throw new CmisUnauthorizedException();
}
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) AuthenticationException(org.structr.core.auth.exception.AuthenticationException) SecurityContext(org.structr.common.SecurityContext) CmisUnauthorizedException(org.apache.chemistry.opencmis.commons.exceptions.CmisUnauthorizedException) SuperUser(org.structr.core.entity.SuperUser) Principal(org.structr.core.entity.Principal)

Example 2 with SuperUser

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

the class UiAuthenticator method initializeAndExamineRequest.

/**
 * 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 {
    Principal user = SessionHelper.checkSessionAuthentication(request);
    SecurityContext securityContext;
    if (user == null) {
        user = checkExternalAuthentication(request, response);
    }
    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);
        }
    }
    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)) {
        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;
    // store a reference of the response object in SecurityContext
    // to be able to stream data directly from builtin functions
    securityContext.setResponse(response);
    // expose Structr edition
    response.setHeader("X-Structr-Edition", Services.getInstance().getEdition());
    return securityContext;
}
Also used : SecurityContext(org.structr.common.SecurityContext) SuperUser(org.structr.core.entity.SuperUser) Principal(org.structr.core.entity.Principal)

Example 3 with SuperUser

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

the class UiAuthenticator method checkResourceAccess.

@Override
public void checkResourceAccess(final SecurityContext securityContext, final HttpServletRequest request, final String rawResourceSignature, final String propertyView) throws FrameworkException {
    final ResourceAccess resourceAccess = ResourceAccess.findGrant(securityContext, rawResourceSignature);
    final Method method = methods.get(request.getMethod());
    final Principal user = securityContext.getUser(false);
    final boolean validUser = (user != null);
    // super user is always authenticated
    if (validUser && (user instanceof SuperUser || user.isAdmin())) {
        return;
    }
    // no grants => no access rights
    if (resourceAccess == null) {
        logger.info("No resource access grant found for signature {}. (URI: {})", new Object[] { rawResourceSignature, securityContext.getCompoundRequestURI() });
        throw new UnauthorizedException("Forbidden");
    } else {
        switch(method) {
            case GET:
                if (!validUser && resourceAccess.hasFlag(NON_AUTH_USER_GET)) {
                    return;
                }
                if (validUser && resourceAccess.hasFlag(AUTH_USER_GET)) {
                    return;
                }
                break;
            case PUT:
                if (!validUser && resourceAccess.hasFlag(NON_AUTH_USER_PUT)) {
                    return;
                }
                if (validUser && resourceAccess.hasFlag(AUTH_USER_PUT)) {
                    return;
                }
                break;
            case POST:
                if (!validUser && resourceAccess.hasFlag(NON_AUTH_USER_POST)) {
                    return;
                }
                if (validUser && resourceAccess.hasFlag(AUTH_USER_POST)) {
                    return;
                }
                break;
            case DELETE:
                if (!validUser && resourceAccess.hasFlag(NON_AUTH_USER_DELETE)) {
                    return;
                }
                if (validUser && resourceAccess.hasFlag(AUTH_USER_DELETE)) {
                    return;
                }
                break;
            case OPTIONS:
                if (!validUser && resourceAccess.hasFlag(NON_AUTH_USER_OPTIONS)) {
                    return;
                }
                if (validUser && resourceAccess.hasFlag(AUTH_USER_OPTIONS)) {
                    return;
                }
                break;
            case HEAD:
                if (!validUser && resourceAccess.hasFlag(NON_AUTH_USER_HEAD)) {
                    return;
                }
                if (validUser && resourceAccess.hasFlag(AUTH_USER_HEAD)) {
                    return;
                }
                break;
        }
    }
    logger.info("Resource access grant found for signature {}, but method {} not allowed for {}.", new Object[] { rawResourceSignature, method, validUser ? "authenticated users" : "public users" });
    throw new UnauthorizedException("Forbidden");
}
Also used : ResourceAccess(org.structr.core.entity.ResourceAccess) UnauthorizedException(org.structr.core.auth.exception.UnauthorizedException) SuperUser(org.structr.core.entity.SuperUser) Principal(org.structr.core.entity.Principal)

Example 4 with SuperUser

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

the class AuthHelper method getPrincipalForPassword.

/**
 * Find a {@link Principal} with matching password and given key or name
 *
 * @param key
 * @param value
 * @param password
 * @return principal
 * @throws AuthenticationException
 */
public static Principal getPrincipalForPassword(final PropertyKey<String> key, final String value, final String password) throws AuthenticationException {
    String errorMsg = null;
    Principal principal = null;
    final String superuserName = Settings.SuperUserName.getValue();
    final String superUserPwd = Settings.SuperUserPassword.getValue();
    if (StringUtils.isEmpty(value)) {
        logger.info("Empty value for key {}", key);
        errorMsg = STANDARD_ERROR_MSG;
    }
    if (StringUtils.isEmpty(password)) {
        logger.info("Empty password");
        errorMsg = STANDARD_ERROR_MSG;
    }
    if (superuserName.equals(value) && superUserPwd.equals(password)) {
        // logger.info("############# Authenticated as superadmin! ############");
        principal = new SuperUser();
    } else if (errorMsg == null) {
        try {
            principal = StructrApp.getInstance().nodeQuery(Principal.class).and().or(key, value).or(AbstractNode.name, value).disableSorting().getFirst();
            if (principal == null) {
                logger.info("No principal found for {} {}", new Object[] { key.dbName(), value });
                errorMsg = STANDARD_ERROR_MSG;
            } else {
                if (principal.isBlocked()) {
                    logger.info("Principal {} is blocked", principal);
                    errorMsg = STANDARD_ERROR_MSG;
                }
                if (StringUtils.isEmpty(password)) {
                    logger.info("Empty password for principal {}", principal);
                    errorMsg = "Empty password, should never happen here!";
                } else {
                    // let Principal decide how to check password
                    if (!principal.isValidPassword(password)) {
                        errorMsg = STANDARD_ERROR_MSG;
                    }
                }
            }
        } catch (FrameworkException fex) {
            logger.warn("", fex);
        }
    }
    if (errorMsg != null) {
        throw new AuthenticationException(errorMsg);
    }
    return principal;
}
Also used : FrameworkException(org.structr.common.error.FrameworkException) AuthenticationException(org.structr.core.auth.exception.AuthenticationException) SuperUser(org.structr.core.entity.SuperUser) Principal(org.structr.core.entity.Principal)

Example 5 with SuperUser

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

the class ScriptingTest method testNonPrimitiveReturnValue.

@Test
public void testNonPrimitiveReturnValue() {
    try (final Tx tx = app.tx()) {
        app.create(SchemaMethod.class, new NodeAttribute<>(SchemaMethod.name, "testReturnValueOfGlobalSchemaMethod"), new NodeAttribute<>(SchemaMethod.source, "{ return { name: 'test', value: 123, me: Structr.me }; }"));
        app.create(SchemaProperty.class, new NodeAttribute<>(SchemaProperty.schemaNode, app.create(SchemaNode.class, new NodeAttribute<>(SchemaNode.name, "Test"))), new NodeAttribute<>(SchemaProperty.name, "returnTest"), new NodeAttribute<>(SchemaProperty.propertyType, "Function"), new NodeAttribute<>(SchemaProperty.readFunction, "{ return { name: 'test', value: 123, me: Structr.this }; }"));
        tx.success();
    } catch (FrameworkException fex) {
        fex.printStackTrace();
        fail("Unexpected exception.");
    }
    try (final Tx tx = app.tx()) {
        final ActionContext ctx = new ActionContext(securityContext, null);
        final Map map = (Map) Scripting.evaluate(ctx, null, "${{return Structr.call('testReturnValueOfGlobalSchemaMethod')}}", "test");
        final Object name = map.get("name");
        final Object value = map.get("value");
        final Object me = map.get("me");
        assertEquals("Invalid non-primitive scripting return value result, name should be of type string.", "test", name);
        assertEquals("Invalid non-primitive scripting return value result, value should be of type integer", Integer.valueOf(123), value);
        assertTrue("Invalid non-primitive scripting return value result,   me should be of type SuperUser", me instanceof SuperUser);
        tx.success();
    } catch (UnlicensedException | FrameworkException fex) {
        fex.printStackTrace();
        fail("Unexpected exception.");
    }
    try (final Tx tx = app.tx()) {
        final Class type = StructrApp.getConfiguration().getNodeEntityClass("Test");
        final NodeInterface obj = app.create(type, "test");
        final Map map = (Map) obj.getProperty(StructrApp.key(type, "returnTest"));
        final Object name = map.get("name");
        final Object value = map.get("value");
        final Object me = map.get("me");
        assertEquals("Invalid non-primitive scripting return value result, name should be of type string.", "test", name);
        assertEquals("Invalid non-primitive scripting return value result, value should be of type integer", Integer.valueOf(123), value);
        assertEquals("Invalid non-primitive scripting return value result, me should be the entity", obj, me);
        tx.success();
    } catch (FrameworkException fex) {
        fex.printStackTrace();
        fail("Unexpected exception.");
    }
}
Also used : UnlicensedException(org.structr.common.error.UnlicensedException) Tx(org.structr.core.graph.Tx) FrameworkException(org.structr.common.error.FrameworkException) GraphObject(org.structr.core.GraphObject) ActionContext(org.structr.schema.action.ActionContext) Map(java.util.Map) PropertyMap(org.structr.core.property.PropertyMap) SuperUser(org.structr.core.entity.SuperUser) NodeInterface(org.structr.core.graph.NodeInterface) StructrTest(org.structr.common.StructrTest) Test(org.junit.Test)

Aggregations

SuperUser (org.structr.core.entity.SuperUser)8 Principal (org.structr.core.entity.Principal)7 SecurityContext (org.structr.common.SecurityContext)3 FrameworkException (org.structr.common.error.FrameworkException)3 AuthenticationException (org.structr.core.auth.exception.AuthenticationException)2 UnauthorizedException (org.structr.core.auth.exception.UnauthorizedException)2 ResourceAccess (org.structr.core.entity.ResourceAccess)2 Tx (org.structr.core.graph.Tx)2 Map (java.util.Map)1 CmisUnauthorizedException (org.apache.chemistry.opencmis.commons.exceptions.CmisUnauthorizedException)1 Test (org.junit.Test)1 StructrTest (org.structr.common.StructrTest)1 UnlicensedException (org.structr.common.error.UnlicensedException)1 GraphObject (org.structr.core.GraphObject)1 Services (org.structr.core.Services)1 App (org.structr.core.app.App)1 StructrApp (org.structr.core.app.StructrApp)1 NodeInterface (org.structr.core.graph.NodeInterface)1 PropertyMap (org.structr.core.property.PropertyMap)1 ActionContext (org.structr.schema.action.ActionContext)1