package com.atlassian.stash.internal.user;

import com.atlassian.bitbucket.user.SecurityService;
import org.springframework.security.authentication.AuthenticationTrustResolverImpl;
import org.springframework.security.core.Authentication;

/**
 * Extending Spring's {@link AuthenticationTrustResolverImpl} to check correctly for anonymous access due to non-null
 * {@link StashUserAuthenticationToken authentication} when using {@link SecurityService#withPermission}.
 * <p>
 * Note that this isn't used in {@link org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestWrapper},
 * which checks for anonymous authentication before returning the non-null object. Because the principal is also checked
 * for null this shouldn't be a problem.
 *
 * @since 2.5
 */
public class ExtendedAuthenticationTrustResolver extends AuthenticationTrustResolverImpl {

    public boolean isAnonymous(Authentication authentication) {
        if (authentication instanceof StashUserAuthenticationToken) {
            return ((StashUserAuthenticationToken) authentication).getPrincipal() == null;
        }
        return super.isAnonymous(authentication);
    }
}
