package eu.dnetlib.openaire.usermanagement;

import org.mitre.openid.connect.model.OIDCAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class OverviewServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        boolean isAuthenticated = !SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString()
                .equals("anonymousUser");

        if (isAuthenticated) {
            OIDCAuthenticationToken authentication = (OIDCAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();

            StringBuilder name = new StringBuilder().append(authentication.getUserInfo().getGivenName().charAt(0));
            name.append(authentication.getUserInfo().getFamilyName().charAt(0));
            request.getSession().setAttribute("authenticated", isAuthenticated);
            request.getSession().setAttribute("name", name.toString());
        }

        response.setContentType("text/html");
        request.getRequestDispatcher("./overview.jsp").include(request, response);
    }
}
