package com.njcn.product.auth.security.clientdetails;


import com.njcn.common.pojo.enums.auth.PasswordEncoderTypeEnum;

import com.njcn.common.pojo.response.HttpResult;
import com.njcn.product.auth.pojo.po.AuthClient;
import com.njcn.product.auth.service.IAuthClientService;
import lombok.RequiredArgsConstructor;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.NoSuchClientException;
import org.springframework.security.oauth2.provider.client.BaseClientDetails;
import org.springframework.stereotype.Service;

/**
 * OAuth2 客户端信息
 * @author hongawen
 */
@Service
@RequiredArgsConstructor
public class ClientDetailsServiceImpl implements ClientDetailsService {

    private final IAuthClientService authClientService;

    @Override
    public ClientDetails loadClientByClientId(String clientName) {
        try {
            AuthClient authClient = authClientService.getAuthClientByName(clientName);
            BaseClientDetails clientDetails = new BaseClientDetails(
                    authClient.getName(),
                    authClient.getResourceIds(),
                    authClient.getScope(),
                    authClient.getAuthorizedGrantTypes(),
                    authClient.getAuthorities(),
                    authClient.getWebServerRedirectUri()
            );
            clientDetails.setClientSecret(PasswordEncoderTypeEnum.BCRYPT.getPrefix() + authClient.getClientSecret());
            clientDetails.setAccessTokenValiditySeconds(authClient.getAccessTokenValidity());
            clientDetails.setRefreshTokenValiditySeconds(authClient.getRefreshTokenValidity());
            return clientDetails;
        } catch (EmptyResultDataAccessException var4) {
            throw new NoSuchClientException("No client with requested id: " + clientName);
        }
    }

    public static void main(String[] args) {
        PasswordEncoder delegatingPasswordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
        String njcnpqs = delegatingPasswordEncoder.encode("njcnpqs");
        //{bcrypt}$2a$10$xIP3g5Rc11zDdclsKXpQXuOobvZ9gaw2Mix1rkOm1MJN1.hTVY7ci
        System.out.println(njcnpqs);
        System.out.println(delegatingPasswordEncoder.matches("njcnpqs","{bcrypt}$2a$10$xIP3g5Rc11zDdclsKXpQXuOobvZ9gaw2Mix1rkOm1MJN1.hTVY7ci"));

    }
}
