package com.persagy.dmp.auth.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.symmetric.AES;
import com.alibaba.fastjson.JSONObject;
import com.persagy.dmp.common.context.AppContext;
import com.persagy.dmp.common.helper.SpringHelper;
import lombok.extern.slf4j.Slf4j;

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

/**
 * BOSS 鉴权实现类
 * 校验token，并从token中获取上下文信息
 * @author Charlie Yu
 * @date 2021-11-02
 */
@Slf4j
public class BossAuthServiceImpl extends AbstractAuthServiceImpl{

    @Override
    public boolean validateLogin(HttpServletRequest request, HttpServletResponse response) {
        // 获取token
        String token = request.getHeader("token");
        if(StrUtil.isBlank(token)) {
            log.error("未获取到token!");
            return false;
        }
        return super.validateLogin(request, response);
    }

    @Override
    public void loginSuccess(HttpServletRequest request, HttpServletResponse response) {
        // 解析token对象
        JSONObject info = getTokenInfo(request.getHeader("token"));
        // 回写上下文
        AppContext.getContext().setGroupCode(info.getString(AppContext.GROUP_CODE));
        AppContext.getContext().setProjectId(info.getString(AppContext.PROJECT_ID));
        AppContext.getContext().setAppId(info.getString(AppContext.APP_ID));
        AppContext.getContext().setAccountId(info.getString(AppContext.ACCOUNT_ID));
    }

    /**
     * 解析token对象
     * @param token
     * @return
     */
    private JSONObject getTokenInfo(String token) {
        // 获取配置密钥
        String accessKey = SpringHelper.getString("persagy.common.token.key", "63499E35378AE1B0733E3FED7F780B68");
        String accessSecret = SpringHelper.getString("persagy.common.token.secret", "C0E7BD39B52A15C7");
        // 解析token
        AES aes = new AES("CBC","PKCS7Padding", accessKey.getBytes(), accessSecret.getBytes());
        String tokenObj = aes.decryptStr(token);
        return JSONObject.parseObject(tokenObj);
    }
}
