You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
483 lines
19 KiB
483 lines
19 KiB
package com.zsw.erp.controller; |
|
|
|
import cn.hutool.core.date.*; |
|
import cn.hutool.core.util.ObjectUtil; |
|
import cn.hutool.jwt.*; |
|
import com.alibaba.fastjson.JSON; |
|
import com.alibaba.fastjson.JSONArray; |
|
import com.alibaba.fastjson.JSONObject; |
|
import com.zsw.erp.constants.BusinessConstants; |
|
import com.zsw.erp.constants.ExceptionConstants; |
|
import com.zsw.erp.datasource.entities.BtnDto; |
|
import com.zsw.erp.datasource.dto.UserLoginDto; |
|
import com.zsw.erp.datasource.entities.Tenant; |
|
import com.zsw.erp.datasource.entities.User; |
|
import com.zsw.erp.datasource.entities.UserEx; |
|
import com.zsw.erp.datasource.vo.TreeNodeEx; |
|
import com.zsw.erp.exception.BusinessParamCheckingException; |
|
import com.zsw.erp.service.inventorySeason.InventorySeasonService; |
|
import com.zsw.erp.service.log.LogService; |
|
import com.zsw.erp.service.redis.RedisService; |
|
import com.zsw.erp.service.tenant.TenantService; |
|
import com.zsw.erp.service.user.UserService; |
|
import com.zsw.base.R; |
|
import com.zsw.erp.utils.*; |
|
import com.zsw.jwt.model.AuthInfo; |
|
import com.zsw.jwt.model.TenantAuthInfo; |
|
import com.zsw.pos.authority.dto.auth.LoginParamDTO; |
|
import com.zsw.pos.oauth.service.LoginService; |
|
import io.swagger.annotations.Api; |
|
import io.swagger.annotations.ApiOperation; |
|
import org.apache.dubbo.config.annotation.DubboReference; |
|
import org.slf4j.Logger; |
|
import org.slf4j.LoggerFactory; |
|
import org.springframework.beans.factory.annotation.Value; |
|
import org.springframework.web.bind.annotation.*; |
|
import org.springframework.web.context.request.RequestContextHolder; |
|
import org.springframework.web.context.request.ServletRequestAttributes; |
|
|
|
import javax.annotation.Resource; |
|
import javax.servlet.http.HttpServletRequest; |
|
import javax.servlet.http.HttpServletResponse; |
|
import java.io.IOException; |
|
import java.nio.charset.StandardCharsets; |
|
import java.time.LocalDateTime; |
|
import java.time.format.DateTimeFormatter; |
|
import java.time.temporal.ChronoUnit; |
|
import java.util.*; |
|
|
|
import static com.zsw.erp.utils.ResponseJsonUtil.returnJson; |
|
|
|
|
|
@RestController |
|
@RequestMapping(value = "/user") |
|
@Api(tags = {"用户管理"}) |
|
public class UserController { |
|
private Logger logger = LoggerFactory.getLogger(UserController.class); |
|
|
|
@Value("${manage.roleId}") |
|
private Integer manageRoleId; |
|
|
|
@Value("${demonstrate.open}") |
|
private boolean demonstrateOpen; |
|
|
|
@Resource |
|
private UserService userService; |
|
|
|
@Resource |
|
private TenantService tenantService; |
|
|
|
@Resource |
|
private LogService logService; |
|
|
|
@Resource |
|
private RedisService redisService; |
|
|
|
@Resource |
|
private InventorySeasonService inventorySeasonService; |
|
|
|
@DubboReference |
|
private LoginService loginService; |
|
|
|
@Value("${tenant.userNumLimit}") |
|
private Integer systemLimit; |
|
|
|
private static final String TEST_USER = "jsh"; |
|
private static String SUCCESS = "操作成功"; |
|
private static String ERROR = "操作失败"; |
|
private static final String HTTP = "http://"; |
|
private static final String CODE_OK = "200"; |
|
private static final String BASE_CHECK_CODES = "qwertyuiplkjhgfdsazxcvbnmQWERTYUPLKJHGFDSAZXCVBNM1234567890"; |
|
|
|
@PostMapping(value = "/login") |
|
@ApiOperation(value = "登录") |
|
public R login(@RequestBody User userParam, |
|
HttpServletRequest request)throws Exception { |
|
logger.info("============用户登录 login 方法调用开始=============="); |
|
String msgTip = ""; |
|
User user=null; |
|
|
|
String loginName = userParam.getLoginName().trim(); |
|
String password = userParam.getPassword().trim(); |
|
|
|
String posTenantCode = null; |
|
JWTPayload payload = new JWTPayload(); |
|
|
|
// 登录zsw-admin |
|
LoginParamDTO dto = new LoginParamDTO(); |
|
dto.setAccount(loginName); |
|
dto.setPassword(password); |
|
R<TenantAuthInfo> result = loginService.grant(dto); |
|
logger.error("result:{}",result); |
|
if (result.getIsSuccess()){ |
|
// 检查系统里是否存在租户和账户 没有准备走注册流程 |
|
posTenantCode = result.getData().getTenantCode(); |
|
// 在这里带了太多的门店ID |
|
payload.setPayload("loginName",loginName); |
|
payload.setPayload("tenantId",posTenantCode); |
|
} |
|
|
|
//获取用户状态 |
|
//int userStatus = -1; |
|
redisService.deleteObjectBySession(request,"userId"); |
|
UserLoginDto loginDto = userService.validateUser(loginName, password); |
|
|
|
switch (loginDto.getUserStatus()) { |
|
case ExceptionCodeConstants.UserExceptionCode.USER_NOT_EXIST: |
|
msgTip = "user is not exist"; |
|
if (posTenantCode != null){ |
|
// 用户不存在 但是用户不存在 可能报错。 |
|
UserEx ex = new UserEx(); |
|
ex.setLoginName(loginName); |
|
ex.setPassword(password); |
|
ex.setTenantId(Long.parseLong(posTenantCode)); |
|
LocalDateTime time = LocalDateTimeUtil.offset(LocalDateTime.now(), 10, ChronoUnit.YEARS); |
|
DateTimeFormatter formater = DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN); |
|
String t = time.format(formater); |
|
ex.setExpireTime(t); |
|
user = this.registerUser(ex,request); |
|
payload.setPayload("userId",user.getId()); |
|
payload.setPayload("loginName",loginName); |
|
payload.setPayload("tenantId",posTenantCode); |
|
msgTip = "user can login"; |
|
} |
|
break; |
|
case ExceptionCodeConstants.UserExceptionCode.USER_PASSWORD_ERROR: |
|
msgTip = "user password error"; |
|
break; |
|
case ExceptionCodeConstants.UserExceptionCode.BLACK_USER: |
|
msgTip = "user is black"; |
|
break; |
|
case ExceptionCodeConstants.UserExceptionCode.USER_ACCESS_EXCEPTION: |
|
msgTip = "access service error"; |
|
break; |
|
case ExceptionCodeConstants.UserExceptionCode.BLACK_TENANT: |
|
msgTip = "tenant is black"; |
|
break; |
|
case ExceptionCodeConstants.UserExceptionCode.EXPIRE_TENANT: |
|
msgTip = "tenant is expire"; |
|
break; |
|
case ExceptionCodeConstants.UserExceptionCode.USER_CONDITION_FIT: |
|
msgTip = "user can login"; |
|
user = loginDto.getUser(); |
|
payload.setPayload("userId",user.getId()); |
|
payload.setPayload("loginName",loginName); |
|
payload.setPayload("tenantId",user.getTenantId()); |
|
break; |
|
default: |
|
break; |
|
} |
|
|
|
// 1个月过期 |
|
DateTime exAt = DateUtil.offset(new Date(), DateField.MONTH, 1); |
|
payload.setExpiresAt(exAt); |
|
String token = JWTUtil.createToken(payload.getClaimsJson(), "88888888".getBytes(StandardCharsets.UTF_8)); |
|
|
|
Map<String, Object> data = new HashMap<String, Object>(); |
|
data.put("msgTip", msgTip); |
|
if(user!=null){ |
|
redisService.storageObjectBySession(token,"userId",user.getId()); |
|
String roleType = userService.getRoleTypeByUserId(user.getId()); //角色类型 |
|
if (roleType == null){ |
|
logger.error("角色错误!"); |
|
} |
|
redisService.storageObjectBySession(token,"roleType",roleType); |
|
redisService.storageObjectBySession(token,"clientIp", Tools.getLocalIp(request)); |
|
logService.insertLogWithUserId(user.getId(), user.getTenantId(), "用户", |
|
new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_LOGIN).append(user.getLoginName()).toString(), |
|
((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()); |
|
List<BtnDto> btnStrArr = userService.getBtnStrArrById(user.getId()); |
|
data.put("token", token); |
|
data.put("user", user); |
|
LocalUser.setTenantId(user.getTenantId()); |
|
LocalUser.setUserId(user.getId()); |
|
data.put("season",inventorySeasonService.getNow()); |
|
//用户的按钮权限 |
|
if(!"admin".equals(user.getLoginName())){ |
|
data.put("userBtn", btnStrArr); |
|
} |
|
data.put("roleType", roleType); |
|
logger.info("===============用户登录 login 方法调用结束==============="); |
|
return R.success(data); |
|
}else{ |
|
return R.fail("用户名或者密码错误"); |
|
} |
|
|
|
|
|
} |
|
|
|
@GetMapping(value = "/getUserSession") |
|
@ApiOperation(value = "获取用户信息") |
|
public R getSessionUser(HttpServletRequest request)throws Exception { |
|
Map<String, Object> data = new HashMap<>(); |
|
Long userId = Long.parseLong(redisService.getObjectFromSessionByKey(request,"userId").toString()); |
|
User user = userService.getUser(userId); |
|
user.setPassword(null); |
|
data.put("user", user); |
|
return R.success(data); |
|
} |
|
|
|
@GetMapping(value = "/logout") |
|
@ApiOperation(value = "退出") |
|
public R logout(HttpServletRequest request, HttpServletResponse response)throws Exception { |
|
redisService.deleteObjectBySession(request,"userId"); |
|
return R.success(); |
|
} |
|
|
|
@PostMapping(value = "/resetPwd") |
|
@ApiOperation(value = "重置密码") |
|
public String resetPwd(@RequestBody JSONObject jsonObject, |
|
HttpServletRequest request) throws Exception { |
|
Map<String, Object> objectMap = new HashMap<>(); |
|
Long id = jsonObject.getLong("id"); |
|
String password = "123456"; |
|
String md5Pwd = Tools.md5Encryp(password); |
|
int update = userService.resetPwd(md5Pwd, id); |
|
if(update > 0) { |
|
return returnJson(objectMap, SUCCESS, ErpInfo.OK.code); |
|
} else { |
|
return returnJson(objectMap, ERROR, ErpInfo.ERROR.code); |
|
} |
|
} |
|
|
|
@PutMapping(value = "/updatePwd") |
|
@ApiOperation(value = "更新密码") |
|
public String updatePwd(@RequestBody JSONObject jsonObject, HttpServletRequest request)throws Exception { |
|
Integer flag = 0; |
|
Map<String, Object> objectMap = new HashMap<String, Object>(); |
|
try { |
|
String info = ""; |
|
Long userId = jsonObject.getLong("userId"); |
|
String oldpwd = jsonObject.getString("oldpassword"); |
|
String password = jsonObject.getString("password"); |
|
User user = userService.getUser(userId); |
|
//必须和原始密码一致才可以更新密码 |
|
if(demonstrateOpen && user.getLoginName().equals(TEST_USER)){ |
|
flag = 3; //jsh用户不能修改密码 |
|
info = "jsh用户不能修改密码"; |
|
} else if (oldpwd.equalsIgnoreCase(user.getPassword())) { |
|
user.setPassword(password); |
|
flag = userService.updateUserByObj(user); //1-成功 |
|
info = "修改成功"; |
|
} else { |
|
flag = 2; //原始密码输入错误 |
|
info = "原始密码输入错误"; |
|
} |
|
objectMap.put("status", flag); |
|
if(flag > 0) { |
|
return returnJson(objectMap, info, ErpInfo.OK.code); |
|
} else { |
|
return returnJson(objectMap, ERROR, ErpInfo.ERROR.code); |
|
} |
|
} catch (Exception e) { |
|
logger.error(">>>>>>>>>>>>>修改用户ID为 : " + jsonObject.getLong("userId") + "密码信息失败", e); |
|
flag = 3; |
|
objectMap.put("status", flag); |
|
return returnJson(objectMap, ERROR, ErpInfo.ERROR.code); |
|
} |
|
} |
|
|
|
/** |
|
* 获取全部用户数据列表 |
|
* @param request |
|
* @return |
|
*/ |
|
@GetMapping(value = "/getAllList") |
|
@ApiOperation(value = "获取全部用户数据列表") |
|
public R getAllList(HttpServletRequest request)throws Exception { |
|
|
|
Map<String, Object> data = new HashMap<String, Object>(); |
|
List<User> dataList = userService.getUser(); |
|
if(dataList!=null) { |
|
data.put("userList", dataList); |
|
} |
|
return R.success(data); |
|
} |
|
|
|
/** |
|
* 用户列表,用于用户下拉框 |
|
* @param request |
|
* @return |
|
* @throws Exception |
|
*/ |
|
@GetMapping(value = "/getUserList") |
|
@ApiOperation(value = "用户列表") |
|
public JSONArray getUserList(HttpServletRequest request)throws Exception { |
|
JSONArray dataArray = new JSONArray(); |
|
try { |
|
List<User> dataList = userService.getUser(); |
|
if (null != dataList) { |
|
for (User user : dataList) { |
|
JSONObject item = new JSONObject(); |
|
item.put("id", user.getId()); |
|
item.put("userName", user.getUsername()); |
|
dataArray.add(item); |
|
} |
|
} |
|
} catch(Exception e){ |
|
e.printStackTrace(); |
|
} |
|
return dataArray; |
|
} |
|
|
|
/** |
|
* create by: cjl |
|
* description: |
|
* 新增用户及机构和用户关系 |
|
* create time: 2019/3/8 16:06 |
|
* @Param: beanJson |
|
* @return java.lang.Object |
|
*/ |
|
@PostMapping("/addUser") |
|
@ApiOperation(value = "新增用户") |
|
@ResponseBody |
|
public Object addUser(@RequestBody JSONObject obj, HttpServletRequest request)throws Exception{ |
|
JSONObject result = ExceptionConstants.standardSuccess(); |
|
// 系统的人数限制 |
|
Object limit = redisService.getObjectFromSessionByKey(request, "userNumLimit"); |
|
Long userNumLimit = ObjectUtil.isNotEmpty(limit) |
|
? Long.parseLong(limit.toString()) |
|
: systemLimit; |
|
Long count = userService.countUser(null,null); |
|
if(count>= userNumLimit) { |
|
throw new BusinessParamCheckingException(ExceptionConstants.USER_OVER_LIMIT_FAILED_CODE, |
|
ExceptionConstants.USER_OVER_LIMIT_FAILED_MSG); |
|
} else { |
|
UserEx ue= JSONObject.parseObject(obj.toJSONString(), UserEx.class); |
|
userService.addUserAndOrgUserRel(ue, request); |
|
} |
|
return result; |
|
} |
|
|
|
/** |
|
* create by: cjl |
|
* description: |
|
* 修改用户及机构和用户关系 |
|
* create time: 2019/3/8 16:06 |
|
* @Param: beanJson |
|
* @return java.lang.Object |
|
*/ |
|
@PutMapping("/updateUser") |
|
@ApiOperation(value = "修改用户") |
|
@ResponseBody |
|
public Object updateUser(@RequestBody JSONObject obj, HttpServletRequest request)throws Exception{ |
|
JSONObject result = ExceptionConstants.standardSuccess(); |
|
UserEx ue= JSONObject.parseObject(obj.toJSONString(), UserEx.class); |
|
userService.updateUserAndOrgUserRel(ue, request); |
|
return result; |
|
} |
|
|
|
/** |
|
* 注册用户 |
|
* @param ue |
|
* @return |
|
* @throws Exception |
|
*/ |
|
@PostMapping(value = "/registerUser") |
|
@ApiOperation(value = "注册用户") |
|
public UserEx registerUser(@RequestBody UserEx ue, |
|
HttpServletRequest request)throws Exception{ |
|
logger.error("用户注册开始..."); |
|
JSONObject result = ExceptionConstants.standardSuccess(); |
|
ue.setUsername(ue.getLoginName()); |
|
userService.checkUserNameAndLoginName(ue); //检查用户名和登录名 |
|
ue = userService.registerUser(ue,manageRoleId,request); |
|
return ue; |
|
} |
|
|
|
/** |
|
* 获取机构用户树 |
|
* @return |
|
* @throws Exception |
|
*/ |
|
@RequestMapping("/getOrganizationUserTree") |
|
@ApiOperation(value = "获取机构用户树") |
|
public JSONArray getOrganizationUserTree()throws Exception{ |
|
JSONArray arr=new JSONArray(); |
|
List<TreeNodeEx> organizationUserTree= userService.getOrganizationUserTree(); |
|
if(organizationUserTree!=null&&organizationUserTree.size()>0){ |
|
for(TreeNodeEx node:organizationUserTree){ |
|
String str=JSON.toJSONString(node); |
|
JSONObject obj=JSON.parseObject(str); |
|
arr.add(obj) ; |
|
} |
|
} |
|
return arr; |
|
} |
|
|
|
/** |
|
* 获取当前用户的角色类型 |
|
* @param request |
|
* @return |
|
*/ |
|
@GetMapping("/getRoleTypeByCurrentUser") |
|
@ApiOperation(value = "获取当前用户的角色类型") |
|
public R getRoleTypeByCurrentUser(HttpServletRequest request) { |
|
|
|
Map<String, Object> data = new HashMap<String, Object>(); |
|
String roleType = redisService.getObjectFromSessionByKey(request,"roleType").toString(); |
|
data.put("roleType", roleType); |
|
return R.success(data); |
|
} |
|
|
|
/** |
|
* 获取随机校验码 |
|
* @param response |
|
* @param key |
|
* @return |
|
*/ |
|
@GetMapping(value = "/randomImage/{key}") |
|
@ApiOperation(value = "获取随机校验码") |
|
public R randomImage(HttpServletResponse response,@PathVariable String key) throws IOException { |
|
|
|
Map<String, Object> data = new HashMap<>(); |
|
String codeNum = Tools.getCharAndNum(4); |
|
String base64 = RandImageUtil.generate(codeNum); |
|
data.put("codeNum", codeNum); |
|
data.put("base64", base64); |
|
return R.success(data); |
|
} |
|
|
|
/** |
|
* 批量设置状态-启用或者禁用 |
|
* @param jsonObject |
|
* @param request |
|
* @return |
|
*/ |
|
@PostMapping(value = "/batchSetStatus") |
|
@ApiOperation(value = "批量设置状态") |
|
public String batchSetStatus(@RequestBody JSONObject jsonObject, |
|
HttpServletRequest request)throws Exception { |
|
Byte status = jsonObject.getByte("status"); |
|
String ids = jsonObject.getString("ids"); |
|
Map<String, Object> objectMap = new HashMap<>(); |
|
int res = userService.batchSetStatus(status, ids); |
|
if(res > 0) { |
|
return returnJson(objectMap, ErpInfo.OK.name, ErpInfo.OK.code); |
|
} else { |
|
return returnJson(objectMap, ErpInfo.ERROR.name, ErpInfo.ERROR.code); |
|
} |
|
} |
|
|
|
/** |
|
* 获取当前用户的用户数量和租户信息 |
|
* @param request |
|
* @return |
|
*/ |
|
@GetMapping(value = "/infoWithTenant") |
|
@ApiOperation(value = "获取当前用户的用户数量和租户信息") |
|
public R randomImage(HttpServletRequest request){ |
|
|
|
Map<String, Object> data = new HashMap<>(); |
|
Long userId = Long.parseLong(redisService.getObjectFromSessionByKey(request,"userId").toString()); |
|
User user = userService.getUser(userId); |
|
//获取当前用户数 |
|
Long userCurrentNum = userService.countUser(null, null); |
|
Tenant tenant = tenantService.getTenantByTenantId(user.getTenantId()); |
|
data.put("type", tenant.getType()); //租户类型,0免费租户,1付费租户 |
|
data.put("expireTime", Tools.parseDateToStr(tenant.getExpireTime())); |
|
data.put("userCurrentNum", userCurrentNum); |
|
data.put("userNumLimit", tenant.getUserNumLimit()); |
|
return R.success(data); |
|
} |
|
}
|
|
|