package com.cmeeting.ad.util;

import com.cmeeting.ad.entity.RobotSecurityUser;
import lombok.experimental.UtilityClass;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * @Classname SecurityUtil
 * @Description 安全服务工具类
 * @Author robot
 * @Date 2019-05-08 10:12
 * @Version 1.0
 */
@UtilityClass

public class SecurityUtil {

//    public void writeJavaScript(R r, HttpServletResponse response) throws IOException {
//        response.setStatus(200);
//        response.setCharacterEncoding("UTF-8");
//        response.setContentType("application/json; charset=utf-8");
//        PrintWriter printWriter = response.getWriter();
//        printWriter.write(JSON.toJSONString(r));
//        printWriter.flush();
//    }

    /**
     * 获取Authentication
     */
    private Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * 获取用户
     *
     * @return
     */
    public RobotSecurityUser getUser() {
        try {
            return (RobotSecurityUser) getAuthentication().getPrincipal();
        } catch (Exception e) {
            throw new RuntimeException("登录状态过期");
        }
    }

    /**
     * 获取租户信息
     *
     * @return
     */
    public String getTenantId() {
        return getUser().getTenantId();
    }

    public void setUser(RobotSecurityUser robotSecurityUser) {
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(robotSecurityUser, null, robotSecurityUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
    }

}
