package org.jboss.as.web.security;

import java.io.IOException;
import java.security.Principal;

import javax.servlet.ServletException;

import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.Response;
import org.apache.catalina.valves.ValveBase;
import org.jboss.security.SecurityContext;
import org.jboss.security.SimplePrincipal;
import org.jboss.security.SubjectInfo;

public class SubjectInfoSetupValve extends ValveBase {

    @Override
    public void invoke(Request request, Response response) throws IOException, ServletException {

        Principal principal = request.getPrincipal();
        if (principal != null && principal instanceof JBossGenericPrincipal) {
            JBossGenericPrincipal jbossPrincipal = (JBossGenericPrincipal) principal;
            SecurityContext context = SecurityActions.getSecurityContext();
            if (context != null) {
                // we have a context, check if subject info has been properly set.
                SubjectInfo subjectInfo = context.getSubjectInfo();
                if (subjectInfo == null || subjectInfo.getAuthenticatedSubject() == null) {
                    context.getUtil().createSubjectInfo(new SimplePrincipal(jbossPrincipal.getName()), jbossPrincipal.getCredentials(),
                            jbossPrincipal.getSubject());
                }
            }
        }

        getNext().invoke(request, response);
    }
}