package com.example.demo.controller;

import com.example.demo.pojo.UserInfo;
import org.jasig.cas.client.validation.Assertion;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 功能描述：
 * 修改记录:
 * <pre>
 * 修改时间：
 * 修改人：
 * 修改内容：
 * </pre>
 *
 * @title TestController
 * @Author: de
 * @Date: 2020/11/10
 */
@Controller
public class TestController {

    @Value("${cas.server-url-prefix}")
    private String serverUrlPrefix;

    @Value("${cas.client-host-url}")
    private String clientHostUrl;

    private static final Logger LOGGER = LoggerFactory.getLogger(TestController.class);
    /**
     * cas client 默认的session key
     */
    public final static String CAS = "_const_cas_assertion_";

    @RequestMapping("/index")
    public String index(HttpServletRequest request) {
        return "index";
    }


    @RequestMapping("/hello")
    public String hello(HttpServletRequest request) {
        request.setAttribute("user", this.getUserInfoFromCas(request));
        return "hello";
    }

    @RequestMapping("/logout")
    public void logout(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String logoutUrl = serverUrlPrefix + "/logout?service=" + clientHostUrl + "/demo/hello";
        response.sendRedirect(logoutUrl);
    }

    /**
     * 封装UserInfo
     *
     * @param request
     * @return
     */
    private UserInfo getUserInfoFromCas(HttpServletRequest request) {
        Object object = request.getSession().getAttribute(CAS);
        if (null == object) {
            return null;
        }
        Assertion assertion = (Assertion) object;

        return this.buildUserInfoByCas(assertion);
    }

    private UserInfo buildUserInfoByCas(Assertion assertion) {
        if (null == assertion) {
            LOGGER.error("cas对接buildUserInfoByCas没有获取到用户");
            return null;
        }
        UserInfo userInfo = new UserInfo();
        String userName = assertion.getPrincipal().getName();
        LOGGER.info("cas对接登录用户buildUserInfoByCas：" + userName);
        userInfo.setUid(userName);
        //获取属性值
        Map<String, Object> map = assertion.getPrincipal().getAttributes();
        Object name = map.get("cn");
        Object TelephoneNumber = map.get("TelephoneNumber");
        userInfo.setUserName(name == null ? userName : name.toString());
        userInfo.setMap(map);
        return userInfo;
    }
}
