Newer
Older
newfiber-data-adapter / src / main / java / org / springnewfiber / dataadapter / ziguang / common / LoginAction.java
package org.springnewfiber.dataadapter.ziguang.common;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.ImmutableMap;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springnewfiber.dataadapter.config.BladeRedis;

import javax.annotation.PostConstruct;
import java.time.Duration;
import java.util.Map;

/**
 * @program: newfiber-data-adapter
 * @description:
 * @author: djt
 * @create: 2022-01-18 17:00
 **/
@Component
@Slf4j
@AllArgsConstructor
public class LoginAction {
    private final static String username = "username";
    private final static String password = "password";
    private final static String tokenKey = "X-Auth-Token";
    private final static String Bearer = "Bearer";
    private final static String ziguangToken = "ziguang:token";
    private final ZiGuangConfig ziGuangConfig;
    private final BladeRedis bladeRedis;

    @PostConstruct
    public void loginAction() {
        HttpRequest.setGlobalTimeout(300000);
        if (!bladeRedis.exists(ziguangToken)) {
            HttpRequest request = HttpUtil.createPost(ziGuangConfig.getLogin().getLoginurl());
            request.body(JSONObject.toJSONString(ImmutableMap.of(username, ziGuangConfig.getLogin().getUsername(), password, ziGuangConfig.getLogin().getPassword())));
            HttpResponse response = request.execute();
            Map<String, Object> resultMap = BeanUtil.beanToMap(JSONObject.parse(response.body()));
            String code = resultMap.get("code").toString();
            if (StringUtils.equalsIgnoreCase("0", code)) {
                bladeRedis.setEx(ziguangToken, response.header(tokenKey), Duration.ofHours(2L));
            }
            log.info(response.body());
        }
    }

    /**
     * 构建token
     *
     * @return
     */
    public String buildAuthorizationToken() {
        if (bladeRedis.exists(ziguangToken)) {
            return Bearer.concat(" ").concat(bladeRedis.get(ziguangToken));
        } else {
            loginAction();
        }
        return buildAuthorizationToken();
    }

    /**
     * 构建url,post请求,并加权限
     *
     * @param url
     * @return
     */
    public HttpRequest getPostAuthRequest(String url) {
        HttpRequest request = HttpUtil.createPost(url);
        request.auth(buildAuthorizationToken());
        return request;
    }


}