package <%= packageName %>.security;

import <%= packageName %>.security.jwt.TokenProvider;
import org.jeecg.modules.jmreport.api.JmReportTokenServiceI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

import static <%= packageName %>.security.jwt.JWTFilter.AUTHORIZATION_HEADER;

/**
 * 自定义积木报表鉴权(如果不进行自定义，则所有请求不做权限控制)
 *  * 1.自定义获取登录token
 *  * 2.自定义获取登录用户
 */
@Service
public class JimuReportTokenService implements JmReportTokenServiceI {

    @Autowired
    private TokenProvider tokenProvider;

    @Override
    public String getToken(HttpServletRequest request) {
        String token = request.getParameter("token");
        if (token == null) {
            token = request.getHeader("X-Access-Token");
        }
        if (token == null) {
            String bearerToken = request.getHeader(AUTHORIZATION_HEADER);
            if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
                token = bearerToken.substring(7);
            }
        }
        return token;
    }

    @Override
    public String getUsername(String token) {
        return tokenProvider.getAuthentication(token).getPrincipal().toString();
    }

    @Override
    public Boolean verifyToken(String token) {
        return tokenProvider.validateToken(token);
    }

    @Override
    public Map<String, Object> getUserInfo(String token) {
        MyUserDetails userDetails = (MyUserDetails) tokenProvider.getAuthentication(token).getDetails();
        //此处通过token只能拿到一个信息 用户账号  后面的就是根据账号获取其他信息 查询数据或是走redis 用户根据自身业务可自定义
        Map<String, Object> map = new HashMap<>();
        //设置账号名
        map.put(SYS_USER_CODE, userDetails.getUsername());
        //设置部门编码
        map.put(SYS_ORG_CODE, null);
        // 将所有信息存放至map 解析sql/api会根据map的键值解析
        return map;
    }
}
