package org.jeecg.modules.cas.controller;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jasig.cas.client.validation.Assertion;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>
 * CAS单点登录客户端登录认证
 * </p>
 *
 * @Author zhoujf
 * @since 2018-12-20
 */
@Slf4j
@RestController
@RequestMapping("/sys/cas/client")
public class CasClientController {
    @Value("${wellbore.redirect-url}")
    private String redirectUrl;

    @Value("${wellbore.redirect-cas-url}")
    private String redirectCasUrl;
    /**
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @GetMapping("/validateLogin")
    public Object validateLogin(HttpServletRequest request,
                                HttpServletResponse response) throws Exception {
        Result<JSONObject> result = new Result<JSONObject>();
        log.info("Rest api login.");
        try {
            final String principal = ((Assertion) request.getSession().getAttribute(CommonConstant.CAS_USER_SESSION_KEY)).getPrincipal().getName();
            if (StringUtils.isEmpty(principal)) {
                throw new Exception("No principal was found in the response from the CAS server.");
            }
            response.sendRedirect(redirectUrl);
        } catch (Exception e) {
            //e.printStackTrace();
            result.error500(e.getMessage());
        }
        return new HttpEntity<>(result);
    }

    @GetMapping("/redirect")
    public void redirectIframe(HttpServletRequest request,
                               HttpServletResponse response) throws Exception {
        response.sendRedirect(redirectCasUrl);
    }
}
