merge gz to cq

This commit is contained in:
sxu 2024-08-13 15:30:41 +08:00
parent ef18dd3dc4
commit 5d9ff667c6
7 changed files with 371 additions and 44 deletions

View File

@ -0,0 +1,250 @@
package com.bonus.sgzb.auth.controller;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import com.bonus.sgzb.auth.utils.RsaUtil;
import com.bonus.sgzb.auth.form.*;
import com.bonus.sgzb.auth.service.NwRegisterService;
import com.bonus.sgzb.auth.service.NwUserLoginService;
import com.bonus.sgzb.common.core.constant.CacheConstants;
import com.bonus.sgzb.common.core.exception.ServiceException;
import com.bonus.sgzb.common.core.utils.GlobalConstants;
import com.bonus.sgzb.common.core.web.domain.AjaxResult;
import com.bonus.sgzb.common.redis.service.RedisService;
import com.bonus.sgzb.system.api.RemoteUserService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.bonus.sgzb.auth.service.SysLoginService;
import com.bonus.sgzb.common.core.domain.R;
import com.bonus.sgzb.common.core.utils.JwtUtils;
import com.bonus.sgzb.common.core.utils.StringUtils;
import com.bonus.sgzb.common.security.auth.AuthUtil;
import com.bonus.sgzb.common.security.service.TokenService;
import com.bonus.sgzb.common.security.utils.SecurityUtils;
import com.bonus.sgzb.system.api.model.LoginUser;
import java.util.Map;
/**
* token 控制
*
* @author ruoyi
*/
@RestController
@Slf4j
@RequestMapping("/gz")
public class TokenController_GZ {
private final String USER_PASSWORD = "NwCc@2024*";
private final String privateKey = "MIIBVAIBADANBgkqhkiG9w0BAQEFAASCAT4wggE6AgEAAkEAqhHyZfSsYourNxaY7Nt+PrgrxkiA50efORdI5U5lsW79MmFnusUA355oaSXcLhu5xxB38SMSyP2KvuKNPuH3owIDAQABAkAfoiLyL+Z4lf4Myxk6xUDgLaWGximj20CUf+5BKKnlrK+Ed8gAkM0HqoTt2UZwA5E2MzS4EI2gjfQhz5X28uqxAiEA3wNFxfrCZlSZHb0gn2zDpWowcSxQAgiCstxGUoOqlW8CIQDDOerGKH5OmCJ4Z21v+F25WaHYPxCFMvwxpcw99EcvDQIgIdhDTIqD2jfYjPTY8Jj3EDGPbH2HHuffvflECt3Ek60CIQCFRlCkHpi7hthhYhovyloRYsM+IS9h/0BzlEAuO0ktMQIgSPT3aFAgJYwKpqRYKlLDVcflZFCKY7u3UP8iWi1Qw0Y=";
@Autowired
private TokenService tokenService;
@Autowired
private SysLoginService sysLoginService;
@Resource
private RedisService redisService;
@Resource
private RemoteUserService remoteUserService;
@Resource
private NwUserLoginService nwUserLoginService;
@Autowired
private NwRegisterService registerService;
/**
* web端登录
*
* @param form
* @return
* @throws Exception
*/
@PostMapping("login")
public R<?> login(@RequestBody LoginBody form) throws Exception {
//优先校验图形验证码
String uuid = form.getUuid();
Object cacheObject = redisService.getCacheObject(CacheConstants.CAPTCHA_CODE_KEY + uuid);
String captcha = cacheObject == null ? null : cacheObject.toString();
// 获取后立即删除图形验证码缓存
redisService.deleteObject(CacheConstants.CAPTCHA_CODE_KEY + uuid);
if (StringUtils.isBlank(captcha)) {
throw new ServiceException("图形验证码失效,请重新刷新获取");
}
if (form.getCode() != null && !form.getCode().equals(captcha)) {
throw new ServiceException("图形验证码错误");
}
//根据用户名查询用户信息
LoginUser user = sysLoginService.selectByName(form.getUsername());
if (StringUtils.isNull(user)) {
throw new ServiceException("用户名不存在/密码错误");
}
//获取查询的用户手机号
String phone = user.getSysUser().getPhonenumber();
if ("adminBns".equals(form.getUsername())) {
if (!StringUtils.isNotBlank(phone)) {
throw new ServiceException("手机号为空,请联系管理员!");
}
//管理员用户需要额外校验手机短信验证码
String redisCode = redisService.getCacheObject("code_" + phone);
if (StringUtils.isEmpty(redisCode)) {
throw new ServiceException("短信验证码失效", 500);
}
if (!StringUtils.equals(redisCode.split(GlobalConstants.STRING_UNDERLINE)[0], form.getTextCode())) {
throw new ServiceException("短信验证码错误", 500);
}
}
String decryptedData = RsaUtil.decryptByPrivateKey(form.getPassword(), privateKey);
// 用户登录
LoginUser userInfo = sysLoginService.login(form.getUsername(), decryptedData);
if (decryptedData.equals(USER_PASSWORD)) {
userInfo.setCode(1);
}
if (form.getCode() != null && form.getCode().equals(captcha)) {
redisService.deleteObject("code_" + phone);
// 获取登录token
return R.ok(tokenService.createToken(userInfo));
} else {
return R.fail("登录失败,请联系管理员!");
}
}
/**
* App端登录
*
* @param form
* @return
*/
@PostMapping("loginApp")
public R<?> loginApp(@RequestBody LoginBody form) {
// 用户登录
LoginUser userInfo = sysLoginService.login(form.getUsername(), form.getPassword());
if (userInfo != null) {
userInfo.setLoginMethod("mobile");
return R.ok(tokenService.createToken(userInfo));
} else {
return R.fail("登录信息为空,请重试");
}
}
@PostMapping("sendCode")
public R<?> sendCode(@RequestBody LoginBody form) {
if ("adminBns".equals(form.getUsername())) {
// 根据用户名查询用户信息
LoginUser userInfo = sysLoginService.selectByName(form.getUsername());
//获取查询的用户手机号
String phone = userInfo.getSysUser().getPhonenumber();
if (StringUtils.isBlank(phone)) {
throw new ServiceException("手机号为空,请联系管理员!");
}
//图形验证码校验成功发送短信
R<Boolean> sendState = remoteUserService.sendCode(phone);
return sendState;
} else {
String uuid = form.getUuid();
String captcha = redisService.getCacheObject(CacheConstants.CAPTCHA_CODE_KEY + uuid).toString();
if (StringUtils.isBlank(captcha)) {
// 删除验证码缓存
redisService.deleteObject(CacheConstants.CAPTCHA_CODE_KEY + uuid);
return R.fail("验证码超时,请重新刷新");
}
if (form.getCode() != null && !form.getCode().equals(captcha)) {
// 删除验证码缓存
redisService.deleteObject(CacheConstants.CAPTCHA_CODE_KEY + uuid);
return R.fail("验证码错误");
}
R<Boolean> sendState = remoteUserService.sendCode(form.getPhone());
return sendState;
}
}
@PostMapping("checkCode")
public R<?> checkCode(@RequestBody LoginBody form) {
// 校验验证码
LoginUser loginUser = sysLoginService.loginCode(form.getPhone(), form.getCode());
if (StringUtils.isNotNull(loginUser)) {
loginUser.setLoginMethod("mobile");
// 创建token
Map<String, Object> tokenMap = tokenService.createToken(loginUser);
return R.ok(tokenService.createToken(loginUser));
} else {
return R.fail(null, "验证码错误");
}
}
@DeleteMapping("logout")
public R<?> logout(HttpServletRequest request) {
String token = SecurityUtils.getToken(request);
if (StringUtils.isNotEmpty(token)) {
String username = JwtUtils.getUserName(token);
// 删除用户缓存记录
AuthUtil.logoutByToken(token);
// 记录用户退出日志
sysLoginService.logout(username);
}
return R.ok();
}
@PostMapping("refresh")
public R<?> refresh(HttpServletRequest request) {
LoginUser loginUser = tokenService.getLoginUser(request);
if (StringUtils.isNotNull(loginUser)) {
// 刷新令牌有效期
tokenService.refreshToken(loginUser);
return R.ok();
}
return R.ok();
}
//@PostMapping("register")
public R<?> register(@RequestBody RegisterBody registerBody) {
// 用户注册
sysLoginService.register(registerBody);
return R.ok(null, "注册成功");
}
@PostMapping("loginByMall")
public R<?> loginByMall(@RequestBody LoginUser loginUser) {
// 用户注册
Map map = sysLoginService.loginByMall(loginUser);
if ("1".equals(map.get("status").toString())) {
return R.fail("登录用户未注册");
} else if ("2".equals(map.get("login_user").toString())) {
return R.fail("未携带token");
}
return R.ok(map);
}
@ApiOperation("微服务平台认证接口")
@PostMapping(value = "/onlineApprove")
public R<?> onlineApprove(@RequestBody AuthenticationLoginFrom loginForm) {
if (loginForm == null || StringUtils.isBlank(loginForm.getType())) {
return R.fail("参数异常");
}
try {
return nwUserLoginService.onlineApprove(loginForm);
} catch (Exception e) {
log.error("微服务平台认证登陆 异常: ", e);
return R.fail("微服务平台认证失败");
}
}
@ApiOperation("用户中心注册")
//@PostMapping("/registers")
public AjaxResult registers(HttpServletRequest request, @RequestBody RegisterForms registerForms) {
AccountRegister accountRegister = new AccountRegister();
accountRegister.setCode(1);
accountRegister.setDesc("个人用户注册");
accountRegister.setRemark("个人用户注册");
registerForms.setIsPersonal(accountRegister.getCode());
return AjaxResult.success("success", registerService.registersNew(request, registerForms));
}
}

View File

@ -31,4 +31,9 @@ public class LoginBody {
private String uuid;
/**
* 短信验证码
*/
private String textCode;
}

View File

@ -282,4 +282,15 @@ public class SysLoginService {
}
return password.toString();
}
/**
* 根据用户名查询用户信息
* @param username
* @return
*/
public LoginUser selectByName(String username) {
// 查询用户信息
R<LoginUser> userResult = remoteUserService.getUserInfo(username, SecurityConstants.INNER);
return userResult.getData();
}
}

View File

@ -50,9 +50,6 @@ public class SysProfileController extends BaseController {
@Autowired
private TokenService tokenService;
@Autowired
private RemoteFileService remoteFileService;
@Resource
private SysFileService sysFileService;
@ -122,6 +119,34 @@ public class SysProfileController extends BaseController {
return error("修改密码异常,请联系管理员");
}
/**
* 重置密码
*/
@Log(title = "个人信息", businessType = BusinessType.UPDATE)
@PutMapping("/update")
public AjaxResult updatePwd2(String actionCode, String handleCode) throws Exception {
//对新老密码进行解密
String oldDecrypt = RsaUtil.decryptByPrivateKey(actionCode, Constants.privateKey);
String newDecrypt = RsaUtil.decryptByPrivateKey(handleCode, Constants.privateKey);
String username = SecurityUtils.getUsername();
SysUser user = userService.selectUserByUserName(username);
String password = user.getPassword();
if (!SecurityUtils.matchesPassword(oldDecrypt, password)) {
return error("修改密码失败,旧密码错误");
}
if (SecurityUtils.matchesPassword(newDecrypt, password)) {
return error("新密码不能与旧密码相同");
}
if (userService.resetUserPwd(username, SecurityUtils.encryptPassword(newDecrypt)) > 0) {
// 更新缓存用户密码
LoginUser loginUser = SecurityUtils.getLoginUser();
loginUser.getSysUser().setPassword(SecurityUtils.encryptPassword(newDecrypt));
tokenService.setLoginUser(loginUser);
return success();
}
return error("修改密码异常,请联系管理员");
}
/**
* 头像上传
*/

View File

@ -5,7 +5,6 @@ import com.bonus.sgzb.common.core.constant.SecurityConstants;
import com.bonus.sgzb.common.core.constant.UserConstants;
import com.bonus.sgzb.common.core.domain.R;
import com.bonus.sgzb.common.core.exception.ServiceException;
import com.bonus.sgzb.common.core.utils.GlobalConstants;
import com.bonus.sgzb.common.core.utils.StringUtils;
import com.bonus.sgzb.common.core.utils.poi.ExcelUtil;
import com.bonus.sgzb.common.core.web.controller.BaseController;
@ -28,7 +27,6 @@ import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
@ -36,7 +34,6 @@ import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;
@ -134,6 +131,7 @@ public class SysUserController extends BaseController {
@InnerAuth
@GetMapping("/info/{username}")
public R<LoginUser> info(@PathVariable("username") String username) {
log.info("通过用户名获取用户=====================");
SysUser sysUser = userService.selectUserByUserName(username);
if (StringUtils.isNull(sysUser)) {
return R.fail("用户名或密码错误");
@ -274,6 +272,19 @@ public class SysUserController extends BaseController {
return toAjax(userService.resetPwd(user));
}
@RequiresPermissions("system:user:edit")
@Log(title = "用户管理", businessType = BusinessType.UPDATE)
@PutMapping("/reset")
public AjaxResult resetPwd2(@RequestBody SysUser user) throws Exception {
//对密码进行解密
String decrypt = RsaUtil.decryptByPrivateKey(user.getPassword(), Constants.privateKey);
userService.checkUserAllowed(user);
userService.checkUserDataScope(user.getUserId());
user.setPassword(SecurityUtils.encryptPassword(decrypt));
user.setUpdateBy(SecurityUtils.getUsername());
return toAjax(userService.resetPwd(user));
}
/**
* 根据手机验证码重制密码
*/

View File

@ -3,6 +3,7 @@ package com.bonus.sgzb.system.service.impl;
import cn.hutool.http.HttpRequest;
import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.bonus.sgzb.common.core.constant.Constants;
import com.bonus.sgzb.common.core.constant.UserConstants;
import com.bonus.sgzb.common.core.exception.ServiceException;
import com.bonus.sgzb.common.core.utils.GlobalConstants;
@ -20,9 +21,13 @@ import com.tencentcloudapi.sms.v20210111.models.SendSmsResponse;
import com.tencentcloudapi.sms.v20210111.models.SendStatus;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
@ -41,6 +46,9 @@ import static com.bonus.sgzb.common.core.web.domain.AjaxResult.success;
@Slf4j
public class SysSmsServiceImpl implements ISysSmsService {
@Value("${sgzb.customer}")
private String customer;
@Resource
private RedisService redisService;
@ -67,14 +75,17 @@ public class SysSmsServiceImpl implements ISysSmsService {
if (phone.length() != UserConstants.PHONE_DEFAULT_LENGTH_LOGIN) {
return AjaxResult.error("手机号格式不正确");
}
/* try {
String[] args = msg.split(",");
String body = sendMessageNew(phone,tencentSmsConfig.getTemplateId().get(0),args);
return success("发送手机号码:" + phone + ",内容:" + msg + ",返回结果:" + body);
} catch (Exception e) {
return AjaxResult.error("发送失败:" + e.getMessage());
}*/
return sendMsgByPhone( phone, msg);
if (Constants.CUSTOMER_GZ.equals(customer)) {
try {
String[] args = msg.split(",");
String body = sendMessageNew(phone,tencentSmsConfig.getTemplateId().get(0),args);
return success("发送手机号码:" + phone + ",内容:" + msg + ",返回结果:" + body);
} catch (Exception e) {
return AjaxResult.error("发送失败:" + e.getMessage());
}
} else {
return sendMsgByPhone( phone, msg);
}
}
/**
@ -136,6 +147,10 @@ public class SysSmsServiceImpl implements ISysSmsService {
if (phone == null || phone.length() != UserConstants.PHONE_DEFAULT_LENGTH_LOGIN) {
return AjaxResult.error("手机号格式错误请输入11位数字号码");
}
// 检查发送次数是否超限
if (isOverLimit(phone)) {
throw new ServiceException("当天此手机号发送验证码次数超过限制", 1001);
}
String code = getSixBitCode();
// 校验验证码
if (code.length() != UserConstants.CODE_MIN_LENGTH_LOGIN) {
@ -151,12 +166,38 @@ public class SysSmsServiceImpl implements ISysSmsService {
}
// 存储验证码至Redis中键值为code_15588886157 , 有效期5时间颗粒度为MINUTES:分钟
redisService.setCacheObject("code_" + phone, code, 5L, TimeUnit.MINUTES);
return success("手机号:" + phone + ",用户登录验证码:" + code + ",返回结果:" + body);
String key = UserConstants.MOBILE_PHONE_1D_LIMIT_DIR + phone;
Integer sendCount = redisService.getCacheObject(key);
if (sendCount == null) {
sendCount = 1;
} else {
sendCount++;
}
// 获取当前日期和时间
LocalDateTime now = LocalDateTime.now();
// 获取当天午夜时间
LocalDateTime midnight = LocalDateTime.of(now.toLocalDate(), LocalTime.MIDNIGHT).plusDays(1);
// 计算当前时间到当天午夜的时间差
long secondsUntilMidnight = now.until(midnight, ChronoUnit.SECONDS);
//存储一天手机号发送验证码数据
redisService.setCacheObject(key, sendCount, secondsUntilMidnight, TimeUnit.SECONDS);
return success("手机号:" + phone + ",短信验证码发送成功 ");
} catch (Exception e) {
return AjaxResult.error("发送失败:" + e.getMessage());
}
}
/**
* 检查发送次数是否超过限制
* @param phone 手机号
* @return
*/
private boolean isOverLimit(String phone) {
String key = UserConstants.MOBILE_PHONE_1D_LIMIT_DIR + phone;
Integer sendCount = redisService.getCacheObject(key);
// 限制每个手机号每天最多发送10次
return sendCount != null && sendCount >= 10;
}
/**
* 判断验证码是否存在Redis中
@ -180,10 +221,6 @@ public class SysSmsServiceImpl implements ISysSmsService {
}
}
public static void main(String[] args) {
System.out.println(getSixBitCode());
}
/**
* 随机生成6位验证码
*/
@ -247,7 +284,7 @@ public class SysSmsServiceImpl implements ISysSmsService {
}
}
return resp.getRequestId();
return resp.getRequestId();
} catch (TencentCloudSDKException e) {
e.printStackTrace();
log.error("短信发送失败:{}", e.getMessage());

View File

@ -1,5 +1,6 @@
package com.bonus.sgzb.system.service.impl;
import com.bonus.sgzb.common.core.constant.Constants;
import com.bonus.sgzb.common.core.constant.UserConstants;
import com.bonus.sgzb.common.core.enums.RoleEnum;
import com.bonus.sgzb.common.core.enums.TaskStatusEnum;
@ -13,6 +14,7 @@ import com.bonus.sgzb.common.security.utils.SecurityUtils;
import com.bonus.sgzb.system.api.domain.SysDept;
import com.bonus.sgzb.system.api.domain.SysRole;
import com.bonus.sgzb.system.api.domain.SysUser;
import com.bonus.sgzb.system.api.model.LoginUser;
import com.bonus.sgzb.system.domain.SysPost;
import com.bonus.sgzb.system.domain.SysUserPost;
import com.bonus.sgzb.system.domain.SysUserRole;
@ -24,6 +26,7 @@ import com.bonus.sgzb.system.service.ISysUserService;
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.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
@ -33,6 +36,7 @@ import javax.validation.Validator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import static com.bonus.sgzb.common.core.web.domain.AjaxResult.success;
@ -46,6 +50,9 @@ import static com.bonus.sgzb.common.core.web.domain.AjaxResult.success;
public class SysUserServiceImpl implements ISysUserService {
private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);
@Value("${sgzb.customer}")
private String customer;
@Resource
private SysUserMapper userMapper;
@ -79,6 +86,11 @@ public class SysUserServiceImpl implements ISysUserService {
@Override
@DataScope(deptAlias = "d", userAlias = "u")
public List<SysUser> selectUserList(SysUser user) {
if (Constants.CUSTOMER_GZ.equals(customer)) {
LoginUser loginUser = SecurityUtils.getLoginUser();
SysUser sysUser = loginUser.getSysUser();
user.setCompanyId(Objects.nonNull(sysUser) ? sysUser.getCompanyId() : null);
}
return userMapper.selectUserList(user);
}
@ -244,30 +256,6 @@ public class SysUserServiceImpl implements ISysUserService {
@Override
@Transactional(rollbackFor = Exception.class)
public int insertUser(SysUser user) {
// 暂时使用,需修改
Long deptId = user.getDeptId();
SysDept sysDept = deptMapper.selectDeptById(deptId);
String ancestors = sysDept.getAncestors();
String[] split = ancestors.split(",");
/* List<SysDept> deptList = deptMapper.selectDeptByAncestors(split);
for (SysDept dept : deptList) {
String ancestors1 = dept.getAncestors();
String[] split1 = ancestors1.split(",");
List<String> list = Arrays.asList(split1);
//表示属于分公司下的某个部门
if (list.size() >= 3) {
user.setCompanyId(dept.getDeptId());
}
}*/
if (split.length == 2) {
//表示属于分公司
user.setCompanyId(sysDept.getDeptId());
}
if (split.length >= 3) {
//表示属于分公司下的某个部门
user.setCompanyId(Long.parseLong(split[2]));
}
// 新增用户信息
int rows = userMapper.insertUser(user);
// 新增用户岗位关联