package com.cool.bang.core.secure.process;

import com.alibaba.druid.util.StringUtils;
import com.cool.bang.common.tools.servlet.ServletUtil;
import com.cool.bang.common.web.response.Result;
import com.cool.bang.modules.system.domain.po.Menu;
import com.cool.bang.modules.system.domain.po.User;
import com.cool.bang.modules.system.domain.vo.Token;
import com.cool.bang.modules.system.service.ITokenService;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 自定义 spring security 用户登录成功处理类
 *
 * @author PeiZhi Guo
 * 2021-2-18 14:50
 */
@Component
public class SecurityAccessSuccessHandler implements AuthenticationSuccessHandler {

    @Resource
    private ITokenService sysTokenService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                                        Authentication authentication) throws IOException {

        User user = (User) authentication.getPrincipal();
        Token token = sysTokenService.cacheAndReturnToken(user);

        Map<String, Object> map = new HashMap<>();
        map.put("accessToken", token.getAccessToken());
        map.put("permissions", user.getMenuList().parallelStream().filter(p -> !StringUtils.isEmpty(p.getCode()))
                .map(Menu::getCode).collect(Collectors.toSet()));

        ServletUtil.jsonWrite(Result.success("登录成功", map));
    }
}
