Compare commits

..

22 Commits
v1.1 ... 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
28 changed files with 272 additions and 213 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,30 +0,0 @@
image: maven:3.3.9-jdk-8
cache:
paths:
- .m2/repository
stages:
- test
- deploy
test:
stage: test
script:
- cp "$APP_TEST" ./src/main/resources/application-test.properties
- mvn clean test && cat target/site/jacoco/index.html
deploy:
stage: deploy
script:
- cp "$APP_PROD" ./src/main/resources/application-prod.properties
- mvn package -DskipTests
- eval $(ssh-agent -s)
- ssh-add <(echo "$SSH_PRIVATE_KEY" | base64 --decode)
- mkdir -p ~/.ssh
- chmod 700 ~/.ssh
- ssh-keyscan celess.cn >> ~/.ssh/known_hosts
- chmod 644 ~/.ssh/known_hosts
- scp target/blog-0.0.1-SNAPSHOT.jar root@celess.cn:/www/wwwroot/api.celess.cn
- ssh root@celess.cn "cd /www/wwwroot/api.celess.cn && bash build.sh"

View File

@@ -1,5 +1,5 @@
# 小海博客后端管理系统 # 小海博客后端管理系统
![Gitlab pipeline status](https://img.shields.io/gitlab/pipeline/xiaohai2271/blog-backEnd) ![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) ![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的后端博客管理系统

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");
// 本地调试时的跨域 // 本地调试时的跨域
config.addAllowedOrigin("http://localhost:4200"); if ("dev".equals(activeModel)) {
config.addAllowedOrigin("http://127.0.0.1:4200"); config.addAllowedOrigin("http://localhost: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

@@ -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;
@@ -63,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

@@ -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,6 +6,7 @@ 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;
@@ -73,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());
@@ -161,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());
@@ -175,40 +177,13 @@ public class Other {
@GetMapping("/bingPic") @GetMapping("/bingPic")
public Response bingPic() { public Response bingPic() {
StringBuffer sb = new StringBuffer();
JSONObject imageObj;
try { try {
//建立URL imageObj = JSONObject.fromObject(HttpUtil.get("https://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=zh-CN"));
URL url = new URL("https://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=zh-CN"); } catch (IOException e) {
//打开http
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoInput(true);
urlConnection.setRequestMethod("GET");
urlConnection.connect();
//获得输入
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);
}
//关闭bufferReader和输入流
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
//断开连接
urlConnection.disconnect();
} catch (Exception e) {
e.printStackTrace();
return ResponseUtil.failure(null); return ResponseUtil.failure(null);
} }
JSONObject imageObj = JSONObject.fromObject(sb.toString());
JSONArray jsonArray = imageObj.getJSONArray("images"); JSONArray jsonArray = imageObj.getJSONArray("images");
String imageName = jsonArray.getJSONObject(0).getString("url"); String imageName = jsonArray.getJSONObject(0).getString("url");
return ResponseUtil.success("https://cn.bing.com" + imageName); return ResponseUtil.success("https://cn.bing.com" + imageName);

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

@@ -28,8 +28,10 @@ public enum ResponseEnum {
USEREMAIL_NULL(3310, "未设置邮箱"), USEREMAIL_NULL(3310, "未设置邮箱"),
USEREMAIL_NOT_VERIFY(3320, "邮箱未验证"), USEREMAIL_NOT_VERIFY(3320, "邮箱未验证"),
LOGIN_LATER(3500, "错误次数已达5次请稍后再试"), LOGIN_LATER(3500, "错误次数已达5次请稍后再试"),
PWD_SAME(3600, "新密码与原密码相同"), PWD_SAME(3601, "新密码与原密码相同"),
PWD_NOT_SAME(3602, "新密码与原密码不相同"),
LOGIN_EXPIRED(3700, "登陆过期"), LOGIN_EXPIRED(3700, "登陆过期"),
PWD_WRONG(3800, "密码不正确"),
JWT_EXPIRED(3810, "Token过期"), JWT_EXPIRED(3810, "Token过期"),
JWT_MALFORMED(3820, "Token格式不对"), JWT_MALFORMED(3820, "Token格式不对"),

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

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

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

@@ -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

@@ -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;
@@ -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().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

@@ -433,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

@@ -41,8 +41,9 @@ 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; return user;
} }

View File

@@ -1,87 +0,0 @@
server.port=8081
## 七牛的密钥配置
qiniu.accessKey=
qiniu.secretKey=
qiniu.bucket=
## sitemap 存放地址
sitemap.path=
## 生成JWT时候的密钥
jwt.secret=
##spring.jpa.show-sql=false
##spring.jpa.hibernate.ddl-auto=update
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=
spring.datasource.username=
spring.datasource.password=
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=
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

@@ -2,4 +2,6 @@ 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

@@ -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

@@ -14,6 +14,9 @@ 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.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import java.io.InputStream; import java.io.InputStream;
import java.net.HttpURLConnection; import java.net.HttpURLConnection;
import java.net.URL; import java.net.URL;
@@ -247,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

@@ -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"));
});
}
} }