package spring.security;

import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;
import org.apache.tomcat.util.descriptor.web.SecurityCollection;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class SecurityFormApplication {

    public static void main(String[] args) {
        SpringApplication.run(SecurityFormApplication.class, args);
    }

    @Bean
    public ServletWebServerFactory servletContainer(){
        // Enable SSL Traffic
        TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory(){
            @Override
            protected void postProcessContext(Context context) {
                SecurityConstraint securityConstraint = new SecurityConstraint();
                securityConstraint.setUserConstraint("CONFIDENTIAL");
                SecurityCollection collection = new SecurityCollection();
                collection.addPattern("/*");
                securityConstraint.addCollection(collection);
                context.addConstraint(securityConstraint);
            }
        };

        // Add HTTP to HTTPS redirect
        tomcat.addAdditionalTomcatConnectors(httpToHttpRedirectConnector());
        return tomcat;
    }

    /*
    *  We need redirect from HTTP to HTTPS. Without SSL, this application used port 8082. With SSL it will use port 8443.
    *  SO, any request for 8090 needs to be redirected to HTTPS on 8443.
    * */

    private Connector httpToHttpRedirectConnector(){
        Connector connector = new Connector(TomcatServletWebServerFactory.DEFAULT_PROTOCOL);
        connector.setScheme("http");
        connector.setPort(8080);
        connector.setSecure(false);
        connector.setRedirectPort(8443);
        return connector;
    }
}


/**1. localhost:8090/admin --> https://localhost:8443/login
 * 2. Login page
 * 3.
 * Start will be initliaze https://localhost:8443/login
 * **/

