private static Session handleImpersonation()

in src/main/java/org/apache/sling/jcr/resource/internal/helper/jcr/JcrProviderStateFactory.java [194:224]


    private static Session handleImpersonation(final Session session, final Map<String, Object> authenticationInfo,
                                               final boolean logoutSession, boolean explicitSessionUsed) throws LoginException {
        final String sudoUser = getSudoUser(authenticationInfo);
        // Do we need session.impersonate() because we are asked to impersonate another user?
        boolean needsSudo = (sudoUser != null) && !session.getUserID().equals(sudoUser);
        // Do we need session.impersonate() to get an independent copy of the session we were given in the auth info?
        boolean needsCloning = !needsSudo && explicitSessionUsed && authenticationInfo.containsKey(ResourceProvider.AUTH_CLONE);
        if (!needsSudo && !needsCloning) {
            // Nothing to do, but we need to make sure not to enter the try-finally below because it could close the session.
            return session;
        }
        try {
            if (needsSudo) {
                SimpleCredentials creds = new SimpleCredentials(sudoUser, new char[0]);
                copyAttributes(creds, authenticationInfo);
                creds.setAttribute(ResourceResolver.USER_IMPERSONATOR, session.getUserID());
                return session.impersonate(creds);
            } else {
                assert needsCloning;
                SimpleCredentials creds = new SimpleCredentials(session.getUserID(), new char[0]);
                copyAttributes(creds, authenticationInfo);
                return session.impersonate(creds);
            }
        } catch (final RepositoryException re) {
            throw getLoginException(re);
        } finally {
            if (logoutSession) {
                session.logout();
            }
        }
    }