Newer
Older
casic-callcenter-xz / casic-web / src / main / java / com / casic / missiles / controller / CardLoginController.java
liwenhao on 2 Mar 2023 6 KB 徐州呼叫中心代码提交
package com.casic.missiles.controller;

import com.casic.missiles.core.base.controller.BaseController;
import com.casic.missiles.core.base.response.ResponseData;
import com.casic.missiles.core.common.constant.Const;
import com.casic.missiles.core.log.LogManager;
import com.casic.missiles.core.log.factory.LogTaskFactory;
import com.casic.missiles.core.shiro.ShiroKit;
import com.casic.missiles.core.shiro.ShiroUser;
import com.casic.missiles.core.util.RSAUtils;
import com.casic.missiles.core.util.ToolUtil;
import com.casic.missiles.modular.constant.PermissionContant;
import com.casic.missiles.modular.system.model.User;
import com.casic.missiles.modular.system.service.IUserService;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.jasig.cas.client.authentication.AttributePrincipal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Serializable;
import java.security.NoSuchAlgorithmException;
import java.security.Principal;
import java.util.Map;

/**
 * 仅为mock登录使用
 */
@Controller
@RequestMapping("/app")
public class CardLoginController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(CardLoginController.class);
    @Autowired
    private HttpSession session;
    @Autowired
    private IUserService userService;
    public static final String HOST_8083 = "/callcenter/#/?sid=";
    @Value("${casic.web.host:http://10.18.0.94:8083}")
    private String webHost;
    @Value("${casic.sync.recRoleTips:monitor,receiver,administrator,dispatcher}")
    private String recRoleTips;
    @Value("${casic.sync.ssoLoginHost}")
    private String ssoLoginHost;

    @GetMapping("/redirect")
    public String redirect(HttpServletRequest response) {
        return "redirect:../../index.html";
    }
    @Autowired
    private HttpSession session1;

    @GetMapping("/caslogin")
    public void caslogin(HttpServletRequest request, String systemName, HttpServletResponse response) throws IOException {
        Serializable shiroId = ShiroKit.getSession().getId();
        Object account = ShiroKit.getSession().getAttribute("login_account");
        if (ToolUtil.isNotEmpty(account)) {
            // 跳转到前端
            response.sendRedirect(webHost + "/callcenter/#/?sid=" + shiroId);
        } else {
            try {
                ShiroKit.getSubject().logout();
                response.setContentType("text/html; charset=utf8");
                PrintWriter out = response.getWriter();
//              Serializable token = login(request, username);
                out.print("<script>window.location.href=\"" + ssoLoginHost + "platform-sso-server/login?service=" + webHost + "/callcenter/api/app/token?sid=" + ShiroKit.getSession().getId() + "\";</script>");
                out.close();
            } catch (IOException e) {
                e.printStackTrace();

            }
        }
    }

    /**
     * cardByToken
     */
    @GetMapping("/token")
    @ResponseBody
    public Object cardByToken(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HttpSession session = request.getSession();
        if (session.getAttribute("casCasicLogin") != null) {
            response.sendRedirect(webHost + HOST_8083 + session.getId());
        }
        if (session.getAttribute("initFlag") == null) {
            Principal principal = request.getUserPrincipal();
            if (principal == null) {
                return ResponseData.error("为空");
            }
            AttributePrincipal attributePrincipal = (AttributePrincipal) principal;
            if (attributePrincipal == null || attributePrincipal.getAttributes().isEmpty()) {
                return ResponseData.error("为空");
            }
            String uid = String.valueOf(attributePrincipal.getAttributes().get("uid"));
            Object token = login(request, uid);
            session.setAttribute("casCasicLogin", true);
            response.sendRedirect(webHost + "/callcenter/#/?sid=" + token);
            return ResponseData.error(402, "未认证,请联系管理员", session.getId());
        } else {
            response.sendRedirect(webHost + "/callcenter/#/401");
            return ResponseData.error(402, "未认证,请联系管理员", session.getId());
        }
    }

    private Object login(HttpServletRequest request, String username) {
        super.getSession().setAttribute(PermissionContant.IS_APP, false);
        if (ToolUtil.isEmpty(username)) {
            return ResponseData.error("用户名不能为空");
        }
        Subject currentUser = ShiroKit.getSubject();

        try {
            Map<String, String> key = RSAUtils.genKeyPair();
            ShiroKit.getSession().setAttribute(PermissionContant.PRIVATE_KEY, key.get(RSAUtils.RSAPrivateKey));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        User user = userService.getByAccount(username);
        if (user == null) {
            return ResponseData.error(402, "该账户暂未同步,请联系管理员");
        }

        //查询用户名密码
        UsernamePasswordToken token = new UsernamePasswordToken(user.getAccount(), Const.DEFAULT_PWD.toCharArray());
        token.setRememberMe(false);
        try {
            currentUser.login(token);

        } catch (Exception e) {
            e.printStackTrace();
        }
        ShiroUser shiroUser = ShiroKit.getUser();
        super.getSession().setAttribute("shiroUser", shiroUser);
        super.getSession().setAttribute("username", shiroUser.getAccount());
        String devId = null;
        if (ToolUtil.isNotEmpty(shiroUser.getDevices())) {
            devId = shiroUser.getDevices().get(0).getImei();
        }

//        LogFactory.createLoginLog(LogType.LOGIN, shiroUser.getId(), "登录成功", null);
        super.getSession().setAttribute(PermissionContant.SESSION_KEY, shiroUser.getId());

        LogManager.me().executeLog(LogTaskFactory.loginLog(shiroUser.getId(), devId));

        return ShiroKit.getSession().getId().toString();
    }
}