Pārlūkot izejas kodu

webchat springcloud 统一登录

wangqi49 3 mēneši atpakaļ
vecāks
revīzija
4a1bad2334
30 mainītis faili ar 499 papildinājumiem un 45 dzēšanām
  1. 0 0
      resources/nacos-yaml/webchat-act-service-dev.yaml
  2. 0 0
      resources/nacos-yaml/webchat-search-service-dev.yaml
  3. 0 0
      resources/nacos-yaml/webchat-sso-service-dev.yaml
  4. 3 3
      webchat-act/src/main/java/com/webchat/act/WebchatActApplication.java
  5. 0 34
      webchat-act/src/main/java/com/webchat/gateway/controller/TestController.java
  6. 3 0
      webchat-admin/src/main/java/com/webchat/admin/WebchatAdminApplication.java
  7. 99 0
      webchat-admin/src/main/java/com/webchat/admin/filter/OauthFilter.java
  8. 13 0
      webchat-common/src/main/java/com/webchat/common/config/properties/OauthProperties.java
  9. 16 0
      webchat-common/src/main/java/com/webchat/common/enums/BaseErrCodeEnum.java
  10. 10 0
      webchat-common/src/main/java/com/webchat/common/enums/RedisKeyEnum.java
  11. 15 0
      webchat-domain/src/main/java/com/webchat/domain/vo/response/UserBaseResponseVO.java
  12. 2 2
      webchat-gateway/src/main/java/com/webchat/gateway/WebchatGatewayApplication.java
  13. 29 0
      webchat-gateway/src/main/java/com/webchat/gateway/config/GwCorsFilter.java
  14. 0 1
      webchat-gateway/src/main/resources/application.yml
  15. 7 1
      webchat-gateway/src/main/resources/bootstrap.yml
  16. 14 0
      webchat-remote/src/main/java/com/webchat/rmi/sso/OauthServiceClient.java
  17. 10 0
      webchat-remote/src/main/java/com/webchat/rmi/user/UserServiceClient.java
  18. 0 1
      webchat-search/src/main/resources/application.properties
  19. 1 0
      webchat-search/src/main/resources/application.yml
  20. 16 0
      webchat-search/src/main/resources/bootstrap.yml
  21. 9 1
      webchat-sso/pom.xml
  22. 64 0
      webchat-sso/src/main/java/com/webchat/sso/GlobalExceptionAdvice.java
  23. 5 1
      webchat-sso/src/main/java/com/webchat/sso/WebchatSSOApplication.java
  24. 36 0
      webchat-sso/src/main/java/com/webchat/sso/controller/SSOServiceController.java
  25. 102 0
      webchat-sso/src/main/java/com/webchat/sso/service/SSOCoreService.java
  26. 0 1
      webchat-sso/src/main/resources/application.properties
  27. 1 0
      webchat-sso/src/main/resources/application.yml
  28. 22 0
      webchat-sso/src/main/resources/bootstrap.yml
  29. 8 0
      webchat-user/src/main/java/com/webchat/user/controller/UserServiceController.java
  30. 14 0
      webchat-user/src/main/java/com/webchat/user/service/UserService.java

+ 0 - 0
resources/nacos-yaml/webchat-act-service-dev.yaml


+ 0 - 0
resources/nacos-yaml/webchat-search-service-dev.yaml


+ 0 - 0
resources/nacos-yaml/webchat-sso-service-dev.yaml


+ 3 - 3
webchat-act/src/main/java/com/webchat/gateway/WebchatPGCApplication.java → webchat-act/src/main/java/com/webchat/act/WebchatActApplication.java

@@ -1,4 +1,4 @@
-package com.webchat.gateway;
+package com.webchat.act;
 
 import org.springframework.boot.SpringApplication;
 import org.springframework.boot.autoconfigure.SpringBootApplication;
@@ -10,10 +10,10 @@ import org.springframework.context.annotation.ComponentScan;
 @EnableDiscoveryClient
 @ComponentScan("com.webchat")
 @EnableFeignClients("com.webchat.rmi")
-public class WebchatPGCApplication {
+public class WebchatActApplication {
 
     public static void main(String[] args) {
-        SpringApplication.run(WebchatPGCApplication.class, args);
+        SpringApplication.run(WebchatActApplication.class, args);
     }
 
 }

+ 0 - 34
webchat-act/src/main/java/com/webchat/gateway/controller/TestController.java

@@ -1,34 +0,0 @@
-package com.webchat.gateway.controller;
-
-import com.webchat.common.bean.APIResponseBean;
-import com.webchat.common.bean.APIResponseBeanUtil;
-import com.webchat.domain.vo.response.UserBaseResponseInfoVO;
-import com.webchat.rmi.user.UserServiceClient;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.cloud.context.config.annotation.RefreshScope;
-import org.springframework.web.bind.annotation.GetMapping;
-import org.springframework.web.bind.annotation.PathVariable;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RestController;
-
-/**
- * @Author 程序员七七
- * @webSite https://www.coderutil.com
- * @Date 2025/1/14 00:55
- * @description
- */
-@RefreshScope
-@RestController
-@RequestMapping("/pgc-service")
-public class TestController {
-
-    @Autowired
-    private UserServiceClient userServiceClient;
-
-    @GetMapping("/user/{userId}")
-    public APIResponseBean<UserBaseResponseInfoVO> user(@PathVariable String userId) {
-
-        return APIResponseBeanUtil.success(userServiceClient.userInfo(userId));
-    }
-
-}

+ 3 - 0
webchat-admin/src/main/java/com/webchat/admin/WebchatAdminApplication.java

@@ -2,10 +2,13 @@ package com.webchat.admin;
 
 import org.springframework.boot.SpringApplication;
 import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.boot.web.servlet.ServletComponentScan;
+import org.springframework.cloud.openfeign.EnableFeignClients;
 import org.springframework.context.annotation.ComponentScan;
 
 @SpringBootApplication
 @ComponentScan("com.webchat")
+@EnableFeignClients("com.webchat.rmi")
 public class WebchatAdminApplication {
 
     public static void main(String[] args) {

+ 99 - 0
webchat-admin/src/main/java/com/webchat/admin/filter/OauthFilter.java

@@ -0,0 +1,99 @@
+package com.webchat.admin.filter;
+
+import com.webchat.common.config.properties.OauthProperties;
+import com.webchat.common.constants.CookieConstants;
+import com.webchat.common.enums.BaseErrCodeEnum;
+import com.webchat.common.helper.SessionHelper;
+import com.webchat.common.util.JsonUtil;
+import com.webchat.common.util.RemoteIpUtil;
+import com.webchat.rmi.sso.OauthServiceClient;
+import jakarta.servlet.Filter;
+import jakarta.servlet.FilterChain;
+import jakarta.servlet.FilterConfig;
+import jakarta.servlet.ServletException;
+import jakarta.servlet.ServletRequest;
+import jakarta.servlet.ServletResponse;
+import jakarta.servlet.annotation.WebFilter;
+import jakarta.servlet.http.Cookie;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.core.annotation.Order;
+import org.springframework.stereotype.Component;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * @Author: 程序员七七
+ * @Date: 16.11.21 11:26 下午
+ */
+@Slf4j
+@Order(-6)
+@WebFilter(filterName = "oauthFilter", urlPatterns = {"/*"})
+@Component
+public class OauthFilter implements Filter {
+
+    @Autowired
+    private OauthProperties oauthProperties;
+
+    @Autowired
+    private OauthServiceClient oauthServiceClient;
+
+    /***
+     * 未登录
+     */
+    private static final String DEFAULT_USER_ID = "访客";
+
+
+    @Override
+    public void init(FilterConfig filterConfig) throws ServletException {
+
+    }
+
+    @Override
+    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
+        HttpServletRequest request = (HttpServletRequest) servletRequest;
+        HttpServletResponse response = (HttpServletResponse) servletResponse;
+        // 取集中session服务判断是否已经登录,如果已经登录则直接进入后续方法。
+
+        String oauthCode = request.getParameter("oauth_code");
+
+        if (StringUtils.isNotBlank(oauthCode)) {
+            String userId = oauthServiceClient.getUserIdByOauthCode(oauthCode).getData();
+            // TODO..
+        }
+
+        Cookie[] cookies = request.getCookies();
+        this.unLogin(request, response);
+
+    }
+
+    private void unLogin(HttpServletRequest request, HttpServletResponse response) {
+        Map<String, Object> responseMap = new HashMap<>();
+        response.setCharacterEncoding("UTF-8"); // 设置字符编码为 UTF-8
+        response.setContentType("application/json;charset=UTF-8"); // 设置内容类型和字符编码
+        responseMap.put("code", BaseErrCodeEnum.UN_LOGIN.getCode());
+        responseMap.put("message", BaseErrCodeEnum.UN_LOGIN.getMessage());
+        responseMap.put("redirect_url", getRedirectUrl(request));
+        try {
+            response.getWriter().println(JsonUtil.toJsonString(responseMap));
+        } catch (IOException e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    private String getRedirectUrl(HttpServletRequest request) {
+        String serverUrl = oauthProperties.getServerUrl();
+        String originUrl = request.getHeader("origin_url");
+        return String.format(serverUrl, originUrl);
+    }
+
+    @Override
+    public void destroy() {
+
+    }
+}

+ 13 - 0
webchat-common/src/main/java/com/webchat/common/config/properties/OauthProperties.java

@@ -0,0 +1,13 @@
+package com.webchat.common.config.properties;
+
+import lombok.Data;
+import org.springframework.boot.context.properties.ConfigurationProperties;
+import org.springframework.context.annotation.Configuration;
+
+@Data
+@Configuration
+@ConfigurationProperties(prefix = "oauth")
+public class OauthProperties {
+
+    private String serverUrl = "";
+}

+ 16 - 0
webchat-common/src/main/java/com/webchat/common/enums/BaseErrCodeEnum.java

@@ -0,0 +1,16 @@
+package com.webchat.common.enums;
+
+import lombok.AllArgsConstructor;
+import lombok.Getter;
+import lombok.NoArgsConstructor;
+
+@Getter
+@NoArgsConstructor
+@AllArgsConstructor
+public enum BaseErrCodeEnum {
+
+    UN_LOGIN(40001, "未登录");
+
+    private int code;
+    private String message;
+}

+ 10 - 0
webchat-common/src/main/java/com/webchat/common/enums/RedisKeyEnum.java

@@ -7,6 +7,16 @@ import org.apache.commons.lang3.StringUtils;
 @Getter
 public enum RedisKeyEnum {
 
+    /**
+     * 统一登录授权码缓存
+     */
+    OAUTH_CODE_CACHE("OAUTH_CODE_CACHE", 2 * 60L),
+
+    /**
+     * 统一登录授权码兑换计数
+     */
+    OAUTH_CODE_GET_COUNT_CACHE("OAUTH_CODE_GET_COUNT_CACHE", 2 * 60L),
+
     /***
      * 注册限流,5S内一次
      */

+ 15 - 0
webchat-domain/src/main/java/com/webchat/domain/vo/response/UserBaseResponseVO.java

@@ -0,0 +1,15 @@
+package com.webchat.domain.vo.response;
+
+import lombok.Data;
+
+@Data
+public class UserBaseResponseVO {
+
+    private String userId;
+
+    private String mobile;
+
+    private String password;
+
+    private String roleCode;
+}

+ 2 - 2
webchat-gateway/src/main/java/com/webchat/gateway/WebchatGatewayApplication.java

@@ -2,10 +2,10 @@ package com.webchat.gateway;
 
 import org.springframework.boot.SpringApplication;
 import org.springframework.boot.autoconfigure.SpringBootApplication;
-import org.springframework.boot.web.servlet.ServletComponentScan;
 import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
-import org.springframework.context.annotation.ComponentScan;
+import org.springframework.web.reactive.config.EnableWebFlux;
 
+@EnableWebFlux
 @SpringBootApplication
 @EnableDiscoveryClient
 public class WebchatGatewayApplication {

+ 29 - 0
webchat-gateway/src/main/java/com/webchat/gateway/config/GwCorsFilter.java

@@ -0,0 +1,29 @@
+package com.webchat.gateway.config;
+
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.web.cors.CorsConfiguration;
+import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
+import org.springframework.web.filter.CorsFilter;
+
+@Configuration
+public class GwCorsFilter {
+  // 当前跨域请求最大有效时长。这里默认1天
+  private static final long MAX_AGE = 24 * 60 * 60;
+
+  private CorsConfiguration buildConfig() {
+    CorsConfiguration corsConfiguration = new CorsConfiguration();
+    corsConfiguration.addAllowedOrigin("*"); // 1 设置访问源地址
+    corsConfiguration.addAllowedHeader("*"); // 2 设置访问源请求头
+    corsConfiguration.addAllowedMethod("*"); // 3 设置访问源请求方法
+    corsConfiguration.setMaxAge(MAX_AGE);
+    return corsConfiguration;
+  }
+
+  @Bean
+  public CorsFilter corsFilter() {
+    org.springframework.web.cors.UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
+    source.registerCorsConfiguration("/**", buildConfig()); // 4 对接口配置跨域设置
+    return new CorsFilter(source);
+  }
+}

Failā izmaiņas netiks attēlotas, jo tās ir par lielu
+ 0 - 1
webchat-gateway/src/main/resources/application.yml


+ 7 - 1
webchat-gateway/src/main/resources/bootstrap.yml

@@ -7,4 +7,10 @@ spring:
     nacos:
       discovery:
         server-addr: 127.0.0.1:8848
-        namespace: 2cdfb8e3-f127-4020-93df-2d4c3dc805b5
+        namespace: 2cdfb8e3-f127-4020-93df-2d4c3dc805b5
+      config:
+        server-addr: 127.0.0.1:8848
+        namespace: 2cdfb8e3-f127-4020-93df-2d4c3dc805b5
+        file-extension: yaml
+        group: DEFAULT_GROUP
+        refresh-enabled: true

+ 14 - 0
webchat-remote/src/main/java/com/webchat/rmi/sso/OauthServiceClient.java

@@ -0,0 +1,14 @@
+package com.webchat.rmi.sso;
+
+
+import com.webchat.common.bean.APIResponseBean;
+import org.springframework.cloud.openfeign.FeignClient;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PathVariable;
+
+@FeignClient(name = "webchat-sso-service")
+public interface OauthServiceClient {
+
+    @GetMapping("/sso-service/oauth/userId/{oauthCode}")
+    APIResponseBean<String> getUserIdByOauthCode(@PathVariable String oauthCode);
+}

+ 10 - 0
webchat-remote/src/main/java/com/webchat/rmi/user/UserServiceClient.java

@@ -2,6 +2,7 @@ package com.webchat.rmi.user;
 
 import com.webchat.common.bean.APIResponseBean;
 import com.webchat.domain.vo.response.UserBaseResponseInfoVO;
+import com.webchat.domain.vo.response.UserBaseResponseVO;
 import org.springframework.cloud.openfeign.FeignClient;
 import org.springframework.web.bind.annotation.GetMapping;
 import org.springframework.web.bind.annotation.PathVariable;
@@ -23,4 +24,13 @@ public interface UserServiceClient {
      */
     @GetMapping("/user-service/user/info/{userId}")
     APIResponseBean<UserBaseResponseInfoVO> userInfo(@PathVariable String userId);
+
+    /**
+     * 根据手机号查询用户基础信息
+     *
+     * @param mobile
+     * @return
+     */
+    @GetMapping("/user-service/user/mobile/info/{mobile}")
+    APIResponseBean<UserBaseResponseVO> userBaseInfo(@PathVariable String mobile);
 }

+ 0 - 1
webchat-search/src/main/resources/application.properties

@@ -1 +0,0 @@
-spring.application.name=webchat-user

+ 1 - 0
webchat-search/src/main/resources/application.yml

@@ -0,0 +1 @@
+server:
  port: 8089

+ 16 - 0
webchat-search/src/main/resources/bootstrap.yml

@@ -0,0 +1,16 @@
+spring:
+  application:
+    name: webchat-search-service
+  profiles:
+    active: dev
+  cloud:
+    nacos:
+      config:
+        server-addr: 127.0.0.1:8848
+        namespace: 2cdfb8e3-f127-4020-93df-2d4c3dc805b5
+        file-extension: yaml
+        group: DEFAULT_GROUP
+        refresh-enabled: true
+      discovery:
+        server-addr: 127.0.0.1:8848
+        namespace: 2cdfb8e3-f127-4020-93df-2d4c3dc805b5

+ 9 - 1
webchat-sso/pom.xml

@@ -21,10 +21,18 @@
     </properties>
     <dependencies>
         <dependency>
+            <groupId>com.webchat</groupId>
+            <artifactId>webchat-remote</artifactId>
+            <version>1.0-SNAPSHOT</version>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-thymeleaf</artifactId>
+        </dependency>
+        <dependency>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter</artifactId>
         </dependency>
-
         <dependency>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-test</artifactId>

+ 64 - 0
webchat-sso/src/main/java/com/webchat/sso/GlobalExceptionAdvice.java

@@ -0,0 +1,64 @@
+package com.webchat.sso;
+
+import com.webchat.common.bean.APIResponseBean;
+import com.webchat.common.bean.APIResponseBeanUtil;
+import com.webchat.common.enums.APIErrorCommonEnum;
+import com.webchat.common.exception.AuthException;
+import com.webchat.common.exception.BusinessException;
+import com.webchat.common.exception.NotFoundException;
+import jakarta.servlet.http.HttpServletRequest;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.http.converter.HttpMessageConversionException;
+import org.springframework.web.HttpRequestMethodNotSupportedException;
+import org.springframework.web.bind.MethodArgumentNotValidException;
+import org.springframework.web.bind.annotation.ControllerAdvice;
+import org.springframework.web.bind.annotation.ExceptionHandler;
+import org.springframework.web.bind.annotation.ResponseBody;
+
+
+/***
+ * 统一异常处理器
+ * @Author 程序员七七 ==> http://www.coderutil.com网站作者
+ */
+@Slf4j
+@ControllerAdvice
+public class GlobalExceptionAdvice {
+
+    @ExceptionHandler(Exception.class)
+    @ResponseBody
+    public ResponseEntity<APIResponseBean> exceptionHandler(HttpServletRequest request, Exception e) {
+        log.error("异常详情信息:", e);
+        if (e instanceof AuthException) {
+            APIResponseBean apiResponseBean = APIResponseBeanUtil.error(((AuthException) e).getCode(), e.getMessage());
+            return new ResponseEntity(apiResponseBean, HttpStatus.OK);
+        }
+        if (e instanceof IllegalArgumentException) {
+            APIResponseBean apiResponseBean = APIResponseBeanUtil.error(500, e.getMessage());
+            return new ResponseEntity(apiResponseBean, HttpStatus.OK);
+        } else if (e instanceof BusinessException) {
+            APIResponseBean apiResponseBean = APIResponseBeanUtil.error(((BusinessException) e).getCode(), e.getMessage());
+            return new ResponseEntity(apiResponseBean, HttpStatus.OK);
+        } else if (e instanceof NotFoundException) {
+            APIResponseBean apiResponseBean = APIResponseBeanUtil.error(((NotFoundException) e).getCode(), e.getMessage());
+            return new ResponseEntity(apiResponseBean, HttpStatus.OK);
+        } else if (e instanceof HttpRequestMethodNotSupportedException) {
+            APIResponseBean apiResponseBean = APIResponseBeanUtil.error(500, e.getMessage());
+            return new ResponseEntity(apiResponseBean, HttpStatus.OK);
+        } else if (e instanceof MethodArgumentNotValidException) {
+            /***
+             * 处理@Validated参数校验失败异常
+             */
+            APIResponseBean apiResponseBean = APIResponseBeanUtil.error(APIErrorCommonEnum.VALID_EXCEPTION.getCode(),
+                    "参数校验异常");
+            return new ResponseEntity(apiResponseBean, HttpStatus.OK);
+        } else if (e instanceof HttpMessageConversionException) {
+            APIResponseBean apiResponseBean = APIResponseBeanUtil.error(APIErrorCommonEnum.VALID_EXCEPTION.getCode(),
+                    "参数转换异常");
+            return new ResponseEntity(apiResponseBean, HttpStatus.OK);
+        }
+        APIResponseBean apiResponseBean = APIResponseBeanUtil.error(500, "服务端繁忙");
+        return new ResponseEntity(apiResponseBean, HttpStatus.INTERNAL_SERVER_ERROR);
+    }
+}

+ 5 - 1
webchat-sso/src/main/java/com/webchat/web/WebchatSSOApplication.java → webchat-sso/src/main/java/com/webchat/sso/WebchatSSOApplication.java

@@ -1,9 +1,13 @@
-package com.webchat.web;
+package com.webchat.sso;
 
 import org.springframework.boot.SpringApplication;
 import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.cloud.openfeign.EnableFeignClients;
+import org.springframework.context.annotation.ComponentScan;
 
+@ComponentScan(basePackages = "com.webchat")
 @SpringBootApplication
+@EnableFeignClients("com.webchat.rmi")
 public class WebchatSSOApplication {
 
     public static void main(String[] args) {

+ 36 - 0
webchat-sso/src/main/java/com/webchat/sso/controller/SSOServiceController.java

@@ -0,0 +1,36 @@
+package com.webchat.sso.controller;
+
+import com.webchat.common.bean.APIResponseBean;
+import com.webchat.common.bean.APIResponseBeanUtil;
+import com.webchat.domain.vo.request.UserLoginInfoRequestVO;
+import com.webchat.rmi.sso.OauthServiceClient;
+import com.webchat.sso.service.SSOCoreService;
+import lombok.Getter;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+@RestController
+@RequestMapping("/sso-service/oauth")
+public class SSOServiceController implements OauthServiceClient {
+
+    @Autowired
+    private SSOCoreService ssoCoreService;
+
+    @PostMapping("/login")
+    public APIResponseBean<String> login(@RequestBody UserLoginInfoRequestVO loginInfoRequest) {
+
+        return APIResponseBeanUtil.success(ssoCoreService.login(loginInfoRequest));
+    }
+
+    @GetMapping("/userId/{oauthCode}")
+    @Override
+    public APIResponseBean<String> getUserIdByOauthCode(@PathVariable String oauthCode) {
+        String userId = ssoCoreService.getUserIdByOauthCode(oauthCode);
+        return APIResponseBeanUtil.success(userId);
+    }
+}

+ 102 - 0
webchat-sso/src/main/java/com/webchat/sso/service/SSOCoreService.java

@@ -0,0 +1,102 @@
+package com.webchat.sso.service;
+
+import com.webchat.common.bean.APIResponseBean;
+import com.webchat.common.bean.APIResponseBeanUtil;
+import com.webchat.common.constants.WebConstant;
+import com.webchat.common.enums.RedisKeyEnum;
+import com.webchat.common.exception.AuthException;
+import com.webchat.common.service.RedisService;
+import com.webchat.common.util.IDGenerateUtil;
+import com.webchat.common.util.MD5Utils;
+import com.webchat.domain.vo.request.UserLoginInfoRequestVO;
+import com.webchat.domain.vo.response.UserBaseResponseVO;
+import com.webchat.rmi.user.UserServiceClient;
+import org.apache.commons.lang3.ObjectUtils;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+
+@Service
+public class SSOCoreService {
+
+    @Autowired
+    private UserServiceClient userServiceClient;
+
+    @Autowired
+    private RedisService redisService;
+
+    /**
+     * 登录授权码兑换次数限制
+     */
+    private static final int MAX_EXCHANGE_COUNT = 2;
+
+    /**
+     * 账号登录服务
+     *
+     * @param loginInfoRequest
+     * @return
+     */
+    public String login(UserLoginInfoRequestVO loginInfoRequest) {
+        // 1. 查询账号是否存在
+        UserBaseResponseVO user = this.getUserBaseInfo(loginInfoRequest.getMobile());
+        // 2. 校验账号密码
+        String inputPassword = MD5Utils.md5(loginInfoRequest.getPassword().concat(WebConstant.MD5_SALT));
+        if (!ObjectUtils.equals(inputPassword, user.getPassword())) {
+            throw new AuthException("密码错误");
+        }
+        // 3. 生成登录授权码
+        return genLoginOauthCode(user.getUserId());
+    }
+
+    private UserBaseResponseVO getUserBaseInfo(String mobile) {
+        APIResponseBean<UserBaseResponseVO> responseMessage = userServiceClient.userBaseInfo(mobile);
+        if (APIResponseBeanUtil.isOk(responseMessage)) {
+            return responseMessage.getData();
+        }
+        throw new AuthException("用户不存在");
+    }
+
+    /**
+     * 生成登录授权码
+     *
+     * @return
+     */
+    private String genLoginOauthCode(String userId) {
+        // 生成登录授权码
+        String oauthCode = IDGenerateUtil.uuid();
+        String cacheKey = RedisKeyEnum.OAUTH_CODE_CACHE.getKey(oauthCode);
+        redisService.set(cacheKey, userId, RedisKeyEnum.OAUTH_CODE_CACHE.getExpireTime());
+        return oauthCode;
+    }
+
+    /**
+     * 根据授权码获取用户ID
+     *
+     * @param oauthCode
+     * @return
+     */
+    public String getUserIdByOauthCode(String oauthCode) {
+        Long exchangeCount = this.getOauthCodeExchangeCountCache(oauthCode);
+        if (exchangeCount >= MAX_EXCHANGE_COUNT) {
+            throw new AuthException("授权码使用次数过多");
+        }
+        String cacheKey = RedisKeyEnum.OAUTH_CODE_CACHE.getKey(oauthCode);
+        String userId = redisService.get(cacheKey);
+        if (StringUtils.isNotBlank(userId)) {
+            this.addExchangeCountCache(oauthCode);
+            return userId;
+        }
+        throw new AuthException("授权码无效");
+    }
+
+    private void addExchangeCountCache(String oauthCode) {
+        String cacheKey = RedisKeyEnum.OAUTH_CODE_GET_COUNT_CACHE.getKey(oauthCode);
+        redisService.increx(cacheKey, RedisKeyEnum.OAUTH_CODE_GET_COUNT_CACHE.getExpireTime());
+    }
+
+    private Long getOauthCodeExchangeCountCache(String oauthCode) {
+        String cacheKey = RedisKeyEnum.OAUTH_CODE_GET_COUNT_CACHE.getKey(oauthCode);
+        String cache = redisService.get(cacheKey);
+        return StringUtils.isBlank(cache) ? 0L : Long.valueOf(cache);
+    }
+}

+ 0 - 1
webchat-sso/src/main/resources/application.properties

@@ -1 +0,0 @@
-spring.application.name=webchat-sso

+ 1 - 0
webchat-sso/src/main/resources/application.yml

@@ -0,0 +1 @@
+server:
  port: 8079

+ 22 - 0
webchat-sso/src/main/resources/bootstrap.yml

@@ -0,0 +1,22 @@
+spring:
+  application:
+    name: webchat-sso-service
+  profiles:
+    active: dev
+  thymeleaf:
+    prefix: classpath:/templates/
+    suffix: .html
+    mode: HTML5
+    encoding: UTF-8
+    cache: false
+  cloud:
+    nacos:
+      config:
+        server-addr: 127.0.0.1:8848
+        namespace: 2cdfb8e3-f127-4020-93df-2d4c3dc805b5
+        file-extension: yaml
+        group: DEFAULT_GROUP
+        refresh-enabled: true
+      discovery:
+        server-addr: 127.0.0.1:8848
+        namespace: 2cdfb8e3-f127-4020-93df-2d4c3dc805b5

+ 8 - 0
webchat-user/src/main/java/com/webchat/user/controller/UserServiceController.java

@@ -3,9 +3,11 @@ package com.webchat.user.controller;
 import com.webchat.common.bean.APIResponseBean;
 import com.webchat.common.bean.APIResponseBeanUtil;
 import com.webchat.domain.vo.response.UserBaseResponseInfoVO;
+import com.webchat.domain.vo.response.UserBaseResponseVO;
 import com.webchat.rmi.user.UserServiceClient;
 import com.webchat.user.service.UserService;
 import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.PathVariable;
 import org.springframework.web.bind.annotation.RestController;
 
 /**
@@ -25,4 +27,10 @@ public class UserServiceController implements UserServiceClient {
 
         return APIResponseBeanUtil.success(userService.getUserInfoByUserId(userId));
     }
+
+    @Override
+    public APIResponseBean<UserBaseResponseVO> userBaseInfo(String mobile) {
+
+        return APIResponseBeanUtil.success(userService.getUserBaseByMobile(mobile));
+    }
 }

+ 14 - 0
webchat-user/src/main/java/com/webchat/user/service/UserService.java

@@ -19,6 +19,7 @@ import com.webchat.domain.vo.request.CreateRobotRequestVO;
 import com.webchat.domain.vo.request.UpdateUserInfoRequestVO;
 import com.webchat.domain.vo.response.GroupResponseInfoVO;
 import com.webchat.domain.vo.response.UserBaseResponseInfoVO;
+import com.webchat.domain.vo.response.UserBaseResponseVO;
 import com.webchat.domain.vo.response.UserSafeResponseInfoVO;
 import com.webchat.user.repository.dao.IGroupUserDAO;
 import com.webchat.user.repository.dao.IUserDAO;
@@ -73,6 +74,19 @@ public class UserService {
     private static final String GROUP_ID_PREFIX = "G";
     private static final String PUBLIC_ACCOUNT_ID_PREFIX = "P";
 
+
+    public UserBaseResponseVO getUserBaseByMobile(String mobile) {
+
+        UserEntity user = userDAO.findByMobile(mobile);
+        if (user != null) {
+            UserBaseResponseVO userBaseResponseVO = new UserBaseResponseVO();
+            BeanUtils.copyProperties(user, userBaseResponseVO);
+            return userBaseResponseVO;
+        }
+        return null;
+    }
+
+
     /**
      * 用户登录 - 登录成功返回用户基本信息
      * @param mobile

Daži faili netika attēloti, jo izmaiņu fails ir pārāk liels