[UPDATE]:测试角色权限模块

This commit is contained in:
张世琪 2025-02-02 16:18:45 +08:00
parent 1975a0a8a3
commit 9213f8b199
16 changed files with 193 additions and 130 deletions

View File

@ -68,6 +68,22 @@
<version>${tcctlo.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>

View File

@ -1,22 +1,29 @@
package com.tcctlo.web.controller.common;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.tcctlo.common.annotation.Anonymous;
import org.apache.http.HttpResponse;
import org.dromara.x.file.storage.core.FileInfo;
import org.dromara.x.file.storage.core.FileStorageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.tcctlo.common.config.RuoYiConfig;
import com.tcctlo.common.constant.Constants;
@ -31,10 +38,10 @@ import com.tcctlo.framework.config.ServerConfig;
*
* @author ruoyi
*/
@Anonymous
@RestController
@RequestMapping("/common")
public class CommonController
{
public class CommonController {
private static final Logger log = LoggerFactory.getLogger(CommonController.class);
@Autowired
@ -49,15 +56,12 @@ public class CommonController
* 通用下载请求
*
* @param fileName 文件名称
* @param delete 是否删除
* @param delete 是否删除
*/
@GetMapping("/download")
public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request)
{
try
{
if (!FileUtils.checkAllowDownload(fileName))
{
public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request) {
try {
if (!FileUtils.checkAllowDownload(fileName)) {
throw new Exception(StringUtils.format("文件名称({})非法,不允许下载。 ", fileName));
}
String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
@ -66,13 +70,10 @@ public class CommonController
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
FileUtils.setAttachmentResponseHeader(response, realFileName);
FileUtils.writeBytes(filePath, response.getOutputStream());
if (delete)
{
if (delete) {
FileUtils.deleteFile(filePath);
}
}
catch (Exception e)
{
} catch (Exception e) {
log.error("下载文件失败", e);
}
}
@ -81,10 +82,8 @@ public class CommonController
* 通用上传请求单个
*/
@PostMapping("/upload")
public AjaxResult uploadFile(MultipartFile file) throws Exception
{
try
{
public AjaxResult uploadFile(MultipartFile file) throws Exception {
try {
/*// 上传文件路径
String filePath = RuoYiConfig.getUploadPath();
// 上传并返回新文件名称
@ -104,29 +103,50 @@ public class CommonController
ajax.put("newFileName", FileUtils.getName(fileInfo.getUrl()));
ajax.put("originalFilename", file.getOriginalFilename());
return ajax;
}
catch (Exception e)
{
} catch (Exception e) {
return AjaxResult.error(e.getMessage());
}
}
/**
* 下载文件至本地
* @param response 响应
*/
@GetMapping("/downloadFileOnLocal")
public AjaxResult downloadFile(HttpServletResponse response, @RequestParam("urlPath") String urlPath, @RequestParam("path") String path) {
try {
URL url = new URL(urlPath);
String filePath = "F:\\fileDownload\\" + UUID.randomUUID() + urlPath.substring(urlPath.lastIndexOf("."));
URLConnection conn = url.openConnection();
InputStream inputStream = conn.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream(filePath);
int bytesum = 0;
int byteread;
byte[] buffer = new byte[1024];
while ((byteread = inputStream.read(buffer)) != -1) {
bytesum += byteread;
fileOutputStream.write(buffer, 0, byteread);
}
fileOutputStream.close();
return AjaxResult.success("下载成功");
} catch (Exception e) {
throw new RuntimeException("下载失败");
}
}
/**
* 通用上传请求多个
*/
@PostMapping("/uploads")
public AjaxResult uploadFiles(List<MultipartFile> files) throws Exception
{
try
{
public AjaxResult uploadFiles(List<MultipartFile> files) throws Exception {
try {
// 上传文件路径
String filePath = RuoYiConfig.getUploadPath();
List<String> urls = new ArrayList<String>();
List<String> fileNames = new ArrayList<String>();
List<String> newFileNames = new ArrayList<String>();
List<String> originalFilenames = new ArrayList<String>();
for (MultipartFile file : files)
{
for (MultipartFile file : files) {
// 上传并返回新文件名称
String fileName = FileUploadUtils.upload(filePath, file);
String url = serverConfig.getUrl() + fileName;
@ -141,9 +161,7 @@ public class CommonController
ajax.put("newFileNames", StringUtils.join(newFileNames, FILE_DELIMETER));
ajax.put("originalFilenames", StringUtils.join(originalFilenames, FILE_DELIMETER));
return ajax;
}
catch (Exception e)
{
} catch (Exception e) {
return AjaxResult.error(e.getMessage());
}
}
@ -153,12 +171,9 @@ public class CommonController
*/
@GetMapping("/download/resource")
public void resourceDownload(String resource, HttpServletRequest request, HttpServletResponse response)
throws Exception
{
try
{
if (!FileUtils.checkAllowDownload(resource))
{
throws Exception {
try {
if (!FileUtils.checkAllowDownload(resource)) {
throw new Exception(StringUtils.format("资源文件({})非法,不允许下载。 ", resource));
}
// 本地资源路径
@ -170,9 +185,7 @@ public class CommonController
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
FileUtils.setAttachmentResponseHeader(response, downloadName);
FileUtils.writeBytes(downloadPath, response.getOutputStream());
}
catch (Exception e)
{
} catch (Exception e) {
log.error("下载文件失败", e);
}
}

View File

@ -6,7 +6,7 @@ spring:
druid:
# 主库数据源
master:
url: jdbc:mysql://117.72.45.219:23308/low-office-OA?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
url: jdbc:mysql://localhost:3306/low-office-oa?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
username: root
password: root
# 从库数据源

View File

@ -68,7 +68,7 @@ spring:
# redis 配置
redis:
# 地址
host: 117.72.45.219
host: 127.0.0.1
# 端口默认为6379
port: 6379
# 数据库索引
@ -95,7 +95,7 @@ token:
# 令牌密钥
secret: abcdefghijklmnopqrstuvwxyz
# 令牌有效期默认30分钟
expireTime: 30
expireTime: 60
mybatis-plus:
# 搜索指定包别名

View File

@ -0,0 +1,15 @@
import com.tcctlo.TCCTLawOfficeApplication;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest(classes = TCCTLawOfficeApplication.class)
public class FileTest {
@Test
@DisplayName("测试:截取文件后缀名")
public void testFileName(){
String fileName = "https://low-office.oss-cn-beijing.aliyuncs.com/low-office-images/2025/01/25/67948d96229fc1a67923a564.xlsx";
System.out.println(fileName.substring(fileName.lastIndexOf(".")));
}
}

View File

@ -146,6 +146,8 @@
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.1</version>
</dependency>
</dependencies>
</project>

View File

@ -71,7 +71,9 @@ public class SysLoginService
Authentication authentication = null;
try
{
// 创建用户名密码对象
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
//将用户名密码放入认证上下文
AuthenticationContextHolder.setContext(authenticationToken);
// 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
authentication = authenticationManager.authenticate(authenticationToken);
@ -94,7 +96,10 @@ public class SysLoginService
AuthenticationContextHolder.clearContext();
}
AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
//通过springSecurity获取登录用户的信息包含用户角色权限
LoginUser loginUser = (LoginUser) authentication.getPrincipal();
recordLoginInfo(loginUser.getUserId());
// 生成token
return tokenService.createToken(loginUser);

View File

@ -43,12 +43,19 @@ public class SysPasswordService
public void validate(SysUser user)
{
//获取当前的认证信息
Authentication usernamePasswordAuthenticationToken = AuthenticationContextHolder.getContext();
//从认证信息中提取用户名
String username = usernamePasswordAuthenticationToken.getName();
//从认证信息中提取密码
String password = usernamePasswordAuthenticationToken.getCredentials().toString();
//尝试从缓存中获取当前用户的密码重试次数
Integer retryCount = redisCache.getCacheObject(getCacheKey(username));
//如果缓存中没有重试次数初始化为0
if (retryCount == null)
{
retryCount = 0;

View File

@ -54,8 +54,10 @@ public class UserDetailsServiceImpl implements UserDetailsService
throw new ServiceException(MessageUtils.message("user.blocked"));
}
//验证用户名密码是否正确
passwordService.validate(user);
//创建并返回登录用户对象将用户相关信息存入spring Security
return createLoginUser(user);
}

View File

@ -37,7 +37,7 @@ public class GeneratorUIServer {
}
})
//所有生成的java文件的父包名后续也可单独在界面上设置
.basePackage("com.tcctyn.forestfire")
.basePackage("com.tcctlo.law")
.port(8068)
.build();
MybatisPlusToolsApplication.run(config);

View File

@ -1,22 +1,18 @@
package com.tcctlo.law.controller;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import com.tcctlo.common.annotation.Anonymous;
import com.tcctlo.law.entity.Goods;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import com.tcctlo.common.annotation.Log;
import com.tcctlo.common.core.controller.BaseController;
import com.tcctlo.common.core.domain.AjaxResult;
import com.tcctlo.common.enums.BusinessType;
import com.tcctlo.law.domain.Goods;
import com.tcctlo.law.service.IGoodsService;
import com.tcctlo.common.utils.poi.ExcelUtil;
import com.tcctlo.common.core.page.TableDataInfo;
@ -24,24 +20,32 @@ import com.tcctlo.common.core.page.TableDataInfo;
/**
* 商品管理Controller
*
* @author 张世琪
* @date 2025-01-20
* @author coco
* @date 2025-01-30
*/
@RestController
@RequestMapping("/tcctlo-law-office/goods")
public class GoodsController extends BaseController
{
public class GoodsController extends BaseController {
@Autowired
private IGoodsService goodsService;
/**
* 模拟案件转移给其他律师
* @param map 原承办律师与要转移的律师数据集
*/
@Anonymous
@PostMapping("/hello")
public void test(@RequestBody Map<String, Object> map) {
System.out.println(map);
System.out.println("test");
}
/**
* 查询商品管理列表
*/
@PreAuthorize("@ss.hasPermi('tcctlo-law-office:goods:list')")
@GetMapping("/list")
public TableDataInfo list(Goods goods)
{
//测试提交
public TableDataInfo list(Goods goods) {
startPage();
List<Goods> list = goodsService.selectGoodsList(goods);
return getDataTable(list);
@ -53,8 +57,7 @@ public class GoodsController extends BaseController
@PreAuthorize("@ss.hasPermi('tcctlo-law-office:goods:export')")
@Log(title = "商品管理", businessType = BusinessType.EXPORT)
@PostMapping("/export")
public void export(HttpServletResponse response, Goods goods)
{
public void export(HttpServletResponse response, Goods goods) {
List<Goods> list = goodsService.selectGoodsList(goods);
ExcelUtil<Goods> util = new ExcelUtil<Goods>(Goods.class);
util.exportExcel(response, list, "商品管理数据");
@ -65,8 +68,7 @@ public class GoodsController extends BaseController
*/
@PreAuthorize("@ss.hasPermi('tcctlo-law-office:goods:query')")
@GetMapping(value = "/{id}")
public AjaxResult getInfo(@PathVariable("id") Long id)
{
public AjaxResult getInfo(@PathVariable("id") Long id) {
return success(goodsService.selectGoodsById(id));
}
@ -76,8 +78,7 @@ public class GoodsController extends BaseController
@PreAuthorize("@ss.hasPermi('tcctlo-law-office:goods:add')")
@Log(title = "商品管理", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@RequestBody Goods goods)
{
public AjaxResult add(@RequestBody Goods goods) {
return toAjax(goodsService.insertGoods(goods));
}
@ -87,8 +88,7 @@ public class GoodsController extends BaseController
@PreAuthorize("@ss.hasPermi('tcctlo-law-office:goods:edit')")
@Log(title = "商品管理", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@RequestBody Goods goods)
{
public AjaxResult edit(@RequestBody Goods goods) {
return toAjax(goodsService.updateGoods(goods));
}
@ -97,9 +97,8 @@ public class GoodsController extends BaseController
*/
@PreAuthorize("@ss.hasPermi('tcctlo-law-office:goods:remove')")
@Log(title = "商品管理", businessType = BusinessType.DELETE)
@DeleteMapping("/{ids}")
public AjaxResult remove(@PathVariable Long[] ids)
{
@DeleteMapping("/{ids}")
public AjaxResult remove(@PathVariable Long[] ids) {
return toAjax(goodsService.deleteGoodsByIds(ids));
}
}

View File

@ -1,5 +1,6 @@
package com.tcctlo.law.domain;
package com.tcctlo.law.entity;
import java.math.BigDecimal;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import com.tcctlo.common.annotation.Excel;
@ -8,31 +9,31 @@ import com.tcctlo.common.core.domain.BaseEntity;
/**
* 商品管理对象 goods
*
* @author 张世琪
* @date 2025-01-20
* @author coco
* @date 2025-01-30
*/
public class Goods extends BaseEntity
{
private static final long serialVersionUID = 1L;
/** 主键 */
/** 主键id */
private Long id;
/** 商品名称 */
@Excel(name = "商品名称")
private String name;
private String goodsName;
/** 商品图片 */
@Excel(name = "商品图片")
private String goodsImage;
private String goodsImages;
/** 商品文件 */
@Excel(name = "商品文件")
private String goodsFile;
/** 商品价格 */
@Excel(name = "商品价格")
private Long price;
/** 商品金额 */
@Excel(name = "商品金额")
private BigDecimal goodsMoney;
public void setId(Long id)
{
@ -43,23 +44,23 @@ public class Goods extends BaseEntity
{
return id;
}
public void setName(String name)
public void setGoodsName(String goodsName)
{
this.name = name;
this.goodsName = goodsName;
}
public String getName()
public String getGoodsName()
{
return name;
return goodsName;
}
public void setGoodsImage(String goodsImage)
public void setGoodsImages(String goodsImages)
{
this.goodsImage = goodsImage;
this.goodsImages = goodsImages;
}
public String getGoodsImage()
public String getGoodsImages()
{
return goodsImage;
return goodsImages;
}
public void setGoodsFile(String goodsFile)
{
@ -70,24 +71,24 @@ public class Goods extends BaseEntity
{
return goodsFile;
}
public void setPrice(Long price)
public void setGoodsMoney(BigDecimal goodsMoney)
{
this.price = price;
this.goodsMoney = goodsMoney;
}
public Long getPrice()
public BigDecimal getGoodsMoney()
{
return price;
return goodsMoney;
}
@Override
public String toString() {
return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)
.append("id", getId())
.append("name", getName())
.append("goodsImage", getGoodsImage())
.append("goodsName", getGoodsName())
.append("goodsImages", getGoodsImages())
.append("goodsFile", getGoodsFile())
.append("price", getPrice())
.append("goodsMoney", getGoodsMoney())
.toString();
}
}

View File

@ -1,13 +1,14 @@
package com.tcctlo.law.mapper;
import com.tcctlo.law.entity.Goods;
import java.util.List;
import com.tcctlo.law.domain.Goods;
/**
* 商品管理Mapper接口
*
* @author 张世琪
* @date 2025-01-20
* @author coco
* @date 2025-01-30
*/
public interface GoodsMapper
{

View File

@ -1,13 +1,14 @@
package com.tcctlo.law.service;
import com.tcctlo.law.entity.Goods;
import java.util.List;
import com.tcctlo.law.domain.Goods;
/**
* 商品管理Service接口
*
* @author 张世琪
* @date 2025-01-20
* @author coco
* @date 2025-01-30
*/
public interface IGoodsService
{

View File

@ -1,17 +1,18 @@
package com.tcctlo.law.service.impl;
import java.util.List;
import com.tcctlo.law.entity.Goods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.tcctlo.law.mapper.GoodsMapper;
import com.tcctlo.law.domain.Goods;
import com.tcctlo.law.service.IGoodsService;
/**
* 商品管理Service业务层处理
*
* @author 张世琪
* @date 2025-01-20
* @author coco
* @date 2025-01-30
*/
@Service
public class GoodsServiceImpl implements IGoodsService

View File

@ -4,25 +4,25 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.tcctlo.law.mapper.GoodsMapper">
<resultMap type="Goods" id="GoodsResult">
<resultMap type="com.tcctlo.law.entity.Goods" id="GoodsResult">
<result property="id" column="id" />
<result property="name" column="name" />
<result property="goodsImage" column="goods_image" />
<result property="goodsName" column="goods_name" />
<result property="goodsImages" column="goods_images" />
<result property="goodsFile" column="goods_file" />
<result property="price" column="price" />
<result property="goodsMoney" column="goods_money" />
</resultMap>
<sql id="selectGoodsVo">
select id, name, goods_image, goods_file, price from goods
select id, goods_name, goods_images, goods_file, goods_money from goods
</sql>
<select id="selectGoodsList" parameterType="Goods" resultMap="GoodsResult">
<select id="selectGoodsList" parameterType="com.tcctlo.law.entity.Goods" resultMap="GoodsResult">
<include refid="selectGoodsVo"/>
<where>
<if test="name != null and name != ''"> and name like concat('%', #{name}, '%')</if>
<if test="goodsImage != null and goodsImage != ''"> and goods_image = #{goodsImage}</if>
<if test="goodsName != null and goodsName != ''"> and goods_name like concat('%', #{goodsName}, '%')</if>
<if test="goodsImages != null and goodsImages != ''"> and goods_images = #{goodsImages}</if>
<if test="goodsFile != null and goodsFile != ''"> and goods_file = #{goodsFile}</if>
<if test="price != null "> and price = #{price}</if>
<if test="goodsMoney != null "> and goods_money = #{goodsMoney}</if>
</where>
</select>
@ -31,29 +31,29 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
where id = #{id}
</select>
<insert id="insertGoods" parameterType="Goods" useGeneratedKeys="true" keyProperty="id">
<insert id="insertGoods" parameterType="com.tcctlo.law.entity.Goods" useGeneratedKeys="true" keyProperty="id">
insert into goods
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="name != null">name,</if>
<if test="goodsImage != null">goods_image,</if>
<if test="goodsName != null">goods_name,</if>
<if test="goodsImages != null">goods_images,</if>
<if test="goodsFile != null">goods_file,</if>
<if test="price != null">price,</if>
<if test="goodsMoney != null">goods_money,</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="name != null">#{name},</if>
<if test="goodsImage != null">#{goodsImage},</if>
<if test="goodsName != null">#{goodsName},</if>
<if test="goodsImages != null">#{goodsImages},</if>
<if test="goodsFile != null">#{goodsFile},</if>
<if test="price != null">#{price},</if>
<if test="goodsMoney != null">#{goodsMoney},</if>
</trim>
</insert>
<update id="updateGoods" parameterType="Goods">
<update id="updateGoods" parameterType="com.tcctlo.law.entity.Goods">
update goods
<trim prefix="SET" suffixOverrides=",">
<if test="name != null">name = #{name},</if>
<if test="goodsImage != null">goods_image = #{goodsImage},</if>
<if test="goodsName != null">goods_name = #{goodsName},</if>
<if test="goodsImages != null">goods_images = #{goodsImages},</if>
<if test="goodsFile != null">goods_file = #{goodsFile},</if>
<if test="price != null">price = #{price},</if>
<if test="goodsMoney != null">goods_money = #{goodsMoney},</if>
</trim>
where id = #{id}
</update>