package com.yiboshi.science.config.security;

import com.yiboshi.science.service.SystemSetService;
import com.yiboshi.science.utils.SystemSetKey;
import org.springframework.security.oauth2.common.util.OAuth2Utils;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.OAuth2Request;
import org.springframework.security.oauth2.provider.token.DefaultAuthenticationKeyGenerator;

import java.util.*;

/**
 * @Auther: kylin
 * @Date: 2022/7/21 14:31
 * @Description: 重写token生成规则
 */

public class AuthenticationKeyGenerator extends DefaultAuthenticationKeyGenerator {
    private static final String CLIENT_ID = "client_id";
    private static final String SCOPE = "scope";
    private static final String USERNAME = "username";
    private static final String DEVICE_ID = "device_id";

    private SystemSetService systemSetService;

    public AuthenticationKeyGenerator(SystemSetService systemSetService) {
        this.systemSetService = systemSetService;
    }

    @Override
    public String extractKey(OAuth2Authentication authentication) {
        Map<String, String> values = new LinkedHashMap<String, String>();
        OAuth2Request authorizationRequest = authentication.getOAuth2Request();
        if (!authentication.isClientOnly()) {
            values.put(USERNAME, authentication.getName());
        }
        values.put(CLIENT_ID, authorizationRequest.getClientId());
        if (authorizationRequest.getScope() != null) {
            values.put(SCOPE, OAuth2Utils.formatParameterList(new TreeSet<String>(authorizationRequest.getScope())));
        }
        // 1允许同时登录一个账户 2 不允许同时登录有个账户
        String LoginType = systemSetService.getByKey(SystemSetKey.LoginType);
        if (LoginType.equals("1")) {
            String deviceId = authorizationRequest.getRequestParameters().get(DEVICE_ID);
            values.put("DEVICE_ID", Objects.nonNull(deviceId) ? deviceId : UUID.randomUUID().toString());
        }
        return generateKey(values);
    }
}