commit 89bbb45c5211cabe85643b645b2c94e1874083dd Author: LingandRX Date: Mon Mar 24 00:34:55 2025 +0800 feat: 初始化项目结构和基础功能 - 创建项目基本目录结构- 添加 Git 配置文件- 创建数据库配置文件 - 实现用户注册和登录相关功能- 添加邮件验证码功能 - 实现分页和响应封装 - 添加 JWT 工具类 diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..8af972c --- /dev/null +++ b/.gitattributes @@ -0,0 +1,3 @@ +/gradlew text eol=lf +*.bat text eol=crlf +*.jar binary diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c2065bc --- /dev/null +++ b/.gitignore @@ -0,0 +1,37 @@ +HELP.md +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..1ddeeba --- /dev/null +++ b/build.gradle @@ -0,0 +1,55 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '3.4.4' + id 'io.spring.dependency-management' version '1.1.7' +} + +group = 'com.example' +version = '0.0.1-SNAPSHOT' + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(17) + } +} + +configurations { + compileOnly { + extendsFrom annotationProcessor + } +} + +repositories { + maven { + url 'https://maven.aliyun.com/repository/public/' + } + mavenLocal() + mavenCentral() +} + +dependencies { + implementation 'org.springframework.boot:spring-boot-starter-data-jdbc' + implementation 'org.springframework.boot:spring-boot-starter-security' + implementation 'org.springframework.boot:spring-boot-starter-thymeleaf' + implementation 'org.springframework.boot:spring-boot-starter-websocket' + implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:3.0.4' + implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity6' + implementation 'mysql:mysql-connector-java:8.0.28' + implementation 'javax.validation:validation-api:2.0.1.Final' + implementation 'org.hibernate.validator:hibernate-validator:6.0.13.Final' + implementation 'org.springframework.boot:spring-boot-starter-mail' + implementation 'io.jsonwebtoken:jjwt-api:0.11.5' + runtimeOnly 'io.jsonwebtoken:jjwt-impl:0.11.5' + runtimeOnly 'io.jsonwebtoken:jjwt-jackson:0.11.5' + implementation 'org.springframework.boot:spring-boot-starter-data-redis' + compileOnly 'org.projectlombok:lombok' + annotationProcessor 'org.projectlombok:lombok' + testImplementation 'org.springframework.boot:spring-boot-starter-test' + testImplementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter-test:3.0.4' + testImplementation 'org.springframework.security:spring-security-test' + testRuntimeOnly 'org.junit.platform:junit-platform-launcher' +} + +tasks.named('test') { + useJUnitPlatform() +} diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..faf9300 --- /dev/null +++ b/gradlew @@ -0,0 +1,251 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed 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. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +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 + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..9d21a21 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,94 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem 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, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..1dba86b --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'copyKamanotes' diff --git a/src/main/java/com/example/copykamanotes/NotesApplication.java b/src/main/java/com/example/copykamanotes/NotesApplication.java new file mode 100644 index 0000000..446aff1 --- /dev/null +++ b/src/main/java/com/example/copykamanotes/NotesApplication.java @@ -0,0 +1,13 @@ +package com.example.copykamanotes; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication(scanBasePackages = "com.example.copykamanotes") +public class NotesApplication { + + public static void main(String[] args) { + SpringApplication.run(NotesApplication.class, args); + } + +} diff --git a/src/main/java/com/example/copykamanotes/config/MyBatisConfig.java b/src/main/java/com/example/copykamanotes/config/MyBatisConfig.java new file mode 100644 index 0000000..0e4b1fa --- /dev/null +++ b/src/main/java/com/example/copykamanotes/config/MyBatisConfig.java @@ -0,0 +1,11 @@ +package com.example.copykamanotes.config; + +import org.mybatis.spring.annotation.MapperScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +@Configuration +@MapperScan("com.example.copykamanotes.mapper") +@EnableTransactionManagement +public class MyBatisConfig { +} diff --git a/src/main/java/com/example/copykamanotes/config/SecurityConfig.java b/src/main/java/com/example/copykamanotes/config/SecurityConfig.java new file mode 100644 index 0000000..13e8650 --- /dev/null +++ b/src/main/java/com/example/copykamanotes/config/SecurityConfig.java @@ -0,0 +1,36 @@ +package com.example.copykamanotes.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.HttpMethod; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.web.SecurityFilterChain; + + +import java.util.Arrays; + +@Configuration +@EnableWebSecurity +public class SecurityConfig { + + @Bean + public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { + http + .authorizeHttpRequests(auth -> auth + .requestMatchers("/api/**").permitAll() // 允许 /api/** 路径下的所有请求 + .anyRequest().authenticated() // 其他请求需要认证 + ) + .csrf(csrf -> csrf.disable()); // 根据需要禁用 CSRF + + return http.build(); + } + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder() { + }; + } +} diff --git a/src/main/java/com/example/copykamanotes/controller/UserController.java b/src/main/java/com/example/copykamanotes/controller/UserController.java new file mode 100644 index 0000000..17b4c58 --- /dev/null +++ b/src/main/java/com/example/copykamanotes/controller/UserController.java @@ -0,0 +1,34 @@ +package com.example.copykamanotes.controller; + +import com.example.copykamanotes.model.base.ApiResponse; +import com.example.copykamanotes.model.dto.user.RegisterRequest; +import com.example.copykamanotes.model.vo.user.RegisterVO; +import com.example.copykamanotes.service.UserService; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import javax.validation.Valid; + +@Slf4j +@RestController +@RequestMapping("/api") +public class UserController { + + @Autowired + private UserService userService; + + @PostMapping("/users") + public ApiResponse register( + @Valid + @RequestBody + RegisterRequest requestRequest + ) { + return userService.register(requestRequest); + } + + @GetMapping("/") + public ApiResponse hello() { + return ApiResponse.success("Hello World"); + } +} diff --git a/src/main/java/com/example/copykamanotes/mapper/EmailVerifyCodeMapper.java b/src/main/java/com/example/copykamanotes/mapper/EmailVerifyCodeMapper.java new file mode 100644 index 0000000..3992b62 --- /dev/null +++ b/src/main/java/com/example/copykamanotes/mapper/EmailVerifyCodeMapper.java @@ -0,0 +1,23 @@ +package com.example.copykamanotes.mapper; + +import com.example.copykamanotes.model.entity.EmailVerifyCode; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +@Mapper +public interface EmailVerifyCodeMapper { + /** + * 插入验证码 + */ + int insert(EmailVerifyCode emailVerifyCode); + + /** + * 根据邮箱和类型查询验证码 + */ + EmailVerifyCode findLatestValidCode(@Param("email") String email, @Param("type") String type); + + /** + * 将验证码标记为已使用 + */ + int markAsUsed(@Param("id") Long id); +} diff --git a/src/main/java/com/example/copykamanotes/mapper/UserMapper.java b/src/main/java/com/example/copykamanotes/mapper/UserMapper.java new file mode 100644 index 0000000..2827c5e --- /dev/null +++ b/src/main/java/com/example/copykamanotes/mapper/UserMapper.java @@ -0,0 +1,21 @@ +package com.example.copykamanotes.mapper; + +import com.example.copykamanotes.model.entity.User; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +@Mapper +public interface UserMapper { + /** + * 新增用户 + * + * @param user 用户信息 + */ + int insert(User user); + + User findByAccount(@Param("account") String account); + + User findByEmail(@Param("email") String email); + + int updateLastLoginAt(@Param("userId") Long userId); +} diff --git a/src/main/java/com/example/copykamanotes/model/base/ApiResponse.java b/src/main/java/com/example/copykamanotes/model/base/ApiResponse.java new file mode 100644 index 0000000..6f077e8 --- /dev/null +++ b/src/main/java/com/example/copykamanotes/model/base/ApiResponse.java @@ -0,0 +1,93 @@ +package com.example.copykamanotes.model.base; + +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * Api响应类 + * + * @param 响应数据类型 + */ +@Data +@NoArgsConstructor +public class ApiResponse { + + /** + * 响应状态码 + */ + private int code; + + /** + * 响应消息 + */ + private String message; + + /** + * 响应数据 + */ + private T data; + + /** + * 构造函数 + * + * @param code 响应状态码 + * @param message 响应消息 + * @param data 响应数据 + */ + public ApiResponse(int code, String message, T data) { + this.code = code; + this.message = message; + this.data = data; + } + + /** + * 创建成功的响应对象 + * + * @param data 响应数据 + * @param 响应数据类型 + * @return Api响应 + */ + public static ApiResponse success(T data) { + ApiResponse response = new ApiResponse<>(); + response.setCode(200); + response.setMessage("success"); + response.setData(data); + return response; + } + + public static ApiResponse success() { + return success(new EmptyVO()); + } + + /** + * 创建错误响应 + * + * @param code 响应状态码 + * @param message 响应消息 + * @param 响应数据类型 + * @return Api响应 + */ + public static ApiResponse error(int code, String message) { + ApiResponse response = new ApiResponse<>(); + response.setCode(code); + response.setMessage(message); + return response; + } + + /** + * 创建带数据的错误响应 + * @param code 响应状态码 + * @param message 响应消息 + * @param data 响应数据 + * @param 响应数据类型 + * @return Api响应 + */ + public static ApiResponse error(int code, String message, T data) { + ApiResponse response = new ApiResponse<>(); + response.setCode(code); + response.setMessage(message); + response.setData(data); + return response; + } + +} diff --git a/src/main/java/com/example/copykamanotes/model/base/EmptyVO.java b/src/main/java/com/example/copykamanotes/model/base/EmptyVO.java new file mode 100644 index 0000000..d06411a --- /dev/null +++ b/src/main/java/com/example/copykamanotes/model/base/EmptyVO.java @@ -0,0 +1,7 @@ +package com.example.copykamanotes.model.base; + +/** + * 空响应类,用于表示无数据返回的情况。 + */ +public class EmptyVO { +} diff --git a/src/main/java/com/example/copykamanotes/model/base/PageVO.java b/src/main/java/com/example/copykamanotes/model/base/PageVO.java new file mode 100644 index 0000000..28b330f --- /dev/null +++ b/src/main/java/com/example/copykamanotes/model/base/PageVO.java @@ -0,0 +1,53 @@ +package com.example.copykamanotes.model.base; + +import lombok.Data; + +import java.util.List; + +/** + * 分页数据模型 + * + * @param 数据类型 + */ + +@Data +public class PageVO { + /** + * 当前页码 + */ + private Integer page; + + /** + * 每页数量 + */ + private Integer pageSize; + + /** + * 总数 + */ + private Integer total; + + /** + * 总页数 + */ + private Integer totalPage; + + /** + * 数据列表 + */ + private List list; + + public PageVO(Integer page, Integer pageSize, Integer total, List list) { + this.page = page; + this.pageSize = pageSize; + this.total = total; + this.list = list; + } + + public static PageVO of(Integer page, Integer pageSize, Integer total, List list) { + PageVO pageVO = new PageVO<>(page, pageSize, total, list); + pageVO.setTotalPage((total + pageSize - 1) / pageSize); + return pageVO; + } + +} diff --git a/src/main/java/com/example/copykamanotes/model/base/Pagination.java b/src/main/java/com/example/copykamanotes/model/base/Pagination.java new file mode 100644 index 0000000..d9347f5 --- /dev/null +++ b/src/main/java/com/example/copykamanotes/model/base/Pagination.java @@ -0,0 +1,12 @@ +package com.example.copykamanotes.model.base; + +import lombok.AllArgsConstructor; +import lombok.Data; + +@Data +@AllArgsConstructor +public class Pagination { + private Integer page; // 当前页码 + private Integer pageSize; // 每页记录数 + private Integer total; // 总记录数 +} diff --git a/src/main/java/com/example/copykamanotes/model/base/PaginationApiResponse.java b/src/main/java/com/example/copykamanotes/model/base/PaginationApiResponse.java new file mode 100644 index 0000000..d5dd499 --- /dev/null +++ b/src/main/java/com/example/copykamanotes/model/base/PaginationApiResponse.java @@ -0,0 +1,25 @@ +package com.example.copykamanotes.model.base; + +/** + * PaginationApiResponse类用于处理分页的API响应。 + * @param 泛型类型,表示分页数据类型。 + */ + +public class PaginationApiResponse extends ApiResponse { + // 分页对象 + private final Pagination pagination; + + public PaginationApiResponse(int code, String message, T data, Pagination pagination) { + super(code, message, data); + this.pagination = pagination; + } + + /** + * 获取分页对象。 + * + * @return 分页对象 + */ + public Pagination getPagination() { + return pagination; + } +} diff --git a/src/main/java/com/example/copykamanotes/model/base/TokenApiResponse.java b/src/main/java/com/example/copykamanotes/model/base/TokenApiResponse.java new file mode 100644 index 0000000..775c06f --- /dev/null +++ b/src/main/java/com/example/copykamanotes/model/base/TokenApiResponse.java @@ -0,0 +1,27 @@ +package com.example.copykamanotes.model.base; + +import lombok.Data; +import lombok.EqualsAndHashCode; + +@Data +@EqualsAndHashCode(callSuper = true) +public class TokenApiResponse extends ApiResponse { + + /** + * token + */ + private final String token; + + /** + * 构造函数,用初始化TokenApiResponse + * + * @param code 状态码 + * @param message 消息 + * @param data 数据 + * @param token Token + */ + public TokenApiResponse(int code, String message, T data, String token) { + super(code, message, data); + this.token = token; + } +} diff --git a/src/main/java/com/example/copykamanotes/model/dto/user/LoginRequest.java b/src/main/java/com/example/copykamanotes/model/dto/user/LoginRequest.java new file mode 100644 index 0000000..6661e26 --- /dev/null +++ b/src/main/java/com/example/copykamanotes/model/dto/user/LoginRequest.java @@ -0,0 +1,39 @@ +package com.example.copykamanotes.model.dto.user; + +import lombok.Data; + +import javax.validation.constraints.Email; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Pattern; +import javax.validation.constraints.Size; +import javax.validation.constraints.AssertTrue; + +@Data +public class LoginRequest { + + /** + * 账号 + */ + @Size(min = 6, max = 20, message = "account must be between 6 and 20 characters") + @Pattern(regexp = "^[a-zA-Z0-9]+$", message = "account must be alphanumeric") + private String account; + + /** + * 邮箱 + */ + @Email(message = "email is invalid") + private String email; + + /** + * 密码 + * 必填,长度6-20 + */ + @NotBlank(message = "password is required") + @Size(min = 6, max = 20, message = "password must be between 6 and 20 characters") + private String password; + + @AssertTrue(message = "account or email is required") + private boolean isValidLogin() { + return account != null || email != null; + } +} diff --git a/src/main/java/com/example/copykamanotes/model/dto/user/RegisterRequest.java b/src/main/java/com/example/copykamanotes/model/dto/user/RegisterRequest.java new file mode 100644 index 0000000..c417d7b --- /dev/null +++ b/src/main/java/com/example/copykamanotes/model/dto/user/RegisterRequest.java @@ -0,0 +1,36 @@ +package com.example.copykamanotes.model.dto.user; + +import lombok.Data; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Pattern; +import javax.validation.constraints.Size; +import javax.validation.constraints.Email; + +/** + * 用户注册请求DTO + */ +@Data +public class RegisterRequest { + + @NotBlank(message = "account is required") + @Size(min = 6, max = 20, message = "account must be between 6 and 20 characters") + @Pattern(regexp = "^[a-zA-Z0-9]+$", message = "account must be alphanumeric") + private String account; + + @NotBlank(message = "username is required") + @Size(max = 20, message = "account must be between 6 and 20 characters") + @Pattern(regexp = "^[a-zA-Z0-9]+$", message = "account must be alphanumeric") + private String username; + + @NotBlank(message = "password is required") + @Size(min = 6, max = 20, message = "account must be between 6 and 20 characters") + @Pattern(regexp = "^[a-zA-Z0-9]+$", message = "account must be alphanumeric") + private String password; + + @Email(message = "email is invalid") + private String email; + + @Size(min = 6, max = 20, message = "account must be between 6 and 20 characters") + private String verifyCode; +} diff --git a/src/main/java/com/example/copykamanotes/model/dto/user/UpdateUserRequest.java b/src/main/java/com/example/copykamanotes/model/dto/user/UpdateUserRequest.java new file mode 100644 index 0000000..90e9587 --- /dev/null +++ b/src/main/java/com/example/copykamanotes/model/dto/user/UpdateUserRequest.java @@ -0,0 +1,37 @@ +package com.example.copykamanotes.model.dto.user; + +import lombok.Data; + +import javax.validation.constraints.*; +import java.time.LocalDate; + +@Data +public class UpdateUserRequest { + + @Size(max = 20, message = "account must be between 6 and 20 characters") + @Pattern(regexp = "^[a-zA-Z0-9]+$", message = "account must be alphanumeric") + private String username; + + /** + * 性别 + * 非必填,取值范围 1-男,2-女,3-未知 + */ + @Min(value = 1, message = "性别取值无效") + @Max(value = 3, message = "性别取值无效") + private Integer gender; + + @Past(message = "生日必须早于当前日期") + private LocalDate birthday; + + @Pattern(regexp = "^(https?|ftp)://.*$", message = "头像地址必须是有效的 URL") + private String avatarUrl; + + @Email(message = "email is invalid") + private String email; + + @Size(max = 100, message = "签名不能超过 100 个字符") + private String school; + + @Size(max = 100, message = "签名不能超过 100 个字符") + private String signature; +} diff --git a/src/main/java/com/example/copykamanotes/model/dto/user/UploadImageResponse.java b/src/main/java/com/example/copykamanotes/model/dto/user/UploadImageResponse.java new file mode 100644 index 0000000..9fb89b9 --- /dev/null +++ b/src/main/java/com/example/copykamanotes/model/dto/user/UploadImageResponse.java @@ -0,0 +1,35 @@ +package com.example.copykamanotes.model.dto.user; + + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@NoArgsConstructor +@AllArgsConstructor +public class UploadImageResponse { + + /** + * 响应码 + */ + private Integer code; + + /** + * 响应消息 + */ + private String message; + + /** + * 响应数据 + */ + private UploadImageResponseData data; + + public static class UploadImageResponseData { + /** + * 图片地址 + */ + private String url; + } + +} diff --git a/src/main/java/com/example/copykamanotes/model/dto/user/UserQueryParam.java b/src/main/java/com/example/copykamanotes/model/dto/user/UserQueryParam.java new file mode 100644 index 0000000..57e9071 --- /dev/null +++ b/src/main/java/com/example/copykamanotes/model/dto/user/UserQueryParam.java @@ -0,0 +1,38 @@ +package com.example.copykamanotes.model.dto.user; + +import lombok.Data; +import org.hibernate.validator.constraints.Length; + +import javax.validation.constraints.Max; +import javax.validation.constraints.Min; +import javax.validation.constraints.NotNull; + +@Data +public class UserQueryParam { + + @Min(value = 1, message = "userId必须大于0") + private Long userId; + + private String account; + + @Length(max = 20, message = "username不能超过20个字符") + private String username; + + @Min(value = 0, message = "isAdmin取值无效") + @Max(value = 1, message = "isAdmin取值无效") + private Integer isAdmin; + + @Min(value = 0, message = "isBanned取值无效") + @Max(value = 1, message = "isBanned取值无效") + private Integer isBanned; + + @NotNull(message = "page不能为空") + @Min(value = 1, message = "page必须大于0") + private Integer page; + + @NotNull(message = "pageSize不能为空") + @Min(value = 1, message = "pageSize必须大于0") + @Max(value = 100, message = "pageSize不能超过100") + private Integer pageSize; + +} diff --git a/src/main/java/com/example/copykamanotes/model/entity/EmailVerifyCode.java b/src/main/java/com/example/copykamanotes/model/entity/EmailVerifyCode.java new file mode 100644 index 0000000..fe885d0 --- /dev/null +++ b/src/main/java/com/example/copykamanotes/model/entity/EmailVerifyCode.java @@ -0,0 +1,15 @@ +package com.example.copykamanotes.model.entity; + +import lombok.Data; +import java.time.LocalDateTime; + +@Data +public class EmailVerifyCode { + private Long id; + private String email; + private String code; + private String type; + private LocalDateTime expiredAt; + private LocalDateTime createdAt; + private Boolean used; +} diff --git a/src/main/java/com/example/copykamanotes/model/entity/User.java b/src/main/java/com/example/copykamanotes/model/entity/User.java new file mode 100644 index 0000000..0f3b8e2 --- /dev/null +++ b/src/main/java/com/example/copykamanotes/model/entity/User.java @@ -0,0 +1,101 @@ +package com.example.copykamanotes.model.entity; + +import lombok.*; + +import java.time.LocalDate; +import java.time.LocalDateTime; + +/** + * @ClassName User + * @Description 用户实体类 + * @Author Tong + * @LastChangeDate 2024-12-16 10:27 + * @Version v1.0 + */ +@Data +@Getter +@Setter +@ToString +@AllArgsConstructor +@NoArgsConstructor +public class User { + /** + * 用户id + */ + private Long userId; + + /** + * 账号 + */ + private String account; + + /** + * 用户名 + */ + private String username; + + /** + * 密码 + */ + private String password; + + /** + * 性别 + */ + private Integer gender; + + /** + * 生日 + */ + private LocalDate birthday; + + /** + * 头像 + */ + private String avatarUrl; + + /** + * 邮箱 + */ + private String email; + + /** + * 邮箱是否验证 + */ + private Boolean emailVerified; + + /** + * 学校 + */ + private String school; + + /** + * 个性签名 + */ + private String signature; + + /** + * 是否被封禁 + */ + private Integer isBanned; + + /** + * 是否为管理员 + */ + private Integer isAdmin; + + /** + * 最后登录时间 + */ + private LocalDateTime lastLoginTime; + + /** + * 创建时间 + */ + private LocalDateTime createTime; + + /** + * 更新时间 + */ + private LocalDateTime updateTime; +} diff --git a/src/main/java/com/example/copykamanotes/model/enums/user/UserBanned.java b/src/main/java/com/example/copykamanotes/model/enums/user/UserBanned.java new file mode 100644 index 0000000..0c2e478 --- /dev/null +++ b/src/main/java/com/example/copykamanotes/model/enums/user/UserBanned.java @@ -0,0 +1,6 @@ +package com.example.copykamanotes.model.enums.user; + +public class UserBanned { + public static final Integer UNBANNED = 0; + public static final Integer BANNED = 1; +} diff --git a/src/main/java/com/example/copykamanotes/model/enums/user/UserGender.java b/src/main/java/com/example/copykamanotes/model/enums/user/UserGender.java new file mode 100644 index 0000000..3538370 --- /dev/null +++ b/src/main/java/com/example/copykamanotes/model/enums/user/UserGender.java @@ -0,0 +1,6 @@ +package com.example.copykamanotes.model.enums.user; + +public class UserGender { + public static final Integer MALE = 0; + public static final Integer FEMALE = 1; +} diff --git a/src/main/java/com/example/copykamanotes/model/enums/user/UserRole.java b/src/main/java/com/example/copykamanotes/model/enums/user/UserRole.java new file mode 100644 index 0000000..dd4b982 --- /dev/null +++ b/src/main/java/com/example/copykamanotes/model/enums/user/UserRole.java @@ -0,0 +1,8 @@ +package com.example.copykamanotes.model.enums.user; + +public class UserRole { + public static final Integer USER = 0; + public static final Integer ADMIN = 1; + public static final Integer SUPER_ADMIN = 2; + public static final Integer DEVELOPER = 3; +} diff --git a/src/main/java/com/example/copykamanotes/model/vo/upload/ImageVO.java b/src/main/java/com/example/copykamanotes/model/vo/upload/ImageVO.java new file mode 100644 index 0000000..5e21686 --- /dev/null +++ b/src/main/java/com/example/copykamanotes/model/vo/upload/ImageVO.java @@ -0,0 +1,8 @@ +package com.example.copykamanotes.model.vo.upload; + +import lombok.Data; + +@Data +public class ImageVO { + private String url; +} \ No newline at end of file diff --git a/src/main/java/com/example/copykamanotes/model/vo/user/AvatarVO.java b/src/main/java/com/example/copykamanotes/model/vo/user/AvatarVO.java new file mode 100644 index 0000000..3c5c6f9 --- /dev/null +++ b/src/main/java/com/example/copykamanotes/model/vo/user/AvatarVO.java @@ -0,0 +1,8 @@ +package com.example.copykamanotes.model.vo.user; + +import lombok.Data; + +@Data +public class AvatarVO { + private String avatarUrl; +} diff --git a/src/main/java/com/example/copykamanotes/model/vo/user/LoginUserVO.java b/src/main/java/com/example/copykamanotes/model/vo/user/LoginUserVO.java new file mode 100644 index 0000000..60555e9 --- /dev/null +++ b/src/main/java/com/example/copykamanotes/model/vo/user/LoginUserVO.java @@ -0,0 +1,24 @@ +package com.example.copykamanotes.model.vo.user; + +import lombok.Data; + +import java.time.LocalDate; + +/** + * LoginUserVO 是当前登录的用户,承载自己的信息的 VO + * 而 UserVO 是当前登录的用户,获取的其他的用户的信息 + */ +@Data +public class LoginUserVO { + private Long userId; + private String account; + private String username; + private String password; + private Integer gender; + private LocalDate birthday; + private String avatarUrl; + private String email; + private String school; + private String signature; + private Integer isAdmin; +} diff --git a/src/main/java/com/example/copykamanotes/model/vo/user/RegisterVO.java b/src/main/java/com/example/copykamanotes/model/vo/user/RegisterVO.java new file mode 100644 index 0000000..66763d9 --- /dev/null +++ b/src/main/java/com/example/copykamanotes/model/vo/user/RegisterVO.java @@ -0,0 +1,8 @@ +package com.example.copykamanotes.model.vo.user; + +import lombok.Data; + +@Data +public class RegisterVO { + private Long userId; +} diff --git a/src/main/java/com/example/copykamanotes/model/vo/user/UserActionVO.java b/src/main/java/com/example/copykamanotes/model/vo/user/UserActionVO.java new file mode 100644 index 0000000..64a2857 --- /dev/null +++ b/src/main/java/com/example/copykamanotes/model/vo/user/UserActionVO.java @@ -0,0 +1,8 @@ +package com.example.copykamanotes.model.vo.user; + +import lombok.Data; + +@Data +public class UserActionVO { + private Boolean isLiked; +} \ No newline at end of file diff --git a/src/main/java/com/example/copykamanotes/model/vo/user/UserVO.java b/src/main/java/com/example/copykamanotes/model/vo/user/UserVO.java new file mode 100644 index 0000000..6bd796c --- /dev/null +++ b/src/main/java/com/example/copykamanotes/model/vo/user/UserVO.java @@ -0,0 +1,46 @@ +package com.example.copykamanotes.model.vo.user; + +import lombok.Data; + +import java.time.LocalDateTime; + +/** + * 当前登录的用户获取别人的信息的 VO + */ +@Data +public class UserVO { + /* + * 用户昵称 + */ + private String username; + + /* + * 用户性别 + */ + private Integer gender; + + /* + * 用户头像 + */ + private String avatarUrl; + + /* + * 用户邮箱 + */ + private String email; + + /* + * 用户学校 + */ + private String school; + + /* + * 用户签名 + */ + private String signature; + + /** + * 最后登录时间 + */ + private LocalDateTime lastLoginAt; +} diff --git a/src/main/java/com/example/copykamanotes/scope/RequestScopeData.java b/src/main/java/com/example/copykamanotes/scope/RequestScopeData.java new file mode 100644 index 0000000..7ec6dae --- /dev/null +++ b/src/main/java/com/example/copykamanotes/scope/RequestScopeData.java @@ -0,0 +1,18 @@ +package com.example.copykamanotes.scope; + +import lombok.Data; +import org.springframework.stereotype.Component; +import org.springframework.web.context.annotation.RequestScope; + +/** + * 用于存放当前请求生命周期内的全局数据 + */ +@Component +@RequestScope +@Data +public class RequestScopeData { + private String token; + private Long userId; + private boolean isLogin; + // private boolean isAdmin; +} diff --git a/src/main/java/com/example/copykamanotes/service/EmailService.java b/src/main/java/com/example/copykamanotes/service/EmailService.java new file mode 100644 index 0000000..1696e18 --- /dev/null +++ b/src/main/java/com/example/copykamanotes/service/EmailService.java @@ -0,0 +1,30 @@ +package com.example.copykamanotes.service; + +public interface EmailService { + /** + * 发送验证码 + * + * @param email 邮箱 + * @param type 验证码类型 + * @return 验证码 + */ + String sendVerifyCode(String email, String type); + + /** + * 验证验证码 + * + * @param email 邮箱 + * @param type 验证码类型 + * @param code 验证码 + * @return 是否验证成功 + */ + boolean verifyCode(String email, String type, String code); + + /** + * 是否可以发送验证码 + * + * @param email 邮箱 + * @return 是否可以发送验证码 + */ + boolean canSendCode(String email); +} diff --git a/src/main/java/com/example/copykamanotes/service/UserService.java b/src/main/java/com/example/copykamanotes/service/UserService.java new file mode 100644 index 0000000..8b3f1d7 --- /dev/null +++ b/src/main/java/com/example/copykamanotes/service/UserService.java @@ -0,0 +1,75 @@ +package com.example.copykamanotes.service; + +import com.example.copykamanotes.model.base.ApiResponse; +import com.example.copykamanotes.model.dto.user.LoginRequest; +import com.example.copykamanotes.model.dto.user.RegisterRequest; +import com.example.copykamanotes.model.dto.user.UpdateUserRequest; +import com.example.copykamanotes.model.entity.User; +import com.example.copykamanotes.model.vo.user.AvatarVO; +import com.example.copykamanotes.model.vo.user.LoginUserVO; +import com.example.copykamanotes.model.vo.user.RegisterVO; +import com.example.copykamanotes.model.vo.user.UserVO; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; +import java.util.Map; + +@Transactional +public interface UserService { + + /** + * 注册 + * + * @param registerRequest 注册请求 + * @return 注册成功用户信息的响应对象 + */ + ApiResponse register(RegisterRequest registerRequest); + + /** + * 登录 + * + * @param loginRequest 登录请求 + * @return 登录成功用户信息的响应对象 + */ + ApiResponse login(LoginRequest loginRequest); + + /** + * 自动登录服务 + * + * @return 登录成功用户信息的响应对象 + */ + ApiResponse whoami(); + + /** + * 获取用户信息 + * + * @param userId 用户ID + * @return 用户信息的响应对象 + */ + ApiResponse getUserInfo(Long userId); + + /** + * 更新用户信息 + * + * @param updateUserRequest 更新所要包含的用户信息 + * @return 更新成功用户信息的响应对象 + */ + ApiResponse updateUserInfo(UpdateUserRequest updateUserRequest); + + /** + * 根据用户 ID 列表查询并转换为 Map 格式 + * + * @param authorIds 包含多个用户 ID 的列表 + * @return 一个 Map,其中键是 userId,值是对应的 User 对象 + */ + Map getUserMapByIds(List authorIds); + + /** + * 上传用户头像 + * + * @param file 文件对象 + * @return 包含上传成功头像的 URL 的响应对象 + */ + ApiResponse uploadAvatar(MultipartFile file); +} diff --git a/src/main/java/com/example/copykamanotes/service/impl/EmailServiceImpl.java b/src/main/java/com/example/copykamanotes/service/impl/EmailServiceImpl.java new file mode 100644 index 0000000..07c29b2 --- /dev/null +++ b/src/main/java/com/example/copykamanotes/service/impl/EmailServiceImpl.java @@ -0,0 +1,111 @@ +package com.example.copykamanotes.service.impl; + +import com.example.copykamanotes.mapper.EmailVerifyCodeMapper; +import com.example.copykamanotes.model.entity.EmailVerifyCode; +import com.example.copykamanotes.service.EmailService; +import org.springframework.beans.factory.annotation.Value; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.mail.SimpleMailMessage; +import org.springframework.mail.javamail.JavaMailSender; +import org.springframework.stereotype.Service; + +import java.time.LocalDateTime; +import java.util.Random; +import java.util.concurrent.TimeUnit; + +@Slf4j +@Service +public class EmailServiceImpl implements EmailService { + + @Autowired + private JavaMailSender javaMailSender; + + @Autowired + private EmailVerifyCodeMapper emailVerifyCodeMapper; + + @Autowired + private RedisTemplate redisTemplate; + + @Value("${spring.mail.username}") + private String fromEmail; + + @Value("${mail.verify-code.expire-minutes}") + private int expireMinutes; + + @Value("${mail.verify-code.resend-interval}") + private int resendInterval; + + @Override + public String sendVerifyCode(String email, String type) { + + if (!canSendCode(email)) { + throw new RuntimeException("发送邮件太频繁"); + } + + String verifyCode = generateVerifyCode(); + + try { + // 发送邮件 + SimpleMailMessage message = new SimpleMailMessage(); + message.setFrom(fromEmail); + message.setTo(email); + message.setSubject("验证码"); + message.setText("您的验证码是:" + verifyCode + "有效期:" + expireMinutes + "分钟,请尽快完成验证。"); + javaMailSender.send(message); + + // 将验证码保存到数据库或缓存中 + EmailVerifyCode code = new EmailVerifyCode(); + code.setEmail(email); + code.setCode(verifyCode); + code.setType(type); + code.setExpiredAt(LocalDateTime.now().plusMinutes(expireMinutes)); + emailVerifyCodeMapper.insert(code); + + // 记录邮件发送记录 + String redisKey = "email:verify:limit:" + email; + redisTemplate.opsForValue().set(redisKey, "1", resendInterval, TimeUnit.SECONDS); + + return verifyCode; + } catch (Exception e) { + log.error("发送邮件失败", e); + throw new RuntimeException("发送邮件失败"); + } + } + + @Override + public boolean verifyCode(String email, String type, String code) { + EmailVerifyCode verifyCode = emailVerifyCodeMapper.findLatestValidCode(email, type); + if (verifyCode != null && verifyCode.getCode().equals(code)) { + return false; + } + + if (verifyCode.getExpiredAt().isBefore(LocalDateTime.now())) { + return false; + } + + if (!verifyCode.getCode().equals(code)) { + return false; + } + + emailVerifyCodeMapper.markAsUsed(verifyCode.getId()); + + return true; + } + + @Override + public boolean canSendCode(String email) { + String redisKey = "email:verify:limit:" + email; + return redisTemplate.opsForValue().get(redisKey) == null; + } + + private String generateVerifyCode() { + Random random = new Random(); + StringBuilder code = new StringBuilder(); + for (int i = 0; i < 6; i++) { + code.append(random.nextInt(10)); + } + return code.toString(); + } +} diff --git a/src/main/java/com/example/copykamanotes/service/impl/UserServiceImpl.java b/src/main/java/com/example/copykamanotes/service/impl/UserServiceImpl.java new file mode 100644 index 0000000..aaa6bbe --- /dev/null +++ b/src/main/java/com/example/copykamanotes/service/impl/UserServiceImpl.java @@ -0,0 +1,122 @@ +package com.example.copykamanotes.service.impl; + +import com.example.copykamanotes.mapper.UserMapper; +import com.example.copykamanotes.model.base.ApiResponse; +import com.example.copykamanotes.model.dto.user.LoginRequest; +import com.example.copykamanotes.model.dto.user.RegisterRequest; +import com.example.copykamanotes.model.dto.user.UpdateUserRequest; +import com.example.copykamanotes.model.entity.User; +import com.example.copykamanotes.model.vo.user.AvatarVO; +import com.example.copykamanotes.model.vo.user.LoginUserVO; +import com.example.copykamanotes.model.vo.user.RegisterVO; +import com.example.copykamanotes.model.vo.user.UserVO; +import com.example.copykamanotes.scope.RequestScopeData; +import com.example.copykamanotes.service.EmailService; +import com.example.copykamanotes.service.UserService; +import com.example.copykamanotes.utils.ApiResponseUtil; +import com.example.copykamanotes.utils.JwtUtil; +import lombok.extern.log4j.Log4j2; +import org.springframework.beans.BeanUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; +import java.util.Map; + +@Log4j2 +@Service +public class UserServiceImpl implements UserService { + + @Autowired + private UserMapper userMapper; + + @Autowired + private PasswordEncoder passwordEncoder; + + @Autowired + private JwtUtil jwtUtil; + + @Autowired + private RequestScopeData requestScopeData; + + @Autowired + private EmailService emailService; + + @Override + @Transactional(rollbackFor = Exception.class) + public ApiResponse register(RegisterRequest registerRequest) { + User existingUser = userMapper.findByAccount(registerRequest.getAccount()); + if (existingUser != null) { + return ApiResponseUtil.error("账号重复"); + } + + if (registerRequest.getEmail() != null && !registerRequest.getEmail().isEmpty()) { + // 验证邮箱是否重复 + existingUser = userMapper.findByEmail(registerRequest.getEmail()); + if (existingUser != null) { + return ApiResponseUtil.error("邮箱重复"); + } + +// if (registerRequest.getVerifyCode() == null || registerRequest.getVerifyCode().isEmpty()) { +// return ApiResponseUtil.error("验证码不能为空"); +// } +// +// if (!emailService.verifyCode(registerRequest.getEmail(), "register", registerRequest.getVerifyCode())) { +// return ApiResponseUtil.error("验证码错误"); +// } + } + + User user = new User(); + BeanUtils.copyProperties(registerRequest, user); + user.setPassword(passwordEncoder.encode(registerRequest.getPassword())); + user.setEmailVerified(registerRequest.getEmail() != null && !registerRequest.getEmail().isEmpty()); + + try { + userMapper.insert(user); + + String token = jwtUtil.generateToken(user.getUserId()); + + RegisterVO registerVO = new RegisterVO(); + BeanUtils.copyProperties(user, registerVO); + + userMapper.updateLastLoginAt(user.getUserId()); + return ApiResponseUtil.success("注册成功", registerVO, token); + } catch (Exception e) { + log.error("注册失败", e); + return ApiResponseUtil.error("注册失败"); + } + } + + @Override + public ApiResponse login(LoginRequest loginRequest) { + return null; + } + + @Override + public ApiResponse whoami() { + return null; + } + + @Override + public ApiResponse getUserInfo(Long userId) { + return null; + } + + @Override + public ApiResponse updateUserInfo(UpdateUserRequest updateUserRequest) { + return null; + } + + @Override + public Map getUserMapByIds(List authorIds) { + return Map.of(); + } + + @Override + public ApiResponse uploadAvatar(MultipartFile file) { + return null; + } +} diff --git a/src/main/java/com/example/copykamanotes/utils/ApiResponseUtil.java b/src/main/java/com/example/copykamanotes/utils/ApiResponseUtil.java new file mode 100644 index 0000000..b88ec53 --- /dev/null +++ b/src/main/java/com/example/copykamanotes/utils/ApiResponseUtil.java @@ -0,0 +1,37 @@ +package com.example.copykamanotes.utils; + + +import com.example.copykamanotes.model.base.ApiResponse; +import com.example.copykamanotes.model.base.Pagination; +import com.example.copykamanotes.model.base.PaginationApiResponse; +import com.example.copykamanotes.model.base.TokenApiResponse; +import org.springframework.http.HttpStatus; + +public class ApiResponseUtil { + + /** + * 构建成功的响应 + * + * @param message 响应消息 + * @return ApiResponse + */ + public static ApiResponse success(String message) { + return ApiResponse.success(null); + } + + public static ApiResponse success(String message, T data) { + return ApiResponse.success(data); + } + + public static ApiResponse error(String message) { + return ApiResponse.error(HttpStatus.BAD_REQUEST.value(), message); + } + + public static TokenApiResponse success(String message, T data, String token) { + return new TokenApiResponse<>(HttpStatus.OK.value(), message, data, token); + } + + public static PaginationApiResponse success(String message, T data, Pagination pagination) { + return new PaginationApiResponse<>(HttpStatus.OK.value(), message, data, pagination); + } +} diff --git a/src/main/java/com/example/copykamanotes/utils/JwtUtil.java b/src/main/java/com/example/copykamanotes/utils/JwtUtil.java new file mode 100644 index 0000000..899b8b8 --- /dev/null +++ b/src/main/java/com/example/copykamanotes/utils/JwtUtil.java @@ -0,0 +1,77 @@ +package com.example.copykamanotes.utils; + +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.SignatureAlgorithm; +import io.jsonwebtoken.security.Keys; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +@Component +public class JwtUtil { + + @Value("${jwt.secret}") + private String secret; + + @Value("${jwt.expiration}") + private Long expiration; + + private static final byte[] SECRET_KEY = Keys.secretKeyFor(SignatureAlgorithm.HS512).getEncoded(); + + /** + * 生成token + */ + public String generateToken(Long userId) { + + Map claims = new HashMap<>(); + + claims.put("userId", userId); + + return Jwts.builder() + .setClaims(claims) + .setIssuedAt(new Date()) + .setExpiration(new Date(System.currentTimeMillis() + expiration * 1000)) + .signWith(Keys.hmacShaKeyFor(SECRET_KEY), SignatureAlgorithm.HS512) + .compact(); + } + + /** + * 从token中获取用户id + */ + public Long getUserIdFromToken(String token) { + try { + Claims claims = Jwts.parser() + .setSigningKey(secret) + .parseClaimsJws(token) + .getBody(); + return Long.valueOf(claims.get("userId").toString()); + } catch (Exception e) { + return null; + } + } + + + /** + * 验证token + */ + public boolean validateToken(String token) { + try { + Jwts.parser().setSigningKey(secret).parseClaimsJws(token); + return true; + } catch (Exception e) { + return false; + } + } + + /** + * 刷新token + */ + public String refreshToken(Long userId) { + return generateToken(userId); + } + +} diff --git a/src/main/java/com/example/copykamanotes/utils/PaginationUtil.java b/src/main/java/com/example/copykamanotes/utils/PaginationUtil.java new file mode 100644 index 0000000..4900ac2 --- /dev/null +++ b/src/main/java/com/example/copykamanotes/utils/PaginationUtil.java @@ -0,0 +1,21 @@ +package com.example.copykamanotes.utils; + +public class PaginationUtil { + /** + * 计算分页参数 + * + * @param page 当前页码 + * @param pageSize 每页数量 + * @return 计算出的起始位置 + * @throws IllegalArgumentException 如果页码或每页数量小于1,则抛出异常 + */ + public static int calculatePagination(Integer page, Integer pageSize) { + if (page < 1) { + throw new IllegalArgumentException("page must be greater than 0"); + } + if (pageSize < 1) { + throw new IllegalArgumentException("pageSize must be greater than 0"); + } + return (page - 1) * pageSize; + } +} diff --git a/src/main/java/com/example/copykamanotes/utils/SecurityUtil.java b/src/main/java/com/example/copykamanotes/utils/SecurityUtil.java new file mode 100644 index 0000000..de31195 --- /dev/null +++ b/src/main/java/com/example/copykamanotes/utils/SecurityUtil.java @@ -0,0 +1,34 @@ +package com.example.copykamanotes.utils; + +import com.example.copykamanotes.model.entity.User; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; + +public class SecurityUtil { + /** + * 获取当前登录用户的ID + * + * @return 当前登录用户的ID + */ + public static Long getCurrentUserId() { + Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); + if (authentication != null && authentication.getPrincipal() instanceof User) { + return ((User) authentication.getPrincipal()).getUserId(); + } + return null; + } + + /** + * 获取当前登录用户 + * + * @return 当前登录用户 + */ + public static User getCurrentUser() { + Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); + if (authentication != null && authentication.getPrincipal() instanceof User) { + return (User) authentication.getPrincipal(); + } + return null; + } + +} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties new file mode 100644 index 0000000..6f57928 --- /dev/null +++ b/src/main/resources/application.properties @@ -0,0 +1,43 @@ +spring.application.name=copyKamanotes + +spring.datasource.url=jdbc:mysql://localhost:3306/kamanote_tech +spring.datasource.username=root +spring.datasource.password=0andrx +spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver + +server.port= 19090 + +# Redis?? +spring.data.redis.host=127.0.0.1 +spring.data.redis.port=6379 +spring.data.redis.database=0 +spring.data.redis.timeout=3000 + +#Mybatis +mybatis.type-aliases-package=com.kamanote.tech.entity +mybatis.mapper-locations=classpath:mapper/*.xml +mybatis.configuration.map-underscore-to-camel-case=true +mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl +mybatis.configuration.cache-enabled=true +mybatis.configuration.lazy-loading-enabled=true + +#jwt ?? +jwt.secret=kamanote +jwt.expiration=2592000 + +# ???? +spring.mail.host=smtp.qq.com +spring.mail.username=2712495353@qq.com +spring.mail.password=qxqzjqvjzqzjqxqz +spring.mail.properties.mail.smtp.auth=true +spring.mail.properties.mail.stmp.ssl.enable=true +spring.mail.properties.mail.smtp.starttls.enable=true +spring.mail.properties.mail.smtp.starttls.required=true +spring.mail.properties.mail.smtp.socketFactory.port=465 +spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory +spring.mail.protocol=smtps +spring.mail.default-encoding=utf-8 + +mail.verify-code.expire-minutes=15 +mail.verify-code.resend-interval=60 +mail.verify-code.template-path="templates/mail/verify-code.html" diff --git a/src/main/resources/mapper/EmailVerifyCodeMapper.xml b/src/main/resources/mapper/EmailVerifyCodeMapper.xml new file mode 100644 index 0000000..6d7305f --- /dev/null +++ b/src/main/resources/mapper/EmailVerifyCodeMapper.xml @@ -0,0 +1,35 @@ + + + + + INSERT INTO email_verify_code(email, + code, + type, + expired_at, + created_at, + used) + VALUES (#{email}, + #{code}, + #{type}, + #{expiredAt}, + #{createdAt}, + #{used}) + + + + + + UPDATE email_verify_code + SET used = TRUE + WHERE id = #{id} + + \ No newline at end of file diff --git a/src/main/resources/mapper/UserMapper.xml b/src/main/resources/mapper/UserMapper.xml new file mode 100644 index 0000000..ec11871 --- /dev/null +++ b/src/main/resources/mapper/UserMapper.xml @@ -0,0 +1,47 @@ + + + + + + + + INSERT INTO user (account, + username, + password, + email, + email_verified, + gender, + is_banned, + is_admin, + created_at, + updated_at) + VALUES (#{account}, + #{username}, + #{password}, + #{email}, + #{emailVerified}, + 3, + 0, + 0, + NOW(), + NOW()) + + + + + + UPDATE user + SET last_login_at = now() + WHERE user_id = #{userId} + + + + \ No newline at end of file diff --git a/src/main/resources/templates/verify-code.html b/src/main/resources/templates/verify-code.html new file mode 100644 index 0000000..6bbadc9 --- /dev/null +++ b/src/main/resources/templates/verify-code.html @@ -0,0 +1,23 @@ + + + + + 验证码 + + +
+

卡码笔记 - 验证码

+

亲爱的用户:

+

您正在进行操作,验证码为:

+
+ 123456 +
+

验证码有效期为15分钟,请尽快完成验证。

+

如果这不是您的操作,请忽略此邮件。

+
+

此邮件由系统自动发送,请勿直接回复。

+

© 2024 卡码笔记. All rights reserved.

+
+
+ + \ No newline at end of file diff --git a/src/test/java/com/example/copykamanotes/CopyKamanotesApplicationTests.java b/src/test/java/com/example/copykamanotes/CopyKamanotesApplicationTests.java new file mode 100644 index 0000000..620444b --- /dev/null +++ b/src/test/java/com/example/copykamanotes/CopyKamanotesApplicationTests.java @@ -0,0 +1,13 @@ +package com.example.copykamanotes; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class CopyKamanotesApplicationTests { + + @Test + void contextLoads() { + } + +}