package com.atlassian.stash.internal.spring.security;

import com.atlassian.bitbucket.auth.HttpAuthenticationContext;
import com.atlassian.stash.internal.auth.DefaultHttpAuthenticationContext;
import com.atlassian.bitbucket.scm.AuthenticationState;
import org.springframework.security.authentication.AbstractAuthenticationToken;

import static com.google.common.base.Preconditions.checkNotNull;

public class HttpAuthenticationContextToken extends AbstractAuthenticationToken {

    private final transient DefaultHttpAuthenticationContext context;

    public HttpAuthenticationContextToken(DefaultHttpAuthenticationContext context) {
        super(null);

        this.context = checkNotNull(context, "context");
    }

    public HttpAuthenticationContext getContext() {
        return context;
    }

    @Override
    public Object getCredentials() {
        return context != null ? context.getCredentials() : null;
    }

    @Override
    public Object getPrincipal() {
        return context != null ? context.getUsername() : null;
    }

    @Override
    public boolean isAuthenticated() {
        return context != null && context.isAuthenticated();
    }

    @Override
    public void setAuthenticated(boolean authenticated) {
        if (context != null) {
            context.setAuthenticationState(AuthenticationState.AUTHENTICATED);
        }
    }
}
