package com.ruoyi.framework.web.service;
|
|
import com.ruoyi.common.constant.Constants;
|
import com.ruoyi.common.core.domain.entity.SysUser;
|
import com.ruoyi.common.core.domain.model.LoginUser;
|
import com.ruoyi.framework.manager.AsyncManager;
|
import com.ruoyi.framework.manager.factory.AsyncFactory;
|
import com.ruoyi.framework.security.QyWechatAuthenticationToken;
|
import com.ruoyi.system.service.ISysUserService;
|
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.security.authentication.AuthenticationManager;
|
import org.springframework.security.authentication.BadCredentialsException;
|
import org.springframework.security.core.Authentication;
|
import org.springframework.stereotype.Component;
|
|
/**
|
* 企业微信登录校验方法
|
* 类似于SysLoginService
|
*
|
* @author ruoyi
|
*/
|
@Component
|
public class QyWechatLoginService
|
{
|
@Autowired
|
private TokenService tokenService;
|
|
@Autowired
|
private AuthenticationManager authenticationManager;
|
|
@Autowired
|
private SysLoginService sysLoginService;
|
|
@Autowired
|
private ISysUserService userService;
|
|
/**
|
* 企业微信用户ID登录验证
|
*
|
* @param qyUserId 企业微信用户ID
|
* @param corpId 企业微信CorpID
|
* @return token
|
*/
|
public String loginByQyUserId(String qyUserId, String corpId)
|
{
|
try
|
{
|
qyUserId = "qywechat__"+qyUserId;
|
// 创建企业微信认证Token
|
QyWechatAuthenticationToken authenticationToken = new QyWechatAuthenticationToken(qyUserId, corpId);
|
|
// 使用AuthenticationManager进行认证
|
Authentication authentication = authenticationManager.authenticate(authenticationToken);
|
|
// 认证成功,获取LoginUser
|
LoginUser loginUser = (LoginUser) authentication.getPrincipal();
|
|
// 记录登录成功日志
|
AsyncManager.me().execute(AsyncFactory.recordLogininfor(
|
loginUser.getUsername(),
|
Constants.LOGIN_SUCCESS,
|
"企业微信用户ID登录成功"));
|
|
// 记录登录信息(IP和时间)
|
sysLoginService.recordLoginInfo(loginUser.getUserId());
|
|
// 生成token
|
return tokenService.createToken(loginUser);
|
}
|
catch (BadCredentialsException e)
|
{
|
// 记录登录失败日志
|
AsyncManager.me().execute(AsyncFactory.recordLogininfor(
|
qyUserId,
|
Constants.LOGIN_FAIL,
|
e.getMessage()));
|
throw e;
|
}
|
catch (Exception e)
|
{
|
// 记录登录失败日志
|
AsyncManager.me().execute(AsyncFactory.recordLogininfor(
|
qyUserId,
|
Constants.LOGIN_FAIL,
|
e.getMessage()));
|
throw new BadCredentialsException(e.getMessage());
|
}
|
}
|
}
|