Compare commits

..

46 Commits
v1 ... v1.2

Author SHA1 Message Date
禾几海
59b7be00eb 添加密码修改的api 2020-05-19 19:53:38 +08:00
禾几海
2f6a9679da 修复跨域情况下前台获取不到Authorization响应字段 2020-05-18 08:30:50 +08:00
小海
5b8700930b 修改测试的接口地址 2020-04-23 17:57:05 +08:00
小海
18477706d1 添加github对应的url 2020-04-23 17:30:57 +08:00
小海
cd7e6b6378 修改接口名和响应内容 2020-04-23 16:34:04 +08:00
小海
d934fbe284 提取网络请求部分 2020-04-23 16:12:03 +08:00
小海
55589c6a59 修复响应码错误bug 2020-04-22 15:23:19 +08:00
小海
4ab402ccf8 更新readme 2020-04-17 13:27:21 +08:00
小海
c74aea6c3b 移除gitlab ci 2020-04-17 13:27:06 +08:00
小海
7c2b8d8d28 更新配置文件 2020-04-17 13:01:42 +08:00
小海
6798cae1b8 忘记添加环境变量 2020-04-17 12:41:19 +08:00
小海
ba7a02c5c0 Update mavenpublish.yml 2020-04-17 12:37:35 +08:00
小海
bd50cfc339 Update mavenpublish.yml 2020-04-17 12:13:51 +08:00
小海
e282e16fd3 update mavenpublish.yml 2020-04-17 11:56:43 +08:00
小海
18366b7aa4 Merge branch 'master' of https://github.com/xiaohai2271/blog-backEnd 2020-04-17 11:43:27 +08:00
小海
66dffbfefe 配置ci调整配置文件 2020-04-17 11:29:52 +08:00
小海
a7cd83a6b5 Update mavenpublish.yml 2020-04-17 11:11:12 +08:00
小海
0a5921b66d add github ci 2020-04-17 11:09:48 +08:00
小海
e04238f0c9 更新token 2020-04-16 23:26:41 +08:00
小海
09cb012b14 可能出现为空的情况 2020-04-16 23:25:49 +08:00
小海
922b83e169 修复小bug 2020-04-06 19:47:32 +08:00
小海
1cd6e0d7c9 修改部分api以及响应数据结构 2020-04-06 15:26:41 +08:00
小海
ec0b17151c 新增必应每日一图图片获取接口 2020-04-03 17:22:10 +08:00
小海
98430a34f6 修复一个小Bug 2020-03-29 14:17:29 +08:00
小海
23ee331609 修改响应码 2020-03-29 14:16:46 +08:00
小海
ebddbc0ecf 修改响应的Tag的articles字段类型 2020-03-29 14:16:17 +08:00
小海
8181fab48d 修改响应的Category的articles字段类型 2020-03-29 13:55:59 +08:00
小海
7ba287d261 更新Tag 2019-12-04 16:30:51 +08:00
小海
1745a5d821 Fix NullPointer Exception 2019-12-04 15:54:45 +08:00
小海
9a4a930426 用户访问情况记录 2019-12-04 15:28:01 +08:00
小海
a0eaddafec . 2019-12-04 15:25:50 +08:00
小海
450f308f1e 自动注入HttpServletRequest 2019-12-04 14:43:10 +08:00
小海
86bb5e1b13 . 2019-12-04 14:38:49 +08:00
小海
a4c2ec1272 修改JwtUtil的部分方法 2019-12-04 14:08:45 +08:00
小海
2945d091ee Update README.md 2019-12-04 12:08:03 +08:00
小海
900d84b15e Add Test coverage 2019-12-04 11:35:42 +08:00
小海
d9aac0fbd8 自动部署 2019-12-01 13:28:19 +08:00
小海
28aa7cf7e3 Add maven wrapper 2019-12-01 12:42:01 +08:00
小海
7972f4d473 . 2019-11-30 23:08:30 +08:00
小海
79ec6fcc91 Add CI status 2019-11-30 22:56:56 +08:00
小海
1f736dc9c9 修改获取测试资源的方式 2019-11-29 23:58:55 +08:00
小海
55ccff3451 关闭两个不稳定的测试 2019-11-29 23:26:53 +08:00
小海
a5811364c7 添加CI测试 2019-11-29 23:22:20 +08:00
小海
a77dc695f6 修复可能存在的异常 2019-11-29 23:21:32 +08:00
小海
753ea5c9a1 将私钥都分离放到配置文件中 2019-11-29 21:29:48 +08:00
小海
19e0697a01 . 2019-11-29 21:29:07 +08:00
59 changed files with 1423 additions and 956 deletions

47
.github/workflows/mavenpublish.yml vendored Normal file
View File

@@ -0,0 +1,47 @@
# This workflow will build a package using Maven and then publish it to GitHub packages when a release is created
# For more information see: https://github.com/actions/setup-java#apache-maven-with-a-settings-path
name: Blog backEnd CI
on:
push:
branches:
- master
jobs:
build:
runs-on: ubuntu-latest
env:
APPLICATION_PROPERTIES_TEST: ${{ secrets.APPLICATION_PROPERTIES_TEST }}
APPLICATION_PROPERTIES_PROD: ${{ secrets.APPLICATION_PROPERTIES_PROD }}
steps:
- uses: actions/checkout@v2
- name: Set up JDK 1.8
uses: actions/setup-java@v1
with:
java-version: 1.8
- name: Build jar file
run: echo $APPLICATION_PROPERTIES_TEST|base64 -d > src/main/resources/application-test.properties && echo $APPLICATION_PROPERTIES_PROD|base64 -d> src/main/resources/application-prod.properties && mvn -B package --file pom.xml
- name: SCP
uses: appleboy/scp-action@master
with:
host: ${{ secrets.SSH_HOST }}
username: ${{ secrets.SSH_USERNAME }}
password: ${{ secrets.SSH_PASSWORD }}
port: ${{ secrets.SSH_PORT }}
source: "target/blog-0.0.1-SNAPSHOT.jar"
target: "/www/wwwroot/api.celess.cn"
- name: Run SSH command
uses: garygrossgarten/github-action-ssh@v0.5.0
with:
command: cd /www/wwwroot/api.celess.cn && bash build.sh
host: ${{ secrets.SSH_HOST }}
username: ${{ secrets.SSH_USERNAME }}
password: ${{ secrets.SSH_PASSWORD }}
port: ${{ secrets.SSH_PORT }}

3
.gitignore vendored
View File

@@ -4,5 +4,6 @@ target/
# 本地项目的私有文件
back-end/blog-dev.sql
src/main/resources/application-prod.properties
src/main/resources/application-dev.properties
src/main/resources/application-prod.properties
src/main/resources/application-test.properties

View File

@@ -1,38 +1,32 @@
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
* Copyright 2012-2019 the original author or 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.
*/
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.net.*;
import java.io.*;
import java.nio.channels.*;
import java.util.Properties;
public class MavenWrapperDownloader {
private static final String WRAPPER_VERSION = "0.5.5";
/**
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
*/
private static final String DEFAULT_DOWNLOAD_URL =
"https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar";
private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/"
+ WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar";
/**
* Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
@@ -80,13 +74,13 @@ public class MavenWrapperDownloader {
}
}
}
System.out.println("- Downloading from: : " + url);
System.out.println("- Downloading from: " + url);
File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
if (!outputFile.getParentFile().exists()) {
if (!outputFile.getParentFile().mkdirs()) {
System.out.println(
"- ERROR creating output direcrory '" + outputFile.getParentFile().getAbsolutePath() + "'");
"- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'");
}
}
System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
@@ -102,6 +96,16 @@ public class MavenWrapperDownloader {
}
private static void downloadFileFromURL(String urlString, File destination) throws Exception {
if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) {
String username = System.getenv("MVNW_USERNAME");
char[] password = System.getenv("MVNW_PASSWORD").toCharArray();
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
}
URL website = new URL(urlString);
ReadableByteChannel rbc;
rbc = Channels.newChannel(website.openStream());

Binary file not shown.

View File

@@ -1 +1,2 @@
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.0/apache-maven-3.6.0-bin.zip
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.2/apache-maven-3.6.2-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.5/maven-wrapper-0.5.5.jar

View File

@@ -1,7 +1,5 @@
# 小海博客后端管理系统
![Build Staus](https://github.com/xiaohai2271/blog-backEnd/workflows/Blog%20backEnd%20CI/badge.svg?branch=master&event=push) ![coverage report](https://gitlab.com/xiaohai2271/blog-backEnd/badges/master/coverage.svg) ![GitHub](https://img.shields.io/github/license/xiaohai2271/blog-backEnd) [![Website](https://img.shields.io/website?up_message=%E5%B0%8F%E6%B5%B7%E5%8D%9A%E5%AE%A2&url=https%3A%2F%2Fwww.celess.cn)](https://www.celess.cn)
## 基于Springboot的后端博客管理系统

8
build.sh Normal file
View File

@@ -0,0 +1,8 @@
#!/bin/sh
echo "查询已存在进程"
pgrep -af blog-0.0.1-SNAPSHOT.jar
echo "结束已存在进程"
pkill -f blog-0.0.1-SNAPSHOT.jar
echo "开始运行小海博客"
nohup java -jar -Dfile.encoding=UTF-8 blog-0.0.1-SNAPSHOT.jar >blog.log &
echo "更新结束"

116
mvnw vendored
View File

@@ -47,18 +47,19 @@ if [ -z "$MAVEN_SKIP_RC" ] ; then
fi
# OS specific support. $var _must_ be set to either true or false.
cygwin=false;
darwin=false;
cygwin=false
darwin=false
mingw=false
case "`uname`" in
case "$(uname)" in
CYGWIN*) cygwin=true ;;
MINGW*) mingw=true ;;
Darwin*) darwin=true
Darwin*)
darwin=true
# Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
# See https://developer.apple.com/library/mac/qa/qa1170/_index.html
if [ -z "$JAVA_HOME" ]; then
if [ -x "/usr/libexec/java_home" ]; then
export JAVA_HOME="`/usr/libexec/java_home`"
export JAVA_HOME="$(/usr/libexec/java_home)"
else
export JAVA_HOME="/Library/Java/Home"
fi
@@ -68,7 +69,7 @@ esac
if [ -z "$JAVA_HOME" ]; then
if [ -r /etc/gentoo-release ]; then
JAVA_HOME=`java-config --jre-home`
JAVA_HOME=$(java-config --jre-home)
fi
fi
@@ -78,21 +79,21 @@ if [ -z "$M2_HOME" ] ; then
# need this for relative symlinks
while [ -h "$PRG" ]; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
ls=$(ls -ld "$PRG")
link=$(expr "$ls" : '.*-> \(.*\)$')
if expr "$link" : '/.*' >/dev/null; then
PRG="$link"
else
PRG="`dirname "$PRG"`/$link"
PRG="$(dirname "$PRG")/$link"
fi
done
saveddir=`pwd`
saveddir=$(pwd)
M2_HOME=`dirname "$PRG"`/..
M2_HOME=$(dirname "$PRG")/..
# make it fully qualified
M2_HOME=`cd "$M2_HOME" && pwd`
M2_HOME=$(cd "$M2_HOME" && pwd)
cd "$saveddir"
# echo Using m2 at $M2_HOME
@@ -101,36 +102,41 @@ fi
# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --unix "$M2_HOME"`
M2_HOME=$(cygpath --unix "$M2_HOME")
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
JAVA_HOME=$(cygpath --unix "$JAVA_HOME")
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
CLASSPATH=$(cygpath --path --unix "$CLASSPATH")
fi
# For Mingw, ensure paths are in UNIX format before anything is touched
if $mingw; then
[ -n "$M2_HOME" ] &&
M2_HOME="`(cd "$M2_HOME"; pwd)`"
M2_HOME="$( (
cd "$M2_HOME"
pwd
))"
[ -n "$JAVA_HOME" ] &&
JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
# TODO classpath?
JAVA_HOME="$( (
cd "$JAVA_HOME"
pwd
))"
fi
if [ -z "$JAVA_HOME" ]; then
javaExecutable="`which javac`"
if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
javaExecutable="$(which javac)"
if [ -n "$javaExecutable" ] && ! [ "$(expr \"$javaExecutable\" : '\([^ ]*\)')" = "no" ]; then
# readlink(1) is not available as standard on Solaris 10.
readLink=`which readlink`
if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
readLink=$(which readlink)
if [ ! $(expr "$readLink" : '\([^ ]*\)') = "no" ]; then
if $darwin; then
javaHome="`dirname \"$javaExecutable\"`"
javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
javaHome="$(dirname \"$javaExecutable\")"
javaExecutable="$(cd \"$javaHome\" && pwd -P)/javac"
else
javaExecutable="`readlink -f \"$javaExecutable\"`"
javaExecutable="$(readlink -f \"$javaExecutable\")"
fi
javaHome="`dirname \"$javaExecutable\"`"
javaHome=`expr "$javaHome" : '\(.*\)/bin'`
javaHome="$(dirname \"$javaExecutable\")"
javaHome=$(expr "$javaHome" : '\(.*\)/bin')
JAVA_HOME="$javaHome"
export JAVA_HOME
fi
@@ -146,7 +152,7 @@ if [ -z "$JAVACMD" ] ; then
JAVACMD="$JAVA_HOME/bin/java"
fi
else
JAVACMD="`which java`"
JAVACMD="$(which java)"
fi
fi
@@ -166,8 +172,7 @@ CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
# first directory with .mvn subdirectory is considered project base directory
find_maven_basedir() {
if [ -z "$1" ]
then
if [ -z "$1" ]; then
echo "Path not specified to find_maven_basedir"
return 1
fi
@@ -181,7 +186,10 @@ find_maven_basedir() {
fi
# workaround for JBEAP-8937 (on Solaris 10/Sparc)
if [ -d "${wdir}" ]; then
wdir=`cd "$wdir/.."; pwd`
wdir=$(
cd "$wdir/.."
pwd
)
fi
# end of workaround
done
@@ -195,9 +203,9 @@ concat_lines() {
fi
}
BASE_DIR=`find_maven_basedir "$(pwd)"`
BASE_DIR=$(find_maven_basedir "$(pwd)")
if [ -z "$BASE_DIR" ]; then
exit 1;
exit 1
fi
##########################################################################################
@@ -212,31 +220,54 @@ else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
fi
jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar"
if [ -n "$MVNW_REPOURL" ]; then
jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.5/maven-wrapper-0.5.5.jar"
else
jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.5/maven-wrapper-0.5.5.jar"
fi
while IFS="=" read key value; do
case "$key" in (wrapperUrl) jarUrl="$value"; break ;;
case "$key" in wrapperUrl)
jarUrl="$value"
break
;;
esac
done <"$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
if [ "$MVNW_VERBOSE" = true ]; then
echo "Downloading from: $jarUrl"
fi
wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
if $cygwin; then
wrapperJarPath=$(cygpath --path --windows "$wrapperJarPath")
fi
if command -v wget >/dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found wget ... using wget"
fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
wget "$jarUrl" -O "$wrapperJarPath"
else
wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath"
fi
elif command -v curl >/dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found curl ... using curl"
fi
curl -o "$wrapperJarPath" "$jarUrl"
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
curl -o "$wrapperJarPath" "$jarUrl" -f
else
curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Falling back to using Java to download"
fi
javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
# For Cygwin, switch paths to Windows format before running javac
if $cygwin; then
javaClass=$(cygpath --path --windows "$javaClass")
fi
if [ -e "$javaClass" ]; then
if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
@@ -268,15 +299,20 @@ MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
# For Cygwin, switch paths to Windows format before running java
if $cygwin; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --path --windows "$M2_HOME"`
M2_HOME=$(cygpath --path --windows "$M2_HOME")
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
JAVA_HOME=$(cygpath --path --windows "$JAVA_HOME")
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
CLASSPATH=$(cygpath --path --windows "$CLASSPATH")
[ -n "$MAVEN_PROJECTBASEDIR" ] &&
MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
MAVEN_PROJECTBASEDIR=$(cygpath --path --windows "$MAVEN_PROJECTBASEDIR")
fi
# Provide a "standardized" way to retrieve the CLI args that will
# work with both Windows and non-Windows executions.
MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@"
export MAVEN_CMD_LINE_ARGS
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
exec "$JAVACMD" \

29
mvnw.cmd vendored
View File

@@ -37,7 +37,7 @@
@echo off
@REM set title of command window
title %0
@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on'
@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
@@ -120,23 +120,44 @@ SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar"
FOR /F "tokens=1,2 delims==" %%A IN (%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties) DO (
set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.5/maven-wrapper-0.5.5.jar"
FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
)
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
if exist %WRAPPER_JAR% (
if "%MVNW_VERBOSE%" == "true" (
echo Found %WRAPPER_JAR%
)
) else (
if not "%MVNW_REPOURL%" == "" (
SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.5/maven-wrapper-0.5.5.jar"
)
if "%MVNW_VERBOSE%" == "true" (
echo Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %DOWNLOAD_URL%
powershell -Command "(New-Object Net.WebClient).DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"
)
powershell -Command "&{"^
"$webclient = new-object System.Net.WebClient;"^
"if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
"$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
"}"^
"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^
"}"
if "%MVNW_VERBOSE%" == "true" (
echo Finished downloading %WRAPPER_JAR%
)
)
@REM End of extension
@REM Provide a "standardized" way to retrieve the CLI args that will
@REM work with both Windows and non-Windows executions.
set MAVEN_CMD_LINE_ARGS=%*
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
if ERRORLEVEL 1 goto error
goto end

20
pom.xml
View File

@@ -156,6 +156,26 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.7.9</version>
<executions>
<execution>
<id>pre-unit-test</id>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>post-unit-test</id>
<phase>test</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>

View File

@@ -1,5 +1,6 @@
package cn.celess.blog.configuration;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
@@ -13,6 +14,9 @@ import org.springframework.web.filter.CorsFilter;
*/
@Configuration
public class CorsConfig {
@Value("${spring.profiles.active}")
private String activeModel;
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
@@ -22,14 +26,17 @@ public class CorsConfig {
config.addAllowedOrigin("https://celess.cn");
config.addAllowedOrigin("https://www.celess.cn");
// 本地调试时的跨域
if ("dev".equals(activeModel)) {
config.addAllowedOrigin("http://localhost:4200");
config.addAllowedOrigin("http://127.0.0.1:4200");
}
config.addAllowedHeader("*");
config.addAllowedMethod("OPTIONS");
config.addAllowedMethod("GET");
config.addAllowedMethod("POST");
config.addAllowedMethod("PUT");
config.addAllowedMethod("DELETE");
config.addExposedHeader("Authorization");
config.setAllowCredentials(true);
config.setMaxAge(10800L);
source.registerCorsConfiguration("/**", config);

View File

@@ -19,11 +19,9 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
public class InterceptorConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new MultipleSubmitFilter()).addPathPatterns("/*");
registry.addInterceptor(new MultipleSubmitFilter()).addPathPatterns("/**");
registry.addInterceptor(new VisitorRecord()).addPathPatterns("/**");
registry.addInterceptor(authenticationFilter()).addPathPatterns("/**");
// visitor 输出信息杂乱 暂时放弃使用
// registry.addInterceptor(new VisitorRecord()).addPathPatterns("/*");
}
@Bean
@@ -31,11 +29,11 @@ public class InterceptorConfig implements WebMvcConfigurer {
return new AuthenticationFilter();
}
// // session listener register bean
// @Bean
// public ServletListenerRegistrationBean<SessionListener> servletListenerRegistrationBean() {
// ServletListenerRegistrationBean<SessionListener> slrBean = new ServletListenerRegistrationBean<SessionListener>();
// slrBean.setListener(new SessionListener());
// return slrBean;
// }
@Bean
public ServletListenerRegistrationBean<SessionListener> servletListenerRegistrationBean() {
// session listener register bean
ServletListenerRegistrationBean<SessionListener> slrBean = new ServletListenerRegistrationBean<SessionListener>();
slrBean.setListener(new SessionListener());
return slrBean;
}
}

View File

@@ -10,6 +10,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@@ -41,12 +42,16 @@ public class AuthenticationFilter implements HandlerInterceptor {
path = path.replaceAll("/+", "/");
int indexOf = path.indexOf("/", 1);
String rootPath = indexOf == -1 ? path : path.substring(0, indexOf);
String jwtStr = request.getHeader("Authorization");
if (jwtStr != null && !jwtStr.isEmpty() && !jwtUtil.isTokenExpired(jwtStr)) {
// 已登录 记录当前email
request.getSession().setAttribute("email", jwtUtil.getUsernameFromToken(jwtStr));
}
// 不需要鉴权的路径
if (!USER_PREFIX.equals(rootPath.toLowerCase()) && !ADMIN_PREFIX.equals(rootPath.toLowerCase())) {
return true;
}
String jwtStr = request.getHeader("Authorization");
if (jwtStr == null || jwtStr.isEmpty()) {
return writeResponse(ResponseEnum.HAVE_NOT_LOG_IN, response, request);
}
@@ -59,6 +64,11 @@ public class AuthenticationFilter implements HandlerInterceptor {
return writeResponse(ResponseEnum.LOGIN_EXPIRED, response, request);
}
String role = userService.getUserRoleByEmail(email);
if (role.equals(ROLE_USER) || role.equals(ROLE_ADMIN)) {
// 更新token
String token = jwtUtil.updateTokenDate(jwtStr);
response.setHeader("Authorization",token);
}
if (role.equals(ROLE_ADMIN)) {
// admin
return true;

View File

@@ -21,7 +21,11 @@ public class VisitorRecord implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
HttpSession session = request.getSession();
HashMap<String, Integer> visitDetail = (HashMap<String, Integer>) session.getAttribute("visitDetail");
if (visitDetail == null) {
return true;
}
// 获取访问次数
Integer count = visitDetail.get(RequestUtil.getCompleteUrlAndMethod(request));
// 自增

View File

@@ -1,9 +1,7 @@
package cn.celess.blog.configuration.listener;
import cn.celess.blog.entity.User;
import cn.celess.blog.util.RedisUserUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import javax.servlet.annotation.WebListener;
@@ -17,20 +15,21 @@ import java.util.HashMap;
* @Date: 2019/10/18 15:33
* @Description: 监听session的情况
*/
@Log4j2
@WebListener
public class SessionListener implements HttpSessionListener {
@Autowired
RedisUserUtil redisUserUtil;
@Autowired
HttpServletRequest request;
private static final Logger logger = LoggerFactory.getLogger(SessionListener.class);
@Override
public void sessionCreated(HttpSessionEvent se) {
// TODO : can move 'visit' api to here
se.getSession().setAttribute("visitDetail", new HashMap<String, Integer>());
// se.getSession().setMaxInactiveInterval(10);// 10s for debug
logger.info("新增一个Session[{}]", se.getSession().getId());
// 10s for debug
// se.getSession().setMaxInactiveInterval(10);
// log.info("新增一个Session[{}]", se.getSession().getId());
}
@SuppressWarnings("unchecked")
@@ -39,12 +38,15 @@ public class SessionListener implements HttpSessionListener {
HashMap<String, Integer> visitDetail = (HashMap<String, Integer>) se.getSession().getAttribute("visitDetail");
StringBuilder sb = new StringBuilder();
sb.append("ip => ").append(se.getSession().getAttribute("ip"));
User user = redisUserUtil.get(request);
if (visitDetail.size() == 0) {
return;
}
sb.append("\t登录情况 => ");
sb.append(user == null ? "游客访问" : user.getEmail());
String email = (String) se.getSession().getAttribute("email");
sb.append(email == null ? "游客访问" : email);
visitDetail.forEach((s, integer) -> {
sb.append("\n").append("Method:[").append(s.split(":")[1]).append("]\tTimes:[").append(integer).append("]\tPath:[").append(s.split(":")[0]).append("]");
});
logger.info(sb.toString());
log.info(sb.toString());
}
}

View File

@@ -83,7 +83,7 @@ public class ArticleController {
ArticleModel article = articleService.retrieveOneByID(articleId, is4update);
if (article.getOpen()) {
return ResponseUtil.success(article);
} else if (article.getAuthorId().equals(redisUserUtil.get(request).getId())) {
} else if (article.getAuthorId().equals(redisUserUtil.get().getId())) {
return ResponseUtil.success(article);
}
return ResponseUtil.response(ResponseEnum.PERMISSION_ERROR, null);

View File

@@ -58,15 +58,11 @@ public class CommentController {
* 通过pid获取数据
*
* @param pid
* @param count
* @param page
* @return
*/
@GetMapping("/comment/pid/{pid}")
public Response retrievePage(@PathVariable("pid") long pid,
@RequestParam(value = "count", required = false, defaultValue = "10") int count,
@RequestParam(value = "page", required = false, defaultValue = "1") int page) {
return ResponseUtil.success(commentService.retrievePageByPid(pid, page, count));
public Response retrievePage(@PathVariable("pid") long pid) {
return ResponseUtil.success(commentService.retrievePageByPid(pid));
}
/**

View File

@@ -6,9 +6,11 @@ import cn.celess.blog.entity.model.QiniuResponse;
import cn.celess.blog.exception.MyException;
import cn.celess.blog.service.CountService;
import cn.celess.blog.service.QiniuService;
import cn.celess.blog.util.HttpUtil;
import cn.celess.blog.util.RedisUtil;
import cn.celess.blog.util.ResponseUtil;
import cn.celess.blog.util.VeriCodeUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -21,8 +23,10 @@ import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
@@ -70,7 +74,8 @@ public class Other {
Map<String, Object> map = new HashMap<>();
Enumeration<String> headerNames = request.getHeaderNames();
String str = null;
while ((str = headerNames.nextElement()) != null) {
while (headerNames.hasMoreElements()) {
str = headerNames.nextElement();
map.put(str, request.getHeader(str));
}
map.put("sessionID", request.getSession().getId());
@@ -158,7 +163,7 @@ public class Other {
if (".png".equals(mime.toLowerCase()) || ".jpg".equals(mime.toLowerCase()) ||
".jpeg".equals(mime.toLowerCase()) || ".bmp".equals(mime.toLowerCase())) {
QiniuResponse qiniuResponse = qiniuService.uploadFile(file.getInputStream(), "img_" + System.currentTimeMillis() + mime);
jsonObject.put("success", 0);
jsonObject.put("success", 1);
jsonObject.put("message", "上传成功");
jsonObject.put("url", "http://cdn.celess.cn/" + qiniuResponse.key);
response.getWriter().println(jsonObject.toString());
@@ -169,4 +174,18 @@ public class Other {
jsonObject.put("message", "上传失败,请上传图片文件");
response.getWriter().println(jsonObject.toString());
}
@GetMapping("/bingPic")
public Response bingPic() {
JSONObject imageObj;
try {
imageObj = JSONObject.fromObject(HttpUtil.get("https://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=zh-CN"));
} catch (IOException e) {
return ResponseUtil.failure(null);
}
JSONArray jsonArray = imageObj.getJSONArray("images");
String imageName = jsonArray.getJSONObject(0).getString("url");
return ResponseUtil.success("https://cn.bing.com" + imageName);
}
}

View File

@@ -2,6 +2,7 @@ package cn.celess.blog.controller;
import cn.celess.blog.entity.Response;
import cn.celess.blog.entity.Tag;
import cn.celess.blog.entity.model.TagModel;
import cn.celess.blog.service.TagService;
import cn.celess.blog.util.ResponseUtil;
import net.sf.json.JSONObject;
@@ -56,12 +57,11 @@ public class TagController {
@GetMapping("/tags/nac")
public Response getTagNameAndCount() {
List<JSONObject> nameAndCount = new ArrayList<>();
List<Tag> all = tagService.findAll();
for (Tag t : all) {
List<TagModel> all = tagService.findAll();
for (TagModel t : all) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", t.getName());
String articles = t.getArticles();
jsonObject.put("size", articles == null ? 0 : articles.split(",").length);
jsonObject.put("size", t.getArticles() == null ? 0 : t.getArticles().size());
nameAndCount.add(jsonObject);
}
return ResponseUtil.success(nameAndCount);

View File

@@ -93,6 +93,14 @@ public class UserController {
return ResponseUtil.success(userService.reSetPwd(verifyId, email, pwd));
}
@PostMapping("/user/setPwd")
public Response setPwd(@RequestParam("pwd") String pwd,
@RequestParam("newPwd") String newPwd,
@RequestParam("confirmPwd") String confirmPwd) {
return ResponseUtil.success(userService.setPwd(pwd,newPwd,confirmPwd));
}
@DeleteMapping("/admin/user/delete")
public Response multipleDelete(@RequestBody Integer[] ids) {
return ResponseUtil.success(userService.deleteUser(ids));

View File

@@ -39,7 +39,7 @@ public class WebUpdateInfoController {
public Response page(@RequestParam("page") int page, @RequestParam("count") int count) {
return ResponseUtil.success(webUpdateInfoService.pages(count, page));
}
@GetMapping("/lastestUpdateTime")
@GetMapping("/lastestUpdate")
public Response lastestUpdateTime() {
return ResponseUtil.success(webUpdateInfoService.getLastestUpdateTime());
}

View File

@@ -12,55 +12,62 @@ public enum ResponseEnum {
ERROR(-2, "错误"),
//文章类
ARTICLE_NOT_EXIST(201, "文章不存在"),
ARTICLE_HAS_EXIST(202, "文章已存在"),
ARTICLE_NOT_PUBLIC(203, "文章暂未公开"),
ARTICLE_NOT_BELONG_YOU(204, "无权限操作别人的文章"),
ARTICLE_NOT_EXIST(2010, "文章不存在"),
ARTICLE_HAS_EXIST(2020, "文章已存在"),
ARTICLE_NOT_PUBLIC(2030, "文章暂未公开"),
ARTICLE_NOT_BELONG_YOU(2040, "无权限操作别人的文章"),
//用户类
HAVE_NOT_LOG_IN(301, "还未登录"),
PERMISSION_ERROR(302, "没有此权限"),
USER_NOT_EXIST(303, "用户不存在"),
USERNAME_HAS_EXIST(304, "用户名已存在"),
USERNAME_TOO_SHORT(305, "用户名太短"),
PASSWORD_TOO_SHORT_OR_LONG(306, "密码长度过长或者过短"),
LOGIN_FAILURE(310, "登录失败,用户名/密码不正确"),
USEREMAIL_NULL(331, "未设置邮箱"),
USEREMAIL_NOT_VERIFY(332, "邮箱未验证"),
LOGIN_LATER(350, "错误次数已达5次请稍后再试"),
PWD_SAME(360, "新密码与原密码相同"),
LOGIN_EXPIRED(370, "登陆过期"),
HAVE_NOT_LOG_IN(3010, "还未登录"),
PERMISSION_ERROR(3020, "没有此权限"),
USER_NOT_EXIST(3030, "用户不存在"),
USERNAME_HAS_EXIST(3040, "用户名已存在"),
USERNAME_TOO_SHORT(3050, "用户名太短"),
PASSWORD_TOO_SHORT_OR_LONG(3060, "密码长度过长或者过短"),
LOGIN_FAILURE(3100, "登录失败,用户名/密码不正确"),
USEREMAIL_NULL(3310, "未设置邮箱"),
USEREMAIL_NOT_VERIFY(3320, "邮箱未验证"),
LOGIN_LATER(3500, "错误次数已达5次请稍后再试"),
PWD_SAME(3601, "新密码与原密码相同"),
PWD_NOT_SAME(3602, "新密码与原密码不相同"),
LOGIN_EXPIRED(3700, "登陆过期"),
PWD_WRONG(3800, "密码不正确"),
JWT_EXPIRED(3810, "Token过期"),
JWT_MALFORMED(3820, "Token格式不对"),
JWT_SIGNATURE(3830, "Token签名错误"),
JWT_NOT_SUPPORT(3840, "不支持的Token"),
//标签
TAG_NOT_EXIST(401, "标签不存在"),
TAG_HAS_EXIST(402, "标签已存在"),
TAG_NOT_EXIST(4010, "标签不存在"),
TAG_HAS_EXIST(4020, "标签已存在"),
//分类
CATEGORY_NOT_EXIST(501, "分类不存在"),
CATEGORY_HAS_EXIST(502, "分类已存在"),
CATEGORY_NOT_EXIST(5010, "分类不存在"),
CATEGORY_HAS_EXIST(5020, "分类已存在"),
//评论/留言
COMMENT_NOT_EXIST(601, "评论/留言不存在"),
COMMENT_HAS_EXIST(602, "评论/留言已存在,请不要重复提交"),
COMMENT_NOT_EXIST(6010, "评论/留言不存在"),
COMMENT_HAS_EXIST(6020, "评论/留言已存在,请不要重复提交"),
//webUdpateInfo amd PartnerSite
DATA_NOT_EXIST(701, "数据不存在"),
DATA_HAS_EXIST(702, "数据已存在"),
DATA_NOT_EXIST(7010, "数据不存在"),
DATA_HAS_EXIST(7020, "数据已存在"),
//其他
//提交更新之前,没有获取数据/,
DID_NOT_GET_THE_DATA(802, "非法访问"),
IMG_CODE_TIMEOUT(810, "验证码已失效"),
IMG_CODE_DIDNOTVERIFY(820, "请先验证验证码"),
VERIFY_ERROR(830, "验证失败"),
PARAMETERS_ERROR(850, "参数错误"),
PARAMETERS_URL_ERROR(851, "链接格式错误"),
PARAMETERS_EMAIL_ERROR(852, "邮箱格式错误"),
PARAMETERS_PHONE_ERROR(853, "手机格式错误"),
PARAMETERS_QQ_ERROR(854, "QQ格式错误"),
PARAMETERS_PWD_ERROR(855, "密码格式错误"),
VERIFY_OUT(840, "已经验证过了");
DID_NOT_GET_THE_DATA(8020, "非法访问"),
IMG_CODE_TIMEOUT(8100, "验证码已失效"),
IMG_CODE_DIDNOTVERIFY(8200, "请先验证验证码"),
VERIFY_ERROR(8300, "验证失败"),
PARAMETERS_ERROR(8500, "参数错误"),
PARAMETERS_URL_ERROR(8510, "链接格式错误"),
PARAMETERS_EMAIL_ERROR(8520, "邮箱格式错误"),
PARAMETERS_PHONE_ERROR(8530, "手机格式错误"),
PARAMETERS_QQ_ERROR(8540, "QQ格式错误"),
PARAMETERS_PWD_ERROR(8550, "密码格式错误"),
VERIFY_OUT(8400, "已经验证过了");
private int code;
private String msg;

View File

@@ -0,0 +1,43 @@
package cn.celess.blog.entity.model;
import cn.celess.blog.entity.Category;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* @Author: 小海
* @Date: 2020-03-29 12:18
* @Desc:
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class CategoryModel {
private Long id;
private String name;
private List<Integer> articles;
public CategoryModel(Category category) {
this.id = category.getId();
this.name = category.getName();
if (category.getArticles() == null || category.getArticles().length() == 0) {
articles = null;
} else {
articles = new ArrayList<>();
for (String s : category.getArticles().split(",")) {
if ("".equals(s)) {
return;
}
articles.add(Integer.parseInt(s));
}
}
}
}

View File

@@ -3,7 +3,7 @@ package cn.celess.blog.entity.model;
import lombok.Getter;
import lombok.Setter;
import java.util.Date;
import java.util.List;
/**
* @author : xiaohai
@@ -53,5 +53,7 @@ public class CommentModel {
*/
private long pid = -1;
private List<CommentModel> respComment;
}

View File

@@ -0,0 +1,41 @@
package cn.celess.blog.entity.model;
import cn.celess.blog.entity.Tag;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.ArrayList;
import java.util.List;
/**
* @Author: 小海
* @Date: 2020-03-29 13:56
* @Desc:
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class TagModel {
private Long id;
private String name;
private List<Integer> articles;
public TagModel(Tag tag) {
this.id = tag.getId();
this.name = tag.getName();
if (tag.getArticles() == null || tag.getArticles().length() == 0) {
articles = null;
} else {
articles = new ArrayList<>();
for (String s : tag.getArticles().split(",")) {
if ("".equals(s)) {
return;
}
articles.add(Integer.parseInt(s));
}
}
}
}

View File

@@ -27,5 +27,5 @@ public interface WebUpdateInfoMapper {
List<WebUpdate> findAll();
Date getLastestOne();
WebUpdate getLastestOne();
}

View File

@@ -1,6 +1,7 @@
package cn.celess.blog.service;
import cn.celess.blog.entity.Category;
import cn.celess.blog.entity.model.CategoryModel;
import org.springframework.stereotype.Service;
import java.util.List;
@@ -17,7 +18,7 @@ public interface CategoryService {
* @param name 分类名
* @return 所增加的分类数据
*/
Category create(String name);
CategoryModel create(String name);
/**
* 增加一个分类
@@ -25,7 +26,7 @@ public interface CategoryService {
* @param category 分类对象
* @return 所增加的分类数据
*/
Category create(Category category);
CategoryModel create(Category category);
/**
* 通过id删除分类
@@ -42,13 +43,13 @@ public interface CategoryService {
* @param name 分类名字
* @return 更新后的分类的数据
*/
Category update(Long id, String name);
CategoryModel update(Long id, String name);
/**
* 获取全部的分类数据
*
* @return 全部的分类数据
*/
List<Category> retrievePage();
List<CategoryModel> retrievePage();
}

View File

@@ -5,6 +5,8 @@ import cn.celess.blog.entity.request.CommentReq;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @author : xiaohai
* @date : 2019/03/29 16:58
@@ -49,11 +51,9 @@ public interface CommentService {
* 通过pid获取数据
*
* @param pid 父id
* @param count 单页数据量
* @param page 数据页
* @return 分页数据
*/
PageInfo<CommentModel> retrievePageByPid(long pid, int page, int count);
List<CommentModel> retrievePageByPid(long pid);
/**

View File

@@ -1,6 +1,7 @@
package cn.celess.blog.service;
import cn.celess.blog.entity.Tag;
import cn.celess.blog.entity.model.TagModel;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
@@ -18,7 +19,7 @@ public interface TagService {
* @param name 标签名
* @return 新增后的数据
*/
Tag create(String name);
TagModel create(String name);
/**
* 新增数据
@@ -27,7 +28,7 @@ public interface TagService {
* @return 新增后的数据
*/
Tag create(Tag tag);
TagModel create(Tag tag);
/**
* 删除数据
@@ -44,7 +45,7 @@ public interface TagService {
* @param name 改名的name值
* @return 更新后的数据
*/
Tag update(Long id, String name);
TagModel update(Long id, String name);
/**
* 查询单个标签信息
@@ -52,7 +53,7 @@ public interface TagService {
* @param tagId id
* @return 标签的数据
*/
Tag retrieveOneById(long tagId);
TagModel retrieveOneById(long tagId);
/**
* 通过name查询标签的信息
@@ -60,7 +61,7 @@ public interface TagService {
* @param name tag的名称
* @return 标签数据
*/
Tag retrieveOneByName(String name);
TagModel retrieveOneByName(String name);
/**
@@ -70,13 +71,13 @@ public interface TagService {
* @param page 数据页
* @return 分页数据
*/
PageInfo<Tag> retrievePage(int page, int count);
PageInfo<TagModel> retrievePage(int page, int count);
/**
* 获取全部标签数据
*
* @return 标签数据列表
*/
List<Tag> findAll();
List<TagModel> findAll();
}

View File

@@ -174,4 +174,13 @@ public interface UserService {
* @return true:存在 false不存在
*/
boolean getStatusOfEmail(String email);
/**
* 设置密码
* @param pwd
* @param newPwd
* @param confirmPwd
* @return
*/
UserModel setPwd(String pwd, String newPwd, String confirmPwd);
}

View File

@@ -2,6 +2,7 @@ package cn.celess.blog.service;
import cn.celess.blog.entity.model.WebUpdateModel;
import com.github.pagehelper.PageInfo;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Service;
import java.util.List;
@@ -58,5 +59,5 @@ public interface WebUpdateInfoService {
*
* @return
*/
String getLastestUpdateTime();
JSONObject getLastestUpdateTime();
}

View File

@@ -92,7 +92,7 @@ public class ArticleServiceImpl implements ArticleService {
article.setUrl(reqBody.getUrl());
article.setType(reqBody.getType());
article.setAuthorId(redisUserUtil.get(request).getId());
article.setAuthorId(redisUserUtil.get().getId());
article.setPublishDate(new Date());
//防止出现 “null,xxx”这种情况
@@ -198,7 +198,7 @@ public class ArticleServiceImpl implements ArticleService {
Article nextArticle = articleMapper.findArticleById(articleForDel.getNextArticleId());
//对访问情况进行判断 非博主/非自己文章 拒绝访问
User user = redisUserUtil.get(request);
User user = redisUserUtil.get();
if (!user.getRole().contains("admin") && !articleForDel.getAuthorId().equals(user.getId())) {
throw new MyException(ResponseEnum.PERMISSION_ERROR);
}
@@ -278,9 +278,9 @@ public class ArticleServiceImpl implements ArticleService {
throw new MyException(ResponseEnum.PARAMETERS_ERROR);
}
// 暂时不更新tags
// if (reqBody.getTags() == null || reqBody.getTags().replaceAll(" ", "").isEmpty()) {
// throw new MyException(ResponseEnum.PARAMETERS_ERROR);
// }
if (reqBody.getTags() == null || reqBody.getTags().replaceAll(" ", "").isEmpty()) {
throw new MyException(ResponseEnum.PARAMETERS_ERROR);
}
//写入数据库的数据
Article article = new Article();
@@ -317,26 +317,44 @@ public class ArticleServiceImpl implements ArticleService {
article.setCategoryId(oldArticle.getCategoryId());
}
// String[] newTags = reqBody.getTags().replaceAll(" ", "").split(",");
// //防止出现 null2这种情况
// article.setTagsId("");
// for (String t : newTags) {
// Tag tag = tagMapper.findTagByName(t);
// if (tag == null) {
// tag = new Tag();
// tag.setName(t);
// tag.setArticles(oldArticle.getId() + ",");
// tag = tagMapper.save(tag);
// article.setTagsId(article.getTagsId() + tag.getId() + ",");
// continue;
// }
// article.setTagsId(article.getTagsId() + tag.getId() + ",");
// }
// TODO:::: tag的更新
article.setTagsId(oldArticle.getTagsId());
String[] newTags = reqBody.getTags().split(",");
String[] tagIds = oldArticle.getTagsId().split(",");
//防止出现 null2这种情况
article.setTagsId("");
for (String t : newTags) {
Tag tag = tagMapper.findTagByName(t);
if (tag == null) {
tag = new Tag();
tag.setName(t);
tag.setArticles(oldArticle.getId() + ",");
int status = tagMapper.insert(tag);
if (status == 0) {
// 插入失败
throw new MyException(ResponseEnum.FAILURE);
}
article.setTagsId(article.getTagsId() + tag.getId() + ",");
continue;
}
article.setTagsId(article.getTagsId() + tag.getId() + ",");
}
for (String tagId : tagIds) {
Tag tagById = tagMapper.findTagById(Long.parseLong(tagId));
// 在新更新的tag中是否有原有的tag
boolean isOldTag = false;
for (String s : newTags) {
if (s.equals(tagById.getName())) {
isOldTag = true;
break;
}
}
if (!isOldTag) {
tagById.setArticles(tagById.getArticles().replace(oldArticle.getId() + ",", ""));
}
tagMapper.update(tagById);
}
//
// // TODO:::: tag的更新
// article.setTagsId(oldArticle.getTagsId());
article.setUpdateDate(new Date());
@@ -344,7 +362,7 @@ public class ArticleServiceImpl implements ArticleService {
// 设置不定参数
article.setReadingNumber(oldArticle.getReadingNumber());
article.setPublishDate(oldArticle.getPublishDate());
article.setAuthorId(redisUserUtil.get(request).getId());
article.setAuthorId(redisUserUtil.get().getId());
article.setPreArticleId(oldArticle.getPreArticleId());
article.setNextArticleId(oldArticle.getNextArticleId());
String str = StringFromHtmlUtil.getString(MDTool.markdown2Html(article.getMdContent()));
@@ -362,7 +380,7 @@ public class ArticleServiceImpl implements ArticleService {
throw new MyException(ResponseEnum.ARTICLE_NOT_EXIST);
}
if (!article.getOpen()) {
User user = redisUserUtil.getWithOutExc(request);
User user = redisUserUtil.getWithOutExc();
if (user == null || "user".equals(user.getRole())) {
throw new MyException(ResponseEnum.ARTICLE_NOT_PUBLIC);
}

View File

@@ -3,6 +3,7 @@ package cn.celess.blog.service.serviceimpl;
import cn.celess.blog.enmu.ResponseEnum;
import cn.celess.blog.entity.Article;
import cn.celess.blog.entity.Category;
import cn.celess.blog.entity.model.CategoryModel;
import cn.celess.blog.exception.MyException;
import cn.celess.blog.mapper.ArticleMapper;
import cn.celess.blog.mapper.CategoryMapper;
@@ -11,6 +12,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
/**
@@ -27,7 +29,7 @@ public class CategoryServiceImpl implements CategoryService {
ArticleMapper articleMapper;
@Override
public Category create(String name) {
public CategoryModel create(String name) {
if (categoryMapper.existsByName(name)) {
throw new MyException(ResponseEnum.CATEGORY_HAS_EXIST);
}
@@ -35,16 +37,16 @@ public class CategoryServiceImpl implements CategoryService {
category.setName(name);
category.setArticles("");
categoryMapper.insert(category);
return category;
return new CategoryModel(category);
}
@Override
public Category create(Category category) {
public CategoryModel create(Category category) {
if (category == null) {
throw new MyException(ResponseEnum.PARAMETERS_ERROR);
}
categoryMapper.insert(category);
return category;
return new CategoryModel(category);
}
@Override
@@ -74,18 +76,20 @@ public class CategoryServiceImpl implements CategoryService {
@Override
public Category update(Long id, String name) {
public CategoryModel update(Long id, String name) {
if (id == null) {
throw new MyException(ResponseEnum.PARAMETERS_ERROR.getCode(), "id不可为空");
}
Category category = categoryMapper.findCategoryById(id);
category.setName(name);
categoryMapper.update(category);
return category;
return new CategoryModel(category);
}
@Override
public List<Category> retrievePage() {
return categoryMapper.findAll();
public List<CategoryModel> retrievePage() {
List<CategoryModel> list = new ArrayList<>();
categoryMapper.findAll().forEach(e -> list.add(new CategoryModel(e)));
return list;
}
}

View File

@@ -11,6 +11,7 @@ import cn.celess.blog.service.CommentService;
import cn.celess.blog.service.UserService;
import cn.celess.blog.util.DateFormatUtil;
import cn.celess.blog.util.RedisUserUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
@@ -44,7 +45,7 @@ public class CommentServiceImpl implements CommentService {
if (reqBody == null) {
throw new MyException(ResponseEnum.PARAMETERS_ERROR);
}
long authorID = redisUserUtil.get(request).getId();
long authorID = redisUserUtil.get().getId();
Comment pComment = null;
if (reqBody.getPid() != null && reqBody.getPid() != -1) {
pComment = commentMapper.findCommentById(reqBody.getPid());
@@ -112,45 +113,36 @@ public class CommentServiceImpl implements CommentService {
public PageInfo<CommentModel> retrievePage(Boolean isComment, int page, int count) {
PageHelper.startPage(page, count);
List<Comment> commentList = commentMapper.findAllByType(isComment);
PageInfo pageInfo = new PageInfo(commentList);
pageInfo.setList(list2List(commentList));
return pageInfo;
return pageTrans(commentList);
}
@Override
public PageInfo<CommentModel> retrievePageByPid(long pid, int page, int count) {
PageHelper.startPage(page, count);
public List<CommentModel> retrievePageByPid(long pid) {
List<Comment> commentList = commentMapper.findAllByPId(pid);
PageInfo pageInfo = new PageInfo(commentList);
pageInfo.setList(list2List(commentList));
return pageInfo;
List<CommentModel> modelList = new ArrayList<>();
commentList.forEach(m -> modelList.add(trans(m)));
return modelList;
}
@Override
public PageInfo<CommentModel> retrievePageByArticle(long articleID, long pid, int page, int count) {
PageHelper.startPage(page, count);
List<Comment> commentList = commentMapper.findAllByArticleIDAndPId(articleID, pid);
PageInfo pageInfo = new PageInfo(commentList);
pageInfo.setList(list2List(commentList));
return pageInfo;
return pageTrans(commentList);
}
@Override
public PageInfo<CommentModel> retrievePageByTypeAndPid(Boolean isComment, int pid, int page, int count) {
PageHelper.startPage(page, count);
List<Comment> commentList = commentMapper.findCommentsByTypeAndPId(isComment, pid);
PageInfo pageInfo = new PageInfo(commentList);
pageInfo.setList(list2List(commentList));
return pageInfo;
return pageTrans(commentList);
}
@Override
public PageInfo<CommentModel> retrievePageByAuthor(Boolean isComment, int page, int count) {
PageHelper.startPage(page, count);
List<Comment> commentList = commentMapper.findAllByAuthorIDAndType(redisUserUtil.get(request).getId(), isComment);
PageInfo pageInfo = new PageInfo(commentList);
pageInfo.setList(list2List(commentList));
return pageInfo;
List<Comment> commentList = commentMapper.findAllByAuthorIDAndType(redisUserUtil.get().getId(), isComment);
return pageTrans(commentList);
}
@@ -158,17 +150,7 @@ public class CommentServiceImpl implements CommentService {
public PageInfo<CommentModel> retrievePageByType(Boolean isComment, int page, int count) {
PageHelper.startPage(page, count);
List<Comment> commentList = commentMapper.findAllByType(isComment);
PageInfo pageInfo = new PageInfo(commentList);
pageInfo.setList(list2List(commentList));
return pageInfo;
}
private List<CommentModel> list2List(List<Comment> commentList) {
List<CommentModel> content = new ArrayList<>();
for (Comment c : commentList) {
content.add(trans(c));
}
return content;
return pageTrans(commentList);
}
private CommentModel trans(Comment comment) {
@@ -189,4 +171,16 @@ public class CommentServiceImpl implements CommentService {
return commentModel;
}
private PageInfo<CommentModel> pageTrans(List<Comment> commentList) {
PageInfo p = new PageInfo(commentList);
List<CommentModel> modelList = new ArrayList<>();
commentList.forEach(l -> {
CommentModel model = trans(l);
model.setRespComment(this.retrievePageByPid(model.getId()));
modelList.add(model);
});
p.setList(modelList);
return p;
}
}

View File

@@ -10,9 +10,7 @@ import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.FileInfo;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import java.io.InputStream;
@@ -23,31 +21,29 @@ import java.io.InputStream;
*/
@Service
public class QiniuServiceImpl implements QiniuService {
private Configuration cfg = new Configuration(Zone.zone2());
private UploadManager uploadManager;
private BucketManager bucketManager;
private Auth auth;
private static Configuration cfg = new Configuration(Zone.zone2());
private static UploadManager uploadManager;
private static BucketManager bucketManager;
private static Auth auth;
private static String bucket;
{
/* ***** 必填 ******
* 七牛的配置 *
* ***** 必填 ******
*/
// accessKeyString,secretKeyString,bucketString请替换为自己的值
String accessKey = "accessKeyString";
String secretKey = "secretKeyString";
bucket = "bucketString";
@Value("${qiniu.accessKey}")
private String accessKey;
@Value("${qiniu.secretKey}")
private String secretKey;
@Value("${qiniu.bucket}")
private String bucket;
private void init() {
if (auth == null || uploadManager == null || bucketManager == null) {
auth = Auth.create(accessKey, secretKey);
uploadManager = new UploadManager(cfg);
bucketManager = new BucketManager(auth, cfg);
}
}
@Override
public QiniuResponse uploadFile(InputStream is, String fileName) {
init();
//文件存在则删除文件
if (continueFile(fileName)) {
try {
@@ -69,6 +65,7 @@ public class QiniuServiceImpl implements QiniuService {
@Override
public FileInfo[] getFileList() {
init();
BucketManager.FileListIterator fileListIterator = bucketManager.createFileListIterator(bucket, "", 1000, "");
FileInfo[] items = null;
while (fileListIterator.hasNext()) {

View File

@@ -3,6 +3,7 @@ package cn.celess.blog.service.serviceimpl;
import cn.celess.blog.enmu.ResponseEnum;
import cn.celess.blog.entity.Article;
import cn.celess.blog.entity.Tag;
import cn.celess.blog.entity.model.TagModel;
import cn.celess.blog.exception.MyException;
import cn.celess.blog.mapper.ArticleMapper;
import cn.celess.blog.mapper.TagMapper;
@@ -13,6 +14,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
/**
@@ -29,7 +31,7 @@ public class TagServiceImpl implements TagService {
ArticleMapper articleMapper;
@Override
public Tag create(String name) {
public TagModel create(String name) {
boolean b = tagMapper.existsByName(name);
if (b) {
throw new MyException(ResponseEnum.TAG_HAS_EXIST);
@@ -37,16 +39,16 @@ public class TagServiceImpl implements TagService {
Tag tag = new Tag();
tag.setName(name);
tagMapper.insert(tag);
return tag;
return new TagModel(tag);
}
@Override
public Tag create(Tag tag) {
public TagModel create(Tag tag) {
if (tag == null) {
throw new MyException(ResponseEnum.PARAMETERS_ERROR);
}
tagMapper.insert(tag);
return tag;
return new TagModel(tag);
}
@Override
@@ -60,7 +62,7 @@ public class TagServiceImpl implements TagService {
}
String[] articleArray = tag.getArticles().split(",");
for (int i = 0; i < articleArray.length; i++) {
if (articleArray[i] == null || "".equals(articleArray)) {
if (articleArray[i] == null || "".equals(articleArray[i])) {
continue;
}
long articleID = Long.parseLong(articleArray[i]);
@@ -76,7 +78,7 @@ public class TagServiceImpl implements TagService {
@Override
public Tag update(Long id,String name) {
public TagModel update(Long id, String name) {
if (id == null) {
throw new MyException(ResponseEnum.PARAMETERS_ERROR.getCode(), "缺少ID");
}
@@ -84,37 +86,43 @@ public class TagServiceImpl implements TagService {
tagFromDB.setName(name);
tagMapper.update(tagFromDB);
return tagFromDB;
return new TagModel(tagFromDB);
}
@Override
public Tag retrieveOneById(long tagId) {
public TagModel retrieveOneById(long tagId) {
Tag tag = tagMapper.findTagById(tagId);
if (tag == null) {
throw new MyException(ResponseEnum.TAG_NOT_EXIST);
}
return tag;
return new TagModel(tag);
}
@Override
public Tag retrieveOneByName(String name) {
public TagModel retrieveOneByName(String name) {
Tag tag = tagMapper.findTagByName(name);
if (tag == null) {
throw new MyException(ResponseEnum.TAG_NOT_EXIST);
}
return tag;
return new TagModel(tag);
}
@Override
public PageInfo<Tag> retrievePage(int page, int count) {
public PageInfo<TagModel> retrievePage(int page, int count) {
PageHelper.startPage(page, count);
PageInfo pageInfo = new PageInfo(tagMapper.findAll());
List<Tag> tagList = tagMapper.findAll();
PageInfo pageInfo = new PageInfo(tagList);
List<TagModel> list = new ArrayList<>();
tagList.forEach(e -> list.add(new TagModel(e)));
pageInfo.setList(list);
return pageInfo;
}
@Override
public List<Tag> findAll() {
return tagMapper.findAll();
public List<TagModel> findAll() {
List<TagModel> list = new ArrayList<>();
tagMapper.findAll().forEach(e -> list.add(new TagModel(e)));
return list;
}
}

View File

@@ -119,8 +119,7 @@ public class UserServiceImpl implements UserService {
userMapper.updateLoginTime(loginReq.getEmail(), new Date());
redisUtil.delete(loginReq.getEmail() + "-passwordWrongTime");
// redis 标记
redisUtil.setEx(loginReq.getEmail() + "-login", JSONObject.fromObject(user).toString(),
(loginReq.getIsRememberMe() ? JwtUtil.EXPIRATION_LONG_TIME : JwtUtil.EXPIRATION_SHORT_TIME), TimeUnit.MILLISECONDS);
redisUserUtil.set(user, loginReq.getIsRememberMe());
token = jwtUtil.generateToken(user, loginReq.getIsRememberMe());
} else {
logger.info("====> {} 进行权限认证 状态:登录失败 <====", loginReq.getEmail());
@@ -159,7 +158,7 @@ public class UserServiceImpl implements UserService {
@Override
public UserModel update(String desc, String displayName) {
User user = redisUserUtil.get(request);
User user = redisUserUtil.get();
user.setDesc(desc);
user.setDisplayName(displayName);
@@ -193,7 +192,7 @@ public class UserServiceImpl implements UserService {
@Override
public Object updateUserAavatarImg(InputStream is, String mime) {
User user = redisUserUtil.get(request);
User user = redisUserUtil.get();
QiniuResponse upload = qiniuService.uploadFile(is, user.getEmail() + "_" + user.getId() + mime.toLowerCase());
user.setAvatarImgUrl(upload.key);
userMapper.updateAvatarImgUrl(upload.key, user.getId());
@@ -203,7 +202,7 @@ public class UserServiceImpl implements UserService {
@Override
public UserModel getUserInfoBySession() {
User user = redisUserUtil.get(request);
User user = redisUserUtil.get();
return trans(user);
}
@@ -422,7 +421,7 @@ public class UserServiceImpl implements UserService {
if (updateResult == 0) {
throw new MyException(ResponseEnum.FAILURE);
}
if (redisUserUtil.get(request).getId().equals(userReq.getId())) {
if (redisUserUtil.get().getId().equals(userReq.getId())) {
redisUserUtil.set(user);
}
logger.info("修改了用户 [id={}] 的用户的资料", userReq.getId());
@@ -434,6 +433,20 @@ public class UserServiceImpl implements UserService {
return userMapper.existsByEmail(email);
}
@Override
public UserModel setPwd(String pwd, String newPwd, String confirmPwd) {
User user = redisUserUtil.get();
String pwd1 = userMapper.getPwd(user.getEmail());
if (!MD5Util.getMD5(pwd).equals(pwd1)) {
throw new MyException(ResponseEnum.PWD_WRONG);
}
if (!newPwd.equals(confirmPwd)) {
throw new MyException(ResponseEnum.PWD_NOT_SAME);
}
userMapper.updatePwd(user.getEmail(), MD5Util.getMD5(newPwd));
return trans(userMapper.findByEmail(user.getEmail()));
}
private UserModel trans(User u) {
UserModel user = new UserModel();
user.setId(u.getId());

View File

@@ -7,11 +7,18 @@ import cn.celess.blog.exception.MyException;
import cn.celess.blog.mapper.WebUpdateInfoMapper;
import cn.celess.blog.service.WebUpdateInfoService;
import cn.celess.blog.util.DateFormatUtil;
import cn.celess.blog.util.HttpUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@@ -21,6 +28,7 @@ import java.util.List;
* @date : 2019/05/12 11:43
*/
@Service
@Slf4j
public class WebUpdateInfoServiceImpl implements WebUpdateInfoService {
@Autowired
WebUpdateInfoMapper webUpdateInfoMapper;
@@ -80,8 +88,24 @@ public class WebUpdateInfoServiceImpl implements WebUpdateInfoService {
}
@Override
public String getLastestUpdateTime() {
return DateFormatUtil.get(webUpdateInfoMapper.getLastestOne());
public JSONObject getLastestUpdateTime() {
JSONObject jsonObject = new JSONObject();
jsonObject.put("lastUpdateTime", DateFormatUtil.get(webUpdateInfoMapper.getLastestOne().getUpdateTime()));
jsonObject.put("lastUpdateInfo", webUpdateInfoMapper.getLastestOne().getUpdateInfo());
try {
JSONArray array = JSONArray.fromObject(HttpUtil.get("https://api.github.com/repos/xiaohai2271/blog-frontEnd/commits?page=1&per_page=1"));
JSONObject object = array.getJSONObject(0);
JSONObject commit = object.getJSONObject("commit");
jsonObject.put("lastCommit", commit.getString("message"));
jsonObject.put("committerAuthor", commit.getJSONObject("committer").getString("name"));
SimpleDateFormat sdf = new SimpleDateFormat();
Instant parse = Instant.parse(commit.getJSONObject("committer").getString("date"));
jsonObject.put("committerDate", DateFormatUtil.get(Date.from(parse)));
jsonObject.put("commitUrl", "https://github.com/xiaohai2271/blog-frontEnd/tree/"+object.getString("sha"));
} catch (IOException e) {
log.info("网络请求失败{}", e.getMessage());
}
return jsonObject;
}
private List<WebUpdateModel> list2List(List<WebUpdate> webUpdates) {

View File

@@ -0,0 +1,51 @@
package cn.celess.blog.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
/**
* @Author: 小海
* @Date: 2020-04-23 15:51
* @Desc:
*/
public class HttpUtil {
public static String get(String urlStr) throws IOException {
StringBuffer sb = new StringBuffer();
HttpURLConnection urlConnection = null;
try {
URL url = new URL(urlStr);
//打开http
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoInput(true);
urlConnection.setRequestMethod("GET");
urlConnection.connect();
try (
InputStream inputStream = urlConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
) {
//将bufferReader的值给放到buffer里
String str = null;
while ((str = bufferedReader.readLine()) != null) {
sb.append(str);
}
}
} finally {
//断开连接
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return sb.toString();
}
}

View File

@@ -1,10 +1,11 @@
package cn.celess.blog.util;
import cn.celess.blog.enmu.ResponseEnum;
import cn.celess.blog.entity.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import cn.celess.blog.exception.MyException;
import io.jsonwebtoken.*;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.time.Instant;
@@ -18,6 +19,7 @@ import java.util.Map;
* @Description: JWT工具类
*/
@Component
@Log4j2
public class JwtUtil {
private static final String CLAIM_KEY_USERNAME = "sub";
@@ -33,8 +35,8 @@ public class JwtUtil {
/**
* JWT 秘钥需自行设置不可泄露
*/
private static final String SECRET = "xxx";
@Value("${jwt.secret}")
private String SECRET;
public String generateToken(User user, boolean isRemember) {
Map<String, Object> claims = new HashMap<>(16);
@@ -47,46 +49,63 @@ public class JwtUtil {
.compact();
}
public Boolean validateToken(String token, User user) {
String username = getUsernameFromToken(token);
return (username.equals(user.getEmail()) && !isTokenExpired(token));
public String updateTokenDate(String token) {
Claims claims = Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token).getBody();
return Jwts.builder()
.setClaims(claims)
.setExpiration(new Date(claims.getExpiration().getTime() + EXPIRATION_SHORT_TIME))
.signWith(SignatureAlgorithm.HS512, SECRET)
.compact();
}
/**
* 获取token是否过期
*/
public Boolean isTokenExpired(String token) {
try {
Date expiration = getExpirationDateFromToken(token);
return expiration.before(new Date());
} catch (ExpiredJwtException e) {
return true;
}
return expiration == null || expiration.before(new Date());
}
/**
* 根据token获取username
*/
public String getUsernameFromToken(String token) {
return getClaimsFromToken(token).getSubject();
Claims claims = getClaimsFromToken(token);
return claims == null ? null : claims.getSubject();
}
/**
* 获取token的过期时间
*/
public Date getExpirationDateFromToken(String token) {
return getClaimsFromToken(token).getExpiration();
Claims claims = getClaimsFromToken(token);
return claims == null ? null : claims.getExpiration();
}
/**
* 解析JWT
*/
private Claims getClaimsFromToken(String token) {
Claims claims = Jwts.parser()
Claims claims = null;
try {
claims = Jwts.parser()
.setSigningKey(SECRET)
.parseClaimsJws(token)
.getBody();
} catch (ExpiredJwtException e) {
log.info("JWT令牌过期");
} catch (UnsupportedJwtException e) {
log.info("不支持的JWT令牌");
throw new MyException(ResponseEnum.JWT_NOT_SUPPORT);
} catch (MalformedJwtException e) {
log.info("JWT令牌格式错误");
throw new MyException(ResponseEnum.JWT_MALFORMED);
} catch (SignatureException e) {
log.info("JWT签名错误");
throw new MyException(ResponseEnum.JWT_SIGNATURE);
} catch (IllegalArgumentException e) {
log.debug("JWT非法参数");
}
return claims;
}

View File

@@ -20,16 +20,18 @@ public class RedisUserUtil {
RedisUtil redisUtil;
@Autowired
JwtUtil jwtUtil;
@Autowired
HttpServletRequest request;
public User get(HttpServletRequest request) {
User user = getWithOutExc(request);
public User get() {
User user = getWithOutExc();
if (user == null) {
throw new MyException(ResponseEnum.HAVE_NOT_LOG_IN);
}
return user;
}
public User getWithOutExc(HttpServletRequest request) {
public User getWithOutExc() {
String token = request.getHeader("Authorization");
if (token == null || token.isEmpty()) {
return null;
@@ -39,8 +41,16 @@ public class RedisUserUtil {
}
public User set(User user) {
Long expire = redisUtil.getExpire(user.getEmail() + "-login");
redisUtil.setEx(user.getEmail() + "-login", JSONObject.fromObject(user).toString(),
redisUtil.getExpire(user.getEmail() + "-login"), TimeUnit.MILLISECONDS);
expire > 0 ? expire : JwtUtil.EXPIRATION_SHORT_TIME, TimeUnit.MILLISECONDS);
return user;
}
public User set(User user, boolean isRemember) {
redisUtil.setEx(user.getEmail() + "-login", JSONObject.fromObject(user).toString(),
isRemember ? JwtUtil.EXPIRATION_LONG_TIME : JwtUtil.EXPIRATION_SHORT_TIME, TimeUnit.MILLISECONDS);
request.getSession().setAttribute("email", user.getEmail());
return user;
}
}

View File

@@ -43,6 +43,9 @@ public class SitemapGenerateUtil {
@Async
public void createSitemap() {
initList();
if ("".equals(path) || "classpath".equals(path)) {
path = System.getProperty("user.dir")+"/sitemap.xml";
}
File file = new File(path);
try {
if (file.exists()) {

View File

@@ -1,5 +1,14 @@
server.port=8081
# 七牛的密钥配置
qiniu.accessKey=
qiniu.secretKey=
qiniu.bucket=
# sitemap 存放地址
sitemap.path=
# 生成JWT时候的密钥
jwt.secret=
spring.jpa.show-sql=false
spring.jpa.hibernate.ddl-auto=update
# 上传单个文件的大小

View File

@@ -1,80 +0,0 @@
server.port=8081
sitemap.path=C:\\Users\\zh564\\Desktop\\sitemap.xml
##spring.jpa.show-sql=false
##spring.jpa.hibernate.ddl-auto=update
mybatis.type-handlers-package=cn.celess.blog.mapper.typehandler
# 上传单个文件的大小
spring.servlet.multipart.max-file-size=10MB
# 上传文件的总大小
spring.servlet.multipart.max-request-size=10MB
spring.jackson.default-property-inclusion=non_null
################# 数据库 ##################
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.url=jdbc:mysql://localhost:3306/test_blog?serverTimezone=UCT&allowPublicKeyRetrieval=true&useSSL=false
spring.datasource.username=root
spring.datasource.password=zhenghai
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
################## mybatis ##################
mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.type-aliases-package=cn.celess.blog.entity
pagehelper.helper-dialect=mysql
pagehelper.reasonable=true
pagehelper.support-methods-arguments=true
pagehelper.params=count=countSql
#### 用于nginx的代理 获取真实ip
server.use-forward-headers = true
server.tomcat.remote-ip-header = X-Real-IP
server.tomcat.protocol-header = X-Forwarded-Proto
############### email ##############
spring.mail.host=smtp.163.com
spring.mail.username=
spring.mail.password=
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
spring.mail.default-encoding=UTF-8
spring.mail.port=465
spring.mail.properties.mail.smtp.socketFactory.port=465
spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
spring.mail.properties.mail.smtp.socketFactory.fallback=false
############### redis ##############
# REDIS (RedisProperties)
# Redis数据库索引默认为0
spring.redis.database=1
# Redis服务器地址
spring.redis.host=127.0.0.1
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码默认为空
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.jedis.pool.max-active=-1
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.jedis.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.jedis.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.jedis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=5000

View File

@@ -3,3 +3,5 @@ spring.profiles.active=prod
####cn.celess.blog.service.serviceimpl.QiniuServiceImpl
logging.level.cn.celess.blog=debug
logging.level.cn.celess.blog.mapper=info
## 修改openSource 添加-test 文件用于测试 -prod文件用于线上发布

View File

@@ -39,8 +39,8 @@
select *
from web_update
</select>
<select id="getLastestOne" resultType="date">
select update_time
<select id="getLastestOne" resultMap="webUpdateResultMap">
select *
from web_update
order by update_id desc
limit 1

View File

@@ -8,10 +8,12 @@ import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.ResultHandler;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
@@ -20,6 +22,8 @@ import org.springframework.web.context.WebApplicationContext;
import javax.servlet.http.Cookie;
import java.util.UUID;
import static org.junit.Assert.*;
/**
@@ -39,10 +43,12 @@ public class BaseTest {
@Autowired
private WebApplicationContext wac;
protected MockHttpSession session;
@Before
public void before() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
session = new MockHttpSession();
System.out.println("==========> 开始测试 <=========");
}
@@ -94,4 +100,8 @@ public class BaseTest {
public void test() {
}
protected String randomStr(int len) {
return UUID.randomUUID().toString().replaceAll("-", "").substring(0, len);
}
}

View File

@@ -13,8 +13,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import java.util.Arrays;
import java.util.UUID;
import java.util.*;
import static org.junit.Assert.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
@@ -139,32 +138,17 @@ public class ArticleControllerTest extends BaseTest {
articleReq.setCategory("test");
articleReq.setMdContent("test-" + article.getMdContent());
articleReq.setOpen(!article.getOpen());
articleReq.setTags("tag");
String tag1 = randomStr(4);
String tag2 = randomStr(4);
String tag = "test," + tag1 + "," + tag2;
articleReq.setTags(tag);
articleReq.setTitle("test-" + article.getTitle());
try {
mockMvc.perform(put("/admin/article/update")
.content(JSONObject.fromObject(articleReq).toString())
.contentType("application/json"))
.andExpect(status().isOk())
.andDo(result -> {
assertEquals(HAVE_NOT_LOG_IN.getCode(), JSONObject.fromObject(result.getResponse().getContentAsString()).getInt(Code));
});
// User 权限
String token = userLogin();
mockMvc.perform(put("/admin/article/update")
.content(JSONObject.fromObject(articleReq).toString())
.contentType("application/json")
.header("Authorization", token))
.andExpect(status().isOk())
.andDo(result -> {
assertEquals(PERMISSION_ERROR.getCode(), JSONObject.fromObject(result.getResponse().getContentAsString()).getInt(Code));
});
// Admin 权限
token = adminLogin();
mockMvc.perform(put("/admin/article/update")
.content(JSONObject.fromObject(articleReq).toString())
.contentType("application/json")
.header("Authorization", token))
.header("Authorization", adminLogin()))
.andExpect(status().isOk())
.andDo(result -> {
JSONObject jsonObject = JSONObject.fromObject(result.getResponse().getContentAsString());
@@ -175,8 +159,11 @@ public class ArticleControllerTest extends BaseTest {
assertEquals(articleReq.getMdContent(), a.getMdContent());
assertEquals(articleReq.getTitle(), a.getTitle());
assertEquals(articleReq.getType(), a.getOriginal());
// Tag 暂时不支持更新
// assertEquals(articleReq.getTags(), Arrays.toString(a.getTags()).replaceAll(" ", "".replace("[", "".replace("]", ""))));
// Tag
List<String> asList = Arrays.asList(a.getTags());
assertTrue(asList.contains("test"));
assertTrue(asList.contains(tag1));
assertTrue(asList.contains(tag2));
assertEquals(articleReq.getOpen(), a.getOpen());
assertEquals(articleReq.getId(), a.getId());
});

View File

@@ -2,6 +2,7 @@ package cn.celess.blog.controller;
import cn.celess.blog.BaseTest;
import cn.celess.blog.entity.Category;
import cn.celess.blog.entity.model.CategoryModel;
import cn.celess.blog.mapper.CategoryMapper;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
@@ -45,10 +46,10 @@ public class CategoryControllerTest extends BaseTest {
.andDo(result -> {
JSONObject object = JSONObject.fromObject(result.getResponse().getContentAsString());
assertEquals(SUCCESS.getCode(), object.getInt(Code));
Category category = (Category) JSONObject.toBean(object.getJSONObject(Result), Category.class);
CategoryModel category = (CategoryModel) JSONObject.toBean(object.getJSONObject(Result), CategoryModel.class);
assertEquals(categoryName, category.getName());
assertNotNull(category.getId());
assertNotNull(category.getArticles());
assertNotEquals(0, category.getArticles());
});
}
@@ -105,9 +106,9 @@ public class CategoryControllerTest extends BaseTest {
.andDo(result -> {
JSONObject object = JSONObject.fromObject(result.getResponse().getContentAsString());
assertEquals(SUCCESS.getCode(), object.getInt(Code));
Category c = (Category) JSONObject.toBean(object.getJSONObject(Result), Category.class);
CategoryModel c = (CategoryModel) JSONObject.toBean(object.getJSONObject(Result), CategoryModel.class);
assertEquals(name, c.getName());
assertNotNull(c.getArticles());
assertNotEquals(0, c.getArticles());
assertNotNull(c.getId());
});
}
@@ -121,10 +122,10 @@ public class CategoryControllerTest extends BaseTest {
JSONArray jsonArray = object.getJSONArray(Result);
assertNotNull(jsonArray);
jsonArray.forEach(o -> {
Category c = (Category) JSONObject.toBean(JSONObject.fromObject(o), Category.class);
CategoryModel c = (CategoryModel) JSONObject.toBean(JSONObject.fromObject(o), CategoryModel.class);
assertNotNull(c.getName());
assertNotNull(c.getId());
assertNotNull(c.getArticles());
assertNotEquals(0, c.getArticles());
});
});

View File

@@ -9,6 +9,7 @@ import cn.celess.blog.mapper.ArticleMapper;
import cn.celess.blog.mapper.CommentMapper;
import cn.celess.blog.mapper.UserMapper;
import com.github.pagehelper.PageInfo;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
@@ -198,22 +199,17 @@ public class CommentControllerTest extends BaseTest {
@Test
public void retrievePage() throws Exception {
long pid = 17;
mockMvc.perform(get("/comment/pid/" + pid + "?articleId=3&page=1&count=10")).andDo(result -> {
long pid = -1;
mockMvc.perform(get("/comment/pid/" + pid)).andDo(result -> {
JSONObject object = JSONObject.fromObject(result.getResponse().getContentAsString());
assertEquals(SUCCESS.getCode(), object.getInt(Code));
PageInfo pageInfo = (PageInfo) JSONObject.toBean(object.getJSONObject(Result), PageInfo.class);
assertNotEquals(0, pageInfo.getStartRow());
assertNotEquals(0, pageInfo.getEndRow());
assertEquals(1, pageInfo.getPageNum());
assertEquals(10, pageInfo.getPageSize());
pageInfo.getList().forEach(o -> {
JSONArray jsonArray = object.getJSONArray(Result);
assertNotEquals(0, jsonArray.size());
jsonArray.forEach(o -> {
CommentModel model = (CommentModel) JSONObject.toBean(JSONObject.fromObject(o), CommentModel.class);
assertEquals(3, model.getArticleID());
assertNotNull(model.getDate());
assertNotNull(model.getAuthorName());
assertNotNull(model.getAuthorAvatarImgUrl());
assertNotNull(model.getArticleTitle());
assertNotNull(model.getContent());
assertNotNull(model.getResponseId());
});

View File

@@ -161,7 +161,8 @@ public class LinksControllerTest extends BaseTest {
});
}
@Test
// 手动测试
// @Test
public void apply() throws Exception {
long l = System.currentTimeMillis();
String url = "https://www.example.com";

View File

@@ -2,6 +2,7 @@ package cn.celess.blog.controller;
import cn.celess.blog.BaseTest;
import cn.celess.blog.entity.Tag;
import cn.celess.blog.entity.model.TagModel;
import cn.celess.blog.mapper.TagMapper;
import com.github.pagehelper.PageInfo;
import net.sf.json.JSONArray;
@@ -29,7 +30,7 @@ public class TagControllerTest extends BaseTest {
JSONObject object = JSONObject.fromObject(result.getResponse().getContentAsString());
assertEquals(SUCCESS.getCode(), object.getInt(Code));
JSONObject resJson = object.getJSONObject(Result);
Tag tag = (Tag) JSONObject.toBean(resJson, Tag.class);
TagModel tag = (TagModel) JSONObject.toBean(resJson, TagModel.class);
assertNotNull(tag.getId());
assertEquals(name, tag.getName());
});
@@ -63,9 +64,11 @@ public class TagControllerTest extends BaseTest {
JSONObject object = JSONObject.fromObject(result.getResponse().getContentAsString());
assertEquals(SUCCESS.getCode(), object.getInt(Code));
assertNotNull(object.getJSONObject(Result));
Tag t = (Tag) JSONObject.toBean(object.getJSONObject(Result), Tag.class);
TagModel t = (TagModel) JSONObject.toBean(object.getJSONObject(Result), TagModel.class);
assertEquals(name, t.getName());
assertEquals(tag.getArticles(), t.getArticles());
StringBuilder s = new StringBuilder();
t.getArticles().forEach(e -> s.append(e).append(","));
assertEquals(tag.getArticles(), s.toString());
assertEquals(tag.getId(), t.getId());
});
@@ -79,7 +82,7 @@ public class TagControllerTest extends BaseTest {
JSONObject object = JSONObject.fromObject(result.getResponse().getContentAsString());
assertEquals(SUCCESS.getCode(), object.getInt(Code));
assertNotNull(object.getJSONObject(Result));
Tag t = (Tag) JSONObject.toBean(object.getJSONObject(Result), Tag.class);
TagModel t = (TagModel) JSONObject.toBean(object.getJSONObject(Result), TagModel.class);
assertEquals(tag.getId(), t.getId());
assertNotNull(t.getName());
});
@@ -93,7 +96,7 @@ public class TagControllerTest extends BaseTest {
JSONObject object = JSONObject.fromObject(result.getResponse().getContentAsString());
assertEquals(SUCCESS.getCode(), object.getInt(Code));
assertNotNull(object.getJSONObject(Result));
Tag t = (Tag) JSONObject.toBean(object.getJSONObject(Result), Tag.class);
TagModel t = (TagModel) JSONObject.toBean(object.getJSONObject(Result), TagModel.class);
assertEquals(tag.getName(), t.getName());
assertNotNull(t.getId());
});
@@ -119,7 +122,7 @@ public class TagControllerTest extends BaseTest {
assertEquals(5, pageInfo.getPageSize());
// 内容完整
for (Object tag : pageInfo.getList()) {
Tag t = (Tag) JSONObject.toBean(JSONObject.fromObject(tag), Tag.class);
TagModel t = (TagModel) JSONObject.toBean(JSONObject.fromObject(tag), TagModel.class);
assertNotNull(t.getId());
assertNotNull(t.getName());
}

View File

@@ -14,10 +14,12 @@ import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;
import static org.junit.Assert.*;
@@ -93,8 +95,12 @@ public class UserControllerTest extends BaseTest {
@Test
public void upload() throws Exception {
File logoFile = new File("C:\\Users\\zh564\\Pictures\\logo.png");
MockMultipartFile file = new MockMultipartFile("file", "logo.png", MediaType.IMAGE_PNG_VALUE, new FileInputStream(logoFile));
URL url = new URL("https://56462271.oss-cn-beijing.aliyuncs.com/web/logo.png");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
InputStream inputStream = connection.getInputStream();
assertNotNull(inputStream);
MockMultipartFile file = new MockMultipartFile("file", "logo.png", MediaType.IMAGE_PNG_VALUE, inputStream);
mockMvc.perform(multipart("/user/imgUpload").file(file)).andDo(result -> assertEquals(HAVE_NOT_LOG_IN.getCode(), JSONObject.fromObject(result.getResponse().getContentAsString()).getInt(Code)));
mockMvc.perform(multipart("/user/imgUpload").file(file).header("Authorization", userLogin())).andDo(result -> {
JSONObject object = JSONObject.fromObject(result.getResponse().getContentAsString());
@@ -244,4 +250,28 @@ public class UserControllerTest extends BaseTest {
assertTrue(JSONObject.fromObject(content).getBoolean(Result));
});
}
@Test
public void setPwd() throws Exception {
String email = UUID.randomUUID().toString().substring(0, 4) + "@celess.cn";
assertEquals(1, userMapper.addUser(email, MD5Util.getMD5("1234567890")));
LoginReq req = new LoginReq();
req.setEmail(email);
req.setPassword("1234567890");
req.setIsRememberMe(false);
JSONObject loginReq = JSONObject.fromObject(req);
String contentAsString = mockMvc.perform(post("/login").content(loginReq.toString()).contentType("application/json")).andReturn().getResponse().getContentAsString();
assertNotNull(contentAsString);
String token = JSONObject.fromObject(contentAsString).getJSONObject(Result).getString("token");
assertNotNull(token);
MultiValueMap<String, String> param = new LinkedMultiValueMap<String, String>();
param.add("pwd", "1234567890");
param.add("newPwd", "aaabbbccc");
param.add("confirmPwd", "aaabbbccc");
mockMvc.perform(post("/user/setPwd").header("Authorization", token).params(param)).andDo(result -> {
String content = result.getResponse().getContentAsString();
assertEquals(SUCCESS.getCode(), JSONObject.fromObject(content).getInt(Code));
assertEquals(MD5Util.getMD5("aaabbbccc"), userMapper.getPwd(email));
});
}
}

View File

@@ -63,7 +63,8 @@ public class VisitorControllerTest extends BaseTest {
);
}
@Test
// 手动测试
// @Test
public void ipLocation() throws Exception {
String ip = "127.0.0.1";
mockMvc.perform(get("/ip/" + ip)).andDo(MockMvcResultHandlers.print()).andDo(result -> {

View File

@@ -120,6 +120,7 @@ public class WebUpdateInfoControllerTest extends BaseTest {
@Test
public void lastestUpdateTime() throws Exception {
mockMvc.perform(get("/lastestUpdateTime")).andDo(result -> assertEquals(SUCCESS.getCode(), JSONObject.fromObject(result.getResponse().getContentAsString()).getInt(Code)));
mockMvc.perform(get("/lastestUpdate")).andDo(result ->
assertEquals(SUCCESS.getCode(), JSONObject.fromObject(result.getResponse().getContentAsString()).getInt(Code)));
}
}

View File

@@ -61,4 +61,16 @@ public class AuthorizationFilter extends BaseTest {
assertEquals(HAVE_NOT_LOG_IN.getCode(), object.getInt(Code));
});
}
@Test
public void authorizationTest() throws Exception {
// 测试response中有无Authorization字段
String s = userLogin();
mockMvc.perform(get("/user/userInfo").header("Authorization", s)).andDo(result -> {
JSONObject object = JSONObject.fromObject(result.getResponse().getContentAsString());
assertEquals(SUCCESS.getCode(), object.getInt(Code));
assertNotNull(result.getResponse().getHeader("Authorization"));
assertNotEquals(s, result.getResponse().getHeader("Authorization"));
});
}
}

View File

@@ -0,0 +1,26 @@
package cn.celess.blog.util;
import cn.celess.blog.BaseTest;
import org.junit.Test;
import java.util.Date;
import static org.junit.Assert.*;
public class DateFormatUtilTest extends BaseTest {
@Test
public void get() {
assertNotNull(DateFormatUtil.get(new Date()));
}
@Test
public void getForXmlDate() {
assertNotNull(DateFormatUtil.getForXmlDate(new Date()));
}
@Test
public void getNow() {
assertNotNull(DateFormatUtil.getNow());
}
}

View File

@@ -2,51 +2,79 @@ package cn.celess.blog.util;
import cn.celess.blog.BaseTest;
import cn.celess.blog.entity.User;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import java.time.Instant;
import java.util.Date;
import static org.junit.Assert.*;
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class JwtUtilTest extends BaseTest {
@Autowired
JwtUtil jwtUtil;
@Value("${jwt.secret}")
private String secret;
@Test
public void generateToken() {
public void testGenerateToken() {
User user = new User();
user.setEmail("a@celess.cn");
String s = jwtUtil.generateToken(user, true);
System.out.println(s);
String s = jwtUtil.generateToken(user, false);
assertNotNull(s);
String str = null;
try {
str = jwtUtil.generateToken(null, false);
} catch (Exception e) {
// ignore
}
assertNull(str);
}
@Test
public void validateToken() {
public void testIsTokenExpired() throws InterruptedException {
String s = Jwts.builder()
.setClaims(null)
.setExpiration(new Date(Instant.now().toEpochMilli() + 1000))
.signWith(SignatureAlgorithm.HS512, secret)
.compact();
Thread.sleep(1010);
assertTrue(jwtUtil.isTokenExpired(s));
assertFalse(jwtUtil.isTokenExpired(jwtUtil.generateToken(new User(), false)));
}
@Test
public void testGetUsernameFromToken() {
User user = new User();
user.setEmail("a@celess.cn");
assertTrue(jwtUtil.validateToken(createToken(), user));
String s = jwtUtil.generateToken(user, false);
assertEquals(user.getEmail(), jwtUtil.getUsernameFromToken(s));
user.setEmail("example@celess.cn");
assertNotEquals(user.getEmail(), jwtUtil.getUsernameFromToken(s));
}
@Test
public void isTokenExpired() {
assertFalse(jwtUtil.isTokenExpired(createToken()));
}
@Test
public void getUsernameFromToken() {
assertEquals("a@celess.cn", jwtUtil.getUsernameFromToken(createToken()));
}
@Test
public void getExpirationDateFromToken() {
assertNotNull(jwtUtil.getExpirationDateFromToken(createToken()));
}
private String createToken() {
public void testGetExpirationDateFromToken() {
User user = new User();
user.setEmail("a@celess.cn");
return jwtUtil.generateToken(user, true);
String s = jwtUtil.generateToken(user, false);
assertNotNull(jwtUtil.getExpirationDateFromToken(s));
}
@Test
public void updateTokenDate() {
User user = new User();
user.setEmail("a@celess.cn");
String s = jwtUtil.generateToken(user, false);
Date before = jwtUtil.getExpirationDateFromToken(s);
String s1 = jwtUtil.updateTokenDate(s);
assertTrue(jwtUtil.getExpirationDateFromToken(s1).getTime() - jwtUtil.getExpirationDateFromToken(s).getTime() > 0);
}
}

View File

@@ -0,0 +1,14 @@
package cn.celess.blog.util;
import cn.celess.blog.BaseTest;
import org.junit.Test;
import static org.junit.Assert.*;
public class MD5UtilTest extends BaseTest {
@Test
public void getMD5() {
assertEquals("25f9e794323b453885f5181f1b624d0b", MD5Util.getMD5("123456789"));
}
}