package ink.wgink.login.oauth2.server.converter;

import com.alibaba.fastjson.JSONObject;
import ink.wgink.pojo.bos.LoginUser;
import ink.wgink.pojo.bos.UserInfoBO;
import ink.wgink.service.user.service.IUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.oauth2.provider.token.UserAuthenticationConverter;

import java.util.*;

/**
 * @ClassName: UserAuthConverter
 * @Description: 重写用户认证
 * @Author: WangGeng
 * @Date: 2019/2/27 4:57 PM
 * @Version: 1.0
 **/
public class UserAuthConverter implements UserAuthenticationConverter {

    private static final Logger LOG = LoggerFactory.getLogger(UserAuthConverter.class);
    private IUserService userService;

    public UserAuthConverter() {
    }

    @Override
    public Map<String, ?> convertUserAuthentication(Authentication authentication) {
        Map<String, Object> response = new LinkedHashMap<>();
        response.put("user_name", authentication.getName());
        response.put("authorities", authentication.getAuthorities());
        // 删除token中的权限信息，通过客户端请求获取，减少accessToken长度
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        // 传递登录用户
        UserInfoBO userInfoBO = new UserInfoBO();
        userInfoBO.setUserId(loginUser.getUserId());
        userInfoBO.setUserUsername(loginUser.getUsername());
        userInfoBO.setUserName(loginUser.getUserName());
        userInfoBO.setUserPhone(loginUser.getUserPhone());
        userInfoBO.setUserAvatar(loginUser.getUserAvatar());
        userInfoBO.setUserEmail(loginUser.getUserEmail());
        userInfoBO.setRoles(loginUser.getRoles());
        userInfoBO.setDepartments(loginUser.getDepartments());
        userInfoBO.setGroups(loginUser.getGroups());
        userInfoBO.setPositions(loginUser.getPositions());
        userInfoBO.setExpandData(loginUser.getExpandData());
        response.put("user_info", JSONObject.toJSONString(userInfoBO));
        return response;
    }

    @Override
    public Authentication extractAuthentication(Map<String, ?> map) {
        // 解析客户端的权限请求
        Object principal = map.get("user_name");
        if (!Objects.isNull(principal)) {
            Collection<GrantedAuthority> authorities = new ArrayList<>();
            // 包含用户信息，则直接抽取其中的用户信息
            UserInfoBO userInfoBO = JSONObject.parseObject(map.get("user_info").toString(), UserInfoBO.class);
            principal = userInfoBO;
            LOG.debug("获取用户权限");
            return new UsernamePasswordAuthenticationToken(principal, "N/A", authorities);
        }
        return null;
    }

    public IUserService getUserService() {
        return userService;
    }

    public void setUserService(IUserService userService) {
        this.userService = userService;
    }
}
