package com.lantone.userauth.service.impl;

import com.lantone.common.api.CommonResult;
import com.lantone.common.constant.AuthConstant;
import com.lantone.common.domain.UserDto;
import com.lantone.userauth.constant.MessageConstant;
import com.lantone.userauth.domain.SecurityUser;
import com.lantone.userauth.service.UserManagemenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

/**
 * @Description: 用户管理业务类
 * @author: rengb
 * @time: 2021/1/5 18:27
 */
@Service
public class UserServiceImpl implements UserDetailsService {

    @Autowired
    private UserManagemenService userManagemenService;
    @Autowired
    private HttpServletRequest request;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        String clientId = request.getParameter("client_id");
        UserDto userDto = null;
        if (AuthConstant.SECURITY_CENTER_CLIENT_ID.equals(clientId)) {
            CommonResult<UserDto> result = userManagemenService.loadUserByUsername(username);
            userDto = result.getData();
        }
        if (userDto == null) {
            throw new UsernameNotFoundException(MessageConstant.USERNAME_PASSWORD_ERROR);
        }
        userDto.setClientId(clientId);
        SecurityUser securityUser = new SecurityUser(userDto);
        if (!securityUser.isEnabled()) {
            throw new DisabledException(MessageConstant.ACCOUNT_DISABLED);
        } else if (!securityUser.isAccountNonLocked()) {
            throw new LockedException(MessageConstant.ACCOUNT_LOCKED);
        } else if (!securityUser.isAccountNonExpired()) {
            throw new AccountExpiredException(MessageConstant.ACCOUNT_EXPIRED);
        } else if (!securityUser.isCredentialsNonExpired()) {
            throw new CredentialsExpiredException(MessageConstant.CREDENTIALS_EXPIRED);
        }
        return securityUser;
    }

}