master
杜函宇 9 months ago
parent 35fd340695
commit 5b7a3e1c8f

@ -1,10 +1,13 @@
package com.ruoyi.pt.controller; package com.ruoyi.pt.controller;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController; import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult; import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.exception.ServiceException; import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils; import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.pt.entity.CaseInfo; import com.ruoyi.pt.entity.CaseInfo;
import com.ruoyi.pt.entity.CasesImport; import com.ruoyi.pt.entity.CasesImport;
import com.ruoyi.pt.entity.Events; import com.ruoyi.pt.entity.Events;
@ -38,6 +41,35 @@ public class AEventsController extends BaseController {
@Resource @Resource
private EventsService eventsService; private EventsService eventsService;
@Resource
private SysLoginService sysLoginService;
/**
* token
*/
@PostMapping("/login")
@ApiOperation(value = "登录获取token")
public AjaxResult login(@RequestBody LoginBody loginBody) {
AjaxResult ajax = AjaxResult.success();
// 生成令牌
String token = sysLoginService.login1(loginBody.getUsername(), loginBody.getPassword());
ajax.put(Constants.TOKEN, token);
return ajax;
}
/**
* apptoken
*/
@PostMapping("/appLogin")
@ApiOperation(value = "app登录获取token")
public AjaxResult appLogin(@RequestBody LoginBody loginBody) {
AjaxResult ajax = AjaxResult.success();
// 生成令牌
String token = sysLoginService.login2(loginBody.getUsername(), loginBody.getPassword());
ajax.put(Constants.TOKEN, token);
return ajax;
}
/** /**
* *
*/ */
@ -57,7 +89,6 @@ public class AEventsController extends BaseController {
} }
/** /**
* *
*/ */

@ -73,7 +73,7 @@ public class Events implements Serializable {
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@TableField(value = "firstWarnTime") @TableField(value = "firstWarnTime")
private Date firstWarnTime; private Date firstWarnTimeDate;
/** /**
* *
@ -82,7 +82,7 @@ public class Events implements Serializable {
@TableField(value = "eventTime") @TableField(value = "eventTime")
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date eventTime; private Date eventTimeDate;
/** /**
* *

@ -70,6 +70,7 @@ public interface AEventsMapper {
* casesImport退 * casesImport退
*/ */
int updateCasesImport(@Param("list") List<String> list, int updateCasesImport(@Param("list") List<String> list,
@Param("isReport") Integer isReport,
@Param("time") String time); @Param("time") String time);
/** /**

@ -28,11 +28,7 @@ import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource; import javax.annotation.Resource;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.ArrayList; import java.util.*;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/** /**
* *
@ -44,6 +40,7 @@ import java.util.Map;
public class AEventsServiceImpl implements AEventsService { public class AEventsServiceImpl implements AEventsService {
public static final Logger log = LoggerFactory.getLogger(AEventsServiceImpl.class); public static final Logger log = LoggerFactory.getLogger(AEventsServiceImpl.class);
public static final ArrayList<Object> OBJECTS = new ArrayList<>();
@Resource @Resource
private RedisCache redisCache; private RedisCache redisCache;
@ -114,16 +111,26 @@ public class AEventsServiceImpl implements AEventsService {
@Transactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class)
public void eventChangeIsReport(AEventChangeIsReport events) { public void eventChangeIsReport(AEventChangeIsReport events) {
events.setAuditTime(DateUtil.date()); events.setAuditTime(DateUtil.date());
//如果工单编号数组不为0,则将其所有工单进行标记 //获取当前innerEventId对应的事件
Events be = aEventsMapper.getByInnerEventId(events.getInnerEventId());
String str = be.getRelationNums().replaceAll("[\\[\\]']", "");
//当前innerEventId对应的事件对应的工单
List<String> sp = Arrays.asList(str.split(",\\s*"));
List<String> ol = new ArrayList<>(sp); // 可变集合
//如果工单编号数组不为0,则将其工单进行标记
if (events.getCaseSerial() != null && !events.getCaseSerial().isEmpty()) { if (events.getCaseSerial() != null && !events.getCaseSerial().isEmpty()) {
aEventsMapper.updateCasesImport(events.getCaseSerial(), DateUtil.now()); aEventsMapper.updateCasesImport(events.getCaseSerial(), 1, DateUtil.now());
ol.removeAll(events.getCaseSerial());
} else {
//如果不更改 都更改审批时间
aEventsMapper.updateCasesImport(ol, null, DateUtil.now());
} }
aEventsMapper.updateEvent(events); aEventsMapper.updateEvent(events);
if (events.getIsReport() == 1) { if (events.getIsReport() == 1) {
Events a1 = aEventsMapper.getByInnerEventId(events.getInnerEventId()); Events a1 = aEventsMapper.getByInnerEventId(events.getInnerEventId());
StringBuilder sb = new StringBuilder().append("["); StringBuilder sb = new StringBuilder().append("[");
int count = 1; int count = 1;
for (String x : events.getCaseSerial()) { for (String x : ol) {
sb.append("'"); sb.append("'");
sb.append(x); sb.append(x);
sb.append("'"); sb.append("'");
@ -136,8 +143,10 @@ public class AEventsServiceImpl implements AEventsService {
a1.setRelationNums(sb.toString()); a1.setRelationNums(sb.toString());
String substring = a1.getInnerEventId().substring(0, 6); String substring = a1.getInnerEventId().substring(0, 6);
a1.setInnerEventId(substring + IdUtil.randomUUID()); a1.setInnerEventId(substring + IdUtil.randomUUID());
if (!ol.isEmpty()) {
aEventsMapper.addAudit(a1); aEventsMapper.addAudit(a1);
// 重新上报驾驶舱 // 重新上报驾驶舱 todo al.getRelationNums() 需要符合的工单id
RemoteCallsDTO dto = BeanUtil.copyProperties(a1, RemoteCallsDTO.class); RemoteCallsDTO dto = BeanUtil.copyProperties(a1, RemoteCallsDTO.class);
dto.setContent(dto.getTitle()); dto.setContent(dto.getTitle());
// 创建SimpleDateFormat对象指定日期格式为yyyy-MM-dd HH:mm:ss // 创建SimpleDateFormat对象指定日期格式为yyyy-MM-dd HH:mm:ss
@ -149,10 +158,10 @@ public class AEventsServiceImpl implements AEventsService {
dto.setEventTime(firstWarnTime); dto.setEventTime(firstWarnTime);
dto.setLastWarnTime(eventTime); dto.setLastWarnTime(eventTime);
// 获取relationNums转成数组 // 获取relationNums转成数组
JSONArray jsonArray = JSONUtil.parseArray(dto.getRelationNums()); // JSONArray jsonArray = JSONUtil.parseArray(dto.getRelationNums());
List<String> list = jsonArray.toList(String.class); // List<String> list = jsonArray.toList(String.class);
QueryWrapper<CasesImport> wrapper = new QueryWrapper<>(); QueryWrapper<CasesImport> wrapper = new QueryWrapper<>();
wrapper.eq("CASE_SERIAL", list.get(0)); wrapper.eq("CASE_SERIAL", ol.get(0));
CasesImport casesImport = casesImportService.getOne(wrapper); CasesImport casesImport = casesImportService.getOne(wrapper);
if (BeanUtil.isNotEmpty(casesImport)) { if (BeanUtil.isNotEmpty(casesImport)) {
// 如果是紧急事件content使用原始工单的content // 如果是紧急事件content使用原始工单的content
@ -177,8 +186,8 @@ public class AEventsServiceImpl implements AEventsService {
} }
dto.setEventPlaceName(casesImport.getCaseAddress()); dto.setEventPlaceName(casesImport.getCaseAddress());
dto.setEventCoordinate(casesImport.getCaseLnglat()); dto.setEventCoordinate(casesImport.getCaseLnglat());
String accessToken = remoteCallsService.getAccessToken();
String jsonStr = JSONUtil.toJsonStr(dto); String jsonStr = JSONUtil.toJsonStr(dto);
String accessToken = remoteCallsService.getAccessToken();
HttpRequest.post(url + "/gateway/event/event/eventData/imports") HttpRequest.post(url + "/gateway/event/event/eventData/imports")
.header("Authorization", "Bearer " + accessToken) .header("Authorization", "Bearer " + accessToken)
.body(jsonStr).execute().body(); .body(jsonStr).execute().body();
@ -186,6 +195,7 @@ public class AEventsServiceImpl implements AEventsService {
} }
} }
} }
}
/** /**
* 100 * 100
@ -216,8 +226,8 @@ public class AEventsServiceImpl implements AEventsService {
y.setInnerEventId(x.getInnerEventId()); y.setInnerEventId(x.getInnerEventId());
y.setRelationNums(x.getRelationNums()); y.setRelationNums(x.getRelationNums());
y.setAuditTime(x.getAuditTime()); y.setAuditTime(x.getAuditTime());
y.setEventTime(x.getEventTime()); y.setEventTimeDate(x.getEventTimeDate());
y.setFirstWarnTime(x.getFirstWarnTime()); y.setFirstWarnTimeDate(x.getFirstWarnTimeDate());
y.setIsReport(x.getIsReport()); y.setIsReport(x.getIsReport());
y.setMsgTypeName(x.getMsgTypeName()); y.setMsgTypeName(x.getMsgTypeName());
y.setScenceName(x.getScenceName()); y.setScenceName(x.getScenceName());

@ -96,7 +96,7 @@ token:
# 令牌密钥 # 令牌密钥
secret: abcdefghijklmnopqrstuvwxyz secret: abcdefghijklmnopqrstuvwxyz
# 令牌有效期默认30分钟 # 令牌有效期默认30分钟
expireTime: 30 expireTime: 0

@ -3,7 +3,27 @@
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd"> "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ruoyi.pt.mapper.AEventsMapper"> <mapper namespace="com.ruoyi.pt.mapper.AEventsMapper">
<select id="page" resultType="com.ruoyi.pt.entity.Events">
<resultMap type="com.ruoyi.pt.entity.Events" id="EventResult">
<id property="innerEventId" column="innerEventId" />
<result property="title" column="title" />
<result property="msgType" column="msgType" />
<result property="msgTypeName" column="msgTypeName" />
<result property="scenceType" column="scenceType" />
<result property="scenceTypeName" column="scenceTypeName" />
<result property="firstWarnTimeDate" column="firstWarnTime" />
<result property="eventTimeDate" column="eventTime" />
<result property="warnFactor" column="warnFactor" />
<result property="relationNums" column="relationNums" />
<result property="state" column="state" />
<result property="nums" column="nums" />
<result property="scenceName" column="scenceName" />
<result property="titleBefore" column="titleBefore" />
<result property="isReport" column="isReport" />
<result property="auditTime" column="auditTime" />
</resultMap>
<select id="page" resultMap="EventResult">
select a.* from events a select a.* from events a
<where> <where>
<if test="req.title != null and req.title != ''">and a.title like concat('%',#{req.title},'%')</if> <if test="req.title != null and req.title != ''">and a.title like concat('%',#{req.title},'%')</if>
@ -11,7 +31,7 @@
<if test="req.startTime != null">and a.eventTime >= #{req.startTime}</if> <if test="req.startTime != null">and a.eventTime >= #{req.startTime}</if>
<if test="req.endTime != null">and a.eventTime &lt;= #{req.endTime}</if> <if test="req.endTime != null">and a.eventTime &lt;= #{req.endTime}</if>
<if test="req.isReport == 4">and a.isReport is null</if> <if test="req.isReport == 4">and a.isReport is null</if>
<if test="req.isReport == 5">and a.isReport is not null</if> <if test="req.isReport == 5">and (a.isReport = 1 or a.isReport = 2)</if>
<if test="req.isReport == 1">and a.isReport = #{req.isReport}</if> <if test="req.isReport == 1">and a.isReport = #{req.isReport}</if>
<if test="req.isReport == 2">and a.isReport = #{req.isReport}</if> <if test="req.isReport == 2">and a.isReport = #{req.isReport}</if>
<if test="req.isReport == 3">and a.isReport = #{req.isReport}</if> <if test="req.isReport == 3">and a.isReport = #{req.isReport}</if>
@ -34,8 +54,8 @@
<if test="msgTypeName != null">msgTypeName,</if> <if test="msgTypeName != null">msgTypeName,</if>
<if test="scenceType != null">scenceType,</if> <if test="scenceType != null">scenceType,</if>
<if test="scenceTypeName != null">scenceTypeName,</if> <if test="scenceTypeName != null">scenceTypeName,</if>
<if test="firstWarnTime != null">firstWarnTime,</if> <if test="firstWarnTimeDate != null">firstWarnTime,</if>
<if test="eventTime != null">eventTime,</if> <if test="eventTimeDate != null">eventTime,</if>
<if test="warnFactor != null">warnFactor,</if> <if test="warnFactor != null">warnFactor,</if>
<if test="relationNums != null">relationNums,</if> <if test="relationNums != null">relationNums,</if>
<if test="nums != null">nums,</if> <if test="nums != null">nums,</if>
@ -52,8 +72,8 @@
<if test="msgTypeName != null">#{msgTypeName},</if> <if test="msgTypeName != null">#{msgTypeName},</if>
<if test="scenceType != null">#{scenceType},</if> <if test="scenceType != null">#{scenceType},</if>
<if test="scenceTypeName != null">#{scenceTypeName},</if> <if test="scenceTypeName != null">#{scenceTypeName},</if>
<if test="firstWarnTime != null">#{firstWarnTime},</if> <if test="firstWarnTimeDate != null">#{firstWarnTimeDate},</if>
<if test="eventTime != null">#{eventTime},</if> <if test="eventTimeDate != null">#{eventTimeDate},</if>
<if test="warnFactor != null">#{warnFactor},</if> <if test="warnFactor != null">#{warnFactor},</if>
<if test="relationNums != null">#{relationNums},</if> <if test="relationNums != null">#{relationNums},</if>
<if test="nums != null">#{nums},</if> <if test="nums != null">#{nums},</if>
@ -86,10 +106,10 @@
<foreach collection="caseList" item="item" open="(" separator="," close=")"> <foreach collection="caseList" item="item" open="(" separator="," close=")">
#{item} #{item}
</foreach> </foreach>
order by CASE_DATE desc order by CASE_DATE desc,isReport desc
</select> </select>
<select id="getByInnerEventId" resultType="com.ruoyi.pt.entity.Events"> <select id="getByInnerEventId" resultMap="EventResult">
select * from events select * from events
where innerEventId = #{innerEventId} where innerEventId = #{innerEventId}
</select> </select>
@ -98,7 +118,7 @@
select * from cases_import select * from cases_import
where CASE_SERIAL = #{id} where CASE_SERIAL = #{id}
</select> </select>
<select id="limitOneMsg" resultType="com.ruoyi.pt.entity.Events"> <select id="limitOneMsg" resultMap="EventResult">
select * from events select * from events
order by eventTime order by eventTime
limit 1 limit 1
@ -121,7 +141,7 @@
<update id="updateCasesImport"> <update id="updateCasesImport">
update cases_import update cases_import
<trim prefix="SET" suffixOverrides=","> <trim prefix="SET" suffixOverrides=",">
isReport = 1, <if test="isReport != null">isReport = #{isReport},</if>
<if test="time != null">auditTime = #{time},</if> <if test="time != null">auditTime = #{time},</if>
</trim> </trim>
where CASE_SERIAL in where CASE_SERIAL in

@ -0,0 +1,153 @@
package com.ruoyi.common.utils;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
/**
* RSA
*
* @author ruoyi
**/
public class RsaUtils
{
// Rsa 私钥
public static String privateKey = "MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEAnbAlNlYuctm5GmkA\n" +
"5692KWiJd9cTeL2sCvWsGDfWyPXECeF9G4MKGijreQzJkGJ96I5w0Kvj0Z47eP7s\n" +
"2Vj7IwIDAQABAkEAgbPrR+BnYEy5toF8HxXx6Wl0+T/NYlkQ9ArTPTBg2PYTXSvT\n" +
"LoJqrWss688w7WIwUz5lyVKKeRFWkxe9T4RIUQIhAM6BMCzJybFtAszEgBBDdtxj\n" +
"eDiXAk3zcsqcltHE/i/PAiEAw3ulbhgLYnXJIfymCsMgnyrESOyQxKDhQOm2Pnj/\n" +
"YG0CICx9Corroic2S/8falOWpTnPuCvA5L80bouV9qwUm4pjAiEAkJ4U0NHw+jJx\n" +
"Tjd/D08z/wzAkcKRhyYN/tvn+2fAZjECICkVQ6VWohPiibqIdVffCwXK3jSi5SJ3\n" +
"ddcmzYQBJFLv";
/**
*
*
* @param text
* @return
*/
public static String decryptByPrivateKey(String text) throws Exception
{
return decryptByPrivateKey(privateKey, text);
}
/**
*
*
* @param publicKeyString
* @param text
* @return
*/
public static String decryptByPublicKey(String publicKeyString, String text) throws Exception
{
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(Base64.decodeBase64(publicKeyString));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, publicKey);
byte[] result = cipher.doFinal(Base64.decodeBase64(text));
return new String(result);
}
/**
*
*
* @param privateKeyString
* @param text
* @return
*/
public static String encryptByPrivateKey(String privateKeyString, String text) throws Exception
{
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKeyString));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
byte[] result = cipher.doFinal(text.getBytes());
return Base64.encodeBase64String(result);
}
/**
*
*
* @param privateKeyString
* @param text
* @return
*/
public static String decryptByPrivateKey(String privateKeyString, String text) throws Exception
{
PKCS8EncodedKeySpec pkcs8EncodedKeySpec5 = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKeyString));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec5);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] result = cipher.doFinal(Base64.decodeBase64(text));
return new String(result);
}
/**
*
*
* @param publicKeyString
* @param text
* @return
*/
public static String encryptByPublicKey(String publicKeyString, String text) throws Exception
{
X509EncodedKeySpec x509EncodedKeySpec2 = new X509EncodedKeySpec(Base64.decodeBase64(publicKeyString));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec2);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] result = cipher.doFinal(text.getBytes());
return Base64.encodeBase64String(result);
}
/**
* RSA
*
* @return
*/
public static RsaKeyPair generateKeyPair() throws NoSuchAlgorithmException
{
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(1024);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
String publicKeyString = Base64.encodeBase64String(rsaPublicKey.getEncoded());
String privateKeyString = Base64.encodeBase64String(rsaPrivateKey.getEncoded());
return new RsaKeyPair(publicKeyString, privateKeyString);
}
/**
* RSA
*/
public static class RsaKeyPair
{
private final String publicKey;
private final String privateKey;
public RsaKeyPair(String publicKey, String privateKey)
{
this.publicKey = publicKey;
this.privateKey = privateKey;
}
public String getPublicKey()
{
return publicKey;
}
public String getPrivateKey()
{
return privateKey;
}
}
}

@ -119,7 +119,8 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter
// .antMatchers("/pt/**").anonymous() // .antMatchers("/pt/**").anonymous()
// .antMatchers("/gateway/event/event/eventData/**").anonymous() // .antMatchers("/gateway/event/event/eventData/**").anonymous()
// .antMatchers("/gateway/event/event/eventData/eventProgress/**").anonymous() // .antMatchers("/gateway/event/event/eventData/eventProgress/**").anonymous()
.antMatchers("/earlyWarningAudit/**").permitAll() .antMatchers("/earlyWarningAudit/massEvents/login").permitAll()
.antMatchers("/earlyWarningAudit/massEvents/appLogin").permitAll()
// 除上面外的所有请求全部需要鉴权认证 // 除上面外的所有请求全部需要鉴权认证
.anyRequest().authenticated() .anyRequest().authenticated()
.and() .and()

@ -1,6 +1,8 @@
package com.ruoyi.framework.web.service; package com.ruoyi.framework.web.service;
import javax.annotation.Resource; import javax.annotation.Resource;
import com.ruoyi.common.utils.RsaUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.BadCredentialsException;
@ -52,6 +54,104 @@ public class SysLoginService
@Autowired @Autowired
private ISysConfigService configService; private ISysConfigService configService;
/**
*
*
* @param username
* @param password
* @return
*/
public String login1(String username, String password)
{
String strP = "";
try {
strP = RsaUtils.decryptByPrivateKey(password);
} catch (Exception e) {
throw new RuntimeException(e);
}
// 验证码校验
// validateCaptcha(username, code, uuid);
// 登录前置校验
loginPreCheck(username, strP);
// 用户验证
Authentication authentication = null;
try
{
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, strP);
AuthenticationContextHolder.setContext(authenticationToken);
// 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
authentication = authenticationManager.authenticate(authenticationToken);
}
catch (Exception e)
{
if (e instanceof BadCredentialsException)
{
AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
throw new UserPasswordNotMatchException();
}
else
{
AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
throw new ServiceException(e.getMessage());
}
}
finally
{
AuthenticationContextHolder.clearContext();
}
AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
LoginUser loginUser = (LoginUser) authentication.getPrincipal();
recordLoginInfo(loginUser.getUserId());
// 生成token
return tokenService.createToken(loginUser);
}
/**
*
*
* @param username
* @param password
* @return
*/
public String login2(String username, String password)
{
// 验证码校验
// validateCaptcha(username, code, uuid);
// 登录前置校验
loginPreCheck(username, password);
// 用户验证
Authentication authentication = null;
try
{
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
AuthenticationContextHolder.setContext(authenticationToken);
// 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
authentication = authenticationManager.authenticate(authenticationToken);
}
catch (Exception e)
{
if (e instanceof BadCredentialsException)
{
AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
throw new UserPasswordNotMatchException();
}
else
{
AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
throw new ServiceException(e.getMessage());
}
}
finally
{
AuthenticationContextHolder.clearContext();
}
AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
LoginUser loginUser = (LoginUser) authentication.getPrincipal();
recordLoginInfo(loginUser.getUserId());
// 生成token
return tokenService.createToken(loginUser);
}
/** /**
* *
* *

Loading…
Cancel
Save