初步增加微信登录的绑定逻辑

This commit is contained in:
季圣华
2023-05-29 01:12:03 +08:00
parent 146747f916
commit 7d97f0e8ec
11 changed files with 306 additions and 89 deletions

View File

@@ -73,7 +73,11 @@ public class TenantConfig {
public boolean doFilter(MetaObject metaObject) {
MappedStatement ms = SqlParserHelper.getMappedStatement(metaObject);
// 过滤自定义查询此时无租户信息约束出现
if ("com.jsh.erp.datasource.mappers.UserMapperEx.getUserListByUserNameOrLoginName".equals(ms.getId())) {
if ("com.jsh.erp.datasource.mappers.UserMapperEx.getUserByWeixinOpenId".equals(ms.getId())) {
return true;
} else if ("com.jsh.erp.datasource.mappers.UserMapperEx.updateUserWithWeixinOpenId".equals(ms.getId())) {
return true;
} else if ("com.jsh.erp.datasource.mappers.UserMapperEx.getUserListByUserNameOrLoginName".equals(ms.getId())) {
return true;
} else if ("com.jsh.erp.datasource.mappers.UserMapperEx.disableUserByLimit".equals(ms.getId())) {
return true;

View File

@@ -64,94 +64,18 @@ public class UserController {
@Resource
private RedisService redisService;
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 BaseResponseInfo login(@RequestBody User userParam,
HttpServletRequest request)throws Exception {
logger.info("============用户登录 login 方法调用开始==============");
String msgTip = "";
User user=null;
BaseResponseInfo res = new BaseResponseInfo();
try {
String loginName = userParam.getLoginName().trim();
String password = userParam.getPassword().trim();
//判断用户是否已经登录过,登录过不再处理
Object userId = redisService.getObjectFromSessionByKey(request,"userId");
if (userId != null) {
logger.info("====用户已经登录过, login 方法调用结束====");
msgTip = "user already login";
}
//获取用户状态
int userStatus = -1;
try {
redisService.deleteObjectBySession(request,"userId");
userStatus = userService.validateUser(loginName, password);
} catch (Exception e) {
e.printStackTrace();
logger.error(">>>>>>>>>>>>>用户 " + loginName + " 登录 login 方法 访问服务层异常====", e);
msgTip = "access service exception";
}
String token = UUID.randomUUID().toString().replaceAll("-", "") + "";
switch (userStatus) {
case ExceptionCodeConstants.UserExceptionCode.USER_NOT_EXIST:
msgTip = "user is not exist";
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";
//验证通过 可以登录放入session记录登录日志
user = userService.getUserByLoginName(loginName);
if(user.getTenantId()!=null) {
token = token + "_" + user.getTenantId();
}
redisService.storageObjectBySession(token,"userId",user.getId());
break;
default:
break;
}
Map<String, Object> data = new HashMap<String, Object>();
data.put("msgTip", msgTip);
if(user!=null){
String roleType = userService.getRoleTypeByUserId(user.getId()).getType(); //角色类型
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());
JSONArray btnStrArr = userService.getBtnStrArrById(user.getId());
data.put("token", token);
data.put("user", user);
//用户的按钮权限
if(!"admin".equals(user.getLoginName())){
data.put("userBtn", btnStrArr);
}
data.put("roleType", roleType);
}
Map<String, Object> data = userService.login(userParam, request);
res.code = 200;
res.data = data;
logger.info("===============用户登录 login 方法调用结束===============");
} catch(Exception e){
e.printStackTrace();
logger.error(e.getMessage());
@@ -161,6 +85,47 @@ public class UserController {
return res;
}
@PostMapping(value = "/weixinLogin")
@ApiOperation(value = "微信登录")
public BaseResponseInfo weixinLogin(@RequestBody JSONObject jsonObject,
HttpServletRequest request)throws Exception {
BaseResponseInfo res = new BaseResponseInfo();
try {
String weixinCode = jsonObject.getString("weixinCode");
User user = userService.getUserByWeixinCode(weixinCode);
if(user == null) {
res.code = 501;
res.data = "微信未绑定";
} else {
Map<String, Object> data = userService.login(user, request);
res.code = 200;
res.data = data;
}
} catch(Exception e){
e.printStackTrace();
logger.error(e.getMessage());
res.code = 500;
res.data = "用户登录失败";
}
return res;
}
@PostMapping(value = "/weixinBind")
@ApiOperation(value = "绑定微信")
public String weixinBind(@RequestBody JSONObject jsonObject,
HttpServletRequest request)throws Exception {
Map<String, Object> objectMap = new HashMap<>();
String loginName = jsonObject.getString("loginName");
String password = jsonObject.getString("password");
String weixinCode = jsonObject.getString("weixinCode");
int res = userService.weixinBind(loginName, password, weixinCode);
if(res > 0) {
return returnJson(objectMap, ErpInfo.OK.name, ErpInfo.OK.code);
} else {
return returnJson(objectMap, ErpInfo.ERROR.name, ErpInfo.ERROR.code);
}
}
@GetMapping(value = "/getUserSession")
@ApiOperation(value = "获取用户信息")
public BaseResponseInfo getSessionUser(HttpServletRequest request)throws Exception {

View File

@@ -29,6 +29,8 @@ public class User {
private String remark;
private String weixinOpenId;
private Long tenantId;
public Long getId() {
@@ -143,6 +145,14 @@ public class User {
this.remark = remark == null ? null : remark.trim();
}
public String getWeixinOpenId() {
return weixinOpenId;
}
public void setWeixinOpenId(String weixinOpenId) {
this.weixinOpenId = weixinOpenId == null ? null : weixinOpenId.trim();
}
public Long getTenantId() {
return tenantId;
}

View File

@@ -1044,6 +1044,76 @@ public class UserExample {
return (Criteria) this;
}
public Criteria andWeixinOpenIdIsNull() {
addCriterion("weixin_open_id is null");
return (Criteria) this;
}
public Criteria andWeixinOpenIdIsNotNull() {
addCriterion("weixin_open_id is not null");
return (Criteria) this;
}
public Criteria andWeixinOpenIdEqualTo(String value) {
addCriterion("weixin_open_id =", value, "weixinOpenId");
return (Criteria) this;
}
public Criteria andWeixinOpenIdNotEqualTo(String value) {
addCriterion("weixin_open_id <>", value, "weixinOpenId");
return (Criteria) this;
}
public Criteria andWeixinOpenIdGreaterThan(String value) {
addCriterion("weixin_open_id >", value, "weixinOpenId");
return (Criteria) this;
}
public Criteria andWeixinOpenIdGreaterThanOrEqualTo(String value) {
addCriterion("weixin_open_id >=", value, "weixinOpenId");
return (Criteria) this;
}
public Criteria andWeixinOpenIdLessThan(String value) {
addCriterion("weixin_open_id <", value, "weixinOpenId");
return (Criteria) this;
}
public Criteria andWeixinOpenIdLessThanOrEqualTo(String value) {
addCriterion("weixin_open_id <=", value, "weixinOpenId");
return (Criteria) this;
}
public Criteria andWeixinOpenIdLike(String value) {
addCriterion("weixin_open_id like", value, "weixinOpenId");
return (Criteria) this;
}
public Criteria andWeixinOpenIdNotLike(String value) {
addCriterion("weixin_open_id not like", value, "weixinOpenId");
return (Criteria) this;
}
public Criteria andWeixinOpenIdIn(List<String> values) {
addCriterion("weixin_open_id in", values, "weixinOpenId");
return (Criteria) this;
}
public Criteria andWeixinOpenIdNotIn(List<String> values) {
addCriterion("weixin_open_id not in", values, "weixinOpenId");
return (Criteria) this;
}
public Criteria andWeixinOpenIdBetween(String value1, String value2) {
addCriterion("weixin_open_id between", value1, value2, "weixinOpenId");
return (Criteria) this;
}
public Criteria andWeixinOpenIdNotBetween(String value1, String value2) {
addCriterion("weixin_open_id not between", value1, value2, "weixinOpenId");
return (Criteria) this;
}
public Criteria andTenantIdIsNull() {
addCriterion("tenant_id is null");
return (Criteria) this;

View File

@@ -36,4 +36,12 @@ public interface UserMapperEx {
List<User> getListByOrgaId(
@Param("id") Long id,
@Param("orgaId") Long orgaId);
User getUserByWeixinOpenId(
@Param("weixinOpenId") String weixinOpenId);
int updateUserWithWeixinOpenId(
@Param("loginName") String loginName,
@Param("password") String password,
@Param("weixinOpenId") String weixinOpenId);
}

View File

@@ -13,7 +13,7 @@ import java.io.IOException;
@WebFilter(filterName = "LogCostFilter", urlPatterns = {"/*"},
initParams = {@WebInitParam(name = "filterPath",
value = "/jshERP-boot/user/login#/jshERP-boot/user/registerUser#/jshERP-boot/user/randomImage#" +
value = "/jshERP-boot/user/login#/jshERP-boot/user/weixinLogin#/jshERP-boot/user/registerUser#/jshERP-boot/user/randomImage#" +
"/jshERP-boot/platformConfig/getPlatform#/jshERP-boot/v2/api-docs#/jshERP-boot/webjars#" +
"/jshERP-boot/systemConfig/static#/jshERP-boot/api/plugin/wechat/weChat/share")})
public class LogCostFilter implements Filter {

View File

@@ -3,8 +3,10 @@ package com.jsh.erp.service.user;
import com.jsh.erp.datasource.entities.*;
import com.jsh.erp.exception.BusinessParamCheckingException;
import com.jsh.erp.service.functions.FunctionService;
import com.jsh.erp.service.platformConfig.PlatformConfigService;
import com.jsh.erp.service.redis.RedisService;
import com.jsh.erp.service.role.RoleService;
import com.jsh.erp.utils.HttpClient;
import org.springframework.util.StringUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
@@ -59,6 +61,8 @@ public class UserService {
@Resource
private FunctionService functionService;
@Resource
private PlatformConfigService platformConfigService;
@Resource
private RedisService redisService;
public User getUser(long id)throws Exception {
@@ -282,6 +286,87 @@ public class UserService {
return result;
}
/**
* 用户登录
* @param userParam
* @param request
* @return
* @throws Exception
*/
public Map<String, Object> login(User userParam, HttpServletRequest request) throws Exception {
Map<String, Object> data = new HashMap<>();
String msgTip = "";
User user=null;
String loginName = userParam.getLoginName().trim();
String password = userParam.getPassword().trim();
//判断用户是否已经登录过,登录过不再处理
Object userId = redisService.getObjectFromSessionByKey(request,"userId");
if (userId != null) {
logger.info("====用户已经登录过, login 方法调用结束====");
msgTip = "user already login";
}
//获取用户状态
int userStatus = -1;
try {
redisService.deleteObjectBySession(request,"userId");
userStatus = validateUser(loginName, password);
} catch (Exception e) {
e.printStackTrace();
logger.error(">>>>>>>>>>>>>用户 " + loginName + " 登录 login 方法 访问服务层异常====", e);
msgTip = "access service exception";
}
String token = UUID.randomUUID().toString().replaceAll("-", "") + "";
switch (userStatus) {
case ExceptionCodeConstants.UserExceptionCode.USER_NOT_EXIST:
msgTip = "user is not exist";
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";
//验证通过 可以登录放入session记录登录日志
user = getUserByLoginName(loginName);
if(user.getTenantId()!=null) {
token = token + "_" + user.getTenantId();
}
redisService.storageObjectBySession(token,"userId",user.getId());
break;
default:
break;
}
data.put("msgTip", msgTip);
if(user!=null){
String roleType = getRoleTypeByUserId(user.getId()).getType(); //角色类型
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());
JSONArray btnStrArr = getBtnStrArrById(user.getId());
data.put("token", token);
data.put("user", user);
//用户的按钮权限
if(!"admin".equals(user.getLoginName())){
data.put("userBtn", btnStrArr);
}
data.put("roleType", roleType);
}
return data;
}
public int validateUser(String loginName, String password) throws Exception {
/**默认是可以登录的*/
List<User> list = null;
@@ -803,4 +888,36 @@ public class UserService {
}
return result;
}
public User getUserByWeixinCode(String weixinCode) throws Exception {
String weixinUrl = platformConfigService.getPlatformConfigByKey("weixinUrl").getPlatformValue();
String weixinAppid = platformConfigService.getPlatformConfigByKey("weixinAppid").getPlatformValue();
String weixinSecret = platformConfigService.getPlatformConfigByKey("weixinSecret").getPlatformValue();
String url = weixinUrl + "?appid=" + weixinAppid + "&secret=" + weixinSecret + "&js_code=" + weixinCode
+ "&grant_type=authorization_code";
JSONObject jsonObject = HttpClient.httpGet(url);
if(jsonObject!=null) {
String weixinOpenId = jsonObject.getString("openid");
if(StringUtil.isNotEmpty(weixinOpenId)) {
return userMapperEx.getUserByWeixinOpenId(weixinOpenId);
}
}
return null;
}
public int weixinBind(String loginName, String password, String weixinCode) throws Exception {
String weixinUrl = platformConfigService.getPlatformConfigByKey("weixinUrl").getPlatformValue();
String weixinAppid = platformConfigService.getPlatformConfigByKey("weixinAppid").getPlatformValue();
String weixinSecret = platformConfigService.getPlatformConfigByKey("weixinSecret").getPlatformValue();
String url = weixinUrl + "?appid=" + weixinAppid + "&secret=" + weixinSecret + "&js_code=" + weixinCode
+ "&grant_type=authorization_code";
JSONObject jsonObject = HttpClient.httpGet(url);
if(jsonObject!=null) {
String weixinOpenId = jsonObject.getString("openid");
if(StringUtil.isNotEmpty(weixinOpenId)) {
return userMapperEx.updateUserWithWeixinOpenId(loginName, password, weixinOpenId);
}
}
return 0;
}
}

View File

@@ -16,6 +16,7 @@
<result column="Status" jdbcType="TINYINT" property="status" />
<result column="description" jdbcType="VARCHAR" property="description" />
<result column="remark" jdbcType="VARCHAR" property="remark" />
<result column="weixin_open_id" jdbcType="VARCHAR" property="weixinOpenId" />
<result column="tenant_id" jdbcType="BIGINT" property="tenantId" />
</resultMap>
<sql id="Example_Where_Clause">
@@ -78,7 +79,7 @@
</sql>
<sql id="Base_Column_List">
id, username, login_name, password, leader_flag, position, department, email, phonenum,
ismanager, isystem, Status, description, remark, tenant_id
ismanager, isystem, Status, description, remark, weixin_open_id, tenant_id
</sql>
<select id="selectByExample" parameterType="com.jsh.erp.datasource.entities.UserExample" resultMap="BaseResultMap">
select
@@ -115,14 +116,14 @@
password, leader_flag, position,
department, email, phonenum,
ismanager, isystem, Status,
description, remark, tenant_id
)
description, remark, weixin_open_id,
tenant_id)
values (#{id,jdbcType=BIGINT}, #{username,jdbcType=VARCHAR}, #{loginName,jdbcType=VARCHAR},
#{password,jdbcType=VARCHAR}, #{leaderFlag,jdbcType=VARCHAR}, #{position,jdbcType=VARCHAR},
#{department,jdbcType=VARCHAR}, #{email,jdbcType=VARCHAR}, #{phonenum,jdbcType=VARCHAR},
#{ismanager,jdbcType=TINYINT}, #{isystem,jdbcType=TINYINT}, #{status,jdbcType=TINYINT},
#{description,jdbcType=VARCHAR}, #{remark,jdbcType=VARCHAR}, #{tenantId,jdbcType=BIGINT}
)
#{description,jdbcType=VARCHAR}, #{remark,jdbcType=VARCHAR}, #{weixinOpenId,jdbcType=VARCHAR},
#{tenantId,jdbcType=BIGINT})
</insert>
<insert id="insertSelective" parameterType="com.jsh.erp.datasource.entities.User">
insert into jsh_user
@@ -169,6 +170,9 @@
<if test="remark != null">
remark,
</if>
<if test="weixinOpenId != null">
weixin_open_id,
</if>
<if test="tenantId != null">
tenant_id,
</if>
@@ -216,6 +220,9 @@
<if test="remark != null">
#{remark,jdbcType=VARCHAR},
</if>
<if test="weixinOpenId != null">
#{weixinOpenId,jdbcType=VARCHAR},
</if>
<if test="tenantId != null">
#{tenantId,jdbcType=BIGINT},
</if>
@@ -272,6 +279,9 @@
<if test="record.remark != null">
remark = #{record.remark,jdbcType=VARCHAR},
</if>
<if test="record.weixinOpenId != null">
weixin_open_id = #{record.weixinOpenId,jdbcType=VARCHAR},
</if>
<if test="record.tenantId != null">
tenant_id = #{record.tenantId,jdbcType=BIGINT},
</if>
@@ -296,6 +306,7 @@
Status = #{record.status,jdbcType=TINYINT},
description = #{record.description,jdbcType=VARCHAR},
remark = #{record.remark,jdbcType=VARCHAR},
weixin_open_id = #{record.weixinOpenId,jdbcType=VARCHAR},
tenant_id = #{record.tenantId,jdbcType=BIGINT}
<if test="_parameter != null">
<include refid="Update_By_Example_Where_Clause" />
@@ -343,6 +354,9 @@
<if test="remark != null">
remark = #{remark,jdbcType=VARCHAR},
</if>
<if test="weixinOpenId != null">
weixin_open_id = #{weixinOpenId,jdbcType=VARCHAR},
</if>
<if test="tenantId != null">
tenant_id = #{tenantId,jdbcType=BIGINT},
</if>
@@ -364,6 +378,7 @@
Status = #{status,jdbcType=TINYINT},
description = #{description,jdbcType=VARCHAR},
remark = #{remark,jdbcType=VARCHAR},
weixin_open_id = #{weixinOpenId,jdbcType=VARCHAR},
tenant_id = #{tenantId,jdbcType=BIGINT}
where id = #{id,jdbcType=BIGINT}
</update>

View File

@@ -9,6 +9,7 @@
<result column="roleId" jdbcType="VARCHAR" property="roleId" />
<result column="roleName" jdbcType="VARCHAR" property="roleName" />
</resultMap>
<select id="selectByConditionUser" parameterType="com.jsh.erp.datasource.entities.UserExample" resultMap="ResultMapEx">
select tb.*,
(select r.id from jsh_user_business ub
@@ -144,4 +145,16 @@
and u.id != #{id}
</if>
</select>
<select id="getUserByWeixinOpenId" resultType="com.jsh.erp.datasource.entities.User">
select u.* from jsh_user u
where u.weixin_open_id = #{weixinOpenId}
and ifnull(u.status,'0') not in('1','2')
</select>
<update id="updateUserWithWeixinOpenId">
update jsh_user u set u.weixin_open_id = #{weixinOpenId}
where u.login_name = #{loginName} and u.password = #{password}
and ifnull(u.status,'0') not in('1','2')
</update>
</mapper>