package com.lutao.cloud.common.security.sso;

import com.lutao.cloud.common.security.component.CloudPreAuthenticationChecks;
import com.lutao.cloud.common.security.service.CloudUserDetailsService;
import com.lutao.cloud.common.security.util.CloudSecurityMessageSourceUtil;
import lombok.Getter;
import lombok.Setter;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsChecker;

/**

 * 登录校验逻辑 验证码登录、社交登录
 */
@Slf4j
public class SSOAuthenticationProvider implements AuthenticationProvider {

	private MessageSourceAccessor messages = CloudSecurityMessageSourceUtil.getAccessor();

	private UserDetailsChecker detailsChecker = new CloudPreAuthenticationChecks();

	@Getter
	@Setter
	private CloudUserDetailsService userDetailsService;

	@Override
	@SneakyThrows
	public Authentication authenticate(Authentication authentication) {
		SSOAuthenticationToken ssoAuthenticationToken = (SSOAuthenticationToken) authentication;

		String principal = ssoAuthenticationToken.getPrincipal().toString();
		UserDetails userDetails = userDetailsService.loadUserByUsername(principal);
		if (userDetails == null) {
			log.debug("Authentication failed: no credentials provided");

			throw new BadCredentialsException(messages
					.getMessage("AbstractUserDetailsAuthenticationProvider.noopBindAccount", "Noop Bind Account"));
		}

		// 检查账号状态
		detailsChecker.check(userDetails);

		SSOAuthenticationToken authenticationToken = new SSOAuthenticationToken(userDetails,
				userDetails.getAuthorities());
		authenticationToken.setTicket(ssoAuthenticationToken.getTicket());
		authenticationToken.setDetails(ssoAuthenticationToken.getDetails());
		return authenticationToken;
	}

	@Override
	public boolean supports(Class<?> authentication) {
		return SSOAuthenticationToken.class.isAssignableFrom(authentication);
	}
}