Browse Source

新增:统一登录平台用户认证,用户表(t_base_user)添加 sources 字段。

lym 1 year ago
parent
commit
bf70603426
20 changed files with 884 additions and 12 deletions
  1. 5 0
      common-parent/pom.xml
  2. 2 2
      goods-manage-service/src/main/resources/application-dev.properties
  3. 7 0
      org-manage-client/src/main/java/com/hcloud/microservice/org/facade/client/UserManagerService.java
  4. 13 0
      org-manage-client/src/main/java/com/hcloud/microservice/org/facade/entity/BaseUser.java
  5. 5 0
      org-manage-client/src/main/java/com/hcloud/microservice/org/facade/fallback/factory/UserManagerFallbackFactory.java
  6. 4 1
      org-manage-client/src/main/java/com/hcloud/microservice/org/facade/forms/BaseUserForm.java
  7. 27 0
      org-manage-service/src/main/java/com/hcloud/microservice/org/controller/UserManagerController.java
  8. 7 0
      org-manage-service/src/main/java/com/hcloud/microservice/org/dao/BaseUserMapper.java
  9. 6 0
      org-manage-service/src/main/java/com/hcloud/microservice/org/service/BaseUserService.java
  10. 63 1
      org-manage-service/src/main/java/com/hcloud/microservice/org/service/impl/BaseUserServiceImpl.java
  11. 15 0
      org-manage-service/src/main/java/com/hcloud/microservice/org/sso/ISsoService.java
  12. 391 0
      org-manage-service/src/main/java/com/hcloud/microservice/org/sso/JedisUtil.java
  13. 54 0
      org-manage-service/src/main/java/com/hcloud/microservice/org/sso/XxlSsoConfig.java
  14. 142 0
      org-manage-service/src/main/java/com/hcloud/microservice/org/sso/XxlSsoUser.java
  15. 92 0
      org-manage-service/src/main/java/com/hcloud/microservice/org/sso/impl/SsoServiceImpl.java
  16. 8 2
      org-manage-service/src/main/resources/application-dev.properties
  17. 8 0
      org-manage-service/src/main/resources/application-pro.properties
  18. 9 1
      org-manage-service/src/main/resources/application-test.properties
  19. 13 0
      org-manage-service/src/main/resources/mappers/BaseUserMapper.xml
  20. 13 5
      traced-source-web/src/main/java/com/hcloud/microservice/traced/web/sysmanager/UserManagerController.java

+ 5 - 0
common-parent/pom.xml

@@ -146,6 +146,11 @@
                 <artifactId>mysql-connector-java</artifactId>
                 <version>5.1.47</version>
             </dependency>
+            <dependency>
+                <groupId>redis.clients</groupId>
+                <artifactId>jedis</artifactId>
+                <version>2.9.3</version>
+            </dependency>
         </dependencies>
     </dependencyManagement>
 

+ 2 - 2
goods-manage-service/src/main/resources/application-dev.properties

@@ -12,10 +12,10 @@ spring.http.multipart.maxRequestSize=10Mb
 #mysql datasource setting
 spring.datasource.driver-class-name=com.mysql.jdbc.Driver
 spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
-spring.datasource.url=jdbc:mysql://127.0.0.1:3306/forest_traced_source?characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&autoReconnect=true&useSSL=false&&allowMultiQueries=true
+spring.datasource.url=jdbc:mysql://172.16.90.64:3306/forest_traced_source?characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&autoReconnect=true&useSSL=false&&allowMultiQueries=true
 #spring.datasource.url=jdbc:mysql://localhost:3306/food_security_db?characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
 spring.datasource.username=root
-spring.datasource.password=root123456
+spring.datasource.password=123456
 #spring.datasource.password=123456
 #spring.datasource.password=root
 spring.datasource.initialSize=5

+ 7 - 0
org-manage-client/src/main/java/com/hcloud/microservice/org/facade/client/UserManagerService.java

@@ -91,4 +91,11 @@ public interface UserManagerService {
      */
     @PostMapping("/getUserSubAuth")
     ResultVO getSubUserAuthInfo(@RequestBody BaseUserAuthForm baseUserAuthForm);
+
+    /**
+     * sso用户登录系统
+     * @return
+     */
+    @PostMapping("/ssoLogin")
+    ResultVO ssoLogin(@RequestParam("sessionId") String sessionId);
 }

+ 13 - 0
org-manage-client/src/main/java/com/hcloud/microservice/org/facade/entity/BaseUser.java

@@ -54,6 +54,11 @@ public class BaseUser extends BaseEntity {
 
     private Date modifiedTime;
 
+    /**
+     * 用户来源  0:自增    1:sso
+     */
+    private Integer sources;
+
     public String getGuid() {
         return guid;
     }
@@ -237,4 +242,12 @@ public class BaseUser extends BaseEntity {
     public void setModifiedTime(Date modifiedTime) {
         this.modifiedTime = modifiedTime;
     }
+
+    public Integer getSources() {
+        return sources;
+    }
+
+    public void setSources(Integer sources) {
+        this.sources = sources;
+    }
 }

+ 5 - 0
org-manage-client/src/main/java/com/hcloud/microservice/org/facade/fallback/factory/UserManagerFallbackFactory.java

@@ -87,6 +87,11 @@ public class UserManagerFallbackFactory implements FallbackFactory<UserMangerFac
             public ResultVO getSubUserAuthInfo(BaseUserAuthForm baseUserAuthForm) {
                 return new ResultVO<>(ResultEnum.SYS_BREAK_ERROR);
             }
+
+            @Override
+            public ResultVO ssoLogin(String sessionId) {
+                return new ResultVO<>(ResultEnum.SYS_BREAK_ERROR);
+            }
         };
     }
 }

+ 4 - 1
org-manage-client/src/main/java/com/hcloud/microservice/org/facade/forms/BaseUserForm.java

@@ -83,5 +83,8 @@ public class BaseUserForm extends BaseForm {
      */
     private ResultEnum resultEnum;
 
-
+    /**
+     * 统一登录sessionId
+     */
+    private String sessionId;
 }

+ 27 - 0
org-manage-service/src/main/java/com/hcloud/microservice/org/controller/UserManagerController.java

@@ -301,4 +301,31 @@ public class UserManagerController extends BaseController implements UserManager
             throw new RuntimeException();
         }
     }
+
+    @Override
+    public ResultVO ssoLogin(String sessionId) {
+        Map<String,Object> reslutMap;
+        BaseUserForm baseUserForm =  baseUserService.ssoLogin(sessionId);
+        if(null!=baseUserForm){
+            ResultEnum resultEnum = baseUserForm.getResultEnum();
+            if(resultEnum.getCode()!=0){return new ResultVO(resultEnum);}
+            reslutMap =  new HashMap();
+            String userId = baseUserForm.getGuid();
+            String orgGuid = baseUserForm.getFkOrgGuid();
+            BaseOrg baseOrg = baseOrgService.queryByPrimaryKey(orgGuid);
+            List<BaseUserAuthForm> authList = baseUserService.searchUserAuthInfo(userId,baseUserForm.getFkOrgGuid());
+            Token token = TokenUtil.createJwtToken(userId, GlobleConstant.CURRENT_USER);
+            reslutMap.put(GlobleConstant.ACCESS_TOKEN,token.getAccessToken());
+            reslutMap.put(GlobleConstant.AUTH_LIST, authList);
+            reslutMap.put(GlobleConstant.AUTH_MAP,convertAuthListToMap(authList));
+            reslutMap.put(GlobleConstant.AUTH_MENN_OBJ, convertMenuList(authList));
+            reslutMap.put(GlobleConstant.ORG_GUID,baseUserForm.getFkOrgGuid());
+            reslutMap.put(GlobleConstant.CURRENT_USER, baseUserForm);
+            reslutMap.put(GlobleConstant.USER_GUID,baseUserForm.getGuid());
+            reslutMap.put(GlobleConstant.ORG_OBJECT,baseOrg);
+            redisUtils.setValue(token.getAccessToken(), reslutMap, 2, TimeUnit.HOURS);
+            return success(reslutMap);
+        }
+        return new ResultVO(ResultEnum.FAIL_LOGIN_LOGIN_NAME);
+    }
 }

+ 7 - 0
org-manage-service/src/main/java/com/hcloud/microservice/org/dao/BaseUserMapper.java

@@ -29,4 +29,11 @@ public interface BaseUserMapper extends BaseMapper<BaseUser,String> {
     BaseUser getUserInfoByAccount(@Param("account") String account);
 
     BaseUser selectAccountNotSelf(BaseUserForm BaseUserForm);
+
+    /**
+     * 通过用户名查询用户信息
+     * @param userName
+     * @return
+     */
+    BaseUser getUserInfoByUserName(@Param("userName") String userName);
 }

+ 6 - 0
org-manage-service/src/main/java/com/hcloud/microservice/org/service/BaseUserService.java

@@ -116,4 +116,10 @@ public interface BaseUserService extends BaseServie<BaseUser,String>  {
      * @return false
      */
     boolean isAccountsValid(BaseUserForm baseUserForm);
+
+    /**
+     * 查询用户信息
+     * @return
+     */
+    BaseUserForm ssoLogin(String sessionId);
 }

+ 63 - 1
org-manage-service/src/main/java/com/hcloud/microservice/org/service/impl/BaseUserServiceImpl.java

@@ -7,6 +7,7 @@ import com.google.common.collect.Lists;
 import com.hcloud.microserver.commoncore.base.PageBean;
 import com.hcloud.microserver.commoncore.constant.GlobleConstant;
 import com.hcloud.microserver.commoncore.enums.ResultEnum;
+import com.hcloud.microserver.commoncore.exception.GlobalException;
 import com.hcloud.microserver.commoncore.util.BeanCopyUtil;
 import com.hcloud.microserver.commoncore.util.GetUUID;
 import com.hcloud.microserver.commoncore.util.Md5Util;
@@ -27,6 +28,8 @@ import com.hcloud.microservice.org.facade.forms.BaseUserAuthForm;
 import com.hcloud.microservice.org.facade.forms.BaseUserForm;
 import com.hcloud.microservice.org.service.BaseRoleService;
 import com.hcloud.microservice.org.service.BaseUserService;
+import com.hcloud.microservice.org.sso.ISsoService;
+import com.hcloud.microservice.org.sso.XxlSsoUser;
 import lombok.extern.slf4j.Slf4j;
 import org.apache.commons.net.util.Base64;
 import org.springframework.beans.BeanUtils;
@@ -39,6 +42,7 @@ import java.io.UnsupportedEncodingException;
 import java.util.ArrayList;
 import java.util.Date;
 import java.util.List;
+import java.util.Objects;
 
 /**
  * @author xiezt
@@ -68,6 +72,9 @@ public class BaseUserServiceImpl implements BaseUserService {
     @Autowired
     private BaseRoleService baseRoleService;
 
+    @Autowired
+    private ISsoService ssoService;
+
     @Override
     public int delByPrimaryKey(String guid) {
         return baseUserMapper.deleteByPrimaryKey(guid);
@@ -273,8 +280,8 @@ public class BaseUserServiceImpl implements BaseUserService {
         BaseUserForm resultBean = new BaseUserForm();
         BaseUser baseUsers =  baseUserMapper.getUserInfoByAccount(account);
         if(null!=baseUsers){
-            log.info("login password===================>{}",checkoutPwd(password));
             String loginPwd = checkoutPwd(password);
+            log.info("login password===================>{}",loginPwd);
             String pwd = Md5Util.md5(loginPwd);
             Integer isForbid = baseUsers.getIsForbid();
             if(isForbid==1){
@@ -484,4 +491,59 @@ public class BaseUserServiceImpl implements BaseUserService {
             throw new RuntimeException();
         }
     }
+
+    @Override
+    public BaseUserForm ssoLogin(String sessionId) {
+        BaseUserForm baseUserForm = new BaseUserForm();
+        BaseUser baseUser = null;
+        //统一登录校验
+        if (StringUtils.isEmpty(sessionId)) {
+            throw new GlobalException(1,"统一sessionId为空!");
+        }
+
+        XxlSsoUser xxluser = ssoService.loginCheck(sessionId);
+        if (xxluser != null){
+            String account = xxluser.getUsername(),pwd = xxluser.getPasswordPlaintext();
+            baseUser =  baseUserMapper.getUserInfoByAccount(account);
+            //用户账号不存在
+            if (Objects.isNull(baseUser)){
+                    baseUser = new BaseUser();
+                    baseUser.setAccount(account);
+                    baseUser.setPasswd(pwd);
+                    baseUser.setUserName(xxluser.getNickName());
+                    baseUser.setNickname(xxluser.getNickName());
+                    baseUser.setMobileNo(xxluser.getMobile());
+                    baseUser.setState(1);
+                    baseUser.setSources(1);
+                    baseUser.setIsForbid(0);
+                    baseUser.setCreateTime(new Date());
+                    int i = this.saveSelective(baseUser);
+                    log.info("新增sso用户:"+i);
+            }
+        }else {
+            throw new GlobalException(1,"统一sessionId未获取登录信息!");
+        }
+
+        Integer isForbid = baseUser.getIsForbid();
+        if(isForbid==1){
+            baseUserForm.setResultEnum(ResultEnum.LOGIN_FORBIDED);
+            return baseUserForm;
+        }
+        //在子系统可把密码改了
+        /*if(!Md5Util.md5(xxluser.getPasswordPlaintext()).equalsIgnoreCase(baseUser.getPasswd())){
+            baseUserForm.setResultEnum(ResultEnum.LOGIN_PWD_MISS);
+            return baseUserForm;
+        }*/
+
+        //TODO 更新登录时间
+        BaseUser editBaseUser = new BaseUser();
+        editBaseUser.setGuid(baseUser.getGuid());
+        editBaseUser.setLastLoginTime(new Date());
+        baseUserMapper.updateByPrimaryKeySelective(editBaseUser);
+        BeanCopyUtil.copyBean(baseUser,baseUserForm);
+        baseUserForm.setPasswd(null);
+        log.info("======================>{}",baseUserForm);
+        baseUserForm.setResultEnum(ResultEnum.SUCCESS);
+        return baseUserForm;
+    }
 }

+ 15 - 0
org-manage-service/src/main/java/com/hcloud/microservice/org/sso/ISsoService.java

@@ -0,0 +1,15 @@
+package com.hcloud.microservice.org.sso;
+
+
+/**
+ * 功能描述:
+ *
+ * @author: aleyds
+ * @date: 2023/8/22
+ * @package: com.hw.admin.service.common
+ */
+public interface ISsoService {
+
+    XxlSsoUser loginCheck(String sessionId);
+}
+ 

+ 391 - 0
org-manage-service/src/main/java/com/hcloud/microservice/org/sso/JedisUtil.java

@@ -0,0 +1,391 @@
+package com.hcloud.microservice.org.sso;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import redis.clients.jedis.JedisPoolConfig;
+import redis.clients.jedis.JedisShardInfo;
+import redis.clients.jedis.ShardedJedis;
+import redis.clients.jedis.ShardedJedisPool;
+
+import java.io.*;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.locks.ReentrantLock;
+
+
+/**
+ * Redis client base on jedis
+ *
+ * @author xuxueli 2015-7-10 18:34:07
+ */
+public class JedisUtil {
+    private static Logger logger = LoggerFactory.getLogger(JedisUtil.class);
+
+    /**
+     * redis address, like "{ip}"、"{ip}:{port}"、"{redis/rediss}://xxl-sso:{password}@{ip}:{port:6379}/{db}";Multiple "," separated
+     */
+    private static String address;
+
+    public static void init(String address) {
+        JedisUtil.address = address;
+
+        getInstance();
+    }
+
+    // ------------------------ ShardedJedisPool ------------------------
+    /**
+     *  方式01: Redis单节点 + Jedis单例 : Redis单节点压力过重, Jedis单例存在并发瓶颈 》》不可用于线上
+     *      new Jedis("127.0.0.1", 6379).get("cache_key");
+     *  方式02: Redis单节点 + JedisPool单节点连接池 》》 Redis单节点压力过重,负载和容灾比较差
+     *      new JedisPool(new JedisPoolConfig(), "127.0.0.1", 6379, 10000).getResource().get("cache_key");
+     *  方式03: Redis分片(通过client端集群,一致性哈希方式实现) + Jedis多节点连接池 》》Redis集群,负载和容灾较好, ShardedJedisPool一致性哈希分片,读写均匀,动态扩充
+     *      new ShardedJedisPool(new JedisPoolConfig(), new LinkedList<JedisShardInfo>());
+     *  方式03: Redis集群;
+     *      new JedisCluster(jedisClusterNodes);    // TODO
+     */
+
+    private static ShardedJedisPool shardedJedisPool;
+    private static ReentrantLock INSTANCE_INIT_LOCL = new ReentrantLock(false);
+
+    /**
+     * 获取ShardedJedis实例
+     *
+     * @return
+     */
+    private static ShardedJedis getInstance() {
+        if (shardedJedisPool == null) {
+            try {
+                if (INSTANCE_INIT_LOCL.tryLock(2, TimeUnit.SECONDS)) {
+
+                    try {
+
+                        if (shardedJedisPool == null) {
+
+                            // JedisPoolConfig
+                            JedisPoolConfig config = new JedisPoolConfig();
+                            config.setMaxTotal(200);
+                            config.setMaxIdle(50);
+                            config.setMinIdle(8);
+                            config.setMaxWaitMillis(10000);         // 获取连接时的最大等待毫秒数(如果设置为阻塞时BlockWhenExhausted),如果超时就抛异常, 小于零:阻塞不确定的时间,  默认-1
+                            config.setTestOnBorrow(true);           // 在获取连接的时候检查有效性, 默认false
+                            config.setTestOnReturn(false);          // 调用returnObject方法时,是否进行有效检查
+                            config.setTestWhileIdle(true);          // Idle时进行连接扫描
+                            config.setTimeBetweenEvictionRunsMillis(30000);     // 表示idle object evitor两次扫描之间要sleep的毫秒数
+                            config.setNumTestsPerEvictionRun(10);               // 表示idle object evitor每次扫描的最多的对象数
+                            config.setMinEvictableIdleTimeMillis(60000);        // 表示一个对象至少停留在idle状态的最短时间,然后才能被idle object evitor扫描并驱逐;这一项只有在timeBetweenEvictionRunsMillis大于0时才有意义
+
+
+                            // JedisShardInfo List
+                            List<JedisShardInfo> jedisShardInfos = new LinkedList<JedisShardInfo>();
+
+                            String[] addressArr = address.split(",");
+                            for (int i = 0; i < addressArr.length; i++) {
+                                JedisShardInfo jedisShardInfo = new JedisShardInfo(addressArr[i]);
+                                jedisShardInfos.add(jedisShardInfo);
+                            }
+                            shardedJedisPool = new ShardedJedisPool(config, jedisShardInfos);
+                            logger.info(">>>>>>>>>>> xxl-sso, JedisUtil.ShardedJedisPool init success.");
+                        }
+
+                    } finally {
+                        INSTANCE_INIT_LOCL.unlock();
+                    }
+                }
+
+            } catch (InterruptedException e) {
+                logger.error(e.getMessage(), e);
+            }
+        }
+
+        if (shardedJedisPool == null) {
+            throw new NullPointerException(">>>>>>>>>>> xxl-sso, JedisUtil.ShardedJedisPool is null.");
+        }
+
+        ShardedJedis shardedJedis = shardedJedisPool.getResource();
+        return shardedJedis;
+    }
+
+    public static void close() throws IOException {
+        if(shardedJedisPool != null) {
+            shardedJedisPool.close();
+        }
+    }
+
+
+    // ------------------------ serialize and unserialize ------------------------
+
+    /**
+     * 将对象-->byte[] (由于jedis中不支持直接存储object所以转换成byte[]存入)
+     *
+     * @param object
+     * @return
+     */
+    private static byte[] serialize(Object object) {
+        ObjectOutputStream oos = null;
+        ByteArrayOutputStream baos = null;
+        try {
+            // 序列化
+            baos = new ByteArrayOutputStream();
+            oos = new ObjectOutputStream(baos);
+            oos.writeObject(object);
+            byte[] bytes = baos.toByteArray();
+            return bytes;
+        } catch (Exception e) {
+            logger.error(e.getMessage(), e);
+        } finally {
+            try {
+                oos.close();
+                baos.close();
+            } catch (IOException e) {
+                logger.error(e.getMessage(), e);
+            }
+        }
+        return null;
+    }
+
+    /**
+     * 将byte[] -->Object
+     *
+     * @param bytes
+     * @return
+     */
+    private static Object unserialize(byte[] bytes) {
+        ByteArrayInputStream bais = null;
+        try {
+            // 反序列化
+            bais = new ByteArrayInputStream(bytes);
+            ObjectInputStream ois = new ObjectInputStream(bais);
+            return ois.readObject();
+        } catch (Exception e) {
+            logger.error(e.getMessage(), e);
+        } finally {
+            try {
+                bais.close();
+            } catch (IOException e) {
+                logger.error(e.getMessage(), e);
+            }
+        }
+        return null;
+    }
+
+    // ------------------------ jedis util ------------------------
+    /**
+     * 存储简单的字符串或者是Object 因为jedis没有分装直接存储Object的方法,所以在存储对象需斟酌下
+     * 存储对象的字段是不是非常多而且是不是每个字段都用到,如果是的话那建议直接存储对象,
+     * 否则建议用集合的方式存储,因为redis可以针对集合进行日常的操作很方便而且还可以节省空间
+     */
+
+    /**
+     * Set String
+     *
+     * @param key
+     * @param value
+     * @param seconds 存活时间,单位/秒
+     * @return
+     */
+    public static String setStringValue(String key, String value, int seconds) {
+        String result = null;
+        ShardedJedis client = getInstance();
+        try {
+            result = client.setex(key, seconds, value);
+        } catch (Exception e) {
+            logger.error(e.getMessage(), e);
+        } finally {
+            if (client != null) {
+                client.close();
+            }
+        }
+        return result;
+    }
+
+    /**
+     * Set Object
+     *
+     * @param key
+     * @param obj
+     * @param seconds 存活时间,单位/秒
+     */
+    public static String setObjectValue(String key, Object obj, int seconds) {
+        String result = null;
+        ShardedJedis client = getInstance();
+        try {
+            result = client.setex(key.getBytes(), seconds, serialize(obj));
+        } catch (Exception e) {
+            logger.error(e.getMessage(), e);
+        } finally {
+            if (client != null) {
+                client.close();
+            }
+        }
+        return result;
+    }
+
+    /**
+     * Get String
+     *
+     * @param key
+     * @return
+     */
+    public static String getStringValue(String key) {
+        String value = null;
+        ShardedJedis client = getInstance();
+        try {
+            value = client.get(key);
+        } catch (Exception e) {
+            logger.error(e.getMessage(), e);
+        } finally {
+            if (client != null) {
+                client.close();
+            }
+        }
+        return value;
+    }
+
+    /**
+     * Get Object
+     *
+     * @param key
+     * @return
+     */
+    public static Object getObjectValue(String key) {
+        Object obj = null;
+        ShardedJedis client = getInstance();
+        try {
+            byte[] bytes = client.get(key.getBytes());
+            if (bytes != null && bytes.length > 0) {
+                obj = unserialize(bytes);
+            }
+        } catch (Exception e) {
+            logger.error(e.getMessage(), e);
+        } finally {
+            if (client != null) {
+                client.close();
+            }
+        }
+        return obj;
+    }
+
+    /**
+     * Delete key
+     *
+     * @param key
+     * @return Integer reply, specifically:
+     * an integer greater than 0 if one or more keys were removed
+     * 0 if none of the specified key existed
+     */
+    public static Long del(String key) {
+        Long result = null;
+        ShardedJedis client = getInstance();
+        try {
+            result = client.del(key);
+        } catch (Exception e) {
+            logger.error(e.getMessage(), e);
+        } finally {
+            if (client != null) {
+                client.close();
+            }
+        }
+        return result;
+    }
+
+    /**
+     * incrBy i(+i)
+     *
+     * @param key
+     * @param i
+     * @return new value after incr
+     */
+    public static Long incrBy(String key, int i) {
+        Long result = null;
+        ShardedJedis client = getInstance();
+        try {
+            result = client.incrBy(key, i);
+        } catch (Exception e) {
+            logger.error(e.getMessage(), e);
+        } finally {
+            if (client != null) {
+                client.close();
+            }
+        }
+        return result;
+    }
+
+    /**
+     * exists valid
+     *
+     * @param key
+     * @return Boolean reply, true if the key exists, otherwise false
+     */
+    public static boolean exists(String key) {
+        Boolean result = null;
+        ShardedJedis client = getInstance();
+        try {
+            result = client.exists(key);
+        } catch (Exception e) {
+            logger.error(e.getMessage(), e);
+        } finally {
+            if (client != null) {
+                client.close();
+            }
+        }
+        return result;
+    }
+
+    /**
+     * expire reset
+     *
+     * @param key
+     * @param seconds 存活时间,单位/秒
+     * @return Integer reply, specifically:
+     * 1: the timeout was set.
+     * 0: the timeout was not set since the key already has an associated timeout (versions lt 2.1.3), or the key does not exist.
+     */
+    public static long expire(String key, int seconds) {
+        Long result = null;
+        ShardedJedis client = getInstance();
+        try {
+            result = client.expire(key, seconds);
+        } catch (Exception e) {
+            logger.error(e.getMessage(), e);
+        } finally {
+            if (client != null) {
+                client.close();
+            }
+        }
+        return result;
+    }
+
+    /**
+     * expire at unixTime
+     *
+     * @param key
+     * @param unixTime
+     * @return
+     */
+    public static long expireAt(String key, long unixTime) {
+        Long result = null;
+        ShardedJedis client = getInstance();
+        try {
+            result = client.expireAt(key, unixTime);
+        } catch (Exception e) {
+            logger.error(e.getMessage(), e);
+        } finally {
+            if (client != null) {
+                client.close();
+            }
+        }
+        return result;
+    }
+
+    public static void main(String[] args) {
+        String xxlSsoRedisAddress = "redis://xxl-sso:password@127.0.0.1:6379/0";
+        xxlSsoRedisAddress = "redis://127.0.0.1:6379/0";
+        init(xxlSsoRedisAddress);
+
+        setObjectValue("key", "666", 2*60*60);
+        System.out.println(getObjectValue("key"));
+
+    }
+
+}

+ 54 - 0
org-manage-service/src/main/java/com/hcloud/microservice/org/sso/XxlSsoConfig.java

@@ -0,0 +1,54 @@
+package com.hcloud.microservice.org.sso;
+
+import com.hcloud.microserver.commoncore.util.string.StringUtils;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.DisposableBean;
+import org.springframework.beans.factory.InitializingBean;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.context.annotation.Configuration;
+
+/**
+ * @author xuxueli 2018-11-15
+ */
+@Configuration
+@Slf4j
+public class XxlSsoConfig implements InitializingBean,DisposableBean {
+
+
+
+    @Value("${xxl.sso.redis.host}")
+    private String redisHost;
+    @Value("${xxl.sso.redis.port}")
+    private String redisPort;
+    @Value("${xxl.sso.redis.database}")
+    private String redisDatabase;
+    @Value("${xxl.sso.redis.password}")
+    private String redisPassword;
+
+    @Override
+    public void afterPropertiesSet() {
+        String redisCfg = getRedisConfig();
+        log.info("SSO Redis注册: {}", redisCfg);
+        JedisUtil.init(redisCfg);
+    }
+
+
+    @Override
+    public void destroy() throws Exception {
+
+        // xxl-sso, redis close
+        JedisUtil.close();
+    }
+    private String getRedisConfig(){
+        StringBuffer sb = new StringBuffer();
+        sb.append("redis://");
+        if (StringUtils.isNotEmpty(redisPassword) && !redisPassword.equals("''")){
+            sb.append(redisPassword).append("@");
+        }
+        sb.append(redisHost).append(":").append(redisPort)
+                .append("/").append(redisDatabase);
+        return sb.toString();
+    }
+
+
+}

+ 142 - 0
org-manage-service/src/main/java/com/hcloud/microservice/org/sso/XxlSsoUser.java

@@ -0,0 +1,142 @@
+package com.hcloud.microservice.org.sso;
+
+import java.io.Serializable;
+import java.util.Map;
+
+/**
+ * xxl sso user
+ *
+ * @author xuxueli 2018-04-02 19:59:49
+ */
+public class XxlSsoUser implements Serializable {
+    private static final long serialVersionUID = 42L;
+
+    // field
+    /**
+     * 用户ID
+     */
+    private String userid;
+    /**
+     * 用户登录名称
+     */
+    private String username;
+    /**
+     *  用户昵称
+     */
+    private String nickName;
+    /**
+     * 用户手机号
+     */
+    private String mobile;
+    /**
+     * 用户邮箱
+     */
+    private String email;
+    /**
+     * 用户密码-明文
+     */
+    private String passwordPlaintext;
+    /**
+     * 用户登录token
+     */
+    private String token;
+    private Map<String, String> plugininfo;
+
+    private String version;
+    /**登录过期时间  (分钟)
+     *
+     */
+    private int expireMinute;
+    private long expireFreshTime;
+
+
+    // set get
+    public String getUserid() {
+        return userid;
+    }
+
+    public void setUserid(String userid) {
+        this.userid = userid;
+    }
+
+    public String getUsername() {
+        return username;
+    }
+
+    public void setUsername(String username) {
+        this.username = username;
+    }
+
+    public Map<String, String> getPlugininfo() {
+        return plugininfo;
+    }
+
+    public void setPlugininfo(Map<String, String> plugininfo) {
+        this.plugininfo = plugininfo;
+    }
+
+    public String getVersion() {
+        return version;
+    }
+
+    public void setVersion(String version) {
+        this.version = version;
+    }
+
+    public int getExpireMinute() {
+        return expireMinute;
+    }
+
+    public void setExpireMinute(int expireMinute) {
+        this.expireMinute = expireMinute;
+    }
+
+    public long getExpireFreshTime() {
+        return expireFreshTime;
+    }
+
+    public void setExpireFreshTime(long expireFreshTime) {
+        this.expireFreshTime = expireFreshTime;
+    }
+
+
+    public String getToken() {
+        return token;
+    }
+
+    public void setToken(String token) {
+        this.token = token;
+    }
+
+    public String getPasswordPlaintext() {
+        return passwordPlaintext;
+    }
+
+    public void setPasswordPlaintext(String passwordPlaintext) {
+        this.passwordPlaintext = passwordPlaintext;
+    }
+
+    public String getNickName() {
+        return nickName;
+    }
+
+    public void setNickName(String nickName) {
+        this.nickName = nickName;
+    }
+
+    public String getMobile() {
+        return mobile;
+    }
+
+    public void setMobile(String mobile) {
+        this.mobile = mobile;
+    }
+
+    public String getEmail() {
+        return email;
+    }
+
+    public void setEmail(String email) {
+        this.email = email;
+    }
+}

+ 92 - 0
org-manage-service/src/main/java/com/hcloud/microservice/org/sso/impl/SsoServiceImpl.java

@@ -0,0 +1,92 @@
+package com.hcloud.microservice.org.sso.impl;
+
+import com.alibaba.fastjson.JSON;
+import com.hcloud.microservice.org.sso.ISsoService;
+import com.hcloud.microservice.org.sso.JedisUtil;
+import com.hcloud.microservice.org.sso.XxlSsoUser;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.stereotype.Service;
+
+/**
+ * 功能描述:
+ *
+ * @author: aleyds
+ * @date: 2023/8/22
+ * @package: com.hw.admin.service.common.impl
+ */
+@Service
+public class SsoServiceImpl implements ISsoService {
+
+    @Override
+    public XxlSsoUser loginCheck(String sessionId) {
+        String storeKey = parseStoreKey(sessionId);
+        if (storeKey == null) {
+            return null;
+        } else {
+            XxlSsoUser xxlUser = get(storeKey);
+            if (xxlUser != null) {
+                String version = parseVersion(sessionId);
+                if (xxlUser.getVersion().equals(version)) {
+                    if (System.currentTimeMillis() - xxlUser.getExpireFreshTime() > (long)(xxlUser.getExpireMinute() / 2)) {
+                        xxlUser.setExpireFreshTime(System.currentTimeMillis());
+                        put(storeKey, xxlUser,xxlUser.getExpireMinute());
+                    }
+                    return xxlUser;
+                }
+            }
+
+            return null;
+        }
+    }
+
+
+
+    public static String parseStoreKey(String sessionId) {
+        if (sessionId != null && sessionId.indexOf("_") > -1) {
+            String[] sessionIdArr = sessionId.split("_");
+            if (sessionIdArr.length == 2 && sessionIdArr[0] != null && sessionIdArr[0].trim().length() > 0) {
+                String userId = sessionIdArr[0].trim();
+                return userId;
+            }
+        }
+
+        return null;
+    }
+
+    private  XxlSsoUser get(String storeKey) {
+        String redisKey = redisKey(storeKey);
+        String objectValue = JedisUtil.getStringValue("ST" + redisKey);
+        if (StringUtils.isNotEmpty(objectValue)) {
+            return JSON.parseObject(objectValue, XxlSsoUser.class);
+        } else {
+            return null;
+        }
+    }
+
+    private  void put(String storeKey, XxlSsoUser xxlUser, Integer redisExpireMinite) {
+        String redisKey = redisKey(storeKey);
+        JedisUtil.setStringValue("ST" + redisKey, JSON.toJSONString(xxlUser), redisExpireMinite * 60);
+    }
+
+
+    private  void remove(String storeKey) {
+        String redisKey = redisKey(storeKey);
+        JedisUtil.del("ST" + redisKey);
+    }
+
+    private  String redisKey(String userId) {
+        return "xxl_sso_sessionid".concat("#").concat(userId);
+    }
+
+    private  String parseVersion(String sessionId) {
+        if (sessionId != null && sessionId.indexOf("_") > -1) {
+            String[] sessionIdArr = sessionId.split("_");
+            if (sessionIdArr.length == 2 && sessionIdArr[1] != null && sessionIdArr[1].trim().length() > 0) {
+                String version = sessionIdArr[1].trim();
+                return version;
+            }
+        }
+
+        return null;
+    }
+}

+ 8 - 2
org-manage-service/src/main/resources/application-dev.properties

@@ -12,10 +12,10 @@ spring.http.multipart.maxRequestSize=10Mb
 #mysql datasource setting
 spring.datasource.driver-class-name=com.mysql.jdbc.Driver
 spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
-spring.datasource.url=jdbc:mysql://localhost:3306/forest_traced_source?characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&autoReconnect=true&useSSL=false&&allowMultiQueries=true
+spring.datasource.url=jdbc:mysql://172.16.90.64:3306/forest_traced_source?characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&autoReconnect=true&useSSL=false&&allowMultiQueries=true
 #spring.datasource.url=jdbc:mysql://localhost:3306/traced_source?characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
 spring.datasource.username=root
-spring.datasource.password=root123456
+spring.datasource.password=123456
 #spring.datasource.password=123456
 #spring.datasource.password=root
 spring.datasource.initialSize=5
@@ -84,5 +84,11 @@ spring.redis.timeout=5000
 #(接口配置里的EncodingAESKey值)
 #wx.mp.configs.aesKey=123
 
+#统一登录认证
+xxl.sso.redis.database=4
+xxl.sso.redis.host=172.16.90.201
+xxl.sso.redis.port=6379
+xxl.sso.redis.password=
 
+xxl.sso.server: https://sso.hw.hongweisoft.com/
 

+ 8 - 0
org-manage-service/src/main/resources/application-pro.properties

@@ -91,3 +91,11 @@ spring.redis.timeout=5000
 #wx.mp.configs.token=123
 #(接口配置里的EncodingAESKey值)
 #wx.mp.configs.aesKey=123
+
+#统一登录认证
+xxl.sso.redis.database=4
+xxl.sso.redis.host=172.16.90.201
+xxl.sso.redis.port=6379
+xxl.sso.redis.password=
+
+xxl.sso.server: https://sso.hw.hongweisoft.com/

+ 9 - 1
org-manage-service/src/main/resources/application-test.properties

@@ -81,4 +81,12 @@ spring.redis.timeout=5000
 #(接口配置里的Token值)
 #wx.mp.configs.token=123
 #(接口配置里的EncodingAESKey值)
-#wx.mp.configs.aesKey=123
+#wx.mp.configs.aesKey=123
+
+#统一登录认证
+xxl.sso.redis.database=4
+xxl.sso.redis.host=172.16.90.201
+xxl.sso.redis.port=6379
+xxl.sso.redis.password=
+
+xxl.sso.server: https://sso.hw.hongweisoft.com/

+ 13 - 0
org-manage-service/src/main/resources/mappers/BaseUserMapper.xml

@@ -195,6 +195,9 @@
       <if test="modifiedTime != null">
         modified_time,
       </if>
+      <if test="sources != null">
+        sources,
+      </if>
     </trim>
     <trim prefix="values (" suffix=")" suffixOverrides=",">
       <if test="guid != null">
@@ -266,6 +269,9 @@
       <if test="modifiedTime != null">
         #{modifiedTime,jdbcType=TIMESTAMP},
       </if>
+      <if test="sources != null">
+        #{sources},
+      </if>
     </trim>
   </insert>
   <update id="updateByPrimaryKeySelective" parameterType="com.hcloud.microservice.org.facade.entity.BaseUser">
@@ -379,4 +385,11 @@
       </if>
     </where>
   </select>
+
+  <select id="getUserInfoByUserName" resultMap="BaseResultMap">
+    select
+    <include refid="Base_Column_List" />
+    from t_base_user
+    where state=1 and user_name = #{userName}
+  </select>
 </mapper>

+ 13 - 5
traced-source-web/src/main/java/com/hcloud/microservice/traced/web/sysmanager/UserManagerController.java

@@ -1,16 +1,11 @@
 package com.hcloud.microservice.traced.web.sysmanager;
 
 import com.hcloud.microserver.commoncore.annotation.AuthOrgValidate;
-import com.hcloud.microserver.commoncore.annotation.AuthValidate;
-import com.hcloud.microserver.commoncore.base.BaseController;
 import com.hcloud.microserver.commoncore.base.ResponseBase;
 import com.hcloud.microserver.commoncore.base.ResultVO;
-import com.hcloud.microserver.commoncore.constant.GlobleConstant;
-import com.hcloud.microserver.commoncore.enums.AuthEnum;
 import com.hcloud.microserver.commoncore.enums.OrgAuthEnum;
 import com.hcloud.microserver.commoncore.enums.ResultEnum;
 import com.hcloud.microserver.commoncore.util.BeanCopyUtil;
-import com.hcloud.microserver.commoncore.util.Md5Util;
 import com.hcloud.microservice.org.facade.client.UserManagerService;
 import com.hcloud.microservice.org.facade.forms.BaseUserForm;
 import com.hcloud.microservice.traced.common.BaseInfoDO;
@@ -225,4 +220,17 @@ public class UserManagerController extends TracedBaseController {
         }
         return responseError(resultVO);
     }
+
+    @ApiOperation(value = "sso用户登录",notes = "根据sessionId完成登录动作,")
+    @ApiResponse(code =600,message = "账号不正确")
+    @AuthOrgValidate
+    @PostMapping("/ssoLogin")
+    public ResponseBase ssoLogin(@RequestBody BaseUserForm baseUserForm){
+        log.info("sessionId====================>{}",baseUserForm.getSessionId());
+        ResultVO resultVO = userManagerService.ssoLogin(baseUserForm.getSessionId());
+        if(resultVO.getCode()==0){
+            return responseSuccess(resultVO);
+        }
+        return responseError(resultVO);
+    }
 }