Commit db2c68f7 by 水库浪子

多租户登录改造

1 parent 26fd7c50
Showing 18 changed files with 230 additions and 86 deletions
......@@ -12,7 +12,7 @@ import com.linkwechat.framework.web.service.SysPermissionService;
import com.linkwechat.framework.web.service.TokenService;
import com.linkwechat.system.service.ISysMenuService;
import com.linkwechat.wecom.client.WeAccessTokenClient;
import com.linkwechat.wecom.domain.WeCorpAccount;
import com.linkwechat.common.core.domain.entity.WeCorpAccount;
import com.linkwechat.wecom.domain.dto.WeLoginUserInfoDto;
import com.linkwechat.wecom.service.IWeCorpAccountService;
import org.springframework.beans.factory.annotation.Autowired;
......
package com.linkwechat.web.controller.wecom;
import com.linkwechat.common.annotation.Log;
import com.linkwechat.common.constant.HttpStatus;
import com.linkwechat.common.core.controller.BaseController;
import com.linkwechat.common.core.domain.AjaxResult;
import com.linkwechat.common.core.page.TableDataInfo;
import com.linkwechat.common.enums.BusinessType;
import com.linkwechat.wecom.domain.WeCorpAccount;
import com.linkwechat.common.core.domain.entity.WeCorpAccount;
import com.linkwechat.wecom.service.IWeCorpAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
......
#spring.cloud.nacos.config.server-addr=
#spring.cloud.nacos.config.namespace=
#spring.application.name=
#spring.cloud.nacos.config.file-extension=
\ No newline at end of file
spring.cloud.nacos.config.server-addr=${NACOS_SERVER:119.45.28.29:10848}
spring.cloud.nacos.config.namespace=ce45dbdb-7096-4d39-99ac-f3513f1341ad
spring.application.name=link-wechat
spring.cloud.nacos.config.file-extension=yaml
\ No newline at end of file
......@@ -36,4 +36,7 @@ public class WeComeConfig {
/** 第三方自建应用得url*/
private String[] thirdAppUrl;
/**多租户相关表*/
private String[] needTenant=new String[]{};
}
......@@ -2,7 +2,7 @@ package com.linkwechat.common.constant;
/**
* 通用常量信息
*
*
* @author ruoyi
*/
public class Constants
......@@ -61,7 +61,7 @@ public class Constants
* 登录用户 redis key
*/
public static final String LOGIN_TOKEN_KEY = "login_tokens:";
/**
* 防重提交 redis key
*/
......@@ -151,18 +151,17 @@ public class Constants
public static final String USER_TYPE_WECOME="11";
/** 企业管理 */
public static final String USER_TYOE_CORP_ADMIN="22";
/** 企业微信用户系统中默认用户 */
public static final String DEFAULT_WECOME_ROLE_KEY="WeCome";
/** 企业微信用户系统中默认用户 */
public static final String DEFAULT_WECOME_CORP_ADMIN="CROP_ADMIN_ROLE";
/**完成待办*/
public static final String HANDLE_SUCCESS="1";
}
......@@ -21,7 +21,7 @@ import java.util.List;
/**
* 用户对象 sys_user
*
*
* @author ruoyi
*/
@Data
......@@ -88,8 +88,8 @@ public class SysUser extends BaseEntity
/** 部门对象 */
@Excels({
@Excel(name = "部门名称", targetAttr = "deptName", type = Type.EXPORT),
@Excel(name = "部门负责人", targetAttr = "leader", type = Type.EXPORT)
@Excel(name = "部门名称", targetAttr = "deptName", type = Type.EXPORT),
@Excel(name = "部门负责人", targetAttr = "leader", type = Type.EXPORT)
})
private SysDept dept;
......@@ -105,6 +105,9 @@ public class SysUser extends BaseEntity
/** 是否具有有效得cropId */
private boolean validCropId=false;
private WeCorpAccount weCorpAccount;
public SysUser()
{
......@@ -211,7 +214,7 @@ public class SysUser extends BaseEntity
this.avatar = avatar;
}
@JsonIgnore
@JsonIgnore
@JsonProperty
public String getPassword()
{
......@@ -316,26 +319,26 @@ public class SysUser extends BaseEntity
@Override
public String toString() {
return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)
.append("userId", getUserId())
.append("deptId", getDeptId())
.append("userName", getUserName())
.append("nickName", getNickName())
.append("email", getEmail())
.append("phonenumber", getPhonenumber())
.append("sex", getSex())
.append("avatar", getAvatar())
.append("password", getPassword())
.append("salt", getSalt())
.append("status", getStatus())
.append("delFlag", getDelFlag())
.append("loginIp", getLoginIp())
.append("loginDate", getLoginDate())
.append("createBy", getCreateBy())
.append("createTime", getCreateTime())
.append("updateBy", getUpdateBy())
.append("updateTime", getUpdateTime())
.append("remark", getRemark())
.append("dept", getDept())
.toString();
.append("userId", getUserId())
.append("deptId", getDeptId())
.append("userName", getUserName())
.append("nickName", getNickName())
.append("email", getEmail())
.append("phonenumber", getPhonenumber())
.append("sex", getSex())
.append("avatar", getAvatar())
.append("password", getPassword())
.append("salt", getSalt())
.append("status", getStatus())
.append("delFlag", getDelFlag())
.append("loginIp", getLoginIp())
.append("loginDate", getLoginDate())
.append("createBy", getCreateBy())
.append("createTime", getCreateTime())
.append("updateBy", getUpdateBy())
.append("updateTime", getUpdateTime())
.append("remark", getRemark())
.append("dept", getDept())
.toString();
}
}
package com.linkwechat.wecom.domain;
package com.linkwechat.common.core.domain.entity;
import com.linkwechat.common.core.domain.BaseEntity;
import com.linkwechat.common.utils.SnowFlakeUtil;
......@@ -14,7 +14,7 @@ import javax.validation.constraints.NotBlank;
/**
* 企业id相关配置对象 wx_corp_account
*
*
* @author ruoyi
* @date 2020-08-24
*/
......@@ -76,4 +76,8 @@ public class WeCorpAccount extends BaseEntity
@ApiModelProperty("客户流失通知开关 0:关闭 1:开启")
private String customerChurnNoticeSwitch = new String("0");
@ApiModelProperty("企业管理员账号")
private String cropAccount;
}
package com.linkwechat.framework.config;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import com.github.pagehelper.PageInterceptor;
import com.linkwechat.common.config.WeComeConfig;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import org.apache.ibatis.plugin.Interceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Arrays;
import java.util.List;
/**
* Mybatis支持*匹配扫描包
......@@ -14,6 +29,50 @@ import org.springframework.context.annotation.Configuration;
@Configuration
public class MyBatisPlusConfig
{
@Autowired
WeComeConfig weComeConfig;
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
// 如果用了分页插件注意先 add TenantLineInnerInterceptor 再 add PaginationInnerInterceptor
// 用了分页插件必须设置 MybatisConfiguration#useDeprecatedExecutor = false
// interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
interceptor.addInnerInterceptor(new TenantLineInnerInterceptor(
new TenantLineHandler() {
// manager_id = 1088248166370832385
// 获取租户 ID 值表达式,只支持单个 ID 值
@Override
public Expression getTenantId() {
return new LongValue(1088248166370832385L);
}
// 这是 default 方法,默认返回 false 表示所有表都需要拼多租户条件,
// 这里设置 role表不需要该条件
@Override
public boolean ignoreTable(String tableName) {
if (Arrays.asList(weComeConfig.getNeedTenant())
.contains(tableName)){
return false;
}
return true;
}
@Override
public String getTenantIdColumn() {
return "corp_id";
}
}));
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
@Bean
public ConfigurationCustomizer configurationCustomizer() {
return configuration -> configuration.setUseDeprecatedExecutor(false);
}
@Bean
public Interceptor[] plugins() {
......
......@@ -123,7 +123,9 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
.antMatchers("/wecom/user/getUserInfo").anonymous()
// .antMatchers("/common/uploadFile2Cos").anonymous()
.antMatchers("/wecom/material/temporaryMaterialMediaId").anonymous()
.antMatchers("/wecom/portrait/**").anonymous()
.antMatchers("/wecom/findAddaddEmployes").anonymous()
// 除上面外的所有请求全部需要鉴权认证
.anyRequest().authenticated()
.and()
......
......@@ -5,6 +5,7 @@ import com.linkwechat.common.config.RuoYiConfig;
import com.linkwechat.common.constant.Constants;
import com.linkwechat.common.core.domain.entity.SysRole;
import com.linkwechat.common.core.domain.entity.SysUser;
import com.linkwechat.common.core.domain.entity.WeCorpAccount;
import com.linkwechat.common.core.domain.model.LoginUser;
import com.linkwechat.common.enums.UserStatus;
import com.linkwechat.common.exception.BaseException;
......@@ -12,7 +13,7 @@ import com.linkwechat.common.utils.SecurityUtils;
import com.linkwechat.common.utils.StringUtils;
import com.linkwechat.system.mapper.SysRoleMapper;
import com.linkwechat.system.service.ISysUserService;
import com.linkwechat.wecom.domain.WeUser;
import com.linkwechat.wecom.service.IWeCorpAccountService;
import com.linkwechat.wecom.service.IWeUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
......@@ -51,35 +52,57 @@ public class UserDetailsServiceImpl implements UserDetailsService
private SysRoleMapper roleMapper;
@Autowired
private IWeCorpAccountService iWeCorpAccountService;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
{
SysUser user = userService.selectUserByUserName(username);
if (StringUtils.isNull(user))
{
//we_user表中去查询,如果该表为空则提示用户不存在,如果不为空,则将用户记录注册到系统用户表中
WeUser weUser
= iWeUserService.getById(username);
if(null == weUser){
log.info("登录用户:{} 不存在.", username);
throw new UsernameNotFoundException("登录用户:" + username + " 不存在");
//企业管理登录
//查询企业管理相关账号
WeCorpAccount weCorpByAccount = iWeCorpAccountService.findWeCorpByAccount(username);
if(null != weCorpByAccount){
//注册到we_user表中
user= SysUser.builder()
.userName(weCorpByAccount.getCropAccount())
.nickName(weCorpByAccount.getCompanyName())
.userType(Constants.USER_TYOE_CORP_ADMIN)
.roleIds(ArrayUtil.toArray(roleMapper.selectRoleList(SysRole.builder()
.roleKey(Constants.DEFAULT_WECOME_CORP_ADMIN)
.build()).stream().map(SysRole::getRoleId).collect(Collectors.toList()), Long.class))
.password(SecurityUtils.encryptPassword(ruoYiConfig.getWeUserDefaultPwd()))
.build();
}
//注册到we_user表中
user=SysUser.builder()
.userName(weUser.getUserId())
.nickName(weUser.getName())
.userType(Constants.USER_TYPE_WECOME)
.email(weUser.getEmail())
.phonenumber(weUser.getMobile())
.sex(weUser.getGender() ==0 ? "1": weUser.getGender() .toString())
.avatar(weUser.getAvatarMediaid())
.roleIds(ArrayUtil.toArray(roleMapper.selectRoleList(SysRole.builder()
.roleKey(Constants.DEFAULT_WECOME_ROLE_KEY)
.build()).stream().map(SysRole::getRoleId).collect(Collectors.toList()), Long.class))
.password(SecurityUtils.encryptPassword(ruoYiConfig.getWeUserDefaultPwd()))
.build();
// else{
//
// //we_user表中去查询,如果该表为空则提示用户不存在,如果不为空,则将用户记录注册到系统用户表中
// WeUser weUser
// = iWeUserService.getById(username);
// if(null == weUser){
// log.info("登录用户:{} 不存在.", username);
// throw new UsernameNotFoundException("登录用户:" + username + " 不存在");
// }
//
// //注册到we_user表中
// user=SysUser.builder()
// .userName(weUser.getUserId())
// .nickName(weUser.getName())
// .userType(Constants.USER_TYPE_WECOME)
// .email(weUser.getEmail())
// .phonenumber(weUser.getMobile())
// .sex(weUser.getGender() ==0 ? "1": weUser.getGender() .toString())
// .avatar(weUser.getAvatarMediaid())
// .roleIds(ArrayUtil.toArray(roleMapper.selectRoleList(SysRole.builder()
// .roleKey(Constants.DEFAULT_WECOME_ROLE_KEY)
// .build()).stream().map(SysRole::getRoleId).collect(Collectors.toList()), Long.class))
// .password(SecurityUtils.encryptPassword(ruoYiConfig.getWeUserDefaultPwd()))
// .build();
// }
userService.insertUser(
user
);
......@@ -95,6 +118,13 @@ public class UserDetailsServiceImpl implements UserDetailsService
throw new BaseException("对不起,您的账号:" + username + " 已停用");
}
//当前登录用户为企业管理,设置corpId和密钥相关
if(user.getUserType().equals(Constants.USER_TYOE_CORP_ADMIN)){
user.setWeCorpAccount(
iWeCorpAccountService.findWeCorpByAccount(username)
);
}
return createLoginUser(user);
}
......
......@@ -2,6 +2,7 @@ package com.linkwechat.wecom.factory.impl.customer;
import com.alibaba.fastjson.JSONObject;
import com.linkwechat.common.constant.WeConstans;
import com.linkwechat.common.core.domain.entity.WeCorpAccount;
import com.linkwechat.common.enums.MessageType;
import com.linkwechat.wecom.client.WeMessagePushClient;
import com.linkwechat.wecom.domain.*;
......
......@@ -8,6 +8,7 @@ import com.dtflys.forest.interceptor.Interceptor;
import com.dtflys.forest.utils.ForestDataType;
import com.linkwechat.common.config.WeComeConfig;
import com.linkwechat.common.constant.WeConstans;
import com.linkwechat.common.utils.SecurityUtils;
import com.linkwechat.wecom.domain.dto.WeResultDto;
import com.linkwechat.wecom.service.IWeAccessTokenService;
import lombok.extern.slf4j.Slf4j;
......
package com.linkwechat.wecom.mapper;
import java.util.List;
import com.linkwechat.wecom.domain.WeCorpAccount;
import com.linkwechat.common.core.domain.entity.WeCorpAccount;
import org.apache.ibatis.annotations.Param;
/**
......@@ -59,4 +59,12 @@ public interface WeCorpAccountMapper
* @return
*/
public int startVailWeCorpAccount(@Param("corpId") String corpId);
/**
* 根据企业账号获取企业相关配置
* @param corpAccount
* @return
*/
WeCorpAccount findWeCorpByAccount(@Param("corpAccount") String corpAccount);
}
package com.linkwechat.wecom.service;
import java.util.List;
import com.linkwechat.wecom.domain.WeCorpAccount;
import org.apache.ibatis.annotations.Param;
import com.linkwechat.common.core.domain.entity.WeCorpAccount;
/**
* 企业id相关配置Service接口
......@@ -71,4 +70,6 @@ public interface IWeCorpAccountService
* 客户流失通知开关查询
*/
public String getCustomerChurnNoticeSwitch();
WeCorpAccount findWeCorpByAccount(String corpAccount);
}
......@@ -3,12 +3,15 @@ package com.linkwechat.wecom.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.linkwechat.common.constant.Constants;
import com.linkwechat.common.constant.WeConstans;
import com.linkwechat.common.core.domain.entity.SysUser;
import com.linkwechat.common.core.domain.model.LoginUser;
import com.linkwechat.common.core.redis.RedisCache;
import com.linkwechat.common.exception.wecom.WeComException;
import com.linkwechat.common.utils.SecurityUtils;
import com.linkwechat.common.utils.StringUtils;
import com.linkwechat.wecom.client.WeAccessTokenClient;
import com.linkwechat.wecom.domain.WeApp;
import com.linkwechat.wecom.domain.WeCorpAccount;
import com.linkwechat.common.core.domain.entity.WeCorpAccount;
import com.linkwechat.wecom.domain.dto.WeAccessTokenDtoDto;
import com.linkwechat.wecom.service.IWeAccessTokenService;
import com.linkwechat.wecom.service.IWeAppService;
......@@ -133,16 +136,27 @@ public class WeAccessTokenServiceImpl implements IWeAccessTokenService {
private String findAccessToken(String accessTokenKey){
String weAccessToken =redisCache.getCacheObject(accessTokenKey);
// WeCorpAccount wxCorpAccount
// = iWxCorpAccountService.findValidWeCorpAccount();
WeCorpAccount wxCorpAccount
= SecurityUtils.getLoginUser().getUser().getWeCorpAccount();
if(null == wxCorpAccount){
//返回错误异常,让用户绑定企业id相关信息
throw new WeComException("无可用的corpid和secret");
}
String weAccessToken =redisCache.getCacheObject(accessTokenKey+"::"+wxCorpAccount.getAgentId());
//为空,请求微信服务器同时缓存到redis中
if(StringUtils.isEmpty(weAccessToken)){
WeCorpAccount wxCorpAccount
= iWxCorpAccountService.findValidWeCorpAccount();
if(null == wxCorpAccount){
//返回错误异常,让用户绑定企业id相关信息
throw new WeComException("无可用的corpid和secret");
}
String token="";
Long expires_in=null;
if(WeConstans.WE_COMMON_ACCESS_TOKEN.equals(accessTokenKey) || WeConstans.WE_CONTACT_ACCESS_TOKEN.equals(accessTokenKey)){
......@@ -166,7 +180,7 @@ public class WeAccessTokenServiceImpl implements IWeAccessTokenService {
}
if(StringUtils.isNotEmpty(token)){
redisCache.setCacheObject(accessTokenKey,token,expires_in.intValue(), TimeUnit.SECONDS);
redisCache.setCacheObject(accessTokenKey+"::"+wxCorpAccount.getAgentId(),token,expires_in.intValue(), TimeUnit.SECONDS);
weAccessToken = token;
}
......@@ -181,9 +195,20 @@ public class WeAccessTokenServiceImpl implements IWeAccessTokenService {
*/
@Override
public void removeToken() {
redisCache.deleteObject(WeConstans.WE_COMMON_ACCESS_TOKEN);
redisCache.deleteObject(WeConstans.WE_CONTACT_ACCESS_TOKEN);
redisCache.deleteObject(WeConstans.WE_PROVIDER_ACCESS_TOKEN);
LoginUser loginUser = SecurityUtils.getLoginUser();
if(null != loginUser){
SysUser user = loginUser.getUser();
if(null != user){
WeCorpAccount weCorpAccount = user.getWeCorpAccount();
if(null != weCorpAccount){
redisCache.deleteObject(WeConstans.WE_COMMON_ACCESS_TOKEN+"::"+weCorpAccount.getAgentId());
redisCache.deleteObject(WeConstans.WE_CONTACT_ACCESS_TOKEN+"::"+weCorpAccount.getAgentId());
redisCache.deleteObject(WeConstans.WE_PROVIDER_ACCESS_TOKEN+"::"+weCorpAccount.getAgentId());
}
}
}
}
......
......@@ -5,14 +5,12 @@ import java.util.Optional;
import com.linkwechat.common.constant.Constants;
import com.linkwechat.common.constant.WeConstans;
import com.linkwechat.common.utils.DateUtils;
import com.linkwechat.wecom.service.IWeAccessTokenService;
import com.linkwechat.wecom.service.IWeCorpAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.linkwechat.wecom.mapper.WeCorpAccountMapper;
import com.linkwechat.wecom.domain.WeCorpAccount;
import org.springframework.transaction.annotation.Transactional;
import com.linkwechat.common.core.domain.entity.WeCorpAccount;
/**
* 企业id相关配置Service业务层处理
......@@ -137,4 +135,10 @@ public class WeCorpAccountServiceImpl implements IWeCorpAccountService {
}
@Override
public WeCorpAccount findWeCorpByAccount(String corpAccount) {
return weCorpAccountMapper.findWeCorpByAccount(corpAccount);
}
}
......@@ -13,7 +13,7 @@ import com.linkwechat.common.utils.DateUtils;
import com.linkwechat.common.utils.SecurityUtils;
import com.linkwechat.common.utils.StringUtils;
import com.linkwechat.wecom.client.WeMessagePushClient;
import com.linkwechat.wecom.domain.WeCorpAccount;
import com.linkwechat.common.core.domain.entity.WeCorpAccount;
import com.linkwechat.wecom.domain.WeSensitive;
import com.linkwechat.wecom.domain.WeSensitiveAuditScope;
import com.linkwechat.wecom.domain.WeUser;
......
......@@ -125,8 +125,14 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
</update>
<select id="findWeCorpByAccount" resultMap="WeCorpAccountResult">
<include refid="selectWeCorpAccountVo"/>
WHERE
del_flag = 0
AND corp_account = #{corpAccount}
</select>
</mapper>
\ No newline at end of file
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!