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 back-end/blog-dev.sql
src/main/resources/application-prod.properties
src/main/resources/application-dev.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 * Copyright 2012-2019 the original author or authors.
or more contributor license agreements. See the NOTICE file *
distributed with this work for additional information * Licensed under the Apache License, Version 2.0 (the "License");
regarding copyright ownership. The ASF licenses this file * you may not use this file except in compliance with the License.
to you under the Apache License, Version 2.0 (the * You may obtain a copy of the License at
"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
*
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,
Unless required by applicable law or agreed to in writing, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
software distributed under the License is distributed on an * See the License for the specific language governing permissions and
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * limitations under the License.
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.net.*;
import java.io.FileInputStream; import java.io.*;
import java.io.FileOutputStream; import java.nio.channels.*;
import java.io.IOException;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.Properties; import java.util.Properties;
public class MavenWrapperDownloader { 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. * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
*/ */
private static final String DEFAULT_DOWNLOAD_URL = private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/"
"https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar"; + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar";
/** /**
* Path to the maven-wrapper.properties file, which might contain a downloadUrl property to * 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); File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
if (!outputFile.getParentFile().exists()) { if (!outputFile.getParentFile().exists()) {
if (!outputFile.getParentFile().mkdirs()) { if (!outputFile.getParentFile().mkdirs()) {
System.out.println( System.out.println(
"- ERROR creating output direcrory '" + outputFile.getParentFile().getAbsolutePath() + "'"); "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'");
} }
} }
System.out.println("- Downloading to: " + outputFile.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 { 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); URL website = new URL(urlString);
ReadableByteChannel rbc; ReadableByteChannel rbc;
rbc = Channels.newChannel(website.openStream()); 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的后端博客管理系统 ## 基于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 fi
# OS specific support. $var _must_ be set to either true or false. # OS specific support. $var _must_ be set to either true or false.
cygwin=false; cygwin=false
darwin=false; darwin=false
mingw=false mingw=false
case "`uname`" in case "$(uname)" in
CYGWIN*) cygwin=true ;; CYGWIN*) cygwin=true ;;
MINGW*) mingw=true ;; MINGW*) mingw=true ;;
Darwin*) darwin=true Darwin*)
darwin=true
# Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home # 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 # See https://developer.apple.com/library/mac/qa/qa1170/_index.html
if [ -z "$JAVA_HOME" ]; then if [ -z "$JAVA_HOME" ]; then
if [ -x "/usr/libexec/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 else
export JAVA_HOME="/Library/Java/Home" export JAVA_HOME="/Library/Java/Home"
fi fi
@@ -68,7 +69,7 @@ esac
if [ -z "$JAVA_HOME" ]; then if [ -z "$JAVA_HOME" ]; then
if [ -r /etc/gentoo-release ]; then if [ -r /etc/gentoo-release ]; then
JAVA_HOME=`java-config --jre-home` JAVA_HOME=$(java-config --jre-home)
fi fi
fi fi
@@ -78,21 +79,21 @@ if [ -z "$M2_HOME" ] ; then
# need this for relative symlinks # need this for relative symlinks
while [ -h "$PRG" ]; do while [ -h "$PRG" ]; do
ls=`ls -ld "$PRG"` ls=$(ls -ld "$PRG")
link=`expr "$ls" : '.*-> \(.*\)$'` link=$(expr "$ls" : '.*-> \(.*\)$')
if expr "$link" : '/.*' >/dev/null; then if expr "$link" : '/.*' >/dev/null; then
PRG="$link" PRG="$link"
else else
PRG="`dirname "$PRG"`/$link" PRG="$(dirname "$PRG")/$link"
fi fi
done done
saveddir=`pwd` saveddir=$(pwd)
M2_HOME=`dirname "$PRG"`/.. M2_HOME=$(dirname "$PRG")/..
# make it fully qualified # make it fully qualified
M2_HOME=`cd "$M2_HOME" && pwd` M2_HOME=$(cd "$M2_HOME" && pwd)
cd "$saveddir" cd "$saveddir"
# echo Using m2 at $M2_HOME # echo Using m2 at $M2_HOME
@@ -101,36 +102,41 @@ fi
# For Cygwin, ensure paths are in UNIX format before anything is touched # For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin; then if $cygwin; then
[ -n "$M2_HOME" ] && [ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --unix "$M2_HOME"` M2_HOME=$(cygpath --unix "$M2_HOME")
[ -n "$JAVA_HOME" ] && [ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --unix "$JAVA_HOME"` JAVA_HOME=$(cygpath --unix "$JAVA_HOME")
[ -n "$CLASSPATH" ] && [ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --unix "$CLASSPATH"` CLASSPATH=$(cygpath --path --unix "$CLASSPATH")
fi fi
# For Mingw, ensure paths are in UNIX format before anything is touched # For Mingw, ensure paths are in UNIX format before anything is touched
if $mingw; then if $mingw; then
[ -n "$M2_HOME" ] && [ -n "$M2_HOME" ] &&
M2_HOME="`(cd "$M2_HOME"; pwd)`" M2_HOME="$( (
cd "$M2_HOME"
pwd
))"
[ -n "$JAVA_HOME" ] && [ -n "$JAVA_HOME" ] &&
JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" JAVA_HOME="$( (
# TODO classpath? cd "$JAVA_HOME"
pwd
))"
fi fi
if [ -z "$JAVA_HOME" ]; then if [ -z "$JAVA_HOME" ]; then
javaExecutable="`which javac`" javaExecutable="$(which javac)"
if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then if [ -n "$javaExecutable" ] && ! [ "$(expr \"$javaExecutable\" : '\([^ ]*\)')" = "no" ]; then
# readlink(1) is not available as standard on Solaris 10. # readlink(1) is not available as standard on Solaris 10.
readLink=`which readlink` readLink=$(which readlink)
if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then if [ ! $(expr "$readLink" : '\([^ ]*\)') = "no" ]; then
if $darwin; then if $darwin; then
javaHome="`dirname \"$javaExecutable\"`" javaHome="$(dirname \"$javaExecutable\")"
javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" javaExecutable="$(cd \"$javaHome\" && pwd -P)/javac"
else else
javaExecutable="`readlink -f \"$javaExecutable\"`" javaExecutable="$(readlink -f \"$javaExecutable\")"
fi fi
javaHome="`dirname \"$javaExecutable\"`" javaHome="$(dirname \"$javaExecutable\")"
javaHome=`expr "$javaHome" : '\(.*\)/bin'` javaHome=$(expr "$javaHome" : '\(.*\)/bin')
JAVA_HOME="$javaHome" JAVA_HOME="$javaHome"
export JAVA_HOME export JAVA_HOME
fi fi
@@ -146,7 +152,7 @@ if [ -z "$JAVACMD" ] ; then
JAVACMD="$JAVA_HOME/bin/java" JAVACMD="$JAVA_HOME/bin/java"
fi fi
else else
JAVACMD="`which java`" JAVACMD="$(which java)"
fi fi
fi fi
@@ -166,8 +172,7 @@ CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
# first directory with .mvn subdirectory is considered project base directory # first directory with .mvn subdirectory is considered project base directory
find_maven_basedir() { find_maven_basedir() {
if [ -z "$1" ] if [ -z "$1" ]; then
then
echo "Path not specified to find_maven_basedir" echo "Path not specified to find_maven_basedir"
return 1 return 1
fi fi
@@ -181,7 +186,10 @@ find_maven_basedir() {
fi fi
# workaround for JBEAP-8937 (on Solaris 10/Sparc) # workaround for JBEAP-8937 (on Solaris 10/Sparc)
if [ -d "${wdir}" ]; then if [ -d "${wdir}" ]; then
wdir=`cd "$wdir/.."; pwd` wdir=$(
cd "$wdir/.."
pwd
)
fi fi
# end of workaround # end of workaround
done done
@@ -195,9 +203,9 @@ concat_lines() {
fi fi
} }
BASE_DIR=`find_maven_basedir "$(pwd)"` BASE_DIR=$(find_maven_basedir "$(pwd)")
if [ -z "$BASE_DIR" ]; then if [ -z "$BASE_DIR" ]; then
exit 1; exit 1
fi fi
########################################################################################## ##########################################################################################
@@ -212,31 +220,54 @@ else
if [ "$MVNW_VERBOSE" = true ]; then if [ "$MVNW_VERBOSE" = true ]; then
echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
fi 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 while IFS="=" read key value; do
case "$key" in (wrapperUrl) jarUrl="$value"; break ;; case "$key" in wrapperUrl)
jarUrl="$value"
break
;;
esac esac
done <"$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" done <"$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
if [ "$MVNW_VERBOSE" = true ]; then if [ "$MVNW_VERBOSE" = true ]; then
echo "Downloading from: $jarUrl" echo "Downloading from: $jarUrl"
fi fi
wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" 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 command -v wget >/dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then if [ "$MVNW_VERBOSE" = true ]; then
echo "Found wget ... using wget" echo "Found wget ... using wget"
fi fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
wget "$jarUrl" -O "$wrapperJarPath" 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 elif command -v curl >/dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then if [ "$MVNW_VERBOSE" = true ]; then
echo "Found curl ... using curl" echo "Found curl ... using curl"
fi 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 else
if [ "$MVNW_VERBOSE" = true ]; then if [ "$MVNW_VERBOSE" = true ]; then
echo "Falling back to using Java to download" echo "Falling back to using Java to download"
fi fi
javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" 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 "$javaClass" ]; then
if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
if [ "$MVNW_VERBOSE" = true ]; 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 # For Cygwin, switch paths to Windows format before running java
if $cygwin; then if $cygwin; then
[ -n "$M2_HOME" ] && [ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --path --windows "$M2_HOME"` M2_HOME=$(cygpath --path --windows "$M2_HOME")
[ -n "$JAVA_HOME" ] && [ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` JAVA_HOME=$(cygpath --path --windows "$JAVA_HOME")
[ -n "$CLASSPATH" ] && [ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --windows "$CLASSPATH"` CLASSPATH=$(cygpath --path --windows "$CLASSPATH")
[ -n "$MAVEN_PROJECTBASEDIR" ] && [ -n "$MAVEN_PROJECTBASEDIR" ] &&
MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` MAVEN_PROJECTBASEDIR=$(cygpath --path --windows "$MAVEN_PROJECTBASEDIR")
fi 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 WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
exec "$JAVACMD" \ exec "$JAVACMD" \

29
mvnw.cmd vendored
View File

@@ -37,7 +37,7 @@
@echo off @echo off
@REM set title of command window @REM set title of command window
title %0 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% @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME @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_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 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" 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 (
FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
) )
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central @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. @REM This allows using the maven wrapper in projects that prohibit checking in binary data.
if exist %WRAPPER_JAR% ( if exist %WRAPPER_JAR% (
if "%MVNW_VERBOSE%" == "true" (
echo Found %WRAPPER_JAR% echo Found %WRAPPER_JAR%
)
) else ( ) 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 Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %DOWNLOAD_URL% 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% echo Finished downloading %WRAPPER_JAR%
) )
)
@REM End of extension @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% %* %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 if ERRORLEVEL 1 goto error
goto end goto end

20
pom.xml
View File

@@ -156,6 +156,26 @@
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId> <artifactId>spring-boot-maven-plugin</artifactId>
</plugin> </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> </plugins>
</build> </build>

View File

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

View File

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

View File

@@ -10,6 +10,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
@@ -41,12 +42,16 @@ public class AuthenticationFilter implements HandlerInterceptor {
path = path.replaceAll("/+", "/"); path = path.replaceAll("/+", "/");
int indexOf = path.indexOf("/", 1); int indexOf = path.indexOf("/", 1);
String rootPath = indexOf == -1 ? path : path.substring(0, indexOf); 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())) { if (!USER_PREFIX.equals(rootPath.toLowerCase()) && !ADMIN_PREFIX.equals(rootPath.toLowerCase())) {
return true; return true;
} }
String jwtStr = request.getHeader("Authorization");
if (jwtStr == null || jwtStr.isEmpty()) { if (jwtStr == null || jwtStr.isEmpty()) {
return writeResponse(ResponseEnum.HAVE_NOT_LOG_IN, response, request); 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); return writeResponse(ResponseEnum.LOGIN_EXPIRED, response, request);
} }
String role = userService.getUserRoleByEmail(email); 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)) { if (role.equals(ROLE_ADMIN)) {
// admin // admin
return true; return true;

View File

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

View File

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

View File

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

View File

@@ -6,9 +6,11 @@ import cn.celess.blog.entity.model.QiniuResponse;
import cn.celess.blog.exception.MyException; import cn.celess.blog.exception.MyException;
import cn.celess.blog.service.CountService; import cn.celess.blog.service.CountService;
import cn.celess.blog.service.QiniuService; import cn.celess.blog.service.QiniuService;
import cn.celess.blog.util.HttpUtil;
import cn.celess.blog.util.RedisUtil; import cn.celess.blog.util.RedisUtil;
import cn.celess.blog.util.ResponseUtil; import cn.celess.blog.util.ResponseUtil;
import cn.celess.blog.util.VeriCodeUtil; import cn.celess.blog.util.VeriCodeUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject; import net.sf.json.JSONObject;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@@ -21,8 +23,10 @@ import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage; import java.awt.image.BufferedImage;
import java.io.IOException; import java.io.*;
import java.io.OutputStream; import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration; import java.util.Enumeration;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
@@ -70,7 +74,8 @@ public class Other {
Map<String, Object> map = new HashMap<>(); Map<String, Object> map = new HashMap<>();
Enumeration<String> headerNames = request.getHeaderNames(); Enumeration<String> headerNames = request.getHeaderNames();
String str = null; String str = null;
while ((str = headerNames.nextElement()) != null) { while (headerNames.hasMoreElements()) {
str = headerNames.nextElement();
map.put(str, request.getHeader(str)); map.put(str, request.getHeader(str));
} }
map.put("sessionID", request.getSession().getId()); map.put("sessionID", request.getSession().getId());
@@ -158,7 +163,7 @@ public class Other {
if (".png".equals(mime.toLowerCase()) || ".jpg".equals(mime.toLowerCase()) || if (".png".equals(mime.toLowerCase()) || ".jpg".equals(mime.toLowerCase()) ||
".jpeg".equals(mime.toLowerCase()) || ".bmp".equals(mime.toLowerCase())) { ".jpeg".equals(mime.toLowerCase()) || ".bmp".equals(mime.toLowerCase())) {
QiniuResponse qiniuResponse = qiniuService.uploadFile(file.getInputStream(), "img_" + System.currentTimeMillis() + mime); QiniuResponse qiniuResponse = qiniuService.uploadFile(file.getInputStream(), "img_" + System.currentTimeMillis() + mime);
jsonObject.put("success", 0); jsonObject.put("success", 1);
jsonObject.put("message", "上传成功"); jsonObject.put("message", "上传成功");
jsonObject.put("url", "http://cdn.celess.cn/" + qiniuResponse.key); jsonObject.put("url", "http://cdn.celess.cn/" + qiniuResponse.key);
response.getWriter().println(jsonObject.toString()); response.getWriter().println(jsonObject.toString());
@@ -169,4 +174,18 @@ public class Other {
jsonObject.put("message", "上传失败,请上传图片文件"); jsonObject.put("message", "上传失败,请上传图片文件");
response.getWriter().println(jsonObject.toString()); 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.Response;
import cn.celess.blog.entity.Tag; import cn.celess.blog.entity.Tag;
import cn.celess.blog.entity.model.TagModel;
import cn.celess.blog.service.TagService; import cn.celess.blog.service.TagService;
import cn.celess.blog.util.ResponseUtil; import cn.celess.blog.util.ResponseUtil;
import net.sf.json.JSONObject; import net.sf.json.JSONObject;
@@ -56,12 +57,11 @@ public class TagController {
@GetMapping("/tags/nac") @GetMapping("/tags/nac")
public Response getTagNameAndCount() { public Response getTagNameAndCount() {
List<JSONObject> nameAndCount = new ArrayList<>(); List<JSONObject> nameAndCount = new ArrayList<>();
List<Tag> all = tagService.findAll(); List<TagModel> all = tagService.findAll();
for (Tag t : all) { for (TagModel t : all) {
JSONObject jsonObject = new JSONObject(); JSONObject jsonObject = new JSONObject();
jsonObject.put("name", t.getName()); jsonObject.put("name", t.getName());
String articles = t.getArticles(); jsonObject.put("size", t.getArticles() == null ? 0 : t.getArticles().size());
jsonObject.put("size", articles == null ? 0 : articles.split(",").length);
nameAndCount.add(jsonObject); nameAndCount.add(jsonObject);
} }
return ResponseUtil.success(nameAndCount); return ResponseUtil.success(nameAndCount);

View File

@@ -93,6 +93,14 @@ public class UserController {
return ResponseUtil.success(userService.reSetPwd(verifyId, email, pwd)); 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") @DeleteMapping("/admin/user/delete")
public Response multipleDelete(@RequestBody Integer[] ids) { public Response multipleDelete(@RequestBody Integer[] ids) {
return ResponseUtil.success(userService.deleteUser(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) { public Response page(@RequestParam("page") int page, @RequestParam("count") int count) {
return ResponseUtil.success(webUpdateInfoService.pages(count, page)); return ResponseUtil.success(webUpdateInfoService.pages(count, page));
} }
@GetMapping("/lastestUpdateTime") @GetMapping("/lastestUpdate")
public Response lastestUpdateTime() { public Response lastestUpdateTime() {
return ResponseUtil.success(webUpdateInfoService.getLastestUpdateTime()); return ResponseUtil.success(webUpdateInfoService.getLastestUpdateTime());
} }

View File

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

View File

@@ -1,6 +1,7 @@
package cn.celess.blog.service; package cn.celess.blog.service;
import cn.celess.blog.entity.Category; import cn.celess.blog.entity.Category;
import cn.celess.blog.entity.model.CategoryModel;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.util.List; import java.util.List;
@@ -17,7 +18,7 @@ public interface CategoryService {
* @param name 分类名 * @param name 分类名
* @return 所增加的分类数据 * @return 所增加的分类数据
*/ */
Category create(String name); CategoryModel create(String name);
/** /**
* 增加一个分类 * 增加一个分类
@@ -25,7 +26,7 @@ public interface CategoryService {
* @param category 分类对象 * @param category 分类对象
* @return 所增加的分类数据 * @return 所增加的分类数据
*/ */
Category create(Category category); CategoryModel create(Category category);
/** /**
* 通过id删除分类 * 通过id删除分类
@@ -42,13 +43,13 @@ public interface CategoryService {
* @param name 分类名字 * @param name 分类名字
* @return 更新后的分类的数据 * @return 更新后的分类的数据
*/ */
Category update(Long id, String name); CategoryModel update(Long id, String name);
/** /**
* 获取全部的分类数据 * 获取全部的分类数据
* *
* @return 全部的分类数据 * @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 com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.util.List;
/** /**
* @author : xiaohai * @author : xiaohai
* @date : 2019/03/29 16:58 * @date : 2019/03/29 16:58
@@ -49,11 +51,9 @@ public interface CommentService {
* 通过pid获取数据 * 通过pid获取数据
* *
* @param pid 父id * @param pid 父id
* @param count 单页数据量
* @param page 数据页
* @return 分页数据 * @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; package cn.celess.blog.service;
import cn.celess.blog.entity.Tag; import cn.celess.blog.entity.Tag;
import cn.celess.blog.entity.model.TagModel;
import com.github.pagehelper.PageInfo; import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@@ -18,7 +19,7 @@ public interface TagService {
* @param name 标签名 * @param name 标签名
* @return 新增后的数据 * @return 新增后的数据
*/ */
Tag create(String name); TagModel create(String name);
/** /**
* 新增数据 * 新增数据
@@ -27,7 +28,7 @@ public interface TagService {
* @return 新增后的数据 * @return 新增后的数据
*/ */
Tag create(Tag tag); TagModel create(Tag tag);
/** /**
* 删除数据 * 删除数据
@@ -44,7 +45,7 @@ public interface TagService {
* @param name 改名的name值 * @param name 改名的name值
* @return 更新后的数据 * @return 更新后的数据
*/ */
Tag update(Long id, String name); TagModel update(Long id, String name);
/** /**
* 查询单个标签信息 * 查询单个标签信息
@@ -52,7 +53,7 @@ public interface TagService {
* @param tagId id * @param tagId id
* @return 标签的数据 * @return 标签的数据
*/ */
Tag retrieveOneById(long tagId); TagModel retrieveOneById(long tagId);
/** /**
* 通过name查询标签的信息 * 通过name查询标签的信息
@@ -60,7 +61,7 @@ public interface TagService {
* @param name tag的名称 * @param name tag的名称
* @return 标签数据 * @return 标签数据
*/ */
Tag retrieveOneByName(String name); TagModel retrieveOneByName(String name);
/** /**
@@ -70,13 +71,13 @@ public interface TagService {
* @param page 数据页 * @param page 数据页
* @return 分页数据 * @return 分页数据
*/ */
PageInfo<Tag> retrievePage(int page, int count); PageInfo<TagModel> retrievePage(int page, int count);
/** /**
* 获取全部标签数据 * 获取全部标签数据
* *
* @return 标签数据列表 * @return 标签数据列表
*/ */
List<Tag> findAll(); List<TagModel> findAll();
} }

View File

@@ -174,4 +174,13 @@ public interface UserService {
* @return true:存在 false不存在 * @return true:存在 false不存在
*/ */
boolean getStatusOfEmail(String email); 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 cn.celess.blog.entity.model.WebUpdateModel;
import com.github.pagehelper.PageInfo; import com.github.pagehelper.PageInfo;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.util.List; import java.util.List;
@@ -58,5 +59,5 @@ public interface WebUpdateInfoService {
* *
* @return * @return
*/ */
String getLastestUpdateTime(); JSONObject getLastestUpdateTime();
} }

View File

@@ -92,7 +92,7 @@ public class ArticleServiceImpl implements ArticleService {
article.setUrl(reqBody.getUrl()); article.setUrl(reqBody.getUrl());
article.setType(reqBody.getType()); article.setType(reqBody.getType());
article.setAuthorId(redisUserUtil.get(request).getId()); article.setAuthorId(redisUserUtil.get().getId());
article.setPublishDate(new Date()); article.setPublishDate(new Date());
//防止出现 “null,xxx”这种情况 //防止出现 “null,xxx”这种情况
@@ -198,7 +198,7 @@ public class ArticleServiceImpl implements ArticleService {
Article nextArticle = articleMapper.findArticleById(articleForDel.getNextArticleId()); 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())) { if (!user.getRole().contains("admin") && !articleForDel.getAuthorId().equals(user.getId())) {
throw new MyException(ResponseEnum.PERMISSION_ERROR); throw new MyException(ResponseEnum.PERMISSION_ERROR);
} }
@@ -278,9 +278,9 @@ public class ArticleServiceImpl implements ArticleService {
throw new MyException(ResponseEnum.PARAMETERS_ERROR); throw new MyException(ResponseEnum.PARAMETERS_ERROR);
} }
// 暂时不更新tags // 暂时不更新tags
// if (reqBody.getTags() == null || reqBody.getTags().replaceAll(" ", "").isEmpty()) { if (reqBody.getTags() == null || reqBody.getTags().replaceAll(" ", "").isEmpty()) {
// throw new MyException(ResponseEnum.PARAMETERS_ERROR); throw new MyException(ResponseEnum.PARAMETERS_ERROR);
// } }
//写入数据库的数据 //写入数据库的数据
Article article = new Article(); Article article = new Article();
@@ -317,26 +317,44 @@ public class ArticleServiceImpl implements ArticleService {
article.setCategoryId(oldArticle.getCategoryId()); article.setCategoryId(oldArticle.getCategoryId());
} }
String[] newTags = reqBody.getTags().split(",");
// String[] newTags = reqBody.getTags().replaceAll(" ", "").split(","); String[] tagIds = oldArticle.getTagsId().split(",");
//防止出现 null2这种情况
// //防止出现 null2这种情况 article.setTagsId("");
// article.setTagsId(""); for (String t : newTags) {
// for (String t : newTags) { Tag tag = tagMapper.findTagByName(t);
// Tag tag = tagMapper.findTagByName(t); if (tag == null) {
// if (tag == null) { tag = new Tag();
// tag = new Tag(); tag.setName(t);
// tag.setName(t); tag.setArticles(oldArticle.getId() + ",");
// tag.setArticles(oldArticle.getId() + ","); int status = tagMapper.insert(tag);
// tag = tagMapper.save(tag); if (status == 0) {
// article.setTagsId(article.getTagsId() + tag.getId() + ","); // 插入失败
// continue; throw new MyException(ResponseEnum.FAILURE);
// } }
// article.setTagsId(article.getTagsId() + tag.getId() + ","); article.setTagsId(article.getTagsId() + tag.getId() + ",");
// } continue;
}
// TODO:::: tag的更新 article.setTagsId(article.getTagsId() + tag.getId() + ",");
article.setTagsId(oldArticle.getTagsId()); }
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()); article.setUpdateDate(new Date());
@@ -344,7 +362,7 @@ public class ArticleServiceImpl implements ArticleService {
// 设置不定参数 // 设置不定参数
article.setReadingNumber(oldArticle.getReadingNumber()); article.setReadingNumber(oldArticle.getReadingNumber());
article.setPublishDate(oldArticle.getPublishDate()); article.setPublishDate(oldArticle.getPublishDate());
article.setAuthorId(redisUserUtil.get(request).getId()); article.setAuthorId(redisUserUtil.get().getId());
article.setPreArticleId(oldArticle.getPreArticleId()); article.setPreArticleId(oldArticle.getPreArticleId());
article.setNextArticleId(oldArticle.getNextArticleId()); article.setNextArticleId(oldArticle.getNextArticleId());
String str = StringFromHtmlUtil.getString(MDTool.markdown2Html(article.getMdContent())); String str = StringFromHtmlUtil.getString(MDTool.markdown2Html(article.getMdContent()));
@@ -362,7 +380,7 @@ public class ArticleServiceImpl implements ArticleService {
throw new MyException(ResponseEnum.ARTICLE_NOT_EXIST); throw new MyException(ResponseEnum.ARTICLE_NOT_EXIST);
} }
if (!article.getOpen()) { if (!article.getOpen()) {
User user = redisUserUtil.getWithOutExc(request); User user = redisUserUtil.getWithOutExc();
if (user == null || "user".equals(user.getRole())) { if (user == null || "user".equals(user.getRole())) {
throw new MyException(ResponseEnum.ARTICLE_NOT_PUBLIC); 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.enmu.ResponseEnum;
import cn.celess.blog.entity.Article; import cn.celess.blog.entity.Article;
import cn.celess.blog.entity.Category; import cn.celess.blog.entity.Category;
import cn.celess.blog.entity.model.CategoryModel;
import cn.celess.blog.exception.MyException; import cn.celess.blog.exception.MyException;
import cn.celess.blog.mapper.ArticleMapper; import cn.celess.blog.mapper.ArticleMapper;
import cn.celess.blog.mapper.CategoryMapper; import cn.celess.blog.mapper.CategoryMapper;
@@ -11,6 +12,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List; import java.util.List;
/** /**
@@ -27,7 +29,7 @@ public class CategoryServiceImpl implements CategoryService {
ArticleMapper articleMapper; ArticleMapper articleMapper;
@Override @Override
public Category create(String name) { public CategoryModel create(String name) {
if (categoryMapper.existsByName(name)) { if (categoryMapper.existsByName(name)) {
throw new MyException(ResponseEnum.CATEGORY_HAS_EXIST); throw new MyException(ResponseEnum.CATEGORY_HAS_EXIST);
} }
@@ -35,16 +37,16 @@ public class CategoryServiceImpl implements CategoryService {
category.setName(name); category.setName(name);
category.setArticles(""); category.setArticles("");
categoryMapper.insert(category); categoryMapper.insert(category);
return category; return new CategoryModel(category);
} }
@Override @Override
public Category create(Category category) { public CategoryModel create(Category category) {
if (category == null) { if (category == null) {
throw new MyException(ResponseEnum.PARAMETERS_ERROR); throw new MyException(ResponseEnum.PARAMETERS_ERROR);
} }
categoryMapper.insert(category); categoryMapper.insert(category);
return category; return new CategoryModel(category);
} }
@Override @Override
@@ -74,18 +76,20 @@ public class CategoryServiceImpl implements CategoryService {
@Override @Override
public Category update(Long id, String name) { public CategoryModel update(Long id, String name) {
if (id == null) { if (id == null) {
throw new MyException(ResponseEnum.PARAMETERS_ERROR.getCode(), "id不可为空"); throw new MyException(ResponseEnum.PARAMETERS_ERROR.getCode(), "id不可为空");
} }
Category category = categoryMapper.findCategoryById(id); Category category = categoryMapper.findCategoryById(id);
category.setName(name); category.setName(name);
categoryMapper.update(category); categoryMapper.update(category);
return category; return new CategoryModel(category);
} }
@Override @Override
public List<Category> retrievePage() { public List<CategoryModel> retrievePage() {
return categoryMapper.findAll(); 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.service.UserService;
import cn.celess.blog.util.DateFormatUtil; import cn.celess.blog.util.DateFormatUtil;
import cn.celess.blog.util.RedisUserUtil; import cn.celess.blog.util.RedisUserUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo; import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@@ -44,7 +45,7 @@ public class CommentServiceImpl implements CommentService {
if (reqBody == null) { if (reqBody == null) {
throw new MyException(ResponseEnum.PARAMETERS_ERROR); throw new MyException(ResponseEnum.PARAMETERS_ERROR);
} }
long authorID = redisUserUtil.get(request).getId(); long authorID = redisUserUtil.get().getId();
Comment pComment = null; Comment pComment = null;
if (reqBody.getPid() != null && reqBody.getPid() != -1) { if (reqBody.getPid() != null && reqBody.getPid() != -1) {
pComment = commentMapper.findCommentById(reqBody.getPid()); pComment = commentMapper.findCommentById(reqBody.getPid());
@@ -112,45 +113,36 @@ public class CommentServiceImpl implements CommentService {
public PageInfo<CommentModel> retrievePage(Boolean isComment, int page, int count) { public PageInfo<CommentModel> retrievePage(Boolean isComment, int page, int count) {
PageHelper.startPage(page, count); PageHelper.startPage(page, count);
List<Comment> commentList = commentMapper.findAllByType(isComment); List<Comment> commentList = commentMapper.findAllByType(isComment);
PageInfo pageInfo = new PageInfo(commentList); return pageTrans(commentList);
pageInfo.setList(list2List(commentList));
return pageInfo;
} }
@Override @Override
public PageInfo<CommentModel> retrievePageByPid(long pid, int page, int count) { public List<CommentModel> retrievePageByPid(long pid) {
PageHelper.startPage(page, count);
List<Comment> commentList = commentMapper.findAllByPId(pid); List<Comment> commentList = commentMapper.findAllByPId(pid);
PageInfo pageInfo = new PageInfo(commentList); List<CommentModel> modelList = new ArrayList<>();
pageInfo.setList(list2List(commentList)); commentList.forEach(m -> modelList.add(trans(m)));
return pageInfo; return modelList;
} }
@Override @Override
public PageInfo<CommentModel> retrievePageByArticle(long articleID, long pid, int page, int count) { public PageInfo<CommentModel> retrievePageByArticle(long articleID, long pid, int page, int count) {
PageHelper.startPage(page, count); PageHelper.startPage(page, count);
List<Comment> commentList = commentMapper.findAllByArticleIDAndPId(articleID, pid); List<Comment> commentList = commentMapper.findAllByArticleIDAndPId(articleID, pid);
PageInfo pageInfo = new PageInfo(commentList); return pageTrans(commentList);
pageInfo.setList(list2List(commentList));
return pageInfo;
} }
@Override @Override
public PageInfo<CommentModel> retrievePageByTypeAndPid(Boolean isComment, int pid, int page, int count) { public PageInfo<CommentModel> retrievePageByTypeAndPid(Boolean isComment, int pid, int page, int count) {
PageHelper.startPage(page, count); PageHelper.startPage(page, count);
List<Comment> commentList = commentMapper.findCommentsByTypeAndPId(isComment, pid); List<Comment> commentList = commentMapper.findCommentsByTypeAndPId(isComment, pid);
PageInfo pageInfo = new PageInfo(commentList); return pageTrans(commentList);
pageInfo.setList(list2List(commentList));
return pageInfo;
} }
@Override @Override
public PageInfo<CommentModel> retrievePageByAuthor(Boolean isComment, int page, int count) { public PageInfo<CommentModel> retrievePageByAuthor(Boolean isComment, int page, int count) {
PageHelper.startPage(page, count); PageHelper.startPage(page, count);
List<Comment> commentList = commentMapper.findAllByAuthorIDAndType(redisUserUtil.get(request).getId(), isComment); List<Comment> commentList = commentMapper.findAllByAuthorIDAndType(redisUserUtil.get().getId(), isComment);
PageInfo pageInfo = new PageInfo(commentList); return pageTrans(commentList);
pageInfo.setList(list2List(commentList));
return pageInfo;
} }
@@ -158,17 +150,7 @@ public class CommentServiceImpl implements CommentService {
public PageInfo<CommentModel> retrievePageByType(Boolean isComment, int page, int count) { public PageInfo<CommentModel> retrievePageByType(Boolean isComment, int page, int count) {
PageHelper.startPage(page, count); PageHelper.startPage(page, count);
List<Comment> commentList = commentMapper.findAllByType(isComment); List<Comment> commentList = commentMapper.findAllByType(isComment);
PageInfo pageInfo = new PageInfo(commentList); return pageTrans(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;
} }
private CommentModel trans(Comment comment) { private CommentModel trans(Comment comment) {
@@ -189,4 +171,16 @@ public class CommentServiceImpl implements CommentService {
return commentModel; 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.UploadManager;
import com.qiniu.storage.model.FileInfo; import com.qiniu.storage.model.FileInfo;
import com.qiniu.util.Auth; import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.io.InputStream; import java.io.InputStream;
@@ -23,31 +21,29 @@ import java.io.InputStream;
*/ */
@Service @Service
public class QiniuServiceImpl implements QiniuService { public class QiniuServiceImpl implements QiniuService {
private Configuration cfg = new Configuration(Zone.zone2()); private static Configuration cfg = new Configuration(Zone.zone2());
private UploadManager uploadManager; private static UploadManager uploadManager;
private BucketManager bucketManager; private static BucketManager bucketManager;
private Auth auth; private static Auth auth;
private static String bucket; @Value("${qiniu.accessKey}")
private String accessKey;
@Value("${qiniu.secretKey}")
{ private String secretKey;
/* ***** 必填 ****** @Value("${qiniu.bucket}")
* 七牛的配置 * private String bucket;
* ***** 必填 ******
*/
// accessKeyString,secretKeyString,bucketString请替换为自己的值
String accessKey = "accessKeyString";
String secretKey = "secretKeyString";
bucket = "bucketString";
private void init() {
if (auth == null || uploadManager == null || bucketManager == null) {
auth = Auth.create(accessKey, secretKey); auth = Auth.create(accessKey, secretKey);
uploadManager = new UploadManager(cfg); uploadManager = new UploadManager(cfg);
bucketManager = new BucketManager(auth, cfg); bucketManager = new BucketManager(auth, cfg);
} }
}
@Override @Override
public QiniuResponse uploadFile(InputStream is, String fileName) { public QiniuResponse uploadFile(InputStream is, String fileName) {
init();
//文件存在则删除文件 //文件存在则删除文件
if (continueFile(fileName)) { if (continueFile(fileName)) {
try { try {
@@ -69,6 +65,7 @@ public class QiniuServiceImpl implements QiniuService {
@Override @Override
public FileInfo[] getFileList() { public FileInfo[] getFileList() {
init();
BucketManager.FileListIterator fileListIterator = bucketManager.createFileListIterator(bucket, "", 1000, ""); BucketManager.FileListIterator fileListIterator = bucketManager.createFileListIterator(bucket, "", 1000, "");
FileInfo[] items = null; FileInfo[] items = null;
while (fileListIterator.hasNext()) { 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.enmu.ResponseEnum;
import cn.celess.blog.entity.Article; import cn.celess.blog.entity.Article;
import cn.celess.blog.entity.Tag; import cn.celess.blog.entity.Tag;
import cn.celess.blog.entity.model.TagModel;
import cn.celess.blog.exception.MyException; import cn.celess.blog.exception.MyException;
import cn.celess.blog.mapper.ArticleMapper; import cn.celess.blog.mapper.ArticleMapper;
import cn.celess.blog.mapper.TagMapper; import cn.celess.blog.mapper.TagMapper;
@@ -13,6 +14,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List; import java.util.List;
/** /**
@@ -29,7 +31,7 @@ public class TagServiceImpl implements TagService {
ArticleMapper articleMapper; ArticleMapper articleMapper;
@Override @Override
public Tag create(String name) { public TagModel create(String name) {
boolean b = tagMapper.existsByName(name); boolean b = tagMapper.existsByName(name);
if (b) { if (b) {
throw new MyException(ResponseEnum.TAG_HAS_EXIST); throw new MyException(ResponseEnum.TAG_HAS_EXIST);
@@ -37,16 +39,16 @@ public class TagServiceImpl implements TagService {
Tag tag = new Tag(); Tag tag = new Tag();
tag.setName(name); tag.setName(name);
tagMapper.insert(tag); tagMapper.insert(tag);
return tag; return new TagModel(tag);
} }
@Override @Override
public Tag create(Tag tag) { public TagModel create(Tag tag) {
if (tag == null) { if (tag == null) {
throw new MyException(ResponseEnum.PARAMETERS_ERROR); throw new MyException(ResponseEnum.PARAMETERS_ERROR);
} }
tagMapper.insert(tag); tagMapper.insert(tag);
return tag; return new TagModel(tag);
} }
@Override @Override
@@ -60,7 +62,7 @@ public class TagServiceImpl implements TagService {
} }
String[] articleArray = tag.getArticles().split(","); String[] articleArray = tag.getArticles().split(",");
for (int i = 0; i < articleArray.length; i++) { for (int i = 0; i < articleArray.length; i++) {
if (articleArray[i] == null || "".equals(articleArray)) { if (articleArray[i] == null || "".equals(articleArray[i])) {
continue; continue;
} }
long articleID = Long.parseLong(articleArray[i]); long articleID = Long.parseLong(articleArray[i]);
@@ -76,7 +78,7 @@ public class TagServiceImpl implements TagService {
@Override @Override
public Tag update(Long id,String name) { public TagModel update(Long id, String name) {
if (id == null) { if (id == null) {
throw new MyException(ResponseEnum.PARAMETERS_ERROR.getCode(), "缺少ID"); throw new MyException(ResponseEnum.PARAMETERS_ERROR.getCode(), "缺少ID");
} }
@@ -84,37 +86,43 @@ public class TagServiceImpl implements TagService {
tagFromDB.setName(name); tagFromDB.setName(name);
tagMapper.update(tagFromDB); tagMapper.update(tagFromDB);
return tagFromDB; return new TagModel(tagFromDB);
} }
@Override @Override
public Tag retrieveOneById(long tagId) { public TagModel retrieveOneById(long tagId) {
Tag tag = tagMapper.findTagById(tagId); Tag tag = tagMapper.findTagById(tagId);
if (tag == null) { if (tag == null) {
throw new MyException(ResponseEnum.TAG_NOT_EXIST); throw new MyException(ResponseEnum.TAG_NOT_EXIST);
} }
return tag; return new TagModel(tag);
} }
@Override @Override
public Tag retrieveOneByName(String name) { public TagModel retrieveOneByName(String name) {
Tag tag = tagMapper.findTagByName(name); Tag tag = tagMapper.findTagByName(name);
if (tag == null) { if (tag == null) {
throw new MyException(ResponseEnum.TAG_NOT_EXIST); throw new MyException(ResponseEnum.TAG_NOT_EXIST);
} }
return tag; return new TagModel(tag);
} }
@Override @Override
public PageInfo<Tag> retrievePage(int page, int count) { public PageInfo<TagModel> retrievePage(int page, int count) {
PageHelper.startPage(page, 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; return pageInfo;
} }
@Override @Override
public List<Tag> findAll() { public List<TagModel> findAll() {
return tagMapper.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()); userMapper.updateLoginTime(loginReq.getEmail(), new Date());
redisUtil.delete(loginReq.getEmail() + "-passwordWrongTime"); redisUtil.delete(loginReq.getEmail() + "-passwordWrongTime");
// redis 标记 // redis 标记
redisUtil.setEx(loginReq.getEmail() + "-login", JSONObject.fromObject(user).toString(), redisUserUtil.set(user, loginReq.getIsRememberMe());
(loginReq.getIsRememberMe() ? JwtUtil.EXPIRATION_LONG_TIME : JwtUtil.EXPIRATION_SHORT_TIME), TimeUnit.MILLISECONDS);
token = jwtUtil.generateToken(user, loginReq.getIsRememberMe()); token = jwtUtil.generateToken(user, loginReq.getIsRememberMe());
} else { } else {
logger.info("====> {} 进行权限认证 状态:登录失败 <====", loginReq.getEmail()); logger.info("====> {} 进行权限认证 状态:登录失败 <====", loginReq.getEmail());
@@ -159,7 +158,7 @@ public class UserServiceImpl implements UserService {
@Override @Override
public UserModel update(String desc, String displayName) { public UserModel update(String desc, String displayName) {
User user = redisUserUtil.get(request); User user = redisUserUtil.get();
user.setDesc(desc); user.setDesc(desc);
user.setDisplayName(displayName); user.setDisplayName(displayName);
@@ -193,7 +192,7 @@ public class UserServiceImpl implements UserService {
@Override @Override
public Object updateUserAavatarImg(InputStream is, String mime) { 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()); QiniuResponse upload = qiniuService.uploadFile(is, user.getEmail() + "_" + user.getId() + mime.toLowerCase());
user.setAvatarImgUrl(upload.key); user.setAvatarImgUrl(upload.key);
userMapper.updateAvatarImgUrl(upload.key, user.getId()); userMapper.updateAvatarImgUrl(upload.key, user.getId());
@@ -203,7 +202,7 @@ public class UserServiceImpl implements UserService {
@Override @Override
public UserModel getUserInfoBySession() { public UserModel getUserInfoBySession() {
User user = redisUserUtil.get(request); User user = redisUserUtil.get();
return trans(user); return trans(user);
} }
@@ -422,7 +421,7 @@ public class UserServiceImpl implements UserService {
if (updateResult == 0) { if (updateResult == 0) {
throw new MyException(ResponseEnum.FAILURE); throw new MyException(ResponseEnum.FAILURE);
} }
if (redisUserUtil.get(request).getId().equals(userReq.getId())) { if (redisUserUtil.get().getId().equals(userReq.getId())) {
redisUserUtil.set(user); redisUserUtil.set(user);
} }
logger.info("修改了用户 [id={}] 的用户的资料", userReq.getId()); logger.info("修改了用户 [id={}] 的用户的资料", userReq.getId());
@@ -434,6 +433,20 @@ public class UserServiceImpl implements UserService {
return userMapper.existsByEmail(email); 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) { private UserModel trans(User u) {
UserModel user = new UserModel(); UserModel user = new UserModel();
user.setId(u.getId()); 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.mapper.WebUpdateInfoMapper;
import cn.celess.blog.service.WebUpdateInfoService; import cn.celess.blog.service.WebUpdateInfoService;
import cn.celess.blog.util.DateFormatUtil; import cn.celess.blog.util.DateFormatUtil;
import cn.celess.blog.util.HttpUtil;
import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo; 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.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
@@ -21,6 +28,7 @@ import java.util.List;
* @date : 2019/05/12 11:43 * @date : 2019/05/12 11:43
*/ */
@Service @Service
@Slf4j
public class WebUpdateInfoServiceImpl implements WebUpdateInfoService { public class WebUpdateInfoServiceImpl implements WebUpdateInfoService {
@Autowired @Autowired
WebUpdateInfoMapper webUpdateInfoMapper; WebUpdateInfoMapper webUpdateInfoMapper;
@@ -80,8 +88,24 @@ public class WebUpdateInfoServiceImpl implements WebUpdateInfoService {
} }
@Override @Override
public String getLastestUpdateTime() { public JSONObject getLastestUpdateTime() {
return DateFormatUtil.get(webUpdateInfoMapper.getLastestOne()); 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) { 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; package cn.celess.blog.util;
import cn.celess.blog.enmu.ResponseEnum;
import cn.celess.blog.entity.User; import cn.celess.blog.entity.User;
import io.jsonwebtoken.Claims; import cn.celess.blog.exception.MyException;
import io.jsonwebtoken.ExpiredJwtException; import io.jsonwebtoken.*;
import io.jsonwebtoken.Jwts; import lombok.extern.log4j.Log4j2;
import io.jsonwebtoken.SignatureAlgorithm; import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import java.time.Instant; import java.time.Instant;
@@ -18,6 +19,7 @@ import java.util.Map;
* @Description: JWT工具类 * @Description: JWT工具类
*/ */
@Component @Component
@Log4j2
public class JwtUtil { public class JwtUtil {
private static final String CLAIM_KEY_USERNAME = "sub"; private static final String CLAIM_KEY_USERNAME = "sub";
@@ -33,8 +35,8 @@ public class JwtUtil {
/** /**
* JWT 秘钥需自行设置不可泄露 * JWT 秘钥需自行设置不可泄露
*/ */
private static final String SECRET = "xxx"; @Value("${jwt.secret}")
private String SECRET;
public String generateToken(User user, boolean isRemember) { public String generateToken(User user, boolean isRemember) {
Map<String, Object> claims = new HashMap<>(16); Map<String, Object> claims = new HashMap<>(16);
@@ -47,46 +49,63 @@ public class JwtUtil {
.compact(); .compact();
} }
public Boolean validateToken(String token, User user) { public String updateTokenDate(String token) {
String username = getUsernameFromToken(token); Claims claims = Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token).getBody();
return Jwts.builder()
return (username.equals(user.getEmail()) && !isTokenExpired(token)); .setClaims(claims)
.setExpiration(new Date(claims.getExpiration().getTime() + EXPIRATION_SHORT_TIME))
.signWith(SignatureAlgorithm.HS512, SECRET)
.compact();
} }
/** /**
* 获取token是否过期 * 获取token是否过期
*/ */
public Boolean isTokenExpired(String token) { public Boolean isTokenExpired(String token) {
try {
Date expiration = getExpirationDateFromToken(token); Date expiration = getExpirationDateFromToken(token);
return expiration.before(new Date()); return expiration == null || expiration.before(new Date());
} catch (ExpiredJwtException e) {
return true;
}
} }
/** /**
* 根据token获取username * 根据token获取username
*/ */
public String getUsernameFromToken(String token) { public String getUsernameFromToken(String token) {
return getClaimsFromToken(token).getSubject(); Claims claims = getClaimsFromToken(token);
return claims == null ? null : claims.getSubject();
} }
/** /**
* 获取token的过期时间 * 获取token的过期时间
*/ */
public Date getExpirationDateFromToken(String token) { public Date getExpirationDateFromToken(String token) {
return getClaimsFromToken(token).getExpiration(); Claims claims = getClaimsFromToken(token);
return claims == null ? null : claims.getExpiration();
} }
/** /**
* 解析JWT * 解析JWT
*/ */
private Claims getClaimsFromToken(String token) { private Claims getClaimsFromToken(String token) {
Claims claims = Jwts.parser() Claims claims = null;
try {
claims = Jwts.parser()
.setSigningKey(SECRET) .setSigningKey(SECRET)
.parseClaimsJws(token) .parseClaimsJws(token)
.getBody(); .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; return claims;
} }

View File

@@ -20,16 +20,18 @@ public class RedisUserUtil {
RedisUtil redisUtil; RedisUtil redisUtil;
@Autowired @Autowired
JwtUtil jwtUtil; JwtUtil jwtUtil;
@Autowired
HttpServletRequest request;
public User get(HttpServletRequest request) { public User get() {
User user = getWithOutExc(request); User user = getWithOutExc();
if (user == null) { if (user == null) {
throw new MyException(ResponseEnum.HAVE_NOT_LOG_IN); throw new MyException(ResponseEnum.HAVE_NOT_LOG_IN);
} }
return user; return user;
} }
public User getWithOutExc(HttpServletRequest request) { public User getWithOutExc() {
String token = request.getHeader("Authorization"); String token = request.getHeader("Authorization");
if (token == null || token.isEmpty()) { if (token == null || token.isEmpty()) {
return null; return null;
@@ -39,8 +41,16 @@ public class RedisUserUtil {
} }
public User set(User user) { public User set(User user) {
Long expire = redisUtil.getExpire(user.getEmail() + "-login");
redisUtil.setEx(user.getEmail() + "-login", JSONObject.fromObject(user).toString(), 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; return user;
} }
} }

View File

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

View File

@@ -1,5 +1,14 @@
server.port=8081 server.port=8081
# 七牛的密钥配置
qiniu.accessKey=
qiniu.secretKey=
qiniu.bucket=
# sitemap 存放地址
sitemap.path=
# 生成JWT时候的密钥
jwt.secret=
spring.jpa.show-sql=false spring.jpa.show-sql=false
spring.jpa.hibernate.ddl-auto=update 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 ####cn.celess.blog.service.serviceimpl.QiniuServiceImpl
logging.level.cn.celess.blog=debug logging.level.cn.celess.blog=debug
logging.level.cn.celess.blog.mapper=info logging.level.cn.celess.blog.mapper=info
## 修改openSource 添加-test 文件用于测试 -prod文件用于线上发布

View File

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

View File

@@ -8,10 +8,12 @@ import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc; 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.ResultHandler;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers; import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
@@ -20,6 +22,8 @@ import org.springframework.web.context.WebApplicationContext;
import javax.servlet.http.Cookie; import javax.servlet.http.Cookie;
import java.util.UUID;
import static org.junit.Assert.*; import static org.junit.Assert.*;
/** /**
@@ -39,10 +43,12 @@ public class BaseTest {
@Autowired @Autowired
private WebApplicationContext wac; private WebApplicationContext wac;
protected MockHttpSession session;
@Before @Before
public void before() { public void before() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
session = new MockHttpSession();
System.out.println("==========> 开始测试 <========="); System.out.println("==========> 开始测试 <=========");
} }
@@ -94,4 +100,8 @@ public class BaseTest {
public void test() { 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 org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import java.util.Arrays; import java.util.*;
import java.util.UUID;
import static org.junit.Assert.*; import static org.junit.Assert.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
@@ -139,32 +138,17 @@ public class ArticleControllerTest extends BaseTest {
articleReq.setCategory("test"); articleReq.setCategory("test");
articleReq.setMdContent("test-" + article.getMdContent()); articleReq.setMdContent("test-" + article.getMdContent());
articleReq.setOpen(!article.getOpen()); 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()); articleReq.setTitle("test-" + article.getTitle());
try { 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 权限 // Admin 权限
token = adminLogin();
mockMvc.perform(put("/admin/article/update") mockMvc.perform(put("/admin/article/update")
.content(JSONObject.fromObject(articleReq).toString()) .content(JSONObject.fromObject(articleReq).toString())
.contentType("application/json") .contentType("application/json")
.header("Authorization", token)) .header("Authorization", adminLogin()))
.andExpect(status().isOk()) .andExpect(status().isOk())
.andDo(result -> { .andDo(result -> {
JSONObject jsonObject = JSONObject.fromObject(result.getResponse().getContentAsString()); JSONObject jsonObject = JSONObject.fromObject(result.getResponse().getContentAsString());
@@ -175,8 +159,11 @@ public class ArticleControllerTest extends BaseTest {
assertEquals(articleReq.getMdContent(), a.getMdContent()); assertEquals(articleReq.getMdContent(), a.getMdContent());
assertEquals(articleReq.getTitle(), a.getTitle()); assertEquals(articleReq.getTitle(), a.getTitle());
assertEquals(articleReq.getType(), a.getOriginal()); assertEquals(articleReq.getType(), a.getOriginal());
// Tag 暂时不支持更新 // Tag
// assertEquals(articleReq.getTags(), Arrays.toString(a.getTags()).replaceAll(" ", "".replace("[", "".replace("]", "")))); 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.getOpen(), a.getOpen());
assertEquals(articleReq.getId(), a.getId()); 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.BaseTest;
import cn.celess.blog.entity.Category; import cn.celess.blog.entity.Category;
import cn.celess.blog.entity.model.CategoryModel;
import cn.celess.blog.mapper.CategoryMapper; import cn.celess.blog.mapper.CategoryMapper;
import net.sf.json.JSONArray; import net.sf.json.JSONArray;
import net.sf.json.JSONObject; import net.sf.json.JSONObject;
@@ -45,10 +46,10 @@ public class CategoryControllerTest extends BaseTest {
.andDo(result -> { .andDo(result -> {
JSONObject object = JSONObject.fromObject(result.getResponse().getContentAsString()); JSONObject object = JSONObject.fromObject(result.getResponse().getContentAsString());
assertEquals(SUCCESS.getCode(), object.getInt(Code)); 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()); assertEquals(categoryName, category.getName());
assertNotNull(category.getId()); assertNotNull(category.getId());
assertNotNull(category.getArticles()); assertNotEquals(0, category.getArticles());
}); });
} }
@@ -105,9 +106,9 @@ public class CategoryControllerTest extends BaseTest {
.andDo(result -> { .andDo(result -> {
JSONObject object = JSONObject.fromObject(result.getResponse().getContentAsString()); JSONObject object = JSONObject.fromObject(result.getResponse().getContentAsString());
assertEquals(SUCCESS.getCode(), object.getInt(Code)); 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()); assertEquals(name, c.getName());
assertNotNull(c.getArticles()); assertNotEquals(0, c.getArticles());
assertNotNull(c.getId()); assertNotNull(c.getId());
}); });
} }
@@ -121,10 +122,10 @@ public class CategoryControllerTest extends BaseTest {
JSONArray jsonArray = object.getJSONArray(Result); JSONArray jsonArray = object.getJSONArray(Result);
assertNotNull(jsonArray); assertNotNull(jsonArray);
jsonArray.forEach(o -> { 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.getName());
assertNotNull(c.getId()); 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.CommentMapper;
import cn.celess.blog.mapper.UserMapper; import cn.celess.blog.mapper.UserMapper;
import com.github.pagehelper.PageInfo; import com.github.pagehelper.PageInfo;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject; import net.sf.json.JSONObject;
import org.junit.Test; import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@@ -198,22 +199,17 @@ public class CommentControllerTest extends BaseTest {
@Test @Test
public void retrievePage() throws Exception { public void retrievePage() throws Exception {
long pid = 17; long pid = -1;
mockMvc.perform(get("/comment/pid/" + pid + "?articleId=3&page=1&count=10")).andDo(result -> { mockMvc.perform(get("/comment/pid/" + pid)).andDo(result -> {
JSONObject object = JSONObject.fromObject(result.getResponse().getContentAsString()); JSONObject object = JSONObject.fromObject(result.getResponse().getContentAsString());
assertEquals(SUCCESS.getCode(), object.getInt(Code)); assertEquals(SUCCESS.getCode(), object.getInt(Code));
PageInfo pageInfo = (PageInfo) JSONObject.toBean(object.getJSONObject(Result), PageInfo.class); JSONArray jsonArray = object.getJSONArray(Result);
assertNotEquals(0, pageInfo.getStartRow()); assertNotEquals(0, jsonArray.size());
assertNotEquals(0, pageInfo.getEndRow()); jsonArray.forEach(o -> {
assertEquals(1, pageInfo.getPageNum());
assertEquals(10, pageInfo.getPageSize());
pageInfo.getList().forEach(o -> {
CommentModel model = (CommentModel) JSONObject.toBean(JSONObject.fromObject(o), CommentModel.class); CommentModel model = (CommentModel) JSONObject.toBean(JSONObject.fromObject(o), CommentModel.class);
assertEquals(3, model.getArticleID());
assertNotNull(model.getDate()); assertNotNull(model.getDate());
assertNotNull(model.getAuthorName()); assertNotNull(model.getAuthorName());
assertNotNull(model.getAuthorAvatarImgUrl()); assertNotNull(model.getAuthorAvatarImgUrl());
assertNotNull(model.getArticleTitle());
assertNotNull(model.getContent()); assertNotNull(model.getContent());
assertNotNull(model.getResponseId()); assertNotNull(model.getResponseId());
}); });

View File

@@ -161,7 +161,8 @@ public class LinksControllerTest extends BaseTest {
}); });
} }
@Test // 手动测试
// @Test
public void apply() throws Exception { public void apply() throws Exception {
long l = System.currentTimeMillis(); long l = System.currentTimeMillis();
String url = "https://www.example.com"; 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.BaseTest;
import cn.celess.blog.entity.Tag; import cn.celess.blog.entity.Tag;
import cn.celess.blog.entity.model.TagModel;
import cn.celess.blog.mapper.TagMapper; import cn.celess.blog.mapper.TagMapper;
import com.github.pagehelper.PageInfo; import com.github.pagehelper.PageInfo;
import net.sf.json.JSONArray; import net.sf.json.JSONArray;
@@ -29,7 +30,7 @@ public class TagControllerTest extends BaseTest {
JSONObject object = JSONObject.fromObject(result.getResponse().getContentAsString()); JSONObject object = JSONObject.fromObject(result.getResponse().getContentAsString());
assertEquals(SUCCESS.getCode(), object.getInt(Code)); assertEquals(SUCCESS.getCode(), object.getInt(Code));
JSONObject resJson = object.getJSONObject(Result); JSONObject resJson = object.getJSONObject(Result);
Tag tag = (Tag) JSONObject.toBean(resJson, Tag.class); TagModel tag = (TagModel) JSONObject.toBean(resJson, TagModel.class);
assertNotNull(tag.getId()); assertNotNull(tag.getId());
assertEquals(name, tag.getName()); assertEquals(name, tag.getName());
}); });
@@ -63,9 +64,11 @@ public class TagControllerTest extends BaseTest {
JSONObject object = JSONObject.fromObject(result.getResponse().getContentAsString()); JSONObject object = JSONObject.fromObject(result.getResponse().getContentAsString());
assertEquals(SUCCESS.getCode(), object.getInt(Code)); assertEquals(SUCCESS.getCode(), object.getInt(Code));
assertNotNull(object.getJSONObject(Result)); 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(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()); assertEquals(tag.getId(), t.getId());
}); });
@@ -79,7 +82,7 @@ public class TagControllerTest extends BaseTest {
JSONObject object = JSONObject.fromObject(result.getResponse().getContentAsString()); JSONObject object = JSONObject.fromObject(result.getResponse().getContentAsString());
assertEquals(SUCCESS.getCode(), object.getInt(Code)); assertEquals(SUCCESS.getCode(), object.getInt(Code));
assertNotNull(object.getJSONObject(Result)); 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()); assertEquals(tag.getId(), t.getId());
assertNotNull(t.getName()); assertNotNull(t.getName());
}); });
@@ -93,7 +96,7 @@ public class TagControllerTest extends BaseTest {
JSONObject object = JSONObject.fromObject(result.getResponse().getContentAsString()); JSONObject object = JSONObject.fromObject(result.getResponse().getContentAsString());
assertEquals(SUCCESS.getCode(), object.getInt(Code)); assertEquals(SUCCESS.getCode(), object.getInt(Code));
assertNotNull(object.getJSONObject(Result)); 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()); assertEquals(tag.getName(), t.getName());
assertNotNull(t.getId()); assertNotNull(t.getId());
}); });
@@ -119,7 +122,7 @@ public class TagControllerTest extends BaseTest {
assertEquals(5, pageInfo.getPageSize()); assertEquals(5, pageInfo.getPageSize());
// 内容完整 // 内容完整
for (Object tag : pageInfo.getList()) { 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.getId());
assertNotNull(t.getName()); assertNotNull(t.getName());
} }

View File

@@ -14,10 +14,12 @@ import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
import org.springframework.mock.web.MockMultipartFile; 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.InputStream;
import java.io.FileInputStream; import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*; import java.util.*;
import static org.junit.Assert.*; import static org.junit.Assert.*;
@@ -93,8 +95,12 @@ public class UserControllerTest extends BaseTest {
@Test @Test
public void upload() throws Exception { public void upload() throws Exception {
File logoFile = new File("C:\\Users\\zh564\\Pictures\\logo.png"); URL url = new URL("https://56462271.oss-cn-beijing.aliyuncs.com/web/logo.png");
MockMultipartFile file = new MockMultipartFile("file", "logo.png", MediaType.IMAGE_PNG_VALUE, new FileInputStream(logoFile)); 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)).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 -> { mockMvc.perform(multipart("/user/imgUpload").file(file).header("Authorization", userLogin())).andDo(result -> {
JSONObject object = JSONObject.fromObject(result.getResponse().getContentAsString()); JSONObject object = JSONObject.fromObject(result.getResponse().getContentAsString());
@@ -244,4 +250,28 @@ public class UserControllerTest extends BaseTest {
assertTrue(JSONObject.fromObject(content).getBoolean(Result)); 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 { public void ipLocation() throws Exception {
String ip = "127.0.0.1"; String ip = "127.0.0.1";
mockMvc.perform(get("/ip/" + ip)).andDo(MockMvcResultHandlers.print()).andDo(result -> { mockMvc.perform(get("/ip/" + ip)).andDo(MockMvcResultHandlers.print()).andDo(result -> {

View File

@@ -120,6 +120,7 @@ public class WebUpdateInfoControllerTest extends BaseTest {
@Test @Test
public void lastestUpdateTime() throws Exception { 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)); 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.BaseTest;
import cn.celess.blog.entity.User; 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.Test;
import org.junit.runners.MethodSorters;
import org.springframework.beans.factory.annotation.Autowired; 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.*; import static org.junit.Assert.*;
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class JwtUtilTest extends BaseTest { public class JwtUtilTest extends BaseTest {
@Autowired @Autowired
JwtUtil jwtUtil; JwtUtil jwtUtil;
@Value("${jwt.secret}")
private String secret;
@Test @Test
public void generateToken() { public void testGenerateToken() {
User user = new User(); User user = new User();
user.setEmail("a@celess.cn"); user.setEmail("a@celess.cn");
String s = jwtUtil.generateToken(user, true); String s = jwtUtil.generateToken(user, false);
System.out.println(s);
assertNotNull(s); assertNotNull(s);
String str = null;
try {
str = jwtUtil.generateToken(null, false);
} catch (Exception e) {
// ignore
}
assertNull(str);
} }
@Test @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 user = new User();
user.setEmail("a@celess.cn"); 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 @Test
public void isTokenExpired() { public void testGetExpirationDateFromToken() {
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() {
User user = new User(); User user = new User();
user.setEmail("a@celess.cn"); 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"));
}
}