feat: init commit

This commit is contained in:
merlin
2025-10-16 16:57:27 +08:00
commit 4f84603d82
57 changed files with 2243 additions and 0 deletions

2
.gitattributes vendored Normal file
View File

@@ -0,0 +1,2 @@
/mvnw text eol=lf
*.cmd text eol=crlf

33
.gitignore vendored Normal file
View File

@@ -0,0 +1,33 @@
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/

19
.mvn/wrapper/maven-wrapper.properties vendored Normal file
View File

@@ -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
#
# http://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.9/apache-maven-3.9.9-bin.zip

259
mvnw vendored Normal file
View File

@@ -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
#
# http://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
mvnw.cmd vendored Normal file
View File

@@ -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 http://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"

93
pom.xml Normal file
View File

@@ -0,0 +1,93 @@
<?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>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.4.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>xin.merlin</groupId>
<artifactId>myblog_server</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>myblog_server</name>
<description>myblog_server</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- JWT (JSON Web Token) -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.12.6</version>
</dependency>
<!-- Jakarta Servlet API适用于 JDK 17 -->
<dependency>
<groupId>jakarta.servlet</groupId>
<artifactId>jakarta.servlet-api</artifactId>
<version>5.0.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.11</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-jsqlparser</artifactId>
<version>3.5.11</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>3.0.4</version>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

View File

@@ -0,0 +1,16 @@
package xin.merlin.myblog_server;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import xin.merlin.myblog_server.config.JwtProperties;
@SpringBootApplication
@EnableConfigurationProperties(JwtProperties.class)
public class MyblogServerApplication {
public static void main(String[] args) {
SpringApplication.run(MyblogServerApplication.class, args);
}
}

View File

@@ -0,0 +1,66 @@
package xin.merlin.myblog_server.config;
import lombok.Getter;
import lombok.Setter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Collection;
public class CustomUserDetails implements UserDetails {
private String username;
private String password;
// Getter 和 Setter
@Setter
@Getter
private String u_id;
@Getter
@Setter
private String role;
private Collection<? extends GrantedAuthority> authorities;
public CustomUserDetails(String username, String password, String u_id,String role, Collection<? extends GrantedAuthority> authorities) {
this.username = username;
this.password = password;
this.u_id = u_id;
this.role = role;
this.authorities = authorities;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return authorities;
}
@Override
public String getPassword() {
return password;
}
@Override
public String getUsername() {
return username;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
}

View File

@@ -0,0 +1,15 @@
package xin.merlin.myblog_server.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@Data
@Configuration
@ConfigurationProperties(prefix = "jwt")
public class JwtProperties {
private String secret;
private String issuer;
private String subject;
private long expire; // 秒
}

View File

@@ -0,0 +1,25 @@
package xin.merlin.myblog_server.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import xin.merlin.myblog_server.entity.Account;
import xin.merlin.myblog_server.service.impl.AccountServiceImpl;
import java.util.ArrayList;
@Service
public class LoginDetails implements UserDetailsService {
@Autowired
private AccountServiceImpl accountServiceImpl;
@Override
public CustomUserDetails loadUserByUsername(String u_account) throws UsernameNotFoundException {
Account account = accountServiceImpl.getAccountInfo(u_account);
return new CustomUserDetails(account.getU_account(), account.getU_password(),account.getU_id(), account.getRole(),new ArrayList<>());
}
}

View File

@@ -0,0 +1,18 @@
package xin.merlin.myblog_server.config;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MyBatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
return interceptor;
}
}

View File

@@ -0,0 +1,64 @@
package xin.merlin.myblog_server.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import xin.merlin.myblog_server.security.JWTAuthenticationFilter;
import static org.springframework.security.config.Customizer.withDefaults;
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Autowired
private JWTAuthenticationFilter jwtAuthenticationFilter;
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.cors(withDefaults()) // <<<<<< 这里明确加上 withDefaults()
.csrf(AbstractHttpConfigurer::disable)
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(authz -> authz
.requestMatchers(
"/login",
"/register",
"/test",
"/admin/login",
"/admin/register",
"/code/sendcode",
"/code/verifycode"
).permitAll()
.anyRequest().authenticated()
)
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
return http.build();
}
// 新增全局CORS配置
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOriginPatterns("*") // 开发阶段允许所有来源
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
.allowedHeaders("*")
.exposedHeaders("Authorization")
.allowCredentials(true)
.maxAge(3600L);
}
};
}
}

View File

@@ -0,0 +1,259 @@
package xin.merlin.myblog_server.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import xin.merlin.myblog_server.config.CustomUserDetails;
import xin.merlin.myblog_server.config.LoginDetails;
import xin.merlin.myblog_server.entity.*;
import xin.merlin.myblog_server.service.impl.*;
import xin.merlin.myblog_server.utils.JwtUtil;
import xin.merlin.myblog_server.utils.RequestBack;
import xin.merlin.myblog_server.utils.SHA256Util;
import xin.merlin.myblog_server.utils.enums.ResultCode;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.UUID;
@RestController
@RequestMapping("/admin")
public class AdminController {
@Autowired
private LoginDetails loginDetails;
@Autowired
private AccountServiceImpl accountService;
@Autowired
private UserServiceImpl userService;
@Autowired
private ArticleServiceImpl articleService;
@Autowired
private NewsServiceImpl newsService;
@Autowired
private CommentServiceImpl commentService;
@Autowired
private ProjectServiceImpl projectService;
@Autowired
private SHA256Util sha256Util;
@Autowired
private JwtUtil jwtUtil;
@Value("${file.image-dir}")
private String avatarDir;
// 登录逻辑p //admin:Blog_779528
@PostMapping("/login")
public RequestBack login(@RequestBody Account account) {
try {
CustomUserDetails userDetails = loginDetails
.loadUserByUsername(account.getU_account());
if(!userDetails.getRole().equals("Admin")) return RequestBack.fail(ResultCode.USER_NOT_FOUND);
account.setU_password(sha256Util
.encryptPassword(account.getU_password(),userDetails.getU_id()));
// 验证密码
if(!account.getU_password().equals(userDetails.getPassword()))
return RequestBack.success(ResultCode.USER_PASSWORD_ERROR,null);
// 生成token
String token = jwtUtil.generateToken(account.getU_account(),userDetails.getU_id());
return RequestBack.success(ResultCode.SUCCESS, Map.of("token",token,"token_type","Bearer","role","Admin"));
} catch (UsernameNotFoundException e) {
System.out.println(e.getMessage());
return RequestBack.fail(ResultCode.SERVER_ERROR);
}
}
// 注册逻辑
@PostMapping("/register")
public RequestBack register(@RequestBody Account account) {
try {
// 分配id
String u_id;
u_id = "A000000001";
// 注册信息初始化
account.setU_id(u_id);
account.setU_password(sha256Util.encryptPassword(account.getU_password(),account.getU_id()));
account.setU_status(0);
account.setRole("Admin");
// 注册
accountService.register(account);
return RequestBack.success(ResultCode.SUCCESS,null);
} catch (Exception e) {
System.out.println(e.getMessage());
return RequestBack.fail(ResultCode.SERVER_ERROR);
}
}
// 获取文章p
@GetMapping("/get/article")
public RequestBack getArticle(@RequestParam Integer current, @RequestParam Integer size) {
Page<Article> page = new Page<> (current,size);
return RequestBack.success(ResultCode.SUCCESS,articleService.page(page));
}
// 发送文章p
@PostMapping("/publish/article")
public RequestBack publishArticle(@RequestBody Article article) {
articleService.publishArticle(article);
return RequestBack.success(ResultCode.SUCCESS);
}
// 修改文章p
@PostMapping("/update/article")
public RequestBack updateArticle(@RequestBody Article article) {
articleService.updateArticle(article);
return RequestBack.success(ResultCode.SUCCESS);
}
// 删除文章p
@PostMapping("/delete/article")
public RequestBack deleteArticle(@RequestBody Article article) {
articleService.deleteArticle(article);
return RequestBack.success(ResultCode.SUCCESS);
}
// 获取新闻p
@GetMapping("/get/news")
public RequestBack getNews(@RequestParam Integer current,@RequestParam Integer size) {
Page<News> page = new Page<>(current,size);
return RequestBack.success(ResultCode.SUCCESS,newsService.page(page));
}
// 发送新闻p
@PostMapping("/publish/news")
public RequestBack publishNews(@RequestBody News news) {
news.setPublished(LocalDateTime.now().truncatedTo(ChronoUnit.SECONDS).toString());
return RequestBack.success(ResultCode.SUCCESS,newsService.save(news));
}
// 删除新闻p
@PostMapping("/delete/news")
public RequestBack deleteNews(@RequestBody News news) {
newsService.deleteNews(news);
return RequestBack.success(ResultCode.SUCCESS);
}
// 查看评论p
@GetMapping("/get/comments")
public RequestBack getComments(@RequestParam Integer current,@RequestParam Integer size) {
Page<Comment> page = new Page<>(current,size);
return RequestBack.success(ResultCode.SUCCESS,commentService.page(page));
}
// 删除评论p
@PostMapping("/delete/comments")
public RequestBack deleteComments(@RequestBody Comment comment){
commentService.deleteComment(comment);
return RequestBack.success(ResultCode.SUCCESS);
}
// 查看用户p
@GetMapping("/get/users")
public RequestBack getUsers(@RequestParam Integer current,@RequestParam Integer size) {
Page<User> page = new Page<>(current,size);
return RequestBack.success(ResultCode.SUCCESS,userService.page(page));
}
// 封禁用户p
@PostMapping("/ban/users")
public RequestBack banUsers(@RequestBody User user) {
String uid= user.getU_id();
UpdateWrapper<Account> updateWrapper = new UpdateWrapper<>();
updateWrapper.eq("u_id",uid)
.set("u_status",1);
accountService.update(updateWrapper);
return RequestBack.success(ResultCode.SUCCESS);
}
// 查看联系 //(缓)
@GetMapping("/get/contact")
public RequestBack getContact(@RequestParam Integer current,@RequestParam Integer size) {
return RequestBack.success(ResultCode.SUCCESS);
}
// 允许的文件类型
private static final List<String> ALLOWED_EXTENSIONS = Arrays.asList(".jpg", ".jpeg", ".png", ".gif");
// 上传图片p
@PostMapping("/upload/img")
public RequestBack uploadImg(@RequestParam("image") MultipartFile file) {
try {
File dir = new File(avatarDir);
if (!dir.exists()) dir.mkdirs();
// 取文件扩展名并检查是否合法
String originalFileName = file.getOriginalFilename();
String fileExtension = "";
if (originalFileName != null && originalFileName.contains(".")) {
fileExtension = originalFileName.substring(originalFileName.lastIndexOf(".")).toLowerCase();
}
if (!ALLOWED_EXTENSIONS.contains(fileExtension)) {
throw new IOException("仅支持 JPG, PNG, GIF 格式");
}
// 生成 UUID 作为文件名
String uuid = UUID.randomUUID().toString();
String fileName = uuid+ fileExtension;
Path targetPath = Paths.get(avatarDir, fileName);
Files.copy(file.getInputStream(), targetPath, StandardCopyOption.REPLACE_EXISTING);
return RequestBack.success(ResultCode.SUCCESS,Map.of("url","https://merlin.xin/images/"+fileName));
}catch (Exception e) {
e.printStackTrace();
return RequestBack.fail(ResultCode.SERVER_ERROR);
}
}
// 获取项目p
@GetMapping("/get/projects")
public RequestBack getProjects(@RequestParam Integer current,@RequestParam Integer size) {
Page<Project> page = new Page<>(current,size);
return RequestBack.success(ResultCode.SUCCESS,projectService.page(page));
}
// 发布项目p
@PostMapping("/publish/project")
public RequestBack publishProject(@RequestBody Project project) {
projectService.save(project);
return RequestBack.success(ResultCode.SUCCESS);
}
// 修改项目p
@PostMapping("/update/project")
public RequestBack updateProject(@RequestBody Project project) {
UpdateWrapper<Project> updateWrapper = new UpdateWrapper<>();
updateWrapper.eq("p_id",project.getP_id());
projectService.update(project,updateWrapper);
return RequestBack.success(ResultCode.SUCCESS);
}
// 删除项目p
@PostMapping("/delete/project")
public RequestBack deleteProject(@RequestBody Project project) {
projectService.deleteProject(project.getP_id());
return RequestBack.success(ResultCode.SUCCESS);
}
}

View File

@@ -0,0 +1,70 @@
package xin.merlin.myblog_server.controller;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import xin.merlin.myblog_server.entity.Comment;
import xin.merlin.myblog_server.entity.News;
import xin.merlin.myblog_server.entity.Project;
import xin.merlin.myblog_server.service.impl.*;
import xin.merlin.myblog_server.utils.JwtUtil;
import xin.merlin.myblog_server.utils.RequestBack;
import xin.merlin.myblog_server.utils.enums.ResultCode;
@RestController
@RequestMapping("/blog")
public class BasicController {
@Resource
private NewsServiceImpl newsService;
@Autowired
private ArticleServiceImpl articleService;
@Autowired
private UserServiceImpl userService;
@Autowired
private ProjectServiceImpl projectService;
@Autowired
private CommentServiceImpl commentService;
@Autowired
private JwtUtil jwtUtil;
// 获取用户个人信息
@GetMapping("/get/userinfo")
public RequestBack getUserinfo(@RequestHeader("Authorization") String token) {
token = token.substring(7);
return RequestBack.success(ResultCode.SUCCESS,userService.getById(jwtUtil.getUId(token)));
}
// 获取新闻
@GetMapping("/get/news")
public RequestBack getNews(@RequestParam Integer current,@RequestParam Integer size) {
Page<News> page = new Page<>(current,size);
return RequestBack.success(ResultCode.SUCCESS,newsService.page(page));
}
// 获取文章
@GetMapping("/get/article/{a_id}")
public RequestBack getArticle(@PathVariable Integer a_id) {
return RequestBack.success(ResultCode.SUCCESS,articleService.getById(a_id));
}
// 获取项目
@GetMapping("/get/projects")
public RequestBack getProjects(@RequestParam Integer current,@RequestParam Integer size) {
Page<Project> page = new Page<>(current,size);
return RequestBack.success(ResultCode.SUCCESS,projectService.page(page));
}
// 参与项目
// 发表评论
@PostMapping("/publish/comment")
public RequestBack publishComment(@RequestBody Comment comment) {
commentService.save(comment);
return RequestBack.success(ResultCode.SUCCESS);
}
// 联系管理员
}

View File

@@ -0,0 +1,95 @@
package xin.merlin.myblog_server.controller;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import xin.merlin.myblog_server.config.CustomUserDetails;
import xin.merlin.myblog_server.config.LoginDetails;
import xin.merlin.myblog_server.entity.Account;
import xin.merlin.myblog_server.service.impl.AccountServiceImpl;
import xin.merlin.myblog_server.utils.JwtUtil;
import xin.merlin.myblog_server.utils.RandomCode;
import xin.merlin.myblog_server.utils.RequestBack;
import xin.merlin.myblog_server.utils.SHA256Util;
import xin.merlin.myblog_server.utils.enums.ResultCode;
import java.util.Map;
@RestController
@RequiredArgsConstructor
public class LoginController {
@Autowired
private LoginDetails loginDetails;
@Autowired
private AccountServiceImpl accountServiceImpl;
@Autowired
private SHA256Util sha256Util;
@Autowired
private JwtUtil jwtUtil;
@Autowired
private HttpServletRequest request;
// 登录逻辑
@PostMapping("/login")
public RequestBack login(@RequestBody Account account) {
try {
String ip = request.getRemoteAddr();
account.setIp(ip);
CustomUserDetails userDetails = loginDetails
.loadUserByUsername(account.getU_account());
account.setU_password(sha256Util
.encryptPassword(account.getU_password(),userDetails.getU_id()));
//System.out.println(account.getU_password());
// 验证密码
if(!account.getU_password().equals(userDetails.getPassword()))
return RequestBack.success(ResultCode.USER_PASSWORD_ERROR,null);
//System.out.println(userDetails.getU_id());
// 生成token
String token = jwtUtil.generateToken(account.getU_account(),userDetails.getU_id());
return RequestBack.success(ResultCode.SUCCESS, Map.of("token",token,"token_type","Bearer","role","User"));
} catch (UsernameNotFoundException e) {
System.out.println(e.getMessage());
return RequestBack.fail(ResultCode.SERVER_ERROR);
}
}
// 注册逻辑
@PostMapping("/register")
public RequestBack register(@RequestBody Account account) {
try {
if(accountServiceImpl.isExist(account.getU_account())) return RequestBack.success(ResultCode.USER_EXIST,null);
// 分配id
String u_id;
do{
u_id = "U"+ RandomCode.generateID();
}while(accountServiceImpl.idIsExist(u_id));
// 注册信息初始化
account.setU_id(u_id);
account.setU_password(sha256Util.encryptPassword(account.getU_password(),account.getU_id()));
account.setU_status(0);
account.setRole("User");
// 注册
accountServiceImpl.register(account);
return RequestBack.success(ResultCode.SUCCESS,null);
} catch (Exception e) {
System.out.println(e.getMessage());
return RequestBack.fail(ResultCode.SERVER_ERROR);
}
}
}

View File

@@ -0,0 +1,95 @@
package xin.merlin.myblog_server.controller;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import xin.merlin.myblog_server.entity.Account;
import xin.merlin.myblog_server.entity.Code;
import xin.merlin.myblog_server.service.impl.MailService;
import xin.merlin.myblog_server.utils.RandomCode;
import xin.merlin.myblog_server.utils.RequestBack;
import xin.merlin.myblog_server.utils.enums.ResultCode;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@RestController
@RequestMapping("/code")
public class MailController {
private static final Cache<String, String> waitingList = Caffeine.newBuilder()
.expireAfterWrite(5, TimeUnit.MINUTES)
.build();
// 冷却缓存:限制邮箱请求频率
private static final Cache<String, Boolean> emailCooldown = Caffeine.newBuilder()
.expireAfterWrite(60, TimeUnit.SECONDS) // 冷却 60 秒
.build();
// 验证码验证次数
private static final Cache<String, Integer> codeFailCount = Caffeine.newBuilder()
.expireAfterWrite(5, TimeUnit.MINUTES)
.build();
@Autowired
private MailService mailService;
@PostMapping("/sendcode")
RequestBack sendcode(@RequestBody Account account) {
if (account.getU_account() == null) return RequestBack.fail(ResultCode.BAD_REQUEST);
System.out.println("发送验证码到:" + account.getU_account());
String email = account.getU_account();
// 检查是否在冷却中
if (emailCooldown.getIfPresent(email) != null) {
return RequestBack.fail(ResultCode.USER_SEND_TOO_FAST);
}
String tempId;
do {
tempId = RandomCode.generateCode();
}
while (waitingList.getIfPresent(tempId) != null);
try {
waitingList.put(tempId, mailService.sendMail(account.getU_account()));
// 加入验证码冷却
emailCooldown.put(account.getU_account(), true);
return RequestBack.success(ResultCode.SUCCESS, Map.of("c_id", tempId));
} catch (Exception e) {
return RequestBack.fail(ResultCode.SERVER_ERROR);
}
}
@PostMapping("/verifycode")
RequestBack verifyCode(@RequestBody Code code) {
//测试验证码
if (code.getCode().equals("666666")) return RequestBack.success(ResultCode.SUCCESS);
String id=code.getC_id();
if(codeFailCount.getIfPresent(id) == null) codeFailCount.put(id, 1);
else if(codeFailCount.getIfPresent(id)<=5){
Integer time = codeFailCount.getIfPresent(id);
codeFailCount.put(id, ++time);
}else{
return RequestBack.fail(ResultCode.USER_SEND_TOO_OFTEN);
}
String tempCode = waitingList.getIfPresent(id);
System.out.println("waitingList" + tempCode + "\nv_id:" + id + "\ncode:" + code.getCode());
if (tempCode == null) return RequestBack.success(ResultCode.USER_VERIFICATION_ERROR);
if (!tempCode.equals(code.getCode())) return RequestBack.success(ResultCode.USER_VERIFICATION_ERROR);
waitingList.invalidate(id);
codeFailCount.invalidate(id);
emailCooldown.invalidate(code.getU_account());
return RequestBack.success(ResultCode.SUCCESS);
}
}

View File

@@ -0,0 +1,19 @@
package xin.merlin.myblog_server.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import xin.merlin.myblog_server.utils.JwtUtil;
@RestController
public class TestController {
@Autowired
private JwtUtil jwtUtil;
@GetMapping("/test")
public String test() {
String token = jwtUtil.generateToken("1223","U123");
return token;
}
}

View File

@@ -0,0 +1,9 @@
package xin.merlin.myblog_server.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/user")
public class UserController {
}

View File

@@ -0,0 +1,20 @@
package xin.merlin.myblog_server.entity;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
@Data
@TableName("account")
public class Account {
@TableId("u_id")
private String u_id;
private String u_account;
private String u_password;
private int u_status;
private String ip;
private String role;
}

View File

@@ -0,0 +1,18 @@
package xin.merlin.myblog_server.entity;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.time.LocalDateTime;
@Data
@TableName("article")
public class Article {
@TableId("a_id")
private Integer a_id;
private String title;
private String content;
private LocalDateTime created;
private LocalDateTime updated;
}

View File

@@ -0,0 +1,11 @@
package xin.merlin.myblog_server.entity;
import lombok.Data;
@Data
public class Code {
private String u_account;
private String c_id;
private String code;
}

View File

@@ -0,0 +1,17 @@
package xin.merlin.myblog_server.entity;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
@Data
@TableName("comment")
public class Comment {
@TableId("a_id")
private Integer a_id;
private String sender;
private String profile;
private String comment;
private String sent;
}

View File

@@ -0,0 +1,15 @@
package xin.merlin.myblog_server.entity;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
@Data
@TableName("contact")
public class Contact {
private String from;
private String to;
private String message;
private String time;
private int handled;
}

View File

@@ -0,0 +1,19 @@
package xin.merlin.myblog_server.entity;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
@Data
@TableName("garbage")
public class Garbage {
@TableId("delete_id")
private Integer delete_id;
private String type;
private String content;
public Garbage(String type, String content) {
this.type = type;
this.content = content;
}
}

View File

@@ -0,0 +1,18 @@
package xin.merlin.myblog_server.entity;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.time.LocalDateTime;
@Data
@TableName("news")
public class News {
@TableId("a_id")
private Integer a_id;
private String n_title;
private String synopsis;
private String published;
}

View File

@@ -0,0 +1,16 @@
package xin.merlin.myblog_server.entity;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
@Data
@TableName("project")
public class Project {
@TableId("p_id")
private Integer p_id;
private String p_name;
private String techstack;
private String details;
private String p_status;
}

View File

@@ -0,0 +1,15 @@
package xin.merlin.myblog_server.entity;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
@Data
@TableName("user")
public class User {
@TableId("u_id")
private String u_id;
private String u_name;
private String u_avatar;
}

View File

@@ -0,0 +1,10 @@
package xin.merlin.myblog_server.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import xin.merlin.myblog_server.entity.Account;
@Mapper
public interface AccountMapper extends BaseMapper<Account> {
}

View File

@@ -0,0 +1,9 @@
package xin.merlin.myblog_server.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import xin.merlin.myblog_server.entity.Article;
@Mapper
public interface ArticleMapper extends BaseMapper<Article> {
}

View File

@@ -0,0 +1,9 @@
package xin.merlin.myblog_server.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import xin.merlin.myblog_server.entity.Comment;
@Mapper
public interface CommentMapper extends BaseMapper<Comment> {
}

View File

@@ -0,0 +1,4 @@
package xin.merlin.myblog_server.mapper;
public interface ContactMapper {
}

View File

@@ -0,0 +1,9 @@
package xin.merlin.myblog_server.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import xin.merlin.myblog_server.entity.Garbage;
@Mapper
public interface GarbageMapper extends BaseMapper<Garbage> {
}

View File

@@ -0,0 +1,10 @@
package xin.merlin.myblog_server.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import xin.merlin.myblog_server.entity.News;
@Mapper
public interface NewsMapper extends BaseMapper<News> {
}

View File

@@ -0,0 +1,10 @@
package xin.merlin.myblog_server.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import xin.merlin.myblog_server.entity.Project;
@Mapper
public interface ProjectMapper extends BaseMapper<Project> {
}

View File

@@ -0,0 +1,10 @@
package xin.merlin.myblog_server.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import xin.merlin.myblog_server.entity.User;
@Mapper
public interface UserMapper extends BaseMapper<User> {
}

View File

@@ -0,0 +1,67 @@
package xin.merlin.myblog_server.security;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import xin.merlin.myblog_server.utils.JwtUtil;
import java.io.IOException;
import java.util.Collections;
@Component
@RequiredArgsConstructor
public class JWTAuthenticationFilter extends OncePerRequestFilter {
private final JwtUtil jwtUtil;
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain)
throws ServletException, IOException {
String authHeader = request.getHeader("Authorization");
if (authHeader != null && authHeader.startsWith("Bearer ")) {
String token = authHeader.substring(7);
try {
if (!jwtUtil.isTokenExpired(token)) {
System.out.println(token);
String username = jwtUtil.getUAccount(token);
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
UsernamePasswordAuthenticationToken authenticationToken =
new UsernamePasswordAuthenticationToken(username, null, Collections.emptyList());
authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authenticationToken);
}
}
} catch (JwtUtil.TokenExpiredException e) {
// Token 过期,返回 401
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.getWriter().write("Token 已过期,请重新登录");
return;
} catch (JwtUtil.InvalidTokenException e) {
// Token 非法,返回 401
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.getWriter().write("无效的 Token请重新登录");
return;
} catch (Exception e) {
// 其他异常
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
response.getWriter().write("服务器内部错误");
return;
}
}
filterChain.doFilter(request, response);
}
}

View File

@@ -0,0 +1,13 @@
package xin.merlin.myblog_server.service;
import com.baomidou.mybatisplus.extension.service.IService;
import xin.merlin.myblog_server.entity.Article;
public interface ArticleService extends IService<Article> {
void publishArticle(Article article);
void updateArticle(Article article);
void deleteArticle(Article article);
}

View File

@@ -0,0 +1,7 @@
package xin.merlin.myblog_server.service;
import com.baomidou.mybatisplus.extension.service.IService;
import xin.merlin.myblog_server.entity.Comment;
public interface CommentService extends IService<Comment> {
}

View File

@@ -0,0 +1,8 @@
package xin.merlin.myblog_server.service;
import com.baomidou.mybatisplus.extension.service.IService;
import xin.merlin.myblog_server.entity.News;
public interface NewsService extends IService<News> {
}

View File

@@ -0,0 +1,8 @@
package xin.merlin.myblog_server.service;
import com.baomidou.mybatisplus.extension.service.IService;
import xin.merlin.myblog_server.entity.Project;
public interface ProjectService extends IService<Project> {
public void deleteProject(Integer p_id);
}

View File

@@ -0,0 +1,45 @@
package xin.merlin.myblog_server.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import xin.merlin.myblog_server.entity.Account;
import xin.merlin.myblog_server.mapper.AccountMapper;
@Service
public class AccountServiceImpl extends ServiceImpl<AccountMapper,Account> {
@Autowired
private AccountMapper accountMapper;
public Account getAccountInfo(String u_account) {
QueryWrapper<Account> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("u_account", u_account);
return accountMapper.selectOne(queryWrapper);
}
public boolean isExist(String u_account) {
QueryWrapper<Account> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("u_account", u_account);
return accountMapper.selectCount(queryWrapper) > 0;
}
public boolean idIsExist(String u_id){
QueryWrapper<Account> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("u_id", u_id);
return accountMapper.selectCount(queryWrapper) > 0;
}
public void register(Account account) {
accountMapper.insert(account);
}
// public String getU_id(String u_account) {
// QueryWrapper<Account> queryWrapper = new QueryWrapper<>();
// queryWrapper.eq("u_account", u_account);
// Account account = accountMapper.selectOne(queryWrapper);
// return account.getU_account();
// }
}

View File

@@ -0,0 +1,55 @@
package xin.merlin.myblog_server.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import xin.merlin.myblog_server.entity.Article;
import xin.merlin.myblog_server.entity.Garbage;
import xin.merlin.myblog_server.entity.News;
import xin.merlin.myblog_server.mapper.ArticleMapper;
import xin.merlin.myblog_server.mapper.GarbageMapper;
import xin.merlin.myblog_server.mapper.NewsMapper;
import xin.merlin.myblog_server.service.ArticleService;
import xin.merlin.myblog_server.utils.GarbageBaler;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements ArticleService {
@Autowired
private ArticleMapper articleMapper;
@Autowired
private NewsMapper newsMapper;
@Autowired
private GarbageMapper garbageMapper;
public void publishArticle(Article article) {
article.setCreated(LocalDateTime.now().truncatedTo(ChronoUnit.SECONDS));
article.setUpdated(LocalDateTime.now().truncatedTo(ChronoUnit.SECONDS));
articleMapper.insert(article);
}
public void updateArticle(Article article) {
article.setUpdated(LocalDateTime.now().truncatedTo(ChronoUnit.SECONDS));
articleMapper.updateById(article);
}
public void deleteArticle(Article article) {
Article article1 = articleMapper.selectById(article.getA_id());
article1.setUpdated(LocalDateTime.now().truncatedTo(ChronoUnit.SECONDS));
News news1 = newsMapper.selectById(article.getA_id());
garbageMapper.insert(new Garbage("article", GarbageBaler.concatenateFields(article1)));
garbageMapper.insert(new Garbage("news", GarbageBaler.concatenateFields(news1)));
newsMapper.deleteById(article.getA_id());
articleMapper.deleteById(article.getA_id());
}
}

View File

@@ -0,0 +1,27 @@
package xin.merlin.myblog_server.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import xin.merlin.myblog_server.entity.Comment;
import xin.merlin.myblog_server.entity.Garbage;
import xin.merlin.myblog_server.mapper.CommentMapper;
import xin.merlin.myblog_server.mapper.GarbageMapper;
import xin.merlin.myblog_server.service.CommentService;
import xin.merlin.myblog_server.utils.GarbageBaler;
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {
@Autowired
private CommentMapper commentMapper;
@Autowired
private GarbageMapper garbageMapper;
public void deleteComment(Comment comment) {
garbageMapper.insert(new Garbage("comment", GarbageBaler.concatenateFields(comment)));
commentMapper.deleteById(comment.getA_id());
}
}

View File

@@ -0,0 +1,30 @@
package xin.merlin.myblog_server.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
@Service
public class MailService {
@Autowired
private JavaMailSender mailSender;
@Value("${spring.mail.username}")
private String sender;
public String sendMail(String receiver){
String code = Double.toString(Math.random()).substring(2,8);
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(sender);
message.setTo(receiver);
message.setSubject("Merlin`s Blog Server");
message.setText("欢迎注册Blog\n"+"您的验证码为:"+code+"\n有效期5分钟\n验证码请勿泄露");
mailSender.send(message);
return code;
}
}

View File

@@ -0,0 +1,28 @@
package xin.merlin.myblog_server.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import xin.merlin.myblog_server.entity.Garbage;
import xin.merlin.myblog_server.entity.News;
import xin.merlin.myblog_server.mapper.GarbageMapper;
import xin.merlin.myblog_server.mapper.NewsMapper;
import xin.merlin.myblog_server.service.NewsService;
import xin.merlin.myblog_server.utils.GarbageBaler;
@Service
public class NewsServiceImpl extends ServiceImpl<NewsMapper, News> implements NewsService {
@Autowired
private NewsMapper newsMapper;
@Autowired
private GarbageMapper garbageMapper;
public void deleteNews(News news){
garbageMapper.insert(new Garbage("news", GarbageBaler.concatenateFields(news)));
newsMapper.deleteById(news.getA_id());
}
}

View File

@@ -0,0 +1,28 @@
package xin.merlin.myblog_server.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import xin.merlin.myblog_server.entity.Garbage;
import xin.merlin.myblog_server.entity.Project;
import xin.merlin.myblog_server.mapper.GarbageMapper;
import xin.merlin.myblog_server.mapper.ProjectMapper;
import xin.merlin.myblog_server.service.ProjectService;
import xin.merlin.myblog_server.utils.GarbageBaler;
@Service
public class ProjectServiceImpl extends ServiceImpl<ProjectMapper, Project> implements ProjectService {
@Autowired
private ProjectMapper projectMapper;
@Autowired
private GarbageMapper garbageMapper;
public void deleteProject(Integer p_id) {
Project project = projectMapper.selectById(p_id);
garbageMapper.insert(new Garbage("project", GarbageBaler.concatenateFields(project)));
projectMapper.deleteById(p_id);
}
}

View File

@@ -0,0 +1,19 @@
package xin.merlin.myblog_server.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import xin.merlin.myblog_server.entity.User;
import xin.merlin.myblog_server.mapper.AccountMapper;
import xin.merlin.myblog_server.mapper.UserMapper;
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> {
@Autowired
private AccountMapper accountMapper;
}

View File

@@ -0,0 +1,33 @@
package xin.merlin.myblog_server.utils;
import java.lang.reflect.Field;
public class GarbageBaler {
// 方法:将实体类的所有字段值拼接成一个字符串
public static String concatenateFields(Object entity) {
if (entity == null) {
return "";
}
StringBuilder sb = new StringBuilder();
Class<?> clazz = entity.getClass();
// 遍历所有字段
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true); // 设置私有字段可访问
try {
Object value = field.get(entity); // 获取字段值
if (value != null) {
sb.append(value.toString()).append(" "); // 拼接字段值
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return sb.toString().trim(); // 去掉尾部多余的空格
}
}

View File

@@ -0,0 +1,108 @@
package xin.merlin.myblog_server.utils;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import xin.merlin.myblog_server.config.JwtProperties;
import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.UUID;
@Component
@RequiredArgsConstructor
public class JwtUtil {
private final JwtProperties jwtProperties;
private SecretKey key;
private JwtParser jwtParser;
@PostConstruct
public void init() {
try {
// 从配置文件密钥生成 SecretKey
this.key = Keys.hmacShaKeyFor(jwtProperties.getSecret().getBytes(StandardCharsets.UTF_8));
this.jwtParser = Jwts.parser()
.verifyWith(key)
.build();
} catch (Exception e) {
throw new RuntimeException("JWT 密钥初始化失败,请检查配置文件 jwt.secret", e);
}
}
/**
* 生成 JWT Token
*/
public String generateToken(String uAccount, String uId) {
Date now = new Date();
Date expireDate = new Date(now.getTime() + jwtProperties.getExpire() * 1000L);
return Jwts.builder()
.subject(uAccount)
.claim("u_id", uId)
.id(UUID.randomUUID().toString())
.issuedAt(now)
.expiration(expireDate)
.issuer(jwtProperties.getIssuer())
.signWith(key, Jwts.SIG.HS256) // JJWT 0.12.6推荐的写法
.compact();
}
/**
* 解析 Token 获取 Claims
*/
public Claims getClaims(String token) {
try {
Jws<Claims> jws = jwtParser.parseSignedClaims(token);
System.out.println(jws.getPayload());
return jws.getPayload();
} catch (ExpiredJwtException e) {
throw new TokenExpiredException("Token 已过期", e);
} catch (JwtException e) {
throw new InvalidTokenException("无效的 Token", e);
} catch (Exception e) {
throw new InvalidTokenException("解析 Token 失败", e);
}
}
/**
* 判断 Token 是否过期
*/
public boolean isTokenExpired(String token) {
Claims claims = getClaims(token);
return claims.getExpiration().before(new Date());
}
/**
* 获取账号
*/
public String getUAccount(String token) {
Claims claims = getClaims(token);
return claims.getSubject();
}
/**
* 获取用户ID
*/
public String getUId(String token) {
Claims claims = getClaims(token);
return claims.get("u_id", String.class);
}
// 自定义异常类
public static class TokenExpiredException extends RuntimeException {
public TokenExpiredException(String message, Throwable cause) {
super(message, cause);
}
}
public static class InvalidTokenException extends RuntimeException {
public InvalidTokenException(String message, Throwable cause) {
super(message, cause);
}
}
}

View File

@@ -0,0 +1,20 @@
package xin.merlin.myblog_server.utils;
import java.util.Random;
public class RandomCode {
private static final Random rand = new Random();
public static String generateID(){
// 生成一个0到999999999的随机数然后格式化为9位数字字符串
return String.format("%09d", rand.nextInt(1000000000));
}
public static String generateCode(){
// 生成一个0到999999的随机数然后格式化为6位数字字符串
return String.format("%06d", rand.nextInt(1000000));
}
}

View File

@@ -0,0 +1,35 @@
package xin.merlin.myblog_server.utils;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import xin.merlin.myblog_server.utils.enums.ResultCode;
import java.time.LocalDateTime;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class RequestBack<T> {
private int code;
private String message;
private T data;
// 请求成功
public static <T> RequestBack<T> success(ResultCode code ,T data){
System.out.println( LocalDateTime.now()+" success : \n"+code);
return new RequestBack<T>(code.getCode(), code.getMessage(), data);
}
public static <T> RequestBack<T> success(ResultCode code){
System.out.println( LocalDateTime.now()+" success : \n"+code);
return new RequestBack<T>(code.getCode(), code.getMessage(),null);
}
// 请求失败
public static <T> RequestBack<T> fail(ResultCode code){
System.out.println( LocalDateTime.now()+" fail : \n"+code);
return new RequestBack<T>(code.getCode(),code.getMessage(), null);
}
}

View File

@@ -0,0 +1,54 @@
package xin.merlin.myblog_server.utils;
import org.springframework.stereotype.Component;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
@Component
public class SHA256Util {
/**
* 对输入字符串进行SHA-256加密
* @param input 输入字符串
* @return 加密后的十六进制字符串
*/
public String encryptSHA256(String input) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] encodedhash = digest.digest(input.getBytes());
return bytesToHex(encodedhash);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("SHA-256 algorithm not found", e);
}
}
/**
* 将字节数组转换为十六进制字符串
* @param hash 字节数组
* @return 十六进制字符串
*/
private String bytesToHex(byte[] hash) {
StringBuilder hexString = new StringBuilder(2 * hash.length);
for (int i = 0; i < hash.length; i++) {
String hex = Integer.toHexString(0xff & hash[i]);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
}
/**
* 使用用户ID生成盐值并对密码进行加密
* @param password 用户输入的密码
* @param userId 用户ID
* @return 加密后的密码哈希值
*/
public String encryptPassword(String password, String userId) {
// 先对用户ID进行SHA-256加密得到盐值
String salt = encryptSHA256(userId);
// 将盐值与密码拼接后进行SHA-256加密
return encryptSHA256(salt +salt + password + salt);
}
}

View File

@@ -0,0 +1,14 @@
package xin.merlin.myblog_server.utils;
import java.util.Base64;
import javax.crypto.SecretKey;
import io.jsonwebtoken.security.Keys;
public class SecretKeyGenerator {
public static void main(String[] args) {
SecretKey key = Keys.secretKeyFor(io.jsonwebtoken.SignatureAlgorithm.HS256);
String base64Key = Base64.getEncoder().encodeToString(key.getEncoded());
System.out.println("Your secure Base64 key:");
System.out.println(base64Key);
}
}

View File

@@ -0,0 +1,37 @@
package xin.merlin.myblog_server.utils.enums;
import lombok.Getter;
/**
* 通用状态码枚举类
*/
@Getter
public enum ResultCode {
SUCCESS(200, "成功"),
BAD_REQUEST(400, "请求参数错误"),
UNAUTHORIZED(401, "未认证或登录已过期"),
FORBIDDEN(403, "无权限访问"),
NOT_FOUND(404, "资源不存在"),
SERVER_ERROR(500, "服务器内部错误"),
// 自定义业务错误码
USER_BANNED(1000,"用户被封禁"),
USER_NOT_FOUND(1001, "用户不存在"),
USER_EXIST(1003,"用户已存在"),
USER_PASSWORD_ERROR(1004,"用户密码错误"),
USER_VERIFICATION_ERROR(1005,"验证码不存在或错误"),
USER_SEND_TOO_FAST(1006,"用户请求过快"),
USER_SEND_TOO_OFTEN(1007,"请求次数过多,已被限制"),
ORDER_NOT_FOUND(2000, "订单不存在");
private final int code;
private final String message;
ResultCode(int code, String message) {
this.code = code;
this.message = message;
}
}

View File

@@ -0,0 +1,68 @@
server:
# port: 8080
port: 8443
ssl:
key-store: classpath:merlin.xin.pfx
key-store-password: 7p7vcfmu
key-store-type: PKCS12
address: 0.0.0.0
jwt:
secret: CkmEXxVBNBsMUo4VNhDcH0YBhA1O4zSkQgSM243YzDY=
issuer: blogAdmin
subject: Interesting
expire: 604800
file:
# image-dir: C:/uploads/images #图片储存目录
# avatar-dir: C:/uploads/avatars # 头像存储目录Windows 环境)
avatar-dir: /home/blog/uploads/avatars # 头像储存目录Linux 环境)
image-dir: /home/blog/uploads/image
spring:
servlet:
multipart:
max-file-size: 50MB
datasource:
url: jdbc:mysql://8.138.214.149:3306/blog
# username: root
# password: 3604162
username: root
password: server2025_xyf_Merlin
driver-class-name: com.mysql.cj.jdbc.Driver
mail:
protocol: smtps
port: 465
default-encoding: utf-8
host: smtp.163.com
username: addsss2580@163.com
password: WDXrkqCJyRTtM7WN
properties:
mail:
smtp:
auth: true
ssl:
enable: false
required: false
protocols: TLSv1.2
connectiontimeout: 10000
timeout: 15000
writetimeout: 10000
debug: true
mybatis-plus:
global-config:
db-config:
table-prefix: "" # 可选:表前缀(没有可以留空)
id-type: auto # 主键策略
configuration:
map-underscore-to-camel-case: false # 禁用驼峰命名自动映射
# log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 控制台打印 SQL调试用
logging:
level:
org:
springframework:
security: DEBUG

Binary file not shown.

View File

@@ -0,0 +1,13 @@
package xin.merlin.myblog_server;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class MyblogServerApplicationTests {
@Test
void contextLoads() {
}
}