소스 검색

0806 新增novel-user模块

Qing 9 달 전
부모
커밋
115752cad9
36개의 변경된 파일1357개의 추가작업 그리고 1개의 파일을 삭제
  1. 6 0
      novel-cloud-demo/novel-core/src/main/java/com/sf/core/util/GeneUtils.java
  2. 6 0
      novel-cloud-demo/novel-gateway/src/main/resources/application.yml
  3. 23 0
      novel-cloud-demo/novel-user/novel-user-api/pom.xml
  4. 19 0
      novel-cloud-demo/novel-user/novel-user-service/.mvn/wrapper/maven-wrapper.properties
  5. 259 0
      novel-cloud-demo/novel-user/novel-user-service/mvnw
  6. 149 0
      novel-cloud-demo/novel-user/novel-user-service/mvnw.cmd
  7. 68 0
      novel-cloud-demo/novel-user/novel-user-service/pom.xml
  8. 15 0
      novel-cloud-demo/novel-user/novel-user-service/src/main/java/com/sf/user/NovelUserServiceApplication.java
  9. 49 0
      novel-cloud-demo/novel-user/novel-user-service/src/main/java/com/sf/user/config/TokenInterceptor.java
  10. 20 0
      novel-cloud-demo/novel-user/novel-user-service/src/main/java/com/sf/user/config/WebConfig.java
  11. 104 0
      novel-cloud-demo/novel-user/novel-user-service/src/main/java/com/sf/user/controller/UserInfoController.java
  12. 22 0
      novel-cloud-demo/novel-user/novel-user-service/src/main/java/com/sf/user/dto/req/UserCommentReqDto.java
  13. 15 0
      novel-cloud-demo/novel-user/novel-user-service/src/main/java/com/sf/user/dto/req/UserCommentUpdateReqDto.java
  14. 20 0
      novel-cloud-demo/novel-user/novel-user-service/src/main/java/com/sf/user/dto/req/UserLoginReqDto.java
  15. 42 0
      novel-cloud-demo/novel-user/novel-user-service/src/main/java/com/sf/user/dto/req/UserRegisterReqDto.java
  16. 28 0
      novel-cloud-demo/novel-user/novel-user-service/src/main/java/com/sf/user/dto/resp/ImgVerifyCodeRespDto.java
  17. 17 0
      novel-cloud-demo/novel-user/novel-user-service/src/main/java/com/sf/user/dto/resp/UserInfoRespDto.java
  18. 19 0
      novel-cloud-demo/novel-user/novel-user-service/src/main/java/com/sf/user/dto/resp/UserLoginRespDto.java
  19. 28 0
      novel-cloud-demo/novel-user/novel-user-service/src/main/java/com/sf/user/dto/resp/UserRegisterRespDto.java
  20. 80 0
      novel-cloud-demo/novel-user/novel-user-service/src/main/java/com/sf/user/entity/UserInfo.java
  21. 16 0
      novel-cloud-demo/novel-user/novel-user-service/src/main/java/com/sf/user/mapper/UserInfoMapper.java
  22. 26 0
      novel-cloud-demo/novel-user/novel-user-service/src/main/java/com/sf/user/service/IUserInfoService.java
  23. 162 0
      novel-cloud-demo/novel-user/novel-user-service/src/main/java/com/sf/user/service/impl/UserInfoServiceImpl.java
  24. 32 0
      novel-cloud-demo/novel-user/novel-user-service/src/main/java/com/sf/user/util/CaptchaUtils.java
  25. 37 0
      novel-cloud-demo/novel-user/novel-user-service/src/main/java/com/sf/user/util/JwtUtils.java
  26. 22 0
      novel-cloud-demo/novel-user/novel-user-service/src/main/java/com/sf/user/util/UserHolder.java
  27. 12 0
      novel-cloud-demo/novel-user/novel-user-service/src/main/resources/application.yml
  28. 6 0
      novel-cloud-demo/novel-user/novel-user-service/src/main/resources/bootstrap.yml
  29. 5 0
      novel-cloud-demo/novel-user/novel-user-service/src/main/resources/mapper/UserInfoMapper.xml
  30. 13 0
      novel-cloud-demo/novel-user/novel-user-service/src/test/java/com/sf/noveluserservice/NovelUserServiceApplicationTests.java
  31. 24 0
      novel-cloud-demo/novel-user/pom.xml
  32. 2 0
      novel-cloud-demo/pom.xml
  33. 7 0
      novel-demo/pom.xml
  34. 1 0
      novel-demo/src/main/java/com/sf/config/CorsConfig.java
  35. 1 1
      novel-demo/src/main/java/com/sf/service/impl/UserInfoServiceImpl.java
  36. 2 0
      novel-demo/src/main/resources/application.yml

+ 6 - 0
novel-cloud-demo/novel-core/src/main/java/com/sf/core/util/GeneUtils.java

@@ -50,6 +50,12 @@ public class GeneUtils {
 
                 list.add("news_info"); // 新闻列表
                 list.add("news_content"); // 新闻内容表
+                break;
+            case "user":
+                projectPathTmp = "novel-user/novel-user-service/";
+                packageNameTmp = ".user";
+
+                list.add("user_info"); // 用户信息表
             default:
         }
 //        list.add("home_book");  // 首页书籍信息表

+ 6 - 0
novel-cloud-demo/novel-gateway/src/main/resources/application.yml

@@ -39,3 +39,9 @@ spring:
           predicates:
             # 路由断言,路径相匹配的进行路由
             - Path=/api/front/news/**
+        - id: novel-user-service
+          # 使用loadbalancer负载均衡来分发
+          uri: lb://novel-user-service
+          predicates:
+            # 路由断言,路径相匹配的进行路由
+            - Path=/api/front/user/**,/api/front/resource/**

+ 23 - 0
novel-cloud-demo/novel-user/novel-user-api/pom.xml

@@ -0,0 +1,23 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+    <modelVersion>4.0.0</modelVersion>
+    <parent>
+        <groupId>com.sf</groupId>
+        <artifactId>novel-user</artifactId>
+        <version>1.0-SNAPSHOT</version>
+    </parent>
+
+    <artifactId>novel-user-api</artifactId>
+    <packaging>jar</packaging>
+
+    <name>novel-user-api</name>
+    <url>http://maven.apache.org</url>
+
+    <properties>
+        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+    </properties>
+
+    <dependencies>
+
+    </dependencies>
+</project>

+ 19 - 0
novel-cloud-demo/novel-user/novel-user-service/.mvn/wrapper/maven-wrapper.properties

@@ -0,0 +1,19 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+wrapperVersion=3.3.2
+distributionType=only-script
+distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.7/apache-maven-3.9.7-bin.zip

+ 259 - 0
novel-cloud-demo/novel-user/novel-user-service/mvnw

@@ -0,0 +1,259 @@
+#!/bin/sh
+# ----------------------------------------------------------------------------
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#    https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+# ----------------------------------------------------------------------------
+
+# ----------------------------------------------------------------------------
+# Apache Maven Wrapper startup batch script, version 3.3.2
+#
+# Optional ENV vars
+# -----------------
+#   JAVA_HOME - location of a JDK home dir, required when download maven via java source
+#   MVNW_REPOURL - repo url base for downloading maven distribution
+#   MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
+#   MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output
+# ----------------------------------------------------------------------------
+
+set -euf
+[ "${MVNW_VERBOSE-}" != debug ] || set -x
+
+# OS specific support.
+native_path() { printf %s\\n "$1"; }
+case "$(uname)" in
+CYGWIN* | MINGW*)
+  [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")"
+  native_path() { cygpath --path --windows "$1"; }
+  ;;
+esac
+
+# set JAVACMD and JAVACCMD
+set_java_home() {
+  # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched
+  if [ -n "${JAVA_HOME-}" ]; then
+    if [ -x "$JAVA_HOME/jre/sh/java" ]; then
+      # IBM's JDK on AIX uses strange locations for the executables
+      JAVACMD="$JAVA_HOME/jre/sh/java"
+      JAVACCMD="$JAVA_HOME/jre/sh/javac"
+    else
+      JAVACMD="$JAVA_HOME/bin/java"
+      JAVACCMD="$JAVA_HOME/bin/javac"
+
+      if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then
+        echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2
+        echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2
+        return 1
+      fi
+    fi
+  else
+    JAVACMD="$(
+      'set' +e
+      'unset' -f command 2>/dev/null
+      'command' -v java
+    )" || :
+    JAVACCMD="$(
+      'set' +e
+      'unset' -f command 2>/dev/null
+      'command' -v javac
+    )" || :
+
+    if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then
+      echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2
+      return 1
+    fi
+  fi
+}
+
+# hash string like Java String::hashCode
+hash_string() {
+  str="${1:-}" h=0
+  while [ -n "$str" ]; do
+    char="${str%"${str#?}"}"
+    h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296))
+    str="${str#?}"
+  done
+  printf %x\\n $h
+}
+
+verbose() { :; }
+[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; }
+
+die() {
+  printf %s\\n "$1" >&2
+  exit 1
+}
+
+trim() {
+  # MWRAPPER-139:
+  #   Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds.
+  #   Needed for removing poorly interpreted newline sequences when running in more
+  #   exotic environments such as mingw bash on Windows.
+  printf "%s" "${1}" | tr -d '[:space:]'
+}
+
+# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties
+while IFS="=" read -r key value; do
+  case "${key-}" in
+  distributionUrl) distributionUrl=$(trim "${value-}") ;;
+  distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;;
+  esac
+done <"${0%/*}/.mvn/wrapper/maven-wrapper.properties"
+[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in ${0%/*}/.mvn/wrapper/maven-wrapper.properties"
+
+case "${distributionUrl##*/}" in
+maven-mvnd-*bin.*)
+  MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/
+  case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in
+  *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;;
+  :Darwin*x86_64) distributionPlatform=darwin-amd64 ;;
+  :Darwin*arm64) distributionPlatform=darwin-aarch64 ;;
+  :Linux*x86_64*) distributionPlatform=linux-amd64 ;;
+  *)
+    echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2
+    distributionPlatform=linux-amd64
+    ;;
+  esac
+  distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip"
+  ;;
+maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;;
+*) MVN_CMD="mvn${0##*/mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;;
+esac
+
+# apply MVNW_REPOURL and calculate MAVEN_HOME
+# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
+[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}"
+distributionUrlName="${distributionUrl##*/}"
+distributionUrlNameMain="${distributionUrlName%.*}"
+distributionUrlNameMain="${distributionUrlNameMain%-bin}"
+MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}"
+MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")"
+
+exec_maven() {
+  unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || :
+  exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD"
+}
+
+if [ -d "$MAVEN_HOME" ]; then
+  verbose "found existing MAVEN_HOME at $MAVEN_HOME"
+  exec_maven "$@"
+fi
+
+case "${distributionUrl-}" in
+*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;;
+*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;;
+esac
+
+# prepare tmp dir
+if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then
+  clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; }
+  trap clean HUP INT TERM EXIT
+else
+  die "cannot create temp dir"
+fi
+
+mkdir -p -- "${MAVEN_HOME%/*}"
+
+# Download and Install Apache Maven
+verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
+verbose "Downloading from: $distributionUrl"
+verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
+
+# select .zip or .tar.gz
+if ! command -v unzip >/dev/null; then
+  distributionUrl="${distributionUrl%.zip}.tar.gz"
+  distributionUrlName="${distributionUrl##*/}"
+fi
+
+# verbose opt
+__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR=''
+[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v
+
+# normalize http auth
+case "${MVNW_PASSWORD:+has-password}" in
+'') MVNW_USERNAME='' MVNW_PASSWORD='' ;;
+has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;;
+esac
+
+if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then
+  verbose "Found wget ... using wget"
+  wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl"
+elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then
+  verbose "Found curl ... using curl"
+  curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl"
+elif set_java_home; then
+  verbose "Falling back to use Java to download"
+  javaSource="$TMP_DOWNLOAD_DIR/Downloader.java"
+  targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName"
+  cat >"$javaSource" <<-END
+	public class Downloader extends java.net.Authenticator
+	{
+	  protected java.net.PasswordAuthentication getPasswordAuthentication()
+	  {
+	    return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() );
+	  }
+	  public static void main( String[] args ) throws Exception
+	  {
+	    setDefault( new Downloader() );
+	    java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() );
+	  }
+	}
+	END
+  # For Cygwin/MinGW, switch paths to Windows format before running javac and java
+  verbose " - Compiling Downloader.java ..."
+  "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java"
+  verbose " - Running Downloader.java ..."
+  "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")"
+fi
+
+# If specified, validate the SHA-256 sum of the Maven distribution zip file
+if [ -n "${distributionSha256Sum-}" ]; then
+  distributionSha256Result=false
+  if [ "$MVN_CMD" = mvnd.sh ]; then
+    echo "Checksum validation is not supported for maven-mvnd." >&2
+    echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
+    exit 1
+  elif command -v sha256sum >/dev/null; then
+    if echo "$distributionSha256Sum  $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c >/dev/null 2>&1; then
+      distributionSha256Result=true
+    fi
+  elif command -v shasum >/dev/null; then
+    if echo "$distributionSha256Sum  $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then
+      distributionSha256Result=true
+    fi
+  else
+    echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2
+    echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
+    exit 1
+  fi
+  if [ $distributionSha256Result = false ]; then
+    echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2
+    echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2
+    exit 1
+  fi
+fi
+
+# unzip and move
+if command -v unzip >/dev/null; then
+  unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip"
+else
+  tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar"
+fi
+printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/mvnw.url"
+mv -- "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME"
+
+clean || :
+exec_maven "$@"

+ 149 - 0
novel-cloud-demo/novel-user/novel-user-service/mvnw.cmd

@@ -0,0 +1,149 @@
+<# : batch portion
+@REM ----------------------------------------------------------------------------
+@REM Licensed to the Apache Software Foundation (ASF) under one
+@REM or more contributor license agreements.  See the NOTICE file
+@REM distributed with this work for additional information
+@REM regarding copyright ownership.  The ASF licenses this file
+@REM to you under the Apache License, Version 2.0 (the
+@REM "License"); you may not use this file except in compliance
+@REM with the License.  You may obtain a copy of the License at
+@REM
+@REM    https://www.apache.org/licenses/LICENSE-2.0
+@REM
+@REM Unless required by applicable law or agreed to in writing,
+@REM software distributed under the License is distributed on an
+@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+@REM KIND, either express or implied.  See the License for the
+@REM specific language governing permissions and limitations
+@REM under the License.
+@REM ----------------------------------------------------------------------------
+
+@REM ----------------------------------------------------------------------------
+@REM Apache Maven Wrapper startup batch script, version 3.3.2
+@REM
+@REM Optional ENV vars
+@REM   MVNW_REPOURL - repo url base for downloading maven distribution
+@REM   MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
+@REM   MVNW_VERBOSE - true: enable verbose log; others: silence the output
+@REM ----------------------------------------------------------------------------
+
+@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0)
+@SET __MVNW_CMD__=
+@SET __MVNW_ERROR__=
+@SET __MVNW_PSMODULEP_SAVE=%PSModulePath%
+@SET PSModulePath=
+@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @(
+  IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B)
+)
+@SET PSModulePath=%__MVNW_PSMODULEP_SAVE%
+@SET __MVNW_PSMODULEP_SAVE=
+@SET __MVNW_ARG0_NAME__=
+@SET MVNW_USERNAME=
+@SET MVNW_PASSWORD=
+@IF NOT "%__MVNW_CMD__%"=="" (%__MVNW_CMD__% %*)
+@echo Cannot start maven from wrapper >&2 && exit /b 1
+@GOTO :EOF
+: end batch / begin powershell #>
+
+$ErrorActionPreference = "Stop"
+if ($env:MVNW_VERBOSE -eq "true") {
+  $VerbosePreference = "Continue"
+}
+
+# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties
+$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl
+if (!$distributionUrl) {
+  Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
+}
+
+switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) {
+  "maven-mvnd-*" {
+    $USE_MVND = $true
+    $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip"
+    $MVN_CMD = "mvnd.cmd"
+    break
+  }
+  default {
+    $USE_MVND = $false
+    $MVN_CMD = $script -replace '^mvnw','mvn'
+    break
+  }
+}
+
+# apply MVNW_REPOURL and calculate MAVEN_HOME
+# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
+if ($env:MVNW_REPOURL) {
+  $MVNW_REPO_PATTERN = if ($USE_MVND) { "/org/apache/maven/" } else { "/maven/mvnd/" }
+  $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace '^.*'+$MVNW_REPO_PATTERN,'')"
+}
+$distributionUrlName = $distributionUrl -replace '^.*/',''
+$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$',''
+$MAVEN_HOME_PARENT = "$HOME/.m2/wrapper/dists/$distributionUrlNameMain"
+if ($env:MAVEN_USER_HOME) {
+  $MAVEN_HOME_PARENT = "$env:MAVEN_USER_HOME/wrapper/dists/$distributionUrlNameMain"
+}
+$MAVEN_HOME_NAME = ([System.Security.Cryptography.MD5]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join ''
+$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME"
+
+if (Test-Path -Path "$MAVEN_HOME" -PathType Container) {
+  Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME"
+  Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
+  exit $?
+}
+
+if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) {
+  Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl"
+}
+
+# prepare tmp dir
+$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile
+$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir"
+$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null
+trap {
+  if ($TMP_DOWNLOAD_DIR.Exists) {
+    try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
+    catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
+  }
+}
+
+New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null
+
+# Download and Install Apache Maven
+Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
+Write-Verbose "Downloading from: $distributionUrl"
+Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
+
+$webclient = New-Object System.Net.WebClient
+if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) {
+  $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD)
+}
+[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
+$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null
+
+# If specified, validate the SHA-256 sum of the Maven distribution zip file
+$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum
+if ($distributionSha256Sum) {
+  if ($USE_MVND) {
+    Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties."
+  }
+  Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash
+  if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) {
+    Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property."
+  }
+}
+
+# unzip and move
+Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null
+Rename-Item -Path "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" -NewName $MAVEN_HOME_NAME | Out-Null
+try {
+  Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null
+} catch {
+  if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) {
+    Write-Error "fail to move MAVEN_HOME"
+  }
+} finally {
+  try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
+  catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
+}
+
+Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"

+ 68 - 0
novel-cloud-demo/novel-user/novel-user-service/pom.xml

@@ -0,0 +1,68 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
+    <modelVersion>4.0.0</modelVersion>
+    <parent>
+        <groupId>com.sf</groupId>
+        <artifactId>novel-user</artifactId>
+        <version>1.0-SNAPSHOT</version>
+    </parent>
+
+    <artifactId>novel-user-service</artifactId>
+    <name>novel-user-service</name>
+    <description>novel-user-service</description>
+
+
+    <properties>
+        <jjwt.version>0.11.5</jjwt.version>
+    </properties>
+    <dependencies>
+        <dependency>
+            <groupId>com.sf</groupId>
+            <artifactId>novel-core</artifactId>
+            <version>${project.version}</version>
+        </dependency>
+
+        <!-- 使用hutool 生成验证码图片 -->
+        <dependency>
+            <groupId>cn.hutool</groupId>
+            <artifactId>hutool-all</artifactId>
+            <version>5.8.27</version>
+        </dependency>
+
+        <dependency>
+            <groupId>org.springframework.data</groupId>
+            <artifactId>spring-data-commons</artifactId>
+            <version>3.3.0</version>
+        </dependency>
+
+        <!-- 使用jwt来做用户登录信息加密和校验 -->
+        <dependency>
+            <groupId>io.jsonwebtoken</groupId>
+            <artifactId>jjwt-api</artifactId>
+            <version>${jjwt.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>io.jsonwebtoken</groupId>
+            <artifactId>jjwt-impl</artifactId>
+            <version>${jjwt.version}</version>
+            <scope>runtime</scope>
+        </dependency>
+        <dependency>
+            <groupId>io.jsonwebtoken</groupId>
+            <artifactId>jjwt-jackson</artifactId>
+            <version>${jjwt.version}</version>
+            <scope>runtime</scope>
+        </dependency>
+    </dependencies>
+
+    <build>
+        <plugins>
+            <plugin>
+                <groupId>org.springframework.boot</groupId>
+                <artifactId>spring-boot-maven-plugin</artifactId>
+            </plugin>
+        </plugins>
+    </build>
+
+</project>

+ 15 - 0
novel-cloud-demo/novel-user/novel-user-service/src/main/java/com/sf/user/NovelUserServiceApplication.java

@@ -0,0 +1,15 @@
+package com.sf.user;
+
+import org.mybatis.spring.annotation.MapperScan;
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+
+@MapperScan("com.sf.user.mapper")
+@SpringBootApplication(scanBasePackages = {"com.sf"})
+public class NovelUserServiceApplication {
+
+    public static void main(String[] args) {
+        SpringApplication.run(NovelUserServiceApplication.class, args);
+    }
+
+}

+ 49 - 0
novel-cloud-demo/novel-user/novel-user-service/src/main/java/com/sf/user/config/TokenInterceptor.java

@@ -0,0 +1,49 @@
+package com.sf.user.config;
+
+import com.sf.user.util.JwtUtils;
+import com.sf.user.util.UserHolder;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.data.redis.core.RedisTemplate;
+import org.springframework.stereotype.Component;
+import org.springframework.web.servlet.HandlerInterceptor;
+
+// 拦截器  要实现HandlerInterceptor接口
+// 要作为spring容器的组件
+@Component
+public class TokenInterceptor implements HandlerInterceptor {
+
+    @Autowired
+    private JwtUtils jwtUtils;
+
+    @Autowired
+    private RedisTemplate redisTemplate;
+
+    // controller执行之前
+    @Override
+    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
+        String token = request.getHeader("Authorization");
+        if (token != null && !token.equals("null")) {
+            Long uid = jwtUtils.parseToken(token, "front");
+            String tokenKey = "token_" + uid;
+//            System.out.println("用拦截器解析uid: " + uid);
+            String str = (String)redisTemplate.opsForValue().get(tokenKey);
+            if(str != null) {
+                UserHolder.setUserId(uid);
+            }else {
+                // 用户登录失效
+            }
+        }
+        return HandlerInterceptor.super.preHandle(request, response, handler);
+    }
+
+    // controller执行之后
+    @Override
+    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
+//        System.out.println("controller执行完成");
+        // 使用ThreadLocal要注意 使用完需要删除数据 不然可能一直占用内存 导致内存溢出
+        UserHolder.clearUserId();
+        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
+    }
+}

+ 20 - 0
novel-cloud-demo/novel-user/novel-user-service/src/main/java/com/sf/user/config/WebConfig.java

@@ -0,0 +1,20 @@
+package com.sf.user.config;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
+import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
+
+// web相关的配置 需要实现WebMvcConfigurer接口
+@Configuration
+public class WebConfig implements WebMvcConfigurer {
+
+    @Autowired
+    private TokenInterceptor tokenInterceptor;
+
+    @Override
+    public void addInterceptors(InterceptorRegistry registry) {
+//        WebMvcConfigurer.super.addInterceptors(registry);
+        registry.addInterceptor(tokenInterceptor).addPathPatterns("/**");
+    }
+}

+ 104 - 0
novel-cloud-demo/novel-user/novel-user-service/src/main/java/com/sf/user/controller/UserInfoController.java

@@ -0,0 +1,104 @@
+package com.sf.user.controller;
+
+import com.sf.core.dto.RestResp;
+import com.sf.user.dto.req.UserLoginReqDto;
+import com.sf.user.dto.req.UserRegisterReqDto;
+import com.sf.user.dto.resp.ImgVerifyCodeRespDto;
+import com.sf.user.dto.resp.UserInfoRespDto;
+import com.sf.user.dto.resp.UserLoginRespDto;
+import com.sf.user.dto.resp.UserRegisterRespDto;
+import com.sf.user.entity.UserInfo;
+import com.sf.user.service.IUserInfoService;
+import com.sf.user.util.UserHolder;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.tags.Tag;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.*;
+import org.springframework.stereotype.Controller;
+
+import java.io.IOException;
+
+/**
+ * <p>
+ * 用户信息 前端控制器
+ * </p>
+ *
+ * @author baomidou
+ * @since 2024-08-06
+ */
+@Tag(name = "UserInfoController", description = "用户信息模块")
+@RestController
+//@RequestMapping("/userInfo")
+public class UserInfoController {
+
+    @Autowired
+    private IUserInfoService userInfoService;
+
+//    @Autowired
+//    private IBookCommentService bookCommentService;
+
+    @Operation(summary = "获取验证码接口")
+    @GetMapping("/api/front/resource/img_verify_code")
+    public RestResp<ImgVerifyCodeRespDto> getImgVerifyCode() throws IOException {
+        ImgVerifyCodeRespDto imgVerifyCodeRespDto = userInfoService.getImgVerifyCode();
+        return RestResp.ok(imgVerifyCodeRespDto);
+    }
+
+    // @RequestBody 代表接受的请求参数  是json结构的对象
+    // 和@ResponseBody 相对应
+    @Operation(summary = "用户注册接口")
+    @PostMapping("/api/front/user/register")
+    public RestResp<UserRegisterRespDto> register(@RequestBody UserRegisterReqDto userRegisterReqDto) {
+        UserRegisterRespDto respDto = userInfoService.register(userRegisterReqDto);
+        if (respDto.getType() == 1) {
+            // 返回错误的信息
+            return RestResp.fail("00001", "验证码错误!");
+        }
+
+        if (respDto.getType() == 2) {
+            // 返回错误的信息
+            return RestResp.fail("00002", "用户名重复了!");
+        }
+
+        return RestResp.ok(respDto);
+    }
+
+    // http://127.0.0.1:8888/api/front/user/login
+    @Operation(summary = "用户登录接口")
+    @PostMapping("/api/front/user/login")
+    public RestResp<UserLoginRespDto> login(@RequestBody UserLoginReqDto userLoginReqDto) {
+        UserLoginRespDto userLoginRespDto = userInfoService.login(userLoginReqDto);
+        if (userLoginRespDto.getType() == 1) {
+            return RestResp.fail("00003", "用户名不存在!");
+        }
+        if (userLoginRespDto.getType() == 2) {
+            return RestResp.fail("00004", "密码错误");
+        }
+        return RestResp.ok(userLoginRespDto);
+    }
+
+    // 查看用户信息
+    // http://127.0.0.1:8888/api/front/user
+    @Operation(summary = "查看我的信息接口")
+    @GetMapping("/api/front/user")
+    public RestResp<UserInfoRespDto> getUserInfo() {
+        Long userId = UserHolder.getUserId();
+        UserInfo userInfo = userInfoService.getById(userId);
+        UserInfoRespDto userInfoRespDto = UserInfoRespDto.builder()
+                .userPhoto(userInfo.getUserPhoto())
+                .nickName(userInfo.getNickName())
+                .userSex((int) userInfo.getUserSex())
+                .build();
+        return RestResp.ok(userInfoRespDto);
+    }
+
+//    // 查询我的评论
+//    @Operation(summary = "查询我的评论接口")
+//    @GetMapping("/api/front/user/comments")
+//    public RestResp<PageRespDto<UserCommentRespDto>> listComments(PageReqDto pageReqDto) {
+//        Long userId = UserHolder.getUserId();
+//        PageRespDto<UserCommentRespDto> commentList = bookCommentService.getCommentList(userId, pageReqDto);
+//        return RestResp.ok(commentList);
+//    }
+
+}

+ 22 - 0
novel-cloud-demo/novel-user/novel-user-service/src/main/java/com/sf/user/dto/req/UserCommentReqDto.java

@@ -0,0 +1,22 @@
+package com.sf.user.dto.req;
+
+import io.swagger.v3.oas.annotations.media.Schema;
+import jakarta.validation.constraints.NotBlank;
+import jakarta.validation.constraints.NotNull;
+import lombok.Data;
+
+@Data
+public class UserCommentReqDto {
+
+    private Long userId;
+
+    @Schema(description = "小说ID", required = true)
+    @NotNull(message="小说ID不能为空!")
+    private Long bookId;
+
+    @Schema(description = "评论内容", required = true)
+    @NotBlank(message="评论不能为空!")
+//    @Length(min = 10,max = 512)
+    private String commentContent;
+
+}

+ 15 - 0
novel-cloud-demo/novel-user/novel-user-service/src/main/java/com/sf/user/dto/req/UserCommentUpdateReqDto.java

@@ -0,0 +1,15 @@
+package com.sf.user.dto.req;
+
+import lombok.AllArgsConstructor;
+import lombok.Builder;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+@Data
+@Builder
+@NoArgsConstructor
+@AllArgsConstructor
+public class UserCommentUpdateReqDto {
+
+    private String content;
+}

+ 20 - 0
novel-cloud-demo/novel-user/novel-user-service/src/main/java/com/sf/user/dto/req/UserLoginReqDto.java

@@ -0,0 +1,20 @@
+package com.sf.user.dto.req;
+
+import io.swagger.v3.oas.annotations.Parameter;
+import lombok.AllArgsConstructor;
+import lombok.Builder;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+// 用户登录接口的请求dto
+@Data
+@Builder
+@NoArgsConstructor
+@AllArgsConstructor
+public class UserLoginReqDto {
+
+    @Parameter(description = "用户名")
+    private String username;
+    @Parameter(description = "密码")
+    private String password;
+}

+ 42 - 0
novel-cloud-demo/novel-user/novel-user-service/src/main/java/com/sf/user/dto/req/UserRegisterReqDto.java

@@ -0,0 +1,42 @@
+package com.sf.user.dto.req;
+
+import io.swagger.v3.oas.annotations.media.Schema;
+import jakarta.validation.constraints.NotBlank;
+import jakarta.validation.constraints.Pattern;
+import lombok.Data;
+
+/**
+ * 用户注册 请求DTO
+ *
+ * @author xiongxiaoyang
+ * @date 2022/5/16
+ */
+@Data
+public class UserRegisterReqDto {
+
+    //  @Schema 是对字段的解释说明
+    //  @NotBlank  是字段的非空校验
+    //  @Pattern  通过表达式来识别符合手机号的格式
+    @Schema(description = "手机号", required = true)
+    @NotBlank(message="手机号不能为空!")
+    @Pattern(regexp="^1[3|4|5|6|7|8|9][0-9]{9}$",message="手机号格式不正确!")
+    private String username;
+
+    @Schema(description = "密码", required = true)
+    @NotBlank(message="密码不能为空!")
+    private String password;
+
+    @Schema(description = "验证码", required = true)
+    @NotBlank(message="验证码不能为空!")
+    @Pattern(regexp="^\\d{4}$",message="验证码格式不正确!")
+    private String velCode;
+
+    /**
+     * 请求会话标识,用来标识图形验证码属于哪个会话
+     * */
+    @Schema(description = "sessionId", required = true)
+    @NotBlank
+//    @Length(min = 32,max = 32)
+    private String sessionId;
+
+}

+ 28 - 0
novel-cloud-demo/novel-user/novel-user-service/src/main/java/com/sf/user/dto/resp/ImgVerifyCodeRespDto.java

@@ -0,0 +1,28 @@
+package com.sf.user.dto.resp;
+
+import io.swagger.v3.oas.annotations.media.Schema;
+import lombok.Builder;
+import lombok.Data;
+
+/**
+ * 图像验证码 响应DTO
+ * @author xiongxiaoyang
+ * @date 2022/5/18
+ */
+@Data
+@Builder
+public class ImgVerifyCodeRespDto {
+
+    /**
+     * 当前会话ID,用于标识改图形验证码属于哪个会话
+     * */
+    @Schema(description = "sessionId")
+    private String sessionId;
+
+    /**
+     * Base64 编码的验证码图片
+     * */
+    @Schema(description = "Base64 编码的验证码图片")
+    private String img;
+
+}

+ 17 - 0
novel-cloud-demo/novel-user/novel-user-service/src/main/java/com/sf/user/dto/resp/UserInfoRespDto.java

@@ -0,0 +1,17 @@
+package com.sf.user.dto.resp;
+
+import lombok.AllArgsConstructor;
+import lombok.Builder;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+@Data
+@Builder
+@AllArgsConstructor
+@NoArgsConstructor
+public class UserInfoRespDto {
+
+    private String nickName;
+    private String userPhoto;
+    private Integer userSex;
+}

+ 19 - 0
novel-cloud-demo/novel-user/novel-user-service/src/main/java/com/sf/user/dto/resp/UserLoginRespDto.java

@@ -0,0 +1,19 @@
+package com.sf.user.dto.resp;
+
+import lombok.AllArgsConstructor;
+import lombok.Builder;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+// 用户登录接口的响应dto
+@Data
+@Builder
+@NoArgsConstructor
+@AllArgsConstructor
+public class UserLoginRespDto {
+
+    private Long uid;
+    private String nickName;
+    private String token;
+    private Integer type;
+}

+ 28 - 0
novel-cloud-demo/novel-user/novel-user-service/src/main/java/com/sf/user/dto/resp/UserRegisterRespDto.java

@@ -0,0 +1,28 @@
+package com.sf.user.dto.resp;
+
+import io.swagger.v3.oas.annotations.media.Schema;
+import lombok.AllArgsConstructor;
+import lombok.Builder;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+/**
+ * 用户注册 响应DTO
+ * @author xiongxiaoyang
+ * @date 2022/5/17
+ */
+@Data
+@Builder
+@NoArgsConstructor
+@AllArgsConstructor
+public class UserRegisterRespDto {
+
+    @Schema(description = "用户ID")
+    private Long uid;
+
+    @Schema(description = "用户token")
+    private String token;
+
+    // 增加一个字段 来识别处理的类型 比如正确的是0  错误是的 1 2 3等
+    private Integer type;
+}

+ 80 - 0
novel-cloud-demo/novel-user/novel-user-service/src/main/java/com/sf/user/entity/UserInfo.java

@@ -0,0 +1,80 @@
+package com.sf.user.entity;
+
+import com.baomidou.mybatisplus.annotation.IdType;
+import com.baomidou.mybatisplus.annotation.TableId;
+import com.baomidou.mybatisplus.annotation.TableName;
+import java.io.Serializable;
+import java.time.LocalDateTime;
+
+import lombok.*;
+
+/**
+ * <p>
+ * 用户信息
+ * </p>
+ *
+ * @author baomidou
+ * @since 2024-08-06
+ */
+@Data
+@Builder
+@NoArgsConstructor
+@AllArgsConstructor
+@TableName("user_info")
+public class UserInfo implements Serializable {
+
+    private static final long serialVersionUID = 1L;
+
+    @TableId(value = "id", type = IdType.AUTO)
+    private Long id;
+
+    /**
+     * 登录名
+     */
+    private String username;
+
+    /**
+     * 登录密码-加密
+     */
+    private String password;
+
+    /**
+     * 加密盐值
+     */
+    private String salt;
+
+    /**
+     * 昵称
+     */
+    private String nickName;
+
+    /**
+     * 用户头像
+     */
+    private String userPhoto;
+
+    /**
+     * 用户性别;0-男 1-女
+     */
+    private Integer userSex;
+
+    /**
+     * 账户余额
+     */
+    private Long accountBalance;
+
+    /**
+     * 用户状态;0-正常
+     */
+    private Integer status;
+
+    /**
+     * 创建时间
+     */
+    private LocalDateTime createTime;
+
+    /**
+     * 更新时间
+     */
+    private LocalDateTime updateTime;
+}

+ 16 - 0
novel-cloud-demo/novel-user/novel-user-service/src/main/java/com/sf/user/mapper/UserInfoMapper.java

@@ -0,0 +1,16 @@
+package com.sf.user.mapper;
+
+import com.sf.user.entity.UserInfo;
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+
+/**
+ * <p>
+ * 用户信息 Mapper 接口
+ * </p>
+ *
+ * @author baomidou
+ * @since 2024-08-06
+ */
+public interface UserInfoMapper extends BaseMapper<UserInfo> {
+
+}

+ 26 - 0
novel-cloud-demo/novel-user/novel-user-service/src/main/java/com/sf/user/service/IUserInfoService.java

@@ -0,0 +1,26 @@
+package com.sf.user.service;
+
+import com.sf.user.dto.req.UserLoginReqDto;
+import com.sf.user.dto.req.UserRegisterReqDto;
+import com.sf.user.dto.resp.ImgVerifyCodeRespDto;
+import com.sf.user.dto.resp.UserLoginRespDto;
+import com.sf.user.dto.resp.UserRegisterRespDto;
+import com.sf.user.entity.UserInfo;
+import com.baomidou.mybatisplus.extension.service.IService;
+
+/**
+ * <p>
+ * 用户信息 服务类
+ * </p>
+ *
+ * @author baomidou
+ * @since 2024-08-06
+ */
+public interface IUserInfoService extends IService<UserInfo> {
+    ImgVerifyCodeRespDto getImgVerifyCode();
+
+    // req -> request 请求  resp -> response 响应
+    UserRegisterRespDto register(UserRegisterReqDto userRegisterReqDto);
+
+    UserLoginRespDto login(UserLoginReqDto userLoginReqDto);
+}

+ 162 - 0
novel-cloud-demo/novel-user/novel-user-service/src/main/java/com/sf/user/service/impl/UserInfoServiceImpl.java

@@ -0,0 +1,162 @@
+package com.sf.user.service.impl;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.baomidou.mybatisplus.core.toolkit.IdWorker;
+import com.sf.core.cons.RedisKeyConst;
+import com.sf.user.dto.req.UserLoginReqDto;
+import com.sf.user.dto.req.UserRegisterReqDto;
+import com.sf.user.dto.resp.ImgVerifyCodeRespDto;
+import com.sf.user.dto.resp.UserLoginRespDto;
+import com.sf.user.dto.resp.UserRegisterRespDto;
+import com.sf.user.entity.UserInfo;
+import com.sf.user.mapper.UserInfoMapper;
+import com.sf.user.service.IUserInfoService;
+import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
+import com.sf.user.util.CaptchaUtils;
+import com.sf.user.util.JwtUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.data.redis.core.RedisTemplate;
+import org.springframework.data.util.Pair;
+import org.springframework.stereotype.Service;
+import org.springframework.util.DigestUtils;
+
+import java.nio.charset.StandardCharsets;
+import java.time.LocalDateTime;
+import java.util.HashMap;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * <p>
+ * 用户信息 服务实现类
+ * </p>
+ *
+ * @author baomidou
+ * @since 2024-08-06
+ */
+@Service
+public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements IUserInfoService {
+
+    // 不使用redis时  使用的本地存储(内存存储)
+    static HashMap<String, String> captcha = new HashMap<String, String>();
+
+    @Autowired
+    private UserInfoMapper userInfoMapper;
+
+    @Autowired
+    private JwtUtils jwtUtils;
+
+    // https://docs.spring.io/spring-data/redis/docs/current/api/org/springframework/data/redis/core/RedisTemplate.html
+    @Autowired
+    private RedisTemplate redisTemplate;
+
+
+    @Override
+    public ImgVerifyCodeRespDto getImgVerifyCode() {
+        Pair<String, String> pair = CaptchaUtils.getImageBase64();
+        // 使用sessionId来区分每次生成的不同的验证码
+        String sessionId = IdWorker.get32UUID();
+        // 将这个唯一的sessionId和code码关联 存储在容器中
+        // 将pair(成对的数据)中的第一个数据 和 sessionId存入map中
+//        captcha.put(sessionId, pair.getFirst());
+
+        // 验证码使用string存储
+        String key = RedisKeyConst.USER_VERIFY_PRE + sessionId;
+        redisTemplate.opsForValue().set(key, pair.getFirst(), 10, TimeUnit.MINUTES);
+        ImgVerifyCodeRespDto verifyCodeRespDto = ImgVerifyCodeRespDto.builder()
+                .sessionId(sessionId)
+                .img(pair.getSecond())   // 将hutool生成的base数据设置进去
+                .build();
+        return verifyCodeRespDto;
+    }
+
+    @Override
+    public UserRegisterRespDto register(UserRegisterReqDto reqDto) {
+        UserRegisterRespDto respDto = UserRegisterRespDto.builder().build();
+        // 判断验证码是否正确
+        String sessionId = reqDto.getSessionId();
+        // 获取验证码图片的正确结果
+//        String resultCode = captcha.get(sessionId);
+        String resultCode = (String) redisTemplate.opsForValue().get(RedisKeyConst.USER_VERIFY_PRE + sessionId);
+        // 如果用户传进来的验证码 不准确  返回验证码错误
+        if (!reqDto.getVelCode().equals(resultCode)) {
+            // 用类型1 代表验证码错误
+            respDto.setType(1);
+            return respDto;
+        }
+
+        // 判断用户名是否被使用
+        // select count(*) from user_info where username = ''
+        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
+        queryWrapper.eq(UserInfo::getUsername, reqDto.getUsername());
+        Long count = userInfoMapper.selectCount(queryWrapper);
+        if (count == 1) {
+            // 用类型2 代表用户名已经存在
+            respDto.setType(2);
+            return respDto;
+        }
+
+        redisTemplate.delete(sessionId);
+        // 存储数据
+        byte[] bytes = reqDto.getPassword().getBytes(StandardCharsets.UTF_8);
+        UserInfo userInfo = UserInfo.builder()
+                .username(reqDto.getUsername())
+                .password(DigestUtils.md5DigestAsHex(bytes))  // 使用spring中的工具类进行加密
+                .nickName(reqDto.getUsername())
+                .salt("0")
+                .accountBalance(0L)
+                .status(0)
+                .createTime(LocalDateTime.now())  // 把当前时间存储进去
+                .updateTime(LocalDateTime.now())
+                .build();
+        userInfoMapper.insert(userInfo);
+
+        respDto.setType(0);
+        // 在存入数据库后 获取生成的id
+        respDto.setUid(userInfo.getId());
+//        respDto.setToken("token_" + userInfo.getId());
+        String token = jwtUtils.generateToken(userInfo.getId(), "front");
+        respDto.setToken(token);
+        // 注册之后 自动登录 同样将token信息存储到redis中
+        // 当前的退出 是客户端处理的 没有登录状态的请求 不携带token信息
+        // 如果服务端也接收退出的请求  那么再从redis中删除此token
+        String tokenKey = RedisKeyConst.USER_TOKEN_PRE + userInfo.getId();
+        redisTemplate.opsForValue().set(tokenKey, token, 10, TimeUnit.DAYS);
+        return respDto;
+    }
+
+    @Override
+    public UserLoginRespDto login(UserLoginReqDto userLoginReqDto) {
+        // 判断用户名和密码是否正确
+        // select * from user_info where username='' and password = ''
+        // 可以一起查询  只返回用户名或密码错误
+        // 也可以分开处理  返回用户名错误 还是密码错误
+        // select * from user_info where username=''
+
+        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
+        queryWrapper.eq(UserInfo::getUsername, userLoginReqDto.getUsername());
+        // 如果有一条 使用selectOne
+        // 如果有多条 使用selectList
+        // 如果只想查询个数 使用selectCount
+        UserInfo userInfo = userInfoMapper.selectOne(queryWrapper);
+        if (userInfo == null) {
+            // 用户名不存在
+            return UserLoginRespDto.builder().type(1).build();
+        }
+
+        String pwd = DigestUtils.md5DigestAsHex(userLoginReqDto.getPassword().getBytes(StandardCharsets.UTF_8));
+        if (!userInfo.getPassword().equals(pwd)) {
+            // 密码错误
+            return UserLoginRespDto.builder().type(2).build();
+        }
+
+        // 登录成功
+        String tokenKey = "token_" + userInfo.getId();
+        String token = jwtUtils.generateToken(userInfo.getId(), "front");
+        redisTemplate.opsForValue().set(tokenKey, token, 10, TimeUnit.DAYS);
+        // token_1  -> 生成的token
+        return UserLoginRespDto.builder().type(0)
+                .uid(userInfo.getId())
+                .nickName(userInfo.getNickName())
+                .token(token).build();
+    }
+}

+ 32 - 0
novel-cloud-demo/novel-user/novel-user-service/src/main/java/com/sf/user/util/CaptchaUtils.java

@@ -0,0 +1,32 @@
+package com.sf.user.util;
+
+import cn.hutool.captcha.CaptchaUtil;
+import cn.hutool.captcha.LineCaptcha;
+import cn.hutool.captcha.generator.RandomGenerator;
+import org.springframework.data.util.Pair;
+
+// 处理验证码的工具类
+public class CaptchaUtils {
+
+    // 获取一个随机的 四位数字的验证码
+    // 返回一对数据Pair  第一个数据是随机的对应值 如“1234” 第二个数据是生成的图片base64字符串
+    public static Pair<String, String> getImageBase64() {
+        // 随机生成器
+        // 参数对应  生成几位数字的验证码  设置宽高
+        RandomGenerator randomGenerator = new RandomGenerator("0123456789", 4);
+        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(100, 38);
+        lineCaptcha.setGenerator(randomGenerator);
+
+        String code = lineCaptcha.getCode();
+        System.out.println("-----------------");
+        System.out.println(code);
+        // 图片数据 是由base64格式进行传输的
+        String imageBase64 = lineCaptcha.getImageBase64();
+        System.out.println(imageBase64);
+        System.out.println("-----------------");
+
+        // 构造一个pair对象
+        Pair<String, String> pair = Pair.of(code, imageBase64);
+        return pair;
+    }
+}

+ 37 - 0
novel-cloud-demo/novel-user/novel-user-service/src/main/java/com/sf/user/util/JwtUtils.java

@@ -0,0 +1,37 @@
+package com.sf.user.util;
+
+import io.jsonwebtoken.Claims;
+import io.jsonwebtoken.Jws;
+import io.jsonwebtoken.Jwts;
+import io.jsonwebtoken.security.Keys;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.stereotype.Component;
+
+// 声明为组件
+@Component
+public class JwtUtils {
+    // @Value 获取配置文件中的值
+    @Value("${novel.jwt.secret}")
+    private String secret;
+
+    public String generateToken(Long uid, String systemKey) {
+        // systemKey是当前系统的标识
+        String token = Jwts.builder()
+                .setHeaderParam("systemKeyHeader", systemKey)
+                .setSubject(uid.toString())
+                .signWith(Keys.hmacShaKeyFor(secret.getBytes())).compact();
+        return token;
+    }
+
+
+    public Long parseToken(String token, String systemKey) {
+        Jws<Claims> claimsJws = Jwts.parserBuilder().setSigningKey(Keys.hmacShaKeyFor(secret.getBytes()))
+                .build().parseClaimsJws(token);
+        // 验证是否是当前系统加密的token
+        if (systemKey.equals(claimsJws.getHeader().get("systemKeyHeader"))) {
+            return Long.parseLong(claimsJws.getBody().getSubject());
+        }
+        return null;
+    }
+
+}

+ 22 - 0
novel-cloud-demo/novel-user/novel-user-service/src/main/java/com/sf/user/util/UserHolder.java

@@ -0,0 +1,22 @@
+package com.sf.user.util;
+
+// 用户上下文
+public class UserHolder {
+
+    // 不同的线程存储不同的数据
+    private static final ThreadLocal<Long> userHolder = new ThreadLocal<Long>();
+
+    public static void setUserId(Long userId) {
+        userHolder.set(userId);
+    }
+
+    public static Long getUserId() {
+        // 这里的threadLocal 是一个map结构
+        // map的key 是当前线程 value是当前线程的ThreadLocal
+        return userHolder.get();
+    }
+
+    public static void clearUserId() {
+        userHolder.remove();
+    }
+}

+ 12 - 0
novel-cloud-demo/novel-user/novel-user-service/src/main/resources/application.yml

@@ -0,0 +1,12 @@
+spring:
+#  application:
+#    name: novel-user-service
+  profiles:
+    include: common
+
+server:
+  port: 8903
+
+novel:
+  jwt:
+    secret: E66559580A1ADF48CDD928516062F12E

+ 6 - 0
novel-cloud-demo/novel-user/novel-user-service/src/main/resources/bootstrap.yml

@@ -0,0 +1,6 @@
+spring:
+  application:
+    name: novel-user-service
+  # 将通用的application.yml文件引入进来
+  profiles:
+    include: common

+ 5 - 0
novel-cloud-demo/novel-user/novel-user-service/src/main/resources/mapper/UserInfoMapper.xml

@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
+<mapper namespace="com.sf.user.mapper.UserInfoMapper">
+
+</mapper>

+ 13 - 0
novel-cloud-demo/novel-user/novel-user-service/src/test/java/com/sf/noveluserservice/NovelUserServiceApplicationTests.java

@@ -0,0 +1,13 @@
+package com.sf.noveluserservice;
+
+import org.junit.jupiter.api.Test;
+import org.springframework.boot.test.context.SpringBootTest;
+
+@SpringBootTest
+class NovelUserServiceApplicationTests {
+
+    @Test
+    void contextLoads() {
+    }
+
+}

+ 24 - 0
novel-cloud-demo/novel-user/pom.xml

@@ -0,0 +1,24 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+    <modelVersion>4.0.0</modelVersion>
+    <parent>
+        <groupId>com.sf</groupId>
+        <artifactId>novel-cloud-demo</artifactId>
+        <version>1.0-SNAPSHOT</version>
+    </parent>
+
+    <artifactId>novel-user</artifactId>
+    <packaging>pom</packaging>
+
+    <name>novel-user</name>
+    <url>http://maven.apache.org</url>
+    <modules>
+        <module>novel-user-api</module>
+        <module>novel-user-service</module>
+    </modules>
+
+    <properties>
+        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+    </properties>
+
+</project>

+ 2 - 0
novel-cloud-demo/pom.xml

@@ -18,6 +18,8 @@
         <module>novel-core</module>
         <module>novel-home</module>
         <module>novel-gateway</module>
+        <module>novel-news</module>
+        <module>novel-user</module>
     </modules>
 
     <!-- 使用属性配置来管理依赖版本 -->

+ 7 - 0
novel-demo/pom.xml

@@ -146,6 +146,13 @@
                 <groupId>org.springframework.boot</groupId>
                 <artifactId>spring-boot-maven-plugin</artifactId>
             </plugin>
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-surefire-plugin</artifactId>
+                <configuration>
+                    <skip>true</skip>
+                </configuration>
+            </plugin>
         </plugins>
     </build>
 

+ 1 - 0
novel-demo/src/main/java/com/sf/config/CorsConfig.java

@@ -26,6 +26,7 @@ public class CorsConfig {
             corsConfiguration.addAllowedOrigin(allowedOrigin);
         });
 //        corsConfiguration.addAllowedOrigin("http://localhost:1024");
+//        corsConfiguration.addAllowedOriginPattern("*");
         corsConfiguration.setAllowCredentials(true);
         // 允许全部的头信息
         corsConfiguration.addAllowedHeader("*");

+ 1 - 1
novel-demo/src/main/java/com/sf/service/impl/UserInfoServiceImpl.java

@@ -76,7 +76,7 @@ public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> i
         String sessionId = reqDto.getSessionId();
         // 获取验证码图片的正确结果
 //        String resultCode = captcha.get(sessionId);
-        String resultCode = (String) redisTemplate.opsForValue().get(sessionId);
+        String resultCode = (String) redisTemplate.opsForValue().get(RedisKeyConst.USER_VERIFY_PRE + sessionId);
         // 如果用户传进来的验证码 不准确  返回验证码错误
         if (!reqDto.getVelCode().equals(resultCode)) {
             // 用类型1 代表验证码错误

+ 2 - 0
novel-demo/src/main/resources/application.yml

@@ -16,6 +16,7 @@ spring:
   application:
     name: novel-demo
   datasource:
+    # spring.datasource.url=jdbc:mysql://localhost:3306/novel-cloud?useUnicode=true&characterEncoding=utf-8&allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=Asia/Shanghai
     url: jdbc:mysql://localhost:3306/novel-cloud?useUnicode=true&characterEncoding=utf-8&allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=Asia/Shanghai
     username: root
     password: root123456
@@ -28,6 +29,7 @@ spring:
   data:
     redis:
       host: localhost
+      # spring.redis.data.host=localhost
       port: 6379
       password:
       database: 1