package com.yunfeiyun.agmp.common.framework.web.service;

import com.yunfeiyun.agmp.common.core.domain.model.IBaseUser;
import com.yunfeiyun.agmp.common.core.domain.model.LoginUser;
import com.yunfeiyun.agmp.common.utils.SecurityUtils;
import com.yunfeiyun.agmp.common.utils.spring.SpringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;

import java.util.Set;

@Component
public class SSoAuthenticationProvider implements AuthenticationProvider {

    private static final Logger log = LoggerFactory.getLogger(SSoAuthenticationProvider.class);


    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = authentication.getName();
        IBaseUser user =  SpringUtils.getBean(ISysUserService.class).selectUserByUserName(username);
        String presentedPassword = authentication.getCredentials().toString();
        log.info("需要认证的 账户={} 提交密码={}",username,presentedPassword);
        Set<String>  permissions = SpringUtils.getBean(SysPermissionService.class).getMenuPermission(user);
        UserDetails userDetails = new LoginUser(user.getUserId(), user.getDeptId(), user , permissions);
        log.info("密码校验测试={} 权限信息={}",SecurityUtils.matchesPassword(presentedPassword, userDetails.getPassword()) + "" , permissions);

        UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(userDetails, authentication.getCredentials(), userDetails.getAuthorities());

        UserDetails userDetails2 = SpringUtils.getBean(UserDetailsService.class).loadUserByUsername(username);
        result.setDetails(userDetails2);
        return result;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return true;
    }
}
