Initial commit

This commit is contained in:
LuRuiqian
2026-04-17 11:46:16 +08:00
commit edead1a026
279 changed files with 18957 additions and 0 deletions

View File

@@ -0,0 +1,33 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package io.renren;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
/**
* renren-admin
*
* @author Mark sunlightcs@gmail.com
*/
@SpringBootApplication
public class AdminApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(AdminApplication.class, args);
}
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(AdminApplication.class);
}
}

View File

@@ -0,0 +1,37 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package io.renren.common.annotation;
import java.lang.annotation.*;
/**
* 数据过滤注解
*
* @author Mark sunlightcs@gmail.com
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DataFilter {
/**
* 表的别名
*/
String tableAlias() default "";
/**
* 用户ID
*/
String userId() default "creator";
/**
* 部门ID
*/
String deptId() default "dept_id";
}

View File

@@ -0,0 +1,28 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package io.renren.common.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 操作日志注解
*
* @author Mark sunlightcs@gmail.com
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface LogOperation {
String value() default "";
}

View File

@@ -0,0 +1,108 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
* <p>
* https://www.renren.io
* <p>
* 版权所有,侵权必究!
*/
package io.renren.common.aspect;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.qiniu.util.StringUtils;
import io.renren.common.annotation.DataFilter;
import io.renren.common.constant.Constant;
import io.renren.common.exception.ErrorCode;
import io.renren.common.exception.RenException;
import io.renren.common.interceptor.DataScope;
import io.renren.modules.security.user.SecurityUser;
import io.renren.modules.security.user.UserDetail;
import io.renren.modules.sys.enums.SuperAdminEnum;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
/**
* 数据过滤,切面处理类
*
* @author Mark sunlightcs@gmail.com
*/
@Aspect
@Component
public class DataFilterAspect {
@Pointcut("@annotation(io.renren.common.annotation.DataFilter)")
public void dataFilterCut() {
}
@Before("dataFilterCut()")
public void dataFilter(JoinPoint point) {
Object params = point.getArgs()[0];
if (params != null && params instanceof Map) {
UserDetail user = SecurityUser.getUser();
//如果是超级管理员,则不进行数据过滤
if (user.getSuperAdmin() == SuperAdminEnum.YES.value()) {
return;
}
try {
//否则进行数据过滤
Map map = (Map) params;
String sqlFilter = getSqlFilter(user, point);
map.put(Constant.SQL_FILTER, new DataScope(sqlFilter));
} catch (Exception e) {
}
return;
}
throw new RenException(ErrorCode.DATA_SCOPE_PARAMS_ERROR);
}
/**
* 获取数据过滤的SQL
*/
private String getSqlFilter(UserDetail user, JoinPoint point) throws Exception {
MethodSignature signature = (MethodSignature) point.getSignature();
Method method = point.getTarget().getClass().getDeclaredMethod(signature.getName(), signature.getParameterTypes());
DataFilter dataFilter = method.getAnnotation(DataFilter.class);
//获取表的别名
String tableAlias = dataFilter.tableAlias();
if (StrUtil.isNotBlank(tableAlias)) {
tableAlias += ".";
}
StringBuilder sqlFilter = new StringBuilder();
sqlFilter.append(" (");
//部门ID列表
List<Long> deptIdList = user.getDeptIdList();
if (CollUtil.isNotEmpty(deptIdList)) {
sqlFilter.append(tableAlias).append(dataFilter.deptId());
sqlFilter.append(" in(").append(StringUtils.join(deptIdList, ",")).append(")");
}
//查询本人数据
if (CollUtil.isNotEmpty(deptIdList)) {
sqlFilter.append(" or ");
}
sqlFilter.append(tableAlias).append(dataFilter.userId()).append("=").append(user.getId());
sqlFilter.append(")");
return sqlFilter.toString();
}
}

View File

@@ -0,0 +1,110 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
* <p>
* https://www.renren.io
* <p>
* 版权所有,侵权必究!
*/
package io.renren.common.aspect;
import io.renren.common.annotation.LogOperation;
import io.renren.common.utils.HttpContextUtils;
import io.renren.common.utils.IpUtils;
import io.renren.common.utils.JsonUtils;
import io.renren.modules.log.entity.SysLogOperationEntity;
import io.renren.modules.log.enums.OperationStatusEnum;
import io.renren.modules.log.service.SysLogOperationService;
import io.renren.modules.security.user.SecurityUser;
import io.renren.modules.security.user.UserDetail;
import jakarta.servlet.http.HttpServletRequest;
import lombok.AllArgsConstructor;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
/**
* 操作日志,切面处理类
*
* @author Mark sunlightcs@gmail.com
*/
@Aspect
@Component
@AllArgsConstructor
public class LogOperationAspect {
private final SysLogOperationService sysLogOperationService;
@Pointcut("@annotation(io.renren.common.annotation.LogOperation)")
public void logPointCut() {
}
@Around("logPointCut()")
public Object around(ProceedingJoinPoint point) throws Throwable {
long beginTime = System.currentTimeMillis();
try {
//执行方法
Object result = point.proceed();
//执行时长(毫秒)
long time = System.currentTimeMillis() - beginTime;
//保存日志
saveLog(point, time, OperationStatusEnum.SUCCESS.value());
return result;
} catch (Exception e) {
//执行时长(毫秒)
long time = System.currentTimeMillis() - beginTime;
//保存日志
saveLog(point, time, OperationStatusEnum.FAIL.value());
throw e;
}
}
private void saveLog(ProceedingJoinPoint joinPoint, long time, Integer status) throws Exception {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = joinPoint.getTarget().getClass().getDeclaredMethod(signature.getName(), signature.getParameterTypes());
LogOperation annotation = method.getAnnotation(LogOperation.class);
SysLogOperationEntity log = new SysLogOperationEntity();
if (annotation != null) {
//注解上的描述
log.setOperation(annotation.value());
}
//登录用户信息
UserDetail user = SecurityUser.getUser();
if (user != null) {
log.setCreatorName(user.getUsername());
}
log.setStatus(status);
log.setRequestTime((int) time);
//请求相关信息
HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
log.setIp(IpUtils.getIpAddr(request));
log.setUserAgent(request.getHeader(HttpHeaders.USER_AGENT));
log.setRequestUri(request.getRequestURI());
log.setRequestMethod(request.getMethod());
//请求参数
Object[] args = joinPoint.getArgs();
try {
String params = JsonUtils.toJsonString(args[0]);
log.setRequestParams(params);
} catch (Exception e) {
}
//保存到DB
sysLogOperationService.save(log);
}
}

View File

@@ -0,0 +1,43 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package io.renren.common.config;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.BlockAttackInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import io.renren.common.interceptor.DataFilterInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* mybatis-plus配置
*
* @author Mark sunlightcs@gmail.com
* @since 1.0.0
*/
@Configuration
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
// 数据权限
mybatisPlusInterceptor.addInnerInterceptor(new DataFilterInterceptor());
// 分页插件
mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor());
// 乐观锁
mybatisPlusInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
// 防止全表更新与删除
mybatisPlusInterceptor.addInnerInterceptor(new BlockAttackInnerInterceptor());
return mybatisPlusInterceptor;
}
}

View File

@@ -0,0 +1,50 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
* <p>
* https://www.renren.io
* <p>
* 版权所有,侵权必究!
*/
package io.renren.common.config;
import io.renren.common.constant.Constant;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.security.SecurityRequirement;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.ArrayList;
import java.util.List;
/**
* Swagger配置
*
* @author Mark sunlightcs@gmail.com
*/
@Configuration
public class SwaggerConfig {
@Bean
public OpenAPI createRestApi() {
return new OpenAPI()
.info(apiInfo())
.security(security());
}
private Info apiInfo() {
return new Info()
.title("人人开源")
.description("renren-admin文档")
.version("5.x");
}
private List<SecurityRequirement> security() {
SecurityRequirement key = new SecurityRequirement();
key.addList(Constant.TOKEN_HEADER, Constant.TOKEN_HEADER);
List<SecurityRequirement> list = new ArrayList<>();
list.add(key);
return list;
}
}

View File

@@ -0,0 +1,92 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
* <p>
* https://www.renren.io
* <p>
* 版权所有,侵权必究!
*/
package io.renren.common.exception;
import cn.hutool.core.map.MapUtil;
import io.renren.common.utils.HttpContextUtils;
import io.renren.common.utils.IpUtils;
import io.renren.common.utils.JsonUtils;
import io.renren.common.utils.Result;
import io.renren.modules.log.entity.SysLogErrorEntity;
import io.renren.modules.log.service.SysLogErrorService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.util.Map;
/**
* 异常处理器
*
* @author Mark sunlightcs@gmail.com
* @since 1.0.0
*/
@Slf4j
@RestControllerAdvice
@AllArgsConstructor
public class RenExceptionHandler {
private final SysLogErrorService sysLogErrorService;
/**
* 处理自定义异常
*/
@ExceptionHandler(RenException.class)
public Result handleRenException(RenException ex) {
Result result = new Result();
result.error(ex.getCode(), ex.getMsg());
return result;
}
@ExceptionHandler(DuplicateKeyException.class)
public Result handleDuplicateKeyException(DuplicateKeyException ex) {
Result result = new Result();
result.error(ErrorCode.DB_RECORD_EXISTS);
return result;
}
@ExceptionHandler(Exception.class)
public Result handleException(Exception ex) {
log.error(ex.getMessage(), ex);
saveLog(ex);
return new Result().error();
}
/**
* 保存异常日志
*/
private void saveLog(Exception ex) {
SysLogErrorEntity log = new SysLogErrorEntity();
//请求相关信息
HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
log.setIp(IpUtils.getIpAddr(request));
log.setUserAgent(request.getHeader(HttpHeaders.USER_AGENT));
log.setRequestUri(request.getRequestURI());
log.setRequestMethod(request.getMethod());
Map<String, String> params = HttpContextUtils.getParameterMap(request);
if (MapUtil.isNotEmpty(params)) {
log.setRequestParams(JsonUtils.toJsonString(params));
}
//异常信息
log.setErrorInfo(ExceptionUtils.getErrorStackTrace(ex));
//保存
sysLogErrorService.save(log);
}
}

View File

@@ -0,0 +1,58 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package io.renren.common.handler;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import io.renren.modules.security.user.SecurityUser;
import io.renren.modules.security.user.UserDetail;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import java.util.Date;
/**
* 公共字段,自动填充值
*
* @author Mark sunlightcs@gmail.com
*/
@Component
public class FieldMetaObjectHandler implements MetaObjectHandler {
private final static String CREATE_DATE = "createDate";
private final static String CREATOR = "creator";
private final static String UPDATE_DATE = "updateDate";
private final static String UPDATER = "updater";
private final static String DEPT_ID = "deptId";
@Override
public void insertFill(MetaObject metaObject) {
UserDetail user = SecurityUser.getUser();
Date date = new Date();
//创建者
strictInsertFill(metaObject, CREATOR, Long.class, user.getId());
//创建时间
strictInsertFill(metaObject, CREATE_DATE, Date.class, date);
//创建者所属部门
strictInsertFill(metaObject, DEPT_ID, Long.class, user.getDeptId());
//更新者
strictInsertFill(metaObject, UPDATER, Long.class, user.getId());
//更新时间
strictInsertFill(metaObject, UPDATE_DATE, Date.class, date);
}
@Override
public void updateFill(MetaObject metaObject) {
//更新者
strictUpdateFill(metaObject, UPDATER, Long.class, SecurityUser.getUserId());
//更新时间
strictUpdateFill(metaObject, UPDATE_DATE, Date.class, new Date());
}
}

View File

@@ -0,0 +1,89 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package io.renren.common.interceptor;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.PluginUtils;
import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
import net.sf.jsqlparser.JSQLParserException;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.StringValue;
import net.sf.jsqlparser.expression.operators.conditional.AndExpression;
import net.sf.jsqlparser.parser.CCJSqlParserUtil;
import net.sf.jsqlparser.statement.select.PlainSelect;
import net.sf.jsqlparser.statement.select.Select;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import java.util.Map;
/**
* 数据过滤
*
* @author Mark sunlightcs@gmail.com
*/
public class DataFilterInterceptor implements InnerInterceptor {
@Override
public void beforeQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {
DataScope scope = getDataScope(parameter);
// 不进行数据过滤
if(scope == null || StrUtil.isBlank(scope.getSqlFilter())){
return;
}
// 拼接新SQL
String buildSql = getSelect(boundSql.getSql(), scope);
// 重写SQL
PluginUtils.mpBoundSql(boundSql).sql(buildSql);
}
private DataScope getDataScope(Object parameter){
if (parameter == null){
return null;
}
// 判断参数里是否有DataScope对象
if (parameter instanceof Map) {
Map<?, ?> parameterMap = (Map<?, ?>) parameter;
for (Map.Entry entry : parameterMap.entrySet()) {
if (entry.getValue() != null && entry.getValue() instanceof DataScope) {
return (DataScope) entry.getValue();
}
}
} else if (parameter instanceof DataScope) {
return (DataScope) parameter;
}
return null;
}
private String getSelect(String buildSql, DataScope scope){
try {
Select select = (Select) CCJSqlParserUtil.parse(buildSql);
PlainSelect plainSelect = (PlainSelect) select.getSelectBody();
Expression expression = plainSelect.getWhere();
if(expression == null){
plainSelect.setWhere(new StringValue(scope.getSqlFilter()));
}else{
AndExpression andExpression = new AndExpression(expression, new StringValue(scope.getSqlFilter()));
plainSelect.setWhere(andExpression);
}
return select.toString().replaceAll("'", "");
}catch (JSQLParserException e){
return buildSql;
}
}
}

View File

@@ -0,0 +1,36 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package io.renren.common.interceptor;
/**
* 数据范围
*
* @author Mark sunlightcs@gmail.com
* @since 1.0.0
*/
public class DataScope {
private String sqlFilter;
public DataScope(String sqlFilter) {
this.sqlFilter = sqlFilter;
}
public String getSqlFilter() {
return sqlFilter;
}
public void setSqlFilter(String sqlFilter) {
this.sqlFilter = sqlFilter;
}
@Override
public String toString() {
return this.sqlFilter;
}
}

View File

@@ -0,0 +1,75 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
* <p>
* https://www.renren.io
* <p>
* 版权所有,侵权必究!
*/
package io.renren.common.utils;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.converters.longconverter.LongStringConverter;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.BeanUtils;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* excel工具类
*
* @author Mark sunlightcs@gmail.com
*/
public class ExcelUtils {
/**
* Excel导出
*
* @param response response
* @param fileName 文件名
* @param sheetName sheetName
* @param list 数据List
* @param pojoClass 对象Class
*/
public static void exportExcel(HttpServletResponse response, String fileName, String sheetName, List<?> list,
Class<?> pojoClass) throws IOException {
if (StrUtil.isBlank(fileName)) {
//当前日期
fileName = DateUtils.format(new Date());
}
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("UTF-8");
fileName = URLUtil.encode(fileName, StandardCharsets.UTF_8);
response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
EasyExcel.write(response.getOutputStream(), pojoClass).registerConverter(new LongStringConverter()).sheet(sheetName).doWrite(list);
}
/**
* Excel导出先sourceList转换成List<targetClass>,再导出
*
* @param response response
* @param fileName 文件名
* @param sheetName sheetName
* @param sourceList 原数据List
* @param targetClass 目标对象Class
*/
public static void exportExcelToTarget(HttpServletResponse response, String fileName, String sheetName, List<?> sourceList,
Class<?> targetClass) throws Exception {
List targetList = new ArrayList<>(sourceList.size());
for (Object source : sourceList) {
Object target = targetClass.newInstance();
BeanUtils.copyProperties(source, target);
targetList.add(target);
}
exportExcel(response, fileName, sheetName, targetList, targetClass);
}
}

View File

@@ -0,0 +1,17 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package io.renren.common.validator.group;
/**
* 阿里云
*
* @author Mark sunlightcs@gmail.com
*/
public interface AliyunGroup {
}

View File

@@ -0,0 +1,17 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package io.renren.common.validator.group;
/**
* 腾讯云
*
* @author Mark sunlightcs@gmail.com
*/
public interface QcloudGroup {
}

View File

@@ -0,0 +1,17 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package io.renren.common.validator.group;
/**
* 七牛
*
* @author Mark sunlightcs@gmail.com
*/
public interface QiniuGroup {
}

View File

@@ -0,0 +1,66 @@
///**
// * Copyright (c) 2018 人人开源 All rights reserved.
// *
// * https://www.renren.io
// *
// * 版权所有,侵权必究!
// */
//
//package io.renren.modules.job.config;
//
//import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration;
//import org.springframework.scheduling.quartz.SchedulerFactoryBean;
//
//import javax.sql.DataSource;
//import java.util.Properties;
//
///**
// * 定时任务配置(备注:集群需要打开注释)
// *
// * @author Mark sunlightcs@gmail.com
// */
//@Configuration
//public class ScheduleConfig {
//
// @Bean
// public SchedulerFactoryBean schedulerFactoryBean(DataSource dataSource) {
// SchedulerFactoryBean factory = new SchedulerFactoryBean();
// factory.setDataSource(dataSource);
//
// //quartz参数
// Properties prop = new Properties();
// prop.put("org.quartz.scheduler.instanceName", "RenrenScheduler");
// prop.put("org.quartz.scheduler.instanceId", "AUTO");
// //线程池配置
// prop.put("org.quartz.threadPool.class", "org.quartz.simpl.SimpleThreadPool");
// prop.put("org.quartz.threadPool.threadCount", "20");
// prop.put("org.quartz.threadPool.threadPriority", "5");
// //JobStore配置
// prop.put("org.quartz.jobStore.class", "org.springframework.scheduling.quartz.LocalDataSourceJobStore");
// //集群配置
// prop.put("org.quartz.jobStore.isClustered", "true");
// prop.put("org.quartz.jobStore.clusterCheckinInterval", "15000");
// prop.put("org.quartz.jobStore.maxMisfiresToHandleAtATime", "1");
//
// prop.put("org.quartz.jobStore.misfireThreshold", "12000");
// prop.put("org.quartz.jobStore.tablePrefix", "QRTZ_");
// prop.put("org.quartz.jobStore.selectWithLockSQL", "SELECT * FROM {0}LOCKS UPDLOCK WHERE LOCK_NAME = ?");
//
// //PostgreSQL数据库需要打开此注释
// //prop.put("org.quartz.jobStore.driverDelegateClass", "org.quartz.impl.jdbcjobstore.PostgreSQLDelegate");
//
// factory.setQuartzProperties(prop);
//
// factory.setSchedulerName("RenrenScheduler");
// //延时启动
// factory.setStartupDelay(30);
// factory.setApplicationContextSchedulerContextKey("applicationContextKey");
// //可选QuartzScheduler 启动时更新己存在的Job这样就不用每次修改targetObject后删除qrtz_job_details表对应记录了
// factory.setOverwriteExistingJobs(true);
// //设置自动启动默认为true
// factory.setAutoStartup(true);
//
// return factory;
// }
//}

View File

@@ -0,0 +1,133 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
* <p>
* https://www.renren.io
* <p>
* 版权所有,侵权必究!
*/
package io.renren.modules.job.controller;
import io.renren.common.annotation.LogOperation;
import io.renren.common.constant.Constant;
import io.renren.common.page.PageData;
import io.renren.common.utils.Result;
import io.renren.common.validator.ValidatorUtils;
import io.renren.common.validator.group.AddGroup;
import io.renren.common.validator.group.DefaultGroup;
import io.renren.common.validator.group.UpdateGroup;
import io.renren.modules.job.dto.ScheduleJobDTO;
import io.renren.modules.job.service.ScheduleJobService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
/**
* 定时任务
*
* @author Mark sunlightcs@gmail.com
*/
@RestController
@RequestMapping("/sys/schedule")
@Tag(name = "定时任务")
@AllArgsConstructor
public class ScheduleJobController {
private final ScheduleJobService scheduleJobService;
@GetMapping("page")
@Operation(summary = "分页")
@Parameters({
@Parameter(name = Constant.PAGE, description = "当前页码从1开始", in = ParameterIn.QUERY, required = true, ref = "int"),
@Parameter(name = Constant.LIMIT, description = "每页显示记录数", in = ParameterIn.QUERY, required = true, ref = "int"),
@Parameter(name = Constant.ORDER_FIELD, description = "排序字段", in = ParameterIn.QUERY, ref = "String"),
@Parameter(name = Constant.ORDER, description = "排序方式,可选值(asc、desc)", in = ParameterIn.QUERY, ref = "String"),
@Parameter(name = "beanName", description = "beanName", in = ParameterIn.QUERY, ref = "String")
})
@RequiresPermissions("sys:schedule:page")
public Result<PageData<ScheduleJobDTO>> page(@Parameter(hidden = true) @RequestParam Map<String, Object> params) {
PageData<ScheduleJobDTO> page = scheduleJobService.page(params);
return new Result<PageData<ScheduleJobDTO>>().ok(page);
}
@GetMapping("{id}")
@Operation(summary = "信息")
@RequiresPermissions("sys:schedule:info")
public Result<ScheduleJobDTO> info(@PathVariable("id") Long id) {
ScheduleJobDTO schedule = scheduleJobService.get(id);
return new Result<ScheduleJobDTO>().ok(schedule);
}
@PostMapping
@Operation(summary = "保存")
@LogOperation("保存")
@RequiresPermissions("sys:schedule:save")
public Result save(@RequestBody ScheduleJobDTO dto) {
ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);
scheduleJobService.save(dto);
return new Result();
}
@PutMapping
@Operation(summary = "修改")
@LogOperation("修改")
@RequiresPermissions("sys:schedule:update")
public Result update(@RequestBody ScheduleJobDTO dto) {
ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);
scheduleJobService.update(dto);
return new Result();
}
@DeleteMapping
@Operation(summary = "删除")
@LogOperation("删除")
@RequiresPermissions("sys:schedule:delete")
public Result delete(@RequestBody Long[] ids) {
scheduleJobService.deleteBatch(ids);
return new Result();
}
@PutMapping("/run")
@Operation(summary = "立即执行")
@LogOperation("立即执行")
@RequiresPermissions("sys:schedule:run")
public Result run(@RequestBody Long[] ids) {
scheduleJobService.run(ids);
return new Result();
}
@PutMapping("/pause")
@Operation(summary = "暂停")
@LogOperation("暂停")
@RequiresPermissions("sys:schedule:pause")
public Result pause(@RequestBody Long[] ids) {
scheduleJobService.pause(ids);
return new Result();
}
@PutMapping("/resume")
@Operation(summary = "恢复")
@LogOperation("恢复")
@RequiresPermissions("sys:schedule:resume")
public Result resume(@RequestBody Long[] ids) {
scheduleJobService.resume(ids);
return new Result();
}
}

View File

@@ -0,0 +1,63 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
* <p>
* https://www.renren.io
* <p>
* 版权所有,侵权必究!
*/
package io.renren.modules.job.controller;
import io.renren.common.constant.Constant;
import io.renren.common.page.PageData;
import io.renren.common.utils.Result;
import io.renren.modules.job.dto.ScheduleJobLogDTO;
import io.renren.modules.job.service.ScheduleJobLogService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
/**
* 定时任务日志
*
* @author Mark sunlightcs@gmail.com
*/
@RestController
@RequestMapping("/sys/scheduleLog")
@Tag(name = "定时任务日志")
@AllArgsConstructor
public class ScheduleJobLogController {
private final ScheduleJobLogService scheduleJobLogService;
@GetMapping("page")
@Operation(summary = "分页")
@Parameters({
@Parameter(name = Constant.PAGE, description = "当前页码从1开始", in = ParameterIn.QUERY, required = true, ref = "int"),
@Parameter(name = Constant.LIMIT, description = "每页显示记录数", in = ParameterIn.QUERY, required = true, ref = "int"),
@Parameter(name = Constant.ORDER_FIELD, description = "排序字段", in = ParameterIn.QUERY, ref = "String"),
@Parameter(name = Constant.ORDER, description = "排序方式,可选值(asc、desc)", in = ParameterIn.QUERY, ref = "String"),
@Parameter(name = "jobId", description = "jobId", in = ParameterIn.QUERY, ref = "String")
})
@RequiresPermissions("sys:schedule:log")
public Result<PageData<ScheduleJobLogDTO>> page(@Parameter(hidden = true) @RequestParam Map<String, Object> params) {
PageData<ScheduleJobLogDTO> page = scheduleJobLogService.page(params);
return new Result<PageData<ScheduleJobLogDTO>>().ok(page);
}
@GetMapping("{id}")
@Operation(summary = "信息")
@RequiresPermissions("sys:schedule:log")
public Result<ScheduleJobLogDTO> info(@PathVariable("id") Long id) {
ScheduleJobLogDTO log = scheduleJobLogService.get(id);
return new Result<ScheduleJobLogDTO>().ok(log);
}
}

View File

@@ -0,0 +1,29 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package io.renren.modules.job.dao;
import io.renren.common.dao.BaseDao;
import io.renren.modules.job.entity.ScheduleJobEntity;
import org.apache.ibatis.annotations.Mapper;
import java.util.Map;
/**
* 定时任务
*
* @author Mark sunlightcs@gmail.com
*/
@Mapper
public interface ScheduleJobDao extends BaseDao<ScheduleJobEntity> {
/**
* 批量更新状态
*/
int updateBatch(Map<String, Object> map);
}

View File

@@ -0,0 +1,23 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package io.renren.modules.job.dao;
import io.renren.common.dao.BaseDao;
import io.renren.modules.job.entity.ScheduleJobLogEntity;
import org.apache.ibatis.annotations.Mapper;
/**
* 定时任务日志
*
* @author Mark sunlightcs@gmail.com
*/
@Mapper
public interface ScheduleJobLogDao extends BaseDao<ScheduleJobLogEntity> {
}

View File

@@ -0,0 +1,63 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package io.renren.modules.job.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.renren.common.validator.group.AddGroup;
import io.renren.common.validator.group.DefaultGroup;
import io.renren.common.validator.group.UpdateGroup;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Null;
import lombok.Data;
import org.hibernate.validator.constraints.Range;
import java.io.Serializable;
import java.util.Date;
/**
* 定时任务
*
* @author Mark sunlightcs@gmail.com
* @since 1.0.0
*/
@Data
@Schema(title = "定时任务")
public class ScheduleJobDTO implements Serializable {
private static final long serialVersionUID = 1L;
@Schema(title = "id")
@Null(message="{id.null}", groups = AddGroup.class)
@NotNull(message="{id.require}", groups = UpdateGroup.class)
private Long id;
@Schema(title = "spring bean名称")
@NotBlank(message = "{schedule.bean.require}", groups = DefaultGroup.class)
private String beanName;
@Schema(title = "参数")
private String params;
@Schema(title = "cron表达式")
@NotBlank(message = "{schedule.cron.require}", groups = DefaultGroup.class)
private String cronExpression;
@Schema(title = "任务状态 0暂停 1正常")
@Range(min=0, max=1, message = "{schedule.status.range}", groups = DefaultGroup.class)
private Integer status;
@Schema(title = "备注")
private String remark;
@Schema(title = "创建时间")
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private Date createDate;
}

View File

@@ -0,0 +1,52 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package io.renren.modules.job.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
* 定时任务日志
*
* @author Mark sunlightcs@gmail.com
* @since 1.0.0
*/
@Data
@Schema(title = "定时任务日志")
public class ScheduleJobLogDTO implements Serializable {
private static final long serialVersionUID = 1L;
@Schema(title = "id")
private Long id;
@Schema(title = "任务id")
private Long jobId;
@Schema(title = "spring bean名称")
private String beanName;
@Schema(title = "参数")
private String params;
@Schema(title = "任务状态 0失败 1成功")
private Integer status;
@Schema(title = "失败信息")
private String error;
@Schema(title = "耗时(单位:毫秒)")
private Integer times;
@Schema(title = "创建时间")
private Date createDate;
}

View File

@@ -0,0 +1,61 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package io.renren.modules.job.entity;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import io.renren.common.entity.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.util.Date;
/**
* 定时任务
*
* @author Mark sunlightcs@gmail.com
*/
@Data
@EqualsAndHashCode(callSuper=false)
@TableName("schedule_job")
public class ScheduleJobEntity extends BaseEntity {
private static final long serialVersionUID = 1L;
/**
* spring bean名称
*/
private String beanName;
/**
* 参数
*/
private String params;
/**
* cron表达式
*/
private String cronExpression;
/**
* 任务状态 0暂停 1正常
*/
private Integer status;
/**
* 备注
*/
private String remark;
/**
* 更新者
*/
@TableField(fill = FieldFill.INSERT_UPDATE)
private Long updater;
/**
* 更新时间
*/
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateDate;
}

View File

@@ -0,0 +1,62 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package io.renren.modules.job.entity;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
* 定时任务日志
*
* @author Mark sunlightcs@gmail.com
*/
@Data
@TableName("schedule_job_log")
public class ScheduleJobLogEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
* id
*/
@TableId
private Long id;
/**
* 任务id
*/
private Long jobId;
/**
* spring bean名称
*/
private String beanName;
/**
* 参数
*/
private String params;
/**
* 任务状态 0失败 1成功
*/
private Integer status;
/**
* 失败信息
*/
private String error;
/**
* 耗时(单位:毫秒)
*/
private Integer times;
/**
* 创建时间
*/
private Date createDate;
}

View File

@@ -0,0 +1,46 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
* <p>
* https://www.renren.io
* <p>
* 版权所有,侵权必究!
*/
package io.renren.modules.job.init;
import io.renren.modules.job.dao.ScheduleJobDao;
import io.renren.modules.job.entity.ScheduleJobEntity;
import io.renren.modules.job.utils.ScheduleUtils;
import lombok.AllArgsConstructor;
import org.quartz.CronTrigger;
import org.quartz.Scheduler;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import java.util.List;
/**
* 初始化定时任务数据
*
* @author Mark sunlightcs@gmail.com
*/
@Component
@AllArgsConstructor
public class JobCommandLineRunner implements CommandLineRunner {
private final Scheduler scheduler;
private final ScheduleJobDao scheduleJobDao;
@Override
public void run(String... args) {
List<ScheduleJobEntity> scheduleJobList = scheduleJobDao.selectList(null);
for (ScheduleJobEntity scheduleJob : scheduleJobList) {
CronTrigger cronTrigger = ScheduleUtils.getCronTrigger(scheduler, scheduleJob.getId());
//如果不存在,则创建
if (cronTrigger == null) {
ScheduleUtils.createScheduleJob(scheduler, scheduleJob);
} else {
ScheduleUtils.updateScheduleJob(scheduler, scheduleJob);
}
}
}
}

View File

@@ -0,0 +1,28 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package io.renren.modules.job.service;
import io.renren.common.page.PageData;
import io.renren.common.service.BaseService;
import io.renren.modules.job.dto.ScheduleJobLogDTO;
import io.renren.modules.job.entity.ScheduleJobLogEntity;
import java.util.Map;
/**
* 定时任务日志
*
* @author Mark sunlightcs@gmail.com
*/
public interface ScheduleJobLogService extends BaseService<ScheduleJobLogEntity> {
PageData<ScheduleJobLogDTO> page(Map<String, Object> params);
ScheduleJobLogDTO get(Long id);
}

View File

@@ -0,0 +1,63 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package io.renren.modules.job.service;
import io.renren.common.page.PageData;
import io.renren.common.service.BaseService;
import io.renren.modules.job.dto.ScheduleJobDTO;
import io.renren.modules.job.entity.ScheduleJobEntity;
import java.util.Map;
/**
* 定时任务
*
* @author Mark sunlightcs@gmail.com
*/
public interface ScheduleJobService extends BaseService<ScheduleJobEntity> {
PageData<ScheduleJobDTO> page(Map<String, Object> params);
ScheduleJobDTO get(Long id);
/**
* 保存定时任务
*/
void save(ScheduleJobDTO dto);
/**
* 更新定时任务
*/
void update(ScheduleJobDTO dto);
/**
* 批量删除定时任务
*/
void deleteBatch(Long[] ids);
/**
* 批量更新定时任务状态
*/
int updateBatch(Long[] ids, int status);
/**
* 立即执行
*/
void run(Long[] ids);
/**
* 暂停运行
*/
void pause(Long[] ids);
/**
* 恢复运行
*/
void resume(Long[] ids);
}

View File

@@ -0,0 +1,54 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package io.renren.modules.job.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.renren.common.constant.Constant;
import io.renren.common.page.PageData;
import io.renren.common.service.impl.BaseServiceImpl;
import io.renren.common.utils.ConvertUtils;
import io.renren.modules.job.dao.ScheduleJobLogDao;
import io.renren.modules.job.dto.ScheduleJobLogDTO;
import io.renren.modules.job.entity.ScheduleJobLogEntity;
import io.renren.modules.job.service.ScheduleJobLogService;
import cn.hutool.core.util.StrUtil;
import org.springframework.stereotype.Service;
import java.util.Map;
@Service
public class ScheduleJobLogServiceImpl extends BaseServiceImpl<ScheduleJobLogDao, ScheduleJobLogEntity> implements ScheduleJobLogService {
@Override
public PageData<ScheduleJobLogDTO> page(Map<String, Object> params) {
IPage<ScheduleJobLogEntity> page = baseDao.selectPage(
getPage(params, Constant.CREATE_DATE, false),
getWrapper(params)
);
return getPageData(page, ScheduleJobLogDTO.class);
}
private QueryWrapper<ScheduleJobLogEntity> getWrapper(Map<String, Object> params){
String jobId = (String)params.get("jobId");
QueryWrapper<ScheduleJobLogEntity> wrapper = new QueryWrapper<>();
wrapper.eq(StrUtil.isNotBlank(jobId), "job_id", jobId);
return wrapper;
}
@Override
public ScheduleJobLogDTO get(Long id) {
ScheduleJobLogEntity entity = baseDao.selectById(id);
return ConvertUtils.sourceToTarget(entity, ScheduleJobLogDTO.class);
}
}

View File

@@ -0,0 +1,130 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
* <p>
* https://www.renren.io
* <p>
* 版权所有,侵权必究!
*/
package io.renren.modules.job.service.impl;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.renren.common.constant.Constant;
import io.renren.common.page.PageData;
import io.renren.common.service.impl.BaseServiceImpl;
import io.renren.common.utils.ConvertUtils;
import io.renren.modules.job.dao.ScheduleJobDao;
import io.renren.modules.job.dto.ScheduleJobDTO;
import io.renren.modules.job.entity.ScheduleJobEntity;
import io.renren.modules.job.service.ScheduleJobService;
import io.renren.modules.job.utils.ScheduleUtils;
import lombok.AllArgsConstructor;
import org.quartz.Scheduler;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
@Service
@AllArgsConstructor
public class ScheduleJobServiceImpl extends BaseServiceImpl<ScheduleJobDao, ScheduleJobEntity> implements ScheduleJobService {
private final Scheduler scheduler;
@Override
public PageData<ScheduleJobDTO> page(Map<String, Object> params) {
IPage<ScheduleJobEntity> page = baseDao.selectPage(
getPage(params, Constant.CREATE_DATE, false),
getWrapper(params)
);
return getPageData(page, ScheduleJobDTO.class);
}
@Override
public ScheduleJobDTO get(Long id) {
ScheduleJobEntity entity = baseDao.selectById(id);
return ConvertUtils.sourceToTarget(entity, ScheduleJobDTO.class);
}
private QueryWrapper<ScheduleJobEntity> getWrapper(Map<String, Object> params) {
String beanName = (String) params.get("beanName");
QueryWrapper<ScheduleJobEntity> wrapper = new QueryWrapper<>();
wrapper.like(StrUtil.isNotBlank(beanName), "bean_name", beanName);
return wrapper;
}
@Override
@Transactional(rollbackFor = Exception.class)
public void save(ScheduleJobDTO dto) {
ScheduleJobEntity entity = ConvertUtils.sourceToTarget(dto, ScheduleJobEntity.class);
entity.setStatus(Constant.ScheduleStatus.NORMAL.getValue());
this.insert(entity);
ScheduleUtils.createScheduleJob(scheduler, entity);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void update(ScheduleJobDTO dto) {
ScheduleJobEntity entity = ConvertUtils.sourceToTarget(dto, ScheduleJobEntity.class);
ScheduleUtils.updateScheduleJob(scheduler, entity);
this.updateById(entity);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void deleteBatch(Long[] ids) {
for (Long id : ids) {
ScheduleUtils.deleteScheduleJob(scheduler, id);
}
//删除数据
this.deleteBatchIds(Arrays.asList(ids));
}
@Override
public int updateBatch(Long[] ids, int status) {
Map<String, Object> map = new HashMap<>(2);
map.put("ids", ids);
map.put("status", status);
return baseDao.updateBatch(map);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void run(Long[] ids) {
for (Long id : ids) {
ScheduleUtils.run(scheduler, this.selectById(id));
}
}
@Override
@Transactional(rollbackFor = Exception.class)
public void pause(Long[] ids) {
for (Long id : ids) {
ScheduleUtils.pauseJob(scheduler, id);
}
updateBatch(ids, Constant.ScheduleStatus.PAUSE.getValue());
}
@Override
@Transactional(rollbackFor = Exception.class)
public void resume(Long[] ids) {
for (Long id : ids) {
ScheduleUtils.resumeJob(scheduler, id);
}
updateBatch(ids, Constant.ScheduleStatus.NORMAL.getValue());
}
}

View File

@@ -0,0 +1,25 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package io.renren.modules.job.task;
/**
* 定时任务接口,所有定时任务都要实现该接口
*
* @author Mark sunlightcs@gmail.com
* @since 1.0.0
*/
public interface ITask {
/**
* 执行定时任务接口
*
* @param params 参数多参数使用JSON数据
*/
void run(String params);
}

View File

@@ -0,0 +1,30 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package io.renren.modules.job.task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
/**
* 测试定时任务(演示Demo可删除)
*
* testTask为spring bean的名称
*
* @author Mark sunlightcs@gmail.com
*/
@Component("testTask")
public class TestTask implements ITask{
private Logger logger = LoggerFactory.getLogger(getClass());
@Override
public void run(String params){
logger.debug("TestTask定时任务正在执行参数为{}", params);
}
}

View File

@@ -0,0 +1,79 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package io.renren.modules.job.utils;
import io.renren.common.constant.Constant;
import io.renren.common.exception.ExceptionUtils;
import io.renren.common.utils.SpringContextUtils;
import io.renren.modules.job.entity.ScheduleJobEntity;
import io.renren.modules.job.entity.ScheduleJobLogEntity;
import io.renren.modules.job.service.ScheduleJobLogService;
import org.quartz.JobExecutionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.quartz.QuartzJobBean;
import java.lang.reflect.Method;
import java.util.Date;
/**
* 定时任务
*
* @author Mark sunlightcs@gmail.com
*/
public class ScheduleJob extends QuartzJobBean {
private Logger logger = LoggerFactory.getLogger(getClass());
@Override
protected void executeInternal(JobExecutionContext context) {
ScheduleJobEntity scheduleJob = (ScheduleJobEntity) context.getMergedJobDataMap().
get(ScheduleUtils.JOB_PARAM_KEY);
//数据库保存执行记录
ScheduleJobLogEntity log = new ScheduleJobLogEntity();
log.setJobId(scheduleJob.getId());
log.setBeanName(scheduleJob.getBeanName());
log.setParams(scheduleJob.getParams());
log.setCreateDate(new Date());
//任务开始时间
long startTime = System.currentTimeMillis();
try {
//执行任务
logger.info("任务准备执行任务ID{}", scheduleJob.getId());
Object target = SpringContextUtils.getBean(scheduleJob.getBeanName());
Method method = target.getClass().getDeclaredMethod("run", String.class);
method.invoke(target, scheduleJob.getParams());
//任务执行总时长
long times = System.currentTimeMillis() - startTime;
log.setTimes((int)times);
//任务状态
log.setStatus(Constant.SUCCESS);
logger.info("任务执行完毕任务ID{} 总共耗时:{} 毫秒", scheduleJob.getId(), times);
} catch (Exception e) {
logger.error("任务执行失败任务ID{}", scheduleJob.getId(), e);
//任务执行总时长
long times = System.currentTimeMillis() - startTime;
log.setTimes((int)times);
//任务状态
log.setStatus(Constant.FAIL);
log.setError(ExceptionUtils.getErrorStackTrace(e));
}finally {
//获取spring bean
ScheduleJobLogService scheduleJobLogService = SpringContextUtils.getBean(ScheduleJobLogService.class);
scheduleJobLogService.insert(log);
}
}
}

View File

@@ -0,0 +1,161 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package io.renren.modules.job.utils;
import io.renren.common.constant.Constant;
import io.renren.common.exception.ErrorCode;
import io.renren.common.exception.RenException;
import io.renren.modules.job.entity.ScheduleJobEntity;
import org.quartz.*;
/**
* 定时任务工具类
*
* @author Mark sunlightcs@gmail.com
*/
public class ScheduleUtils {
private final static String JOB_NAME = "TASK_";
/**
* 任务调度参数key
*/
public static final String JOB_PARAM_KEY = "JOB_PARAM_KEY";
/**
* 获取触发器key
*/
public static TriggerKey getTriggerKey(Long jobId) {
return TriggerKey.triggerKey(JOB_NAME + jobId);
}
/**
* 获取jobKey
*/
public static JobKey getJobKey(Long jobId) {
return JobKey.jobKey(JOB_NAME + jobId);
}
/**
* 获取表达式触发器
*/
public static CronTrigger getCronTrigger(Scheduler scheduler, Long jobId) {
try {
return (CronTrigger) scheduler.getTrigger(getTriggerKey(jobId));
} catch (SchedulerException e) {
throw new RenException(ErrorCode.JOB_ERROR, e);
}
}
/**
* 创建定时任务
*/
public static void createScheduleJob(Scheduler scheduler, ScheduleJobEntity scheduleJob) {
try {
//构建job信息
JobDetail jobDetail = JobBuilder.newJob(ScheduleJob.class).withIdentity(getJobKey(scheduleJob.getId())).build();
//表达式调度构建器
CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(scheduleJob.getCronExpression())
.withMisfireHandlingInstructionDoNothing();
//按新的cronExpression表达式构建一个新的trigger
CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(getTriggerKey(scheduleJob.getId())).withSchedule(scheduleBuilder).build();
//放入参数,运行时的方法可以获取
jobDetail.getJobDataMap().put(JOB_PARAM_KEY, scheduleJob);
scheduler.scheduleJob(jobDetail, trigger);
//暂停任务
if(scheduleJob.getStatus() == Constant.ScheduleStatus.PAUSE.getValue()){
pauseJob(scheduler, scheduleJob.getId());
}
} catch (SchedulerException e) {
throw new RenException(ErrorCode.JOB_ERROR, e);
}
}
/**
* 更新定时任务
*/
public static void updateScheduleJob(Scheduler scheduler, ScheduleJobEntity scheduleJob) {
try {
TriggerKey triggerKey = getTriggerKey(scheduleJob.getId());
//表达式调度构建器
CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(scheduleJob.getCronExpression())
.withMisfireHandlingInstructionDoNothing();
CronTrigger trigger = getCronTrigger(scheduler, scheduleJob.getId());
//按新的cronExpression表达式重新构建trigger
trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();
//参数
trigger.getJobDataMap().put(JOB_PARAM_KEY, scheduleJob);
scheduler.rescheduleJob(triggerKey, trigger);
//暂停任务
if(scheduleJob.getStatus() == Constant.ScheduleStatus.PAUSE.getValue()){
pauseJob(scheduler, scheduleJob.getId());
}
} catch (SchedulerException e) {
throw new RenException(ErrorCode.JOB_ERROR, e);
}
}
/**
* 立即执行任务
*/
public static void run(Scheduler scheduler, ScheduleJobEntity scheduleJob) {
try {
//参数
JobDataMap dataMap = new JobDataMap();
dataMap.put(JOB_PARAM_KEY, scheduleJob);
scheduler.triggerJob(getJobKey(scheduleJob.getId()), dataMap);
} catch (SchedulerException e) {
throw new RenException(ErrorCode.JOB_ERROR, e);
}
}
/**
* 暂停任务
*/
public static void pauseJob(Scheduler scheduler, Long jobId) {
try {
scheduler.pauseJob(getJobKey(jobId));
} catch (SchedulerException e) {
throw new RenException(ErrorCode.JOB_ERROR, e);
}
}
/**
* 恢复任务
*/
public static void resumeJob(Scheduler scheduler, Long jobId) {
try {
scheduler.resumeJob(getJobKey(jobId));
} catch (SchedulerException e) {
throw new RenException(ErrorCode.JOB_ERROR, e);
}
}
/**
* 删除定时任务
*/
public static void deleteScheduleJob(Scheduler scheduler, Long jobId) {
try {
scheduler.deleteJob(getJobKey(jobId));
} catch (SchedulerException e) {
throw new RenException(ErrorCode.JOB_ERROR, e);
}
}
}

View File

@@ -0,0 +1,74 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
* <p>
* https://www.renren.io
* <p>
* 版权所有,侵权必究!
*/
package io.renren.modules.log.controller;
import io.renren.common.annotation.LogOperation;
import io.renren.common.constant.Constant;
import io.renren.common.page.PageData;
import io.renren.common.utils.ExcelUtils;
import io.renren.common.utils.Result;
import io.renren.modules.log.dto.SysLogErrorDTO;
import io.renren.modules.log.excel.SysLogErrorExcel;
import io.renren.modules.log.service.SysLogErrorService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
/**
* 异常日志
*
* @author Mark sunlightcs@gmail.com
* @since 1.0.0
*/
@RestController
@RequestMapping("sys/log/error")
@Tag(name = "异常日志")
@AllArgsConstructor
public class SysLogErrorController {
private final SysLogErrorService sysLogErrorService;
@GetMapping("page")
@Operation(summary = "分页")
@Parameters({
@Parameter(name = Constant.PAGE, description = "当前页码从1开始", in = ParameterIn.QUERY, required = true, ref = "int"),
@Parameter(name = Constant.LIMIT, description = "每页显示记录数", in = ParameterIn.QUERY, required = true, ref = "int"),
@Parameter(name = Constant.ORDER_FIELD, description = "排序字段", in = ParameterIn.QUERY, ref = "String"),
@Parameter(name = Constant.ORDER, description = "排序方式,可选值(asc、desc)", in = ParameterIn.QUERY, ref = "String")
})
@RequiresPermissions("sys:log:error")
public Result<PageData<SysLogErrorDTO>> page(@Parameter(hidden = true) @RequestParam Map<String, Object> params) {
PageData<SysLogErrorDTO> page = sysLogErrorService.page(params);
return new Result<PageData<SysLogErrorDTO>>().ok(page);
}
@GetMapping("export")
@Operation(summary = "导出")
@LogOperation("导出")
@RequiresPermissions("sys:log:error")
public void export(@Parameter(hidden = true) @RequestParam Map<String, Object> params, HttpServletResponse response) throws Exception {
List<SysLogErrorDTO> list = sysLogErrorService.list(params);
ExcelUtils.exportExcelToTarget(response, null, "异常日志", list, SysLogErrorExcel.class);
}
}

View File

@@ -0,0 +1,81 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
* <p>
* https://www.renren.io
* <p>
* 版权所有,侵权必究!
*/
package io.renren.modules.log.controller;
import io.renren.common.annotation.LogOperation;
import io.renren.common.constant.Constant;
import io.renren.common.page.PageData;
import io.renren.common.utils.ExcelUtils;
import io.renren.common.utils.Result;
import io.renren.modules.log.dto.SysLogLoginDTO;
import io.renren.modules.log.excel.SysLogLoginExcel;
import io.renren.modules.log.service.SysLogLoginService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
/**
* 登录日志
*
* @author Mark sunlightcs@gmail.com
* @since 1.0.0
*/
@RestController
@RequestMapping("sys/log/login")
@Tag(name = "登录日志")
@AllArgsConstructor
public class SysLogLoginController {
private final SysLogLoginService sysLogLoginService;
@GetMapping("page")
@Operation(summary = "分页")
@Parameters({
@Parameter(name = Constant.PAGE, description = "当前页码从1开始", in = ParameterIn.QUERY, required = true, ref = "int"),
@Parameter(name = Constant.LIMIT, description = "每页显示记录数", in = ParameterIn.QUERY, required = true, ref = "int"),
@Parameter(name = Constant.ORDER_FIELD, description = "排序字段", in = ParameterIn.QUERY, ref = "String"),
@Parameter(name = Constant.ORDER, description = "排序方式,可选值(asc、desc)", in = ParameterIn.QUERY, ref = "String"),
@Parameter(name = "status", description = "状态 0失败 1成功 2账号已锁定", in = ParameterIn.QUERY, ref = "int"),
@Parameter(name = "creatorName", description = "用户名", in = ParameterIn.QUERY, ref = "String")
})
@RequiresPermissions("sys:log:login")
public Result<PageData<SysLogLoginDTO>> page(@Parameter(hidden = true) @RequestParam Map<String, Object> params) {
PageData<SysLogLoginDTO> page = sysLogLoginService.page(params);
return new Result<PageData<SysLogLoginDTO>>().ok(page);
}
@GetMapping("export")
@Operation(summary = "导出")
@LogOperation("导出")
@Parameters({
@Parameter(name = "status", description = "状态 0失败 1成功 2账号已锁定", in = ParameterIn.QUERY, ref = "int"),
@Parameter(name = "creatorName", description = "用户名", in = ParameterIn.QUERY, ref = "String")
})
@RequiresPermissions("sys:log:login")
public void export(@Parameter(hidden = true) @RequestParam Map<String, Object> params, HttpServletResponse response) throws Exception {
List<SysLogLoginDTO> list = sysLogLoginService.list(params);
ExcelUtils.exportExcelToTarget(response, null, "登录日志", list, SysLogLoginExcel.class);
}
}

View File

@@ -0,0 +1,75 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
* <p>
* https://www.renren.io
* <p>
* 版权所有,侵权必究!
*/
package io.renren.modules.log.controller;
import io.renren.common.annotation.LogOperation;
import io.renren.common.constant.Constant;
import io.renren.common.page.PageData;
import io.renren.common.utils.ExcelUtils;
import io.renren.common.utils.Result;
import io.renren.modules.log.dto.SysLogOperationDTO;
import io.renren.modules.log.excel.SysLogOperationExcel;
import io.renren.modules.log.service.SysLogOperationService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
/**
* 操作日志
*
* @author Mark sunlightcs@gmail.com
* @since 1.0.0
*/
@RestController
@RequestMapping("sys/log/operation")
@Tag(name = "操作日志")
@AllArgsConstructor
public class SysLogOperationController {
private final SysLogOperationService sysLogOperationService;
@GetMapping("page")
@Operation(summary = "分页")
@Parameters({
@Parameter(name = Constant.PAGE, description = "当前页码从1开始", in = ParameterIn.QUERY, required = true, ref = "int"),
@Parameter(name = Constant.LIMIT, description = "每页显示记录数", in = ParameterIn.QUERY, required = true, ref = "int"),
@Parameter(name = Constant.ORDER_FIELD, description = "排序字段", in = ParameterIn.QUERY, ref = "String"),
@Parameter(name = Constant.ORDER, description = "排序方式,可选值(asc、desc)", in = ParameterIn.QUERY, ref = "String"),
@Parameter(name = "status", description = "状态 0失败 1成功", in = ParameterIn.QUERY, ref = "int")
})
@RequiresPermissions("sys:log:operation")
public Result<PageData<SysLogOperationDTO>> page(@Parameter(hidden = true) @RequestParam Map<String, Object> params) {
PageData<SysLogOperationDTO> page = sysLogOperationService.page(params);
return new Result<PageData<SysLogOperationDTO>>().ok(page);
}
@GetMapping("export")
@Operation(summary = "导出")
@LogOperation("导出")
@RequiresPermissions("sys:log:operation")
public void export(@Parameter(hidden = true) @RequestParam Map<String, Object> params, HttpServletResponse response) throws Exception {
List<SysLogOperationDTO> list = sysLogOperationService.list(params);
ExcelUtils.exportExcelToTarget(response, null, "操作日志", list, SysLogOperationExcel.class);
}
}

View File

@@ -0,0 +1,24 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package io.renren.modules.log.dao;
import io.renren.common.dao.BaseDao;
import io.renren.modules.log.entity.SysLogErrorEntity;
import org.apache.ibatis.annotations.Mapper;
/**
* 异常日志
*
* @author Mark sunlightcs@gmail.com
* @since 1.0.0
*/
@Mapper
public interface SysLogErrorDao extends BaseDao<SysLogErrorEntity> {
}

View File

@@ -0,0 +1,24 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package io.renren.modules.log.dao;
import io.renren.common.dao.BaseDao;
import io.renren.modules.log.entity.SysLogLoginEntity;
import org.apache.ibatis.annotations.Mapper;
/**
* 登录日志
*
* @author Mark sunlightcs@gmail.com
* @since 1.0.0
*/
@Mapper
public interface SysLogLoginDao extends BaseDao<SysLogLoginEntity> {
}

View File

@@ -0,0 +1,24 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package io.renren.modules.log.dao;
import io.renren.common.dao.BaseDao;
import io.renren.modules.log.entity.SysLogOperationEntity;
import org.apache.ibatis.annotations.Mapper;
/**
* 操作日志
*
* @author Mark sunlightcs@gmail.com
* @since 1.0.0
*/
@Mapper
public interface SysLogOperationDao extends BaseDao<SysLogOperationEntity> {
}

View File

@@ -0,0 +1,47 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
* <p>
* https://www.renren.io
* <p>
* 版权所有,侵权必究!
*/
package io.renren.modules.log.dto;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.renren.common.utils.DateUtils;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
* 异常日志
*
* @author Mark sunlightcs@gmail.com
* @since 1.0.0
*/
@Data
@Schema(description = "异常日志")
public class SysLogErrorDTO implements Serializable {
@Schema(description = "id")
private Long id;
@Schema(description = "请求URI")
private String requestUri;
@Schema(description = "请求方式")
private String requestMethod;
@Schema(description = "请求参数")
private String requestParams;
@Schema(description = "用户代理")
private String userAgent;
@Schema(description = "操作IP")
private String ip;
@Schema(description = "异常信息")
private String errorInfo;
@Schema(description = "创建时间")
@JsonFormat(pattern = DateUtils.DATE_TIME_PATTERN)
private Date createDate;
}

View File

@@ -0,0 +1,51 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
* <p>
* https://www.renren.io
* <p>
* 版权所有,侵权必究!
*/
package io.renren.modules.log.dto;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.renren.common.utils.DateUtils;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
* 登录日志
*
* @author Mark sunlightcs@gmail.com
* @since 1.0.0
*/
@Data
@Schema(description = "登录日志")
public class SysLogLoginDTO implements Serializable {
@Schema(description = "id")
private Long id;
@Schema(description = "用户操作 0用户登录 1用户退出")
private Integer operation;
@Schema(description = "状态 0失败 1成功 2账号已锁定")
private Integer status;
@Schema(description = "用户代理")
private String userAgent;
@Schema(description = "操作IP")
private String ip;
@Schema(description = "用户名")
private String creatorName;
@Schema(description = "创建时间")
@JsonFormat(pattern = DateUtils.DATE_TIME_PATTERN)
private Date createDate;
}

View File

@@ -0,0 +1,62 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
* <p>
* https://www.renren.io
* <p>
* 版权所有,侵权必究!
*/
package io.renren.modules.log.dto;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.renren.common.utils.DateUtils;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
* 操作日志
*
* @author Mark sunlightcs@gmail.com
* @since 1.0.0
*/
@Data
@Schema(description = "操作日志")
public class SysLogOperationDTO implements Serializable {
@Schema(description = "id")
private Long id;
@Schema(description = "用户操作")
private String operation;
@Schema(description = "请求URI")
private String requestUri;
@Schema(description = "请求方式")
private String requestMethod;
@Schema(description = "请求参数")
private String requestParams;
@Schema(description = "请求时长(毫秒)")
private Integer requestTime;
@Schema(description = "用户代理")
private String userAgent;
@Schema(description = "操作IP")
private String ip;
@Schema(description = "状态 0失败 1成功")
private Integer status;
@Schema(description = "用户名")
private String creatorName;
@Schema(description = "创建时间")
@JsonFormat(pattern = DateUtils.DATE_TIME_PATTERN)
private Date createDate;
}

View File

@@ -0,0 +1,53 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package io.renren.modules.log.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import io.renren.common.entity.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* 异常日志
*
* @author Mark sunlightcs@gmail.com
* @since 1.0.0
*/
@Data
@EqualsAndHashCode(callSuper=false)
@TableName("sys_log_error")
public class SysLogErrorEntity extends BaseEntity {
private static final long serialVersionUID = 1L;
/**
* 请求URI
*/
private String requestUri;
/**
* 请求方式
*/
private String requestMethod;
/**
* 请求参数
*/
private String requestParams;
/**
* 用户代理
*/
private String userAgent;
/**
* 操作IP
*/
private String ip;
/**
* 异常信息
*/
private String errorInfo;
}

View File

@@ -0,0 +1,49 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package io.renren.modules.log.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import io.renren.common.entity.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* 登录日志
*
* @author Mark sunlightcs@gmail.com
* @since 1.0.0
*/
@Data
@EqualsAndHashCode(callSuper=false)
@TableName("sys_log_login")
public class SysLogLoginEntity extends BaseEntity {
private static final long serialVersionUID = 1L;
/**
* 用户操作 0用户登录 1用户退出
*/
private Integer operation;
/**
* 状态 0失败 1成功 2账号已锁定
*/
private Integer status;
/**
* 用户代理
*/
private String userAgent;
/**
* 操作IP
*/
private String ip;
/**
* 用户名
*/
private String creatorName;
}

View File

@@ -0,0 +1,64 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package io.renren.modules.log.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import io.renren.common.entity.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* 操作日志
*
* @author Mark sunlightcs@gmail.com
* @since 1.0.0
*/
@Data
@EqualsAndHashCode(callSuper=false)
@TableName("sys_log_operation")
public class SysLogOperationEntity extends BaseEntity {
private static final long serialVersionUID = 1L;
/**
* 用户操作
*/
private String operation;
/**
* 请求URI
*/
private String requestUri;
/**
* 请求方式
*/
private String requestMethod;
/**
* 请求参数
*/
private String requestParams;
/**
* 请求时长(毫秒)
*/
private Integer requestTime;
/**
* 用户代理
*/
private String userAgent;
/**
* 操作IP
*/
private String ip;
/**
* 状态 0失败 1成功
*/
private Integer status;
/**
* 用户名
*/
private String creatorName;
}

View File

@@ -0,0 +1,36 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package io.renren.modules.log.enums;
/**
* 登录操作枚举
*
* @author Mark sunlightcs@gmail.com
* @since 1.0.0
*/
public enum LoginOperationEnum {
/**
* 用户登录
*/
LOGIN(0),
/**
* 用户退出
*/
LOGOUT(1);
private int value;
LoginOperationEnum(int value) {
this.value = value;
}
public int value() {
return this.value;
}
}

View File

@@ -0,0 +1,40 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package io.renren.modules.log.enums;
/**
* 登录状态枚举
*
* @author Mark sunlightcs@gmail.com
* @since 1.0.0
*/
public enum LoginStatusEnum {
/**
* 失败
*/
FAIL(0),
/**
* 成功
*/
SUCCESS(1),
/**
* 账号已锁定
*/
LOCK(2);
private int value;
LoginStatusEnum(int value) {
this.value = value;
}
public int value() {
return this.value;
}
}

View File

@@ -0,0 +1,36 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package io.renren.modules.log.enums;
/**
* 操作状态枚举
*
* @author Mark sunlightcs@gmail.com
* @since 1.0.0
*/
public enum OperationStatusEnum {
/**
* 失败
*/
FAIL(0),
/**
* 成功
*/
SUCCESS(1);
private int value;
OperationStatusEnum(int value) {
this.value = value;
}
public int value() {
return this.value;
}
}

View File

@@ -0,0 +1,49 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package io.renren.modules.log.excel;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.format.DateTimeFormat;
import com.alibaba.excel.annotation.write.style.ColumnWidth;
import com.alibaba.excel.annotation.write.style.ContentRowHeight;
import com.alibaba.excel.annotation.write.style.HeadRowHeight;
import lombok.Data;
import java.util.Date;
/**
* 异常日志
*
* @author Mark sunlightcs@gmail.com
*/
@Data
@ContentRowHeight(20)
@HeadRowHeight(20)
@ColumnWidth(25)
public class SysLogErrorExcel {
@ExcelProperty("请求URI")
private String requestUri;
@ExcelProperty("请求方式")
private String requestMethod;
@ExcelProperty("请求参数")
private String requestParams;
@ExcelProperty("User-Agent")
private String userAgent;
@ExcelProperty("操作IP")
private String ip;
@DateTimeFormat("yyyy-MM-dd HH:mm:ss")
@ExcelProperty("创建时间")
private Date createDate;
}

View File

@@ -0,0 +1,51 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package io.renren.modules.log.excel;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.format.DateTimeFormat;
import com.alibaba.excel.annotation.write.style.ColumnWidth;
import com.alibaba.excel.annotation.write.style.ContentRowHeight;
import com.alibaba.excel.annotation.write.style.HeadRowHeight;
import io.renren.modules.log.excel.converter.SysLogOperationConverter;
import io.renren.modules.log.excel.converter.SysLogStatusConverter;
import lombok.Data;
import java.util.Date;
/**
* 登录日志
*
* @author Mark sunlightcs@gmail.com
*/
@Data
@ContentRowHeight(20)
@HeadRowHeight(20)
@ColumnWidth(25)
public class SysLogLoginExcel {
@ExcelProperty(value = "操作类型", converter = SysLogOperationConverter.class)
private Integer operation;
@ExcelProperty(value = "状态", converter = SysLogStatusConverter.class)
private Integer status;
@ExcelProperty("User-Agent")
private String userAgent;
@ExcelProperty("操作IP")
private String ip;
@ExcelProperty("用户名")
private String creatorName;
@DateTimeFormat("yyyy-MM-dd HH:mm:ss")
@ExcelProperty("创建时间")
private Date createDate;
}

View File

@@ -0,0 +1,61 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
* <p>
* https://www.renren.io
* <p>
* 版权所有,侵权必究!
*/
package io.renren.modules.log.excel;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.format.DateTimeFormat;
import com.alibaba.excel.annotation.write.style.ColumnWidth;
import com.alibaba.excel.annotation.write.style.ContentRowHeight;
import com.alibaba.excel.annotation.write.style.HeadRowHeight;
import lombok.Data;
import java.util.Date;
/**
* 操作日志
*
* @author Mark sunlightcs@gmail.com
*/
@Data
@ContentRowHeight(20)
@HeadRowHeight(20)
@ColumnWidth(25)
public class SysLogOperationExcel {
@ExcelProperty("用户操作")
private String operation;
@ExcelProperty("请求URI")
private String requestUri;
@ExcelProperty("请求方式")
private String requestMethod;
@ExcelProperty("请求参数")
private String requestParams;
@ExcelProperty("请求时长(毫秒)")
private Integer requestTime;
@ExcelProperty("User-Agent")
private String userAgent;
@ExcelProperty("操作IP")
private String ip;
@ExcelProperty("状态")
private Integer status;
@ExcelProperty("用户名")
private String creatorName;
@DateTimeFormat("yyyy-MM-dd HH:mm:ss")
@ExcelProperty("创建时间")
private Date createDate;
}

View File

@@ -0,0 +1,40 @@
package io.renren.modules.log.excel.converter;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
public class SysLogOperationConverter implements Converter<Integer> {
@Override
public Class<Integer> supportJavaTypeKey() {
return Integer.class;
}
@Override
public CellDataTypeEnum supportExcelTypeKey() {
return CellDataTypeEnum.STRING;
}
@Override
public Integer convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
if(cellData.getStringValue().equals("用户登录")){
return 0;
}else{
return 1;
}
}
@Override
public WriteCellData<?> convertToExcelData(Integer value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
if(value == 0){
return new WriteCellData<>("用户登录");
}else{
return new WriteCellData<>("用户退出");
}
}
}

View File

@@ -0,0 +1,48 @@
package io.renren.modules.log.excel.converter;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
public class SysLogStatusConverter implements Converter<Integer> {
@Override
public Class<Integer> supportJavaTypeKey() {
return Integer.class;
}
@Override
public CellDataTypeEnum supportExcelTypeKey() {
return CellDataTypeEnum.STRING;
}
@Override
public Integer convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
if(cellData.getStringValue().equals("失败")){
return 0;
}else if(cellData.getStringValue().equals("成功")){
return 1;
}else if(cellData.getStringValue().equals("账号已锁定")){
return 2;
}else{
return -1;
}
}
@Override
public WriteCellData<?> convertToExcelData(Integer value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
if(value == 0){
return new WriteCellData<>("失败");
}else if(value == 1){
return new WriteCellData<>("成功");
}else if(value == 2){
return new WriteCellData<>("账号已锁定");
}else{
return new WriteCellData<>("未知");
}
}
}

View File

@@ -0,0 +1,34 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package io.renren.modules.log.service;
import io.renren.common.page.PageData;
import io.renren.common.service.BaseService;
import io.renren.modules.log.dto.SysLogErrorDTO;
import io.renren.modules.log.entity.SysLogErrorEntity;
import java.util.List;
import java.util.Map;
/**
* 异常日志
*
* @author Mark sunlightcs@gmail.com
* @since 1.0.0
*/
public interface SysLogErrorService extends BaseService<SysLogErrorEntity> {
PageData<SysLogErrorDTO> page(Map<String, Object> params);
List<SysLogErrorDTO> list(Map<String, Object> params);
void save(SysLogErrorEntity entity);
}

View File

@@ -0,0 +1,32 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package io.renren.modules.log.service;
import io.renren.common.page.PageData;
import io.renren.common.service.BaseService;
import io.renren.modules.log.dto.SysLogLoginDTO;
import io.renren.modules.log.entity.SysLogLoginEntity;
import java.util.List;
import java.util.Map;
/**
* 登录日志
*
* @author Mark sunlightcs@gmail.com
* @since 1.0.0
*/
public interface SysLogLoginService extends BaseService<SysLogLoginEntity> {
PageData<SysLogLoginDTO> page(Map<String, Object> params);
List<SysLogLoginDTO> list(Map<String, Object> params);
void save(SysLogLoginEntity entity);
}

View File

@@ -0,0 +1,32 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package io.renren.modules.log.service;
import io.renren.common.page.PageData;
import io.renren.common.service.BaseService;
import io.renren.modules.log.dto.SysLogOperationDTO;
import io.renren.modules.log.entity.SysLogOperationEntity;
import java.util.List;
import java.util.Map;
/**
* 操作日志
*
* @author Mark sunlightcs@gmail.com
* @since 1.0.0
*/
public interface SysLogOperationService extends BaseService<SysLogOperationEntity> {
PageData<SysLogOperationDTO> page(Map<String, Object> params);
List<SysLogOperationDTO> list(Map<String, Object> params);
void save(SysLogOperationEntity entity);
}

View File

@@ -0,0 +1,64 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package io.renren.modules.log.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.renren.common.constant.Constant;
import io.renren.common.page.PageData;
import io.renren.common.service.impl.BaseServiceImpl;
import io.renren.common.utils.ConvertUtils;
import io.renren.modules.log.dao.SysLogErrorDao;
import io.renren.modules.log.dto.SysLogErrorDTO;
import io.renren.modules.log.entity.SysLogErrorEntity;
import io.renren.modules.log.service.SysLogErrorService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Map;
/**
* 异常日志
*
* @author Mark sunlightcs@gmail.com
* @since 1.0.0
*/
@Service
public class SysLogErrorServiceImpl extends BaseServiceImpl<SysLogErrorDao, SysLogErrorEntity> implements SysLogErrorService {
@Override
public PageData<SysLogErrorDTO> page(Map<String, Object> params) {
IPage<SysLogErrorEntity> page = baseDao.selectPage(
getPage(params, Constant.CREATE_DATE, false),
getWrapper(params)
);
return getPageData(page, SysLogErrorDTO.class);
}
@Override
public List<SysLogErrorDTO> list(Map<String, Object> params) {
List<SysLogErrorEntity> entityList = baseDao.selectList(getWrapper(params));
return ConvertUtils.sourceToTarget(entityList, SysLogErrorDTO.class);
}
private QueryWrapper<SysLogErrorEntity> getWrapper(Map<String, Object> params){
QueryWrapper<SysLogErrorEntity> wrapper = new QueryWrapper<>();
return wrapper;
}
@Override
@Transactional(rollbackFor = Exception.class)
public void save(SysLogErrorEntity entity) {
insert(entity);
}
}

View File

@@ -0,0 +1,71 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package io.renren.modules.log.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.renren.common.constant.Constant;
import io.renren.common.page.PageData;
import io.renren.common.service.impl.BaseServiceImpl;
import io.renren.common.utils.ConvertUtils;
import io.renren.modules.log.dao.SysLogLoginDao;
import io.renren.modules.log.dto.SysLogLoginDTO;
import io.renren.modules.log.entity.SysLogLoginEntity;
import io.renren.modules.log.service.SysLogLoginService;
import cn.hutool.core.util.StrUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Map;
/**
* 登录日志
*
* @author Mark sunlightcs@gmail.com
* @since 1.0.0
*/
@Service
public class SysLogLoginServiceImpl extends BaseServiceImpl<SysLogLoginDao, SysLogLoginEntity> implements SysLogLoginService {
@Override
public PageData<SysLogLoginDTO> page(Map<String, Object> params) {
IPage<SysLogLoginEntity> page = baseDao.selectPage(
getPage(params, Constant.CREATE_DATE, false),
getWrapper(params)
);
return getPageData(page, SysLogLoginDTO.class);
}
@Override
public List<SysLogLoginDTO> list(Map<String, Object> params) {
List<SysLogLoginEntity> entityList = baseDao.selectList(getWrapper(params));
return ConvertUtils.sourceToTarget(entityList, SysLogLoginDTO.class);
}
private QueryWrapper<SysLogLoginEntity> getWrapper(Map<String, Object> params){
String status = (String) params.get("status");
String creatorName = (String) params.get("creatorName");
QueryWrapper<SysLogLoginEntity> wrapper = new QueryWrapper<>();
wrapper.eq(StrUtil.isNotBlank(status), "status", status);
wrapper.like(StrUtil.isNotBlank(creatorName), "creator_name", creatorName);
return wrapper;
}
@Override
@Transactional(rollbackFor = Exception.class)
public void save(SysLogLoginEntity entity) {
insert(entity);
}
}

View File

@@ -0,0 +1,69 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package io.renren.modules.log.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.renren.common.constant.Constant;
import io.renren.common.page.PageData;
import io.renren.common.service.impl.BaseServiceImpl;
import io.renren.common.utils.ConvertUtils;
import io.renren.modules.log.dao.SysLogOperationDao;
import io.renren.modules.log.dto.SysLogOperationDTO;
import io.renren.modules.log.entity.SysLogOperationEntity;
import io.renren.modules.log.service.SysLogOperationService;
import cn.hutool.core.util.StrUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Map;
/**
* 操作日志
*
* @author Mark sunlightcs@gmail.com
* @since 1.0.0
*/
@Service
public class SysLogOperationServiceImpl extends BaseServiceImpl<SysLogOperationDao, SysLogOperationEntity> implements SysLogOperationService {
@Override
public PageData<SysLogOperationDTO> page(Map<String, Object> params) {
IPage<SysLogOperationEntity> page = baseDao.selectPage(
getPage(params, Constant.CREATE_DATE, false),
getWrapper(params)
);
return getPageData(page, SysLogOperationDTO.class);
}
@Override
public List<SysLogOperationDTO> list(Map<String, Object> params) {
List<SysLogOperationEntity> entityList = baseDao.selectList(getWrapper(params));
return ConvertUtils.sourceToTarget(entityList, SysLogOperationDTO.class);
}
private QueryWrapper<SysLogOperationEntity> getWrapper(Map<String, Object> params){
String status = (String) params.get("status");
QueryWrapper<SysLogOperationEntity> wrapper = new QueryWrapper<>();
wrapper.eq(StrUtil.isNotBlank(status), "status", status);
return wrapper;
}
@Override
@Transactional(rollbackFor = Exception.class)
public void save(SysLogOperationEntity entity) {
insert(entity);
}
}

View File

@@ -0,0 +1,78 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package io.renren.modules.oss.cloud;
import io.renren.common.utils.DateUtils;
import cn.hutool.core.util.StrUtil;
import java.io.InputStream;
import java.util.Date;
import java.util.UUID;
/**
* 云存储(支持七牛、阿里云、腾讯云)
*
* @author Mark sunlightcs@gmail.com
*/
public abstract class AbstractCloudStorageService {
/** 云存储配置信息 */
CloudStorageConfig config;
/**
* 文件路径
* @param prefix 前缀
* @param suffix 后缀
* @return 返回上传路径
*/
public String getPath(String prefix, String suffix) {
//生成uuid
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
//文件路径
String path = DateUtils.format(new Date(), "yyyyMMdd") + "/" + uuid;
if(StrUtil.isNotBlank(prefix)){
path = prefix + "/" + path;
}
return path + "." + suffix;
}
/**
* 文件上传
* @param data 文件字节数组
* @param path 文件路径,包含文件名
* @return 返回http地址
*/
public abstract String upload(byte[] data, String path);
/**
* 文件上传
* @param data 文件字节数组
* @param suffix 后缀
* @return 返回http地址
*/
public abstract String uploadSuffix(byte[] data, String suffix);
/**
* 文件上传
* @param inputStream 字节流
* @param path 文件路径,包含文件名
* @return 返回http地址
*/
public abstract String upload(InputStream inputStream, String path);
/**
* 文件上传
* @param inputStream 字节流
* @param suffix 后缀
* @return 返回http地址
*/
public abstract String uploadSuffix(InputStream inputStream, String suffix);
}

View File

@@ -0,0 +1,57 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package io.renren.modules.oss.cloud;
import com.aliyun.oss.OSSClient;
import io.renren.common.exception.ErrorCode;
import io.renren.common.exception.RenException;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
/**
* 阿里云存储
*
* @author Mark sunlightcs@gmail.com
*/
public class AliyunCloudStorageService extends AbstractCloudStorageService {
public AliyunCloudStorageService(CloudStorageConfig config){
this.config = config;
}
@Override
public String upload(byte[] data, String path) {
return upload(new ByteArrayInputStream(data), path);
}
@Override
public String upload(InputStream inputStream, String path) {
OSSClient client = new OSSClient(config.getAliyunEndPoint(), config.getAliyunAccessKeyId(),
config.getAliyunAccessKeySecret());
try {
client.putObject(config.getAliyunBucketName(), path, inputStream);
client.shutdown();
} catch (Exception e){
throw new RenException(ErrorCode.OSS_UPLOAD_FILE_ERROR, e, "");
}
return config.getAliyunDomain() + "/" + path;
}
@Override
public String uploadSuffix(byte[] data, String suffix) {
return upload(data, getPath(config.getAliyunPrefix(), suffix));
}
@Override
public String uploadSuffix(InputStream inputStream, String suffix) {
return upload(inputStream, getPath(config.getAliyunPrefix(), suffix));
}
}

View File

@@ -0,0 +1,109 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
* <p>
* https://www.renren.io
* <p>
* 版权所有,侵权必究!
*/
package io.renren.modules.oss.cloud;
import io.renren.common.validator.group.AliyunGroup;
import io.renren.common.validator.group.QcloudGroup;
import io.renren.common.validator.group.QiniuGroup;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import lombok.Data;
import org.hibernate.validator.constraints.Range;
import org.hibernate.validator.constraints.URL;
import java.io.Serializable;
/**
* 云存储配置信息
*
* @author Mark sunlightcs@gmail.com
*/
@Data
@Schema(title = "云存储配置信息")
public class CloudStorageConfig implements Serializable {
private static final long serialVersionUID = 1L;
@Schema(title = "类型 1七牛 2阿里云 3腾讯云 ")
@Range(min = 1, max = 6, message = "{oss.type.range}")
private Integer type;
@Schema(title = "七牛绑定的域名")
@NotBlank(message = "{qiniu.domain.require}", groups = QiniuGroup.class)
@URL(message = "{qiniu.domain.url}", groups = QiniuGroup.class)
private String qiniuDomain;
@Schema(title = "七牛路径前缀")
private String qiniuPrefix;
@Schema(title = "七牛ACCESS_KEY")
@NotBlank(message = "{qiniu.accesskey.require}", groups = QiniuGroup.class)
private String qiniuAccessKey;
@Schema(title = "七牛SECRET_KEY")
@NotBlank(message = "{qiniu.secretkey.require}", groups = QiniuGroup.class)
private String qiniuSecretKey;
@Schema(title = "七牛存储空间名")
@NotBlank(message = "{qiniu.bucketName.require}", groups = QiniuGroup.class)
private String qiniuBucketName;
@Schema(title = "阿里云绑定的域名")
@NotBlank(message = "{aliyun.domain.require}", groups = AliyunGroup.class)
@URL(message = "{aliyun.domain.url}", groups = AliyunGroup.class)
private String aliyunDomain;
@Schema(title = "阿里云路径前缀")
private String aliyunPrefix;
@Schema(title = "阿里云EndPoint")
@NotBlank(message = "{aliyun.endPoint.require}", groups = AliyunGroup.class)
private String aliyunEndPoint;
@Schema(title = "阿里云AccessKeyId")
@NotBlank(message = "{aliyun.accesskeyid.require}", groups = AliyunGroup.class)
private String aliyunAccessKeyId;
@Schema(title = "阿里云AccessKeySecret")
@NotBlank(message = "{aliyun.accesskeysecret.require}", groups = AliyunGroup.class)
private String aliyunAccessKeySecret;
@Schema(title = "阿里云BucketName")
@NotBlank(message = "{aliyun.bucketName.require}", groups = AliyunGroup.class)
private String aliyunBucketName;
@Schema(title = "腾讯云绑定的域名")
@NotBlank(message = "{qcloud.domain.require}", groups = QcloudGroup.class)
@URL(message = "{qcloud.domain.url}", groups = QcloudGroup.class)
private String qcloudDomain;
@Schema(title = "腾讯云路径前缀")
private String qcloudPrefix;
@Schema(title = "腾讯云AppId")
@NotNull(message = "{qcloud.appid.require}", groups = QcloudGroup.class)
private Integer qcloudAppId;
@Schema(title = "腾讯云SecretId")
@NotBlank(message = "{qcloud.secretId.require}", groups = QcloudGroup.class)
private String qcloudSecretId;
@Schema(title = "腾讯云SecretKey")
@NotBlank(message = "{qcloud.secretkey.require}", groups = QcloudGroup.class)
private String qcloudSecretKey;
@Schema(title = "腾讯云BucketName")
@NotBlank(message = "{qcloud.bucketName.require}", groups = QcloudGroup.class)
private String qcloudBucketName;
@Schema(title = "腾讯云COS所属地区")
@NotBlank(message = "{qcloud.region.require}", groups = QcloudGroup.class)
private String qcloudRegion;
}

View File

@@ -0,0 +1,41 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package io.renren.modules.oss.cloud;
import io.renren.common.constant.Constant;
import io.renren.common.utils.SpringContextUtils;
import io.renren.modules.sys.service.SysParamsService;
/**
* 文件上传Factory
* @author Mark sunlightcs@gmail.com
*/
public final class OSSFactory {
private static SysParamsService sysParamsService;
static {
OSSFactory.sysParamsService = SpringContextUtils.getBean(SysParamsService.class);
}
public static AbstractCloudStorageService build(){
//获取云存储配置信息
CloudStorageConfig config = sysParamsService.getValueObject(Constant.CLOUD_STORAGE_CONFIG_KEY, CloudStorageConfig.class);
if(config.getType() == Constant.CloudService.QINIU.getValue()){
return new QiniuCloudStorageService(config);
}else if(config.getType() == Constant.CloudService.ALIYUN.getValue()){
return new AliyunCloudStorageService(config);
}else if(config.getType() == Constant.CloudService.QCLOUD.getValue()){
return new QcloudCloudStorageService(config);
}
return null;
}
}

View File

@@ -0,0 +1,86 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package io.renren.modules.oss.cloud;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import io.renren.common.exception.ErrorCode;
import io.renren.common.exception.RenException;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* 腾讯云存储
*
* @author Mark sunlightcs@gmail.com
*/
public class QcloudCloudStorageService extends AbstractCloudStorageService {
private COSCredentials credentials;
private ClientConfig clientConfig;
public QcloudCloudStorageService(CloudStorageConfig config){
this.config = config;
//初始化
init();
}
private void init(){
//1、初始化用户身份信息(secretId, secretKey)
credentials = new BasicCOSCredentials(config.getQcloudSecretId(), config.getQcloudSecretKey());
//2、设置bucket的区域, COS地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
clientConfig = new ClientConfig(new Region(config.getQcloudRegion()));
}
@Override
public String upload(byte[] data, String path) {
return upload(new ByteArrayInputStream(data), path);
}
@Override
public String upload(InputStream inputStream, String path) {
try {
COSClient client = new COSClient(credentials, clientConfig);
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentLength(inputStream.available());
String bucketName = config.getQcloudBucketName() +"-"+ config.getQcloudAppId();
PutObjectRequest request = new PutObjectRequest(bucketName, path, inputStream, metadata);
PutObjectResult result = client.putObject(request);
client.shutdown();
if(result.getETag() == null){
throw new RenException(ErrorCode.OSS_UPLOAD_FILE_ERROR, "");
}
} catch (IOException e) {
throw new RenException(ErrorCode.OSS_UPLOAD_FILE_ERROR, e, "");
}
return config.getQcloudDomain() + "/" + path;
}
@Override
public String uploadSuffix(byte[] data, String suffix) {
return upload(data, getPath(config.getQcloudPrefix(), suffix));
}
@Override
public String uploadSuffix(InputStream inputStream, String suffix) {
return upload(inputStream, getPath(config.getQcloudPrefix(), suffix));
}
}

View File

@@ -0,0 +1,79 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
* <p>
* https://www.renren.io
* <p>
* 版权所有,侵权必究!
*/
package io.renren.modules.oss.cloud;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.qiniu.util.IOUtils;
import io.renren.common.exception.ErrorCode;
import io.renren.common.exception.RenException;
import java.io.IOException;
import java.io.InputStream;
/**
* 七牛云存储
*
* @author Mark sunlightcs@gmail.com
*/
public class QiniuCloudStorageService extends AbstractCloudStorageService {
private UploadManager uploadManager;
private String token;
public QiniuCloudStorageService(CloudStorageConfig config) {
this.config = config;
//初始化
init();
}
private void init() {
uploadManager = new UploadManager(new Configuration(Region.autoRegion()));
token = Auth.create(config.getQiniuAccessKey(), config.getQiniuSecretKey()).
uploadToken(config.getQiniuBucketName());
}
@Override
public String upload(byte[] data, String path) {
try {
Response res = uploadManager.put(data, path, token);
if (!res.isOK()) {
throw new RenException(ErrorCode.OSS_UPLOAD_FILE_ERROR, res.toString());
}
} catch (Exception e) {
throw new RenException(ErrorCode.OSS_UPLOAD_FILE_ERROR, e, "");
}
return config.getQiniuDomain() + "/" + path;
}
@Override
public String upload(InputStream inputStream, String path) {
try {
byte[] data = IOUtils.toByteArray(inputStream);
return this.upload(data, path);
} catch (IOException e) {
throw new RenException(ErrorCode.OSS_UPLOAD_FILE_ERROR, e, "");
}
}
@Override
public String uploadSuffix(byte[] data, String suffix) {
return upload(data, getPath(config.getQiniuPrefix(), suffix));
}
@Override
public String uploadSuffix(InputStream inputStream, String suffix) {
return upload(inputStream, getPath(config.getQiniuPrefix(), suffix));
}
}

View File

@@ -0,0 +1,131 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
* <p>
* https://www.renren.io
* <p>
* 版权所有,侵权必究!
*/
package io.renren.modules.oss.controller;
import cn.hutool.core.io.file.FileNameUtil;
import io.renren.common.annotation.LogOperation;
import io.renren.common.constant.Constant;
import io.renren.common.exception.ErrorCode;
import io.renren.common.page.PageData;
import io.renren.common.utils.JsonUtils;
import io.renren.common.utils.Result;
import io.renren.common.validator.ValidatorUtils;
import io.renren.common.validator.group.AliyunGroup;
import io.renren.common.validator.group.QcloudGroup;
import io.renren.common.validator.group.QiniuGroup;
import io.renren.modules.oss.cloud.CloudStorageConfig;
import io.renren.modules.oss.cloud.OSSFactory;
import io.renren.modules.oss.entity.SysOssEntity;
import io.renren.modules.oss.service.SysOssService;
import io.renren.modules.sys.service.SysParamsService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* 文件上传
*
* @author Mark sunlightcs@gmail.com
*/
@RestController
@RequestMapping("sys/oss")
@Tag(name = "文件上传")
@AllArgsConstructor
public class SysOssController {
private final SysOssService sysOssService;
private final SysParamsService sysParamsService;
private final static String KEY = Constant.CLOUD_STORAGE_CONFIG_KEY;
@GetMapping("page")
@Operation(summary = "分页")
@RequiresPermissions("sys:oss:all")
public Result<PageData<SysOssEntity>> page(@Parameter(hidden = true) @RequestParam Map<String, Object> params) {
PageData<SysOssEntity> page = sysOssService.page(params);
return new Result<PageData<SysOssEntity>>().ok(page);
}
@GetMapping("info")
@Operation(summary = "云存储配置信息")
@RequiresPermissions("sys:oss:all")
public Result<CloudStorageConfig> info() {
CloudStorageConfig config = sysParamsService.getValueObject(KEY, CloudStorageConfig.class);
return new Result<CloudStorageConfig>().ok(config);
}
@PostMapping
@Operation(summary = "保存云存储配置信息")
@LogOperation("保存云存储配置信息")
@RequiresPermissions("sys:oss:all")
public Result saveConfig(@RequestBody CloudStorageConfig config) {
//校验类型
ValidatorUtils.validateEntity(config);
if (config.getType() == Constant.CloudService.QINIU.getValue()) {
//校验七牛数据
ValidatorUtils.validateEntity(config, QiniuGroup.class);
} else if (config.getType() == Constant.CloudService.ALIYUN.getValue()) {
//校验阿里云数据
ValidatorUtils.validateEntity(config, AliyunGroup.class);
} else if (config.getType() == Constant.CloudService.QCLOUD.getValue()) {
//校验腾讯云数据
ValidatorUtils.validateEntity(config, QcloudGroup.class);
}
sysParamsService.updateValueByCode(KEY, JsonUtils.toJsonString(config));
return new Result();
}
@PostMapping("upload")
@Operation(summary = "上传文件")
@RequiresPermissions("sys:oss:all")
public Result<Map<String, Object>> upload(@RequestParam("file") MultipartFile file) throws Exception {
if (file.isEmpty()) {
return new Result<Map<String, Object>>().error(ErrorCode.UPLOAD_FILE_EMPTY);
}
//上传文件
String suffix = FileNameUtil.getSuffix(file.getOriginalFilename());
String url = OSSFactory.build().uploadSuffix(file.getBytes(), suffix);
//保存文件信息
SysOssEntity ossEntity = new SysOssEntity();
ossEntity.setUrl(url);
ossEntity.setCreateDate(new Date());
sysOssService.insert(ossEntity);
Map<String, Object> data = new HashMap<>(1);
data.put("src", url);
return new Result<Map<String, Object>>().ok(data);
}
@DeleteMapping
@Operation(summary = "删除")
@LogOperation("删除")
@RequiresPermissions("sys:oss:all")
public Result delete(@RequestBody Long[] ids) {
sysOssService.deleteBatchIds(Arrays.asList(ids));
return new Result();
}
}

View File

@@ -0,0 +1,23 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package io.renren.modules.oss.dao;
import io.renren.common.dao.BaseDao;
import io.renren.modules.oss.entity.SysOssEntity;
import org.apache.ibatis.annotations.Mapper;
/**
* 文件上传
*
* @author Mark sunlightcs@gmail.com
*/
@Mapper
public interface SysOssDao extends BaseDao<SysOssEntity> {
}

View File

@@ -0,0 +1,32 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package io.renren.modules.oss.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import io.renren.common.entity.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* 文件上传
*
* @author Mark sunlightcs@gmail.com
*/
@Data
@EqualsAndHashCode(callSuper=false)
@TableName("sys_oss")
public class SysOssEntity extends BaseEntity {
private static final long serialVersionUID = 1L;
/**
* URL地址
*/
private String url;
}

View File

@@ -0,0 +1,25 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package io.renren.modules.oss.service;
import io.renren.common.page.PageData;
import io.renren.common.service.BaseService;
import io.renren.modules.oss.entity.SysOssEntity;
import java.util.Map;
/**
* 文件上传
*
* @author Mark sunlightcs@gmail.com
*/
public interface SysOssService extends BaseService<SysOssEntity> {
PageData<SysOssEntity> page(Map<String, Object> params);
}

View File

@@ -0,0 +1,35 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package io.renren.modules.oss.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.renren.common.constant.Constant;
import io.renren.common.page.PageData;
import io.renren.common.service.impl.BaseServiceImpl;
import io.renren.modules.oss.dao.SysOssDao;
import io.renren.modules.oss.entity.SysOssEntity;
import io.renren.modules.oss.service.SysOssService;
import org.springframework.stereotype.Service;
import java.util.Map;
@Service
public class SysOssServiceImpl extends BaseServiceImpl<SysOssDao, SysOssEntity> implements SysOssService {
@Override
public PageData<SysOssEntity> page(Map<String, Object> params) {
IPage<SysOssEntity> page = baseDao.selectPage(
getPage(params, Constant.CREATE_DATE, false),
new QueryWrapper<>()
);
return getPageData(page, SysOssEntity.class);
}
}

View File

@@ -0,0 +1,49 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package io.renren.modules.security.config;
import io.renren.common.xss.XssFilter;
import jakarta.servlet.DispatcherType;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.DelegatingFilterProxy;
/**
* Filter配置
*
* @author Mark sunlightcs@gmail.com
*/
@Configuration
public class FilterConfig {
@Bean
public FilterRegistrationBean shiroFilterRegistration() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(new DelegatingFilterProxy("shiroFilter"));
//该值缺省为false表示生命周期由SpringApplicationContext管理设置为true则表示由ServletContainer管理
registration.addInitParameter("targetFilterLifecycle", "true");
registration.setEnabled(true);
registration.setOrder(Integer.MAX_VALUE - 1);
registration.addUrlPatterns("/*");
return registration;
}
@Bean
public FilterRegistrationBean xssFilterRegistration() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setDispatcherTypes(DispatcherType.REQUEST);
registration.setFilter(new XssFilter());
registration.addUrlPatterns("/*");
registration.setName("xssFilter");
registration.setOrder(Integer.MAX_VALUE);
return registration;
}
}

View File

@@ -0,0 +1,91 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package io.renren.modules.security.config;
import io.renren.modules.security.oauth2.Oauth2Filter;
import io.renren.modules.security.oauth2.Oauth2Realm;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import jakarta.servlet.Filter;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* Shiro的配置文件
*
* @author Mark sunlightcs@gmail.com
*/
@Configuration
public class ShiroConfig {
@Bean
public DefaultWebSessionManager sessionManager(){
DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
sessionManager.setSessionValidationSchedulerEnabled(false);
sessionManager.setSessionIdUrlRewritingEnabled(false);
return sessionManager;
}
@Bean("securityManager")
public SecurityManager securityManager(Oauth2Realm oAuth2Realm, SessionManager sessionManager) {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(oAuth2Realm);
securityManager.setSessionManager(sessionManager);
securityManager.setRememberMeManager(null);
return securityManager;
}
@Bean("shiroFilter")
public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager) {
ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean();
shiroFilter.setSecurityManager(securityManager);
//oauth过滤
Map<String, Filter> filters = new HashMap<>();
filters.put("oauth2", new Oauth2Filter());
shiroFilter.setFilters(filters);
Map<String, String> filterMap = new LinkedHashMap<>();
filterMap.put("/webjars/**", "anon");
filterMap.put("/druid/**", "anon");
filterMap.put("/login", "anon");
filterMap.put("/swagger/**", "anon");
filterMap.put("/v3/api-docs/**", "anon");
filterMap.put("/doc.html", "anon");
filterMap.put("/swagger-resources/**", "anon");
filterMap.put("/captcha", "anon");
filterMap.put("/favicon.ico", "anon");
filterMap.put("/", "anon");
filterMap.put("/**", "oauth2");
shiroFilter.setFilterChainDefinitionMap(filterMap);
return shiroFilter;
}
@Bean("lifecycleBeanPostProcessor")
public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
return new LifecycleBeanPostProcessor();
}
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
advisor.setSecurityManager(securityManager);
return advisor;
}
}

View File

@@ -0,0 +1,80 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
* <p>
* https://www.renren.io
* <p>
* 版权所有,侵权必究!
*/
package io.renren.modules.security.config;
import org.springframework.boot.jackson.autoconfigure.JsonMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import tools.jackson.databind.DeserializationFeature;
import tools.jackson.databind.cfg.DateTimeFeature;
import tools.jackson.databind.ext.javatime.deser.LocalDateDeserializer;
import tools.jackson.databind.ext.javatime.deser.LocalDateTimeDeserializer;
import tools.jackson.databind.ext.javatime.deser.LocalTimeDeserializer;
import tools.jackson.databind.ext.javatime.ser.LocalDateSerializer;
import tools.jackson.databind.ext.javatime.ser.LocalDateTimeSerializer;
import tools.jackson.databind.ext.javatime.ser.LocalTimeSerializer;
import tools.jackson.databind.module.SimpleModule;
import tools.jackson.databind.ser.std.ToStringSerializer;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOriginPatterns("*")
.allowCredentials(true)
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
.maxAge(3600);
}
@Bean
public SimpleModule customSerializerModule() {
SimpleModule module = new SimpleModule("CustomSerializerModule");
// 日期时间序列化
module.addSerializer(LocalDateTime.class,
new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
module.addSerializer(LocalDate.class,
new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
module.addSerializer(LocalTime.class,
new LocalTimeSerializer(DateTimeFormatter.ofPattern("HH:mm:ss")));
// 日期时间反序列化
module.addDeserializer(LocalDateTime.class,
new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
module.addDeserializer(LocalDate.class,
new LocalDateDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
module.addDeserializer(LocalTime.class,
new LocalTimeDeserializer(DateTimeFormatter.ofPattern("HH:mm:ss")));
// Long 类型序列化为 String解决前端 js 精度丢失问题
module.addSerializer(Long.class, ToStringSerializer.instance);
module.addSerializer(Long.TYPE, ToStringSerializer.instance);
return module;
}
/**
* 自定义 JsonMapper 构建器配置
*/
@Bean
public JsonMapperBuilderCustomizer jsonMapperBuilderCustomizer() {
return builder -> builder
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.disable(DateTimeFeature.WRITE_DATES_AS_TIMESTAMPS);
}
}

View File

@@ -0,0 +1,153 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
* <p>
* https://www.renren.io
* <p>
* 版权所有,侵权必究!
*/
package io.renren.modules.security.controller;
import io.renren.common.exception.ErrorCode;
import io.renren.common.exception.RenException;
import io.renren.common.utils.IpUtils;
import io.renren.common.utils.Result;
import io.renren.common.validator.AssertUtils;
import io.renren.common.validator.ValidatorUtils;
import io.renren.modules.log.entity.SysLogLoginEntity;
import io.renren.modules.log.enums.LoginOperationEnum;
import io.renren.modules.log.enums.LoginStatusEnum;
import io.renren.modules.log.service.SysLogLoginService;
import io.renren.modules.security.dto.LoginDTO;
import io.renren.modules.security.password.PasswordUtils;
import io.renren.modules.security.service.CaptchaService;
import io.renren.modules.security.service.SysUserTokenService;
import io.renren.modules.security.user.SecurityUser;
import io.renren.modules.security.user.UserDetail;
import io.renren.modules.sys.dto.SysUserDTO;
import io.renren.modules.sys.enums.UserStatusEnum;
import io.renren.modules.sys.service.SysUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.util.Date;
/**
* 登录
*
* @author Mark sunlightcs@gmail.com
*/
@RestController
@Tag(name = "登录管理")
@AllArgsConstructor
public class LoginController {
private final SysUserService sysUserService;
private final SysUserTokenService sysUserTokenService;
private final CaptchaService captchaService;
private final SysLogLoginService sysLogLoginService;
@GetMapping("captcha")
@Operation(summary = "验证码")
@Parameter(in = ParameterIn.QUERY, ref = "string", name = "uuid", required = true)
public void captcha(HttpServletResponse response, String uuid) throws IOException {
//uuid不能为空
AssertUtils.isBlank(uuid, ErrorCode.IDENTIFIER_NOT_NULL);
//生成验证码
captchaService.create(response, uuid);
}
@PostMapping("login")
@Operation(summary = "登录")
public Result login(HttpServletRequest request, @RequestBody LoginDTO login) {
//效验数据
ValidatorUtils.validateEntity(login);
//验证码是否正确
boolean flag = captchaService.validate(login.getUuid(), login.getCaptcha());
if (!flag) {
return new Result().error(ErrorCode.CAPTCHA_ERROR);
}
//用户信息
SysUserDTO user = sysUserService.getByUsername(login.getUsername());
SysLogLoginEntity log = new SysLogLoginEntity();
log.setOperation(LoginOperationEnum.LOGIN.value());
log.setCreateDate(new Date());
log.setIp(IpUtils.getIpAddr(request));
log.setUserAgent(request.getHeader(HttpHeaders.USER_AGENT));
//用户不存在
if (user == null) {
log.setStatus(LoginStatusEnum.FAIL.value());
log.setCreatorName(login.getUsername());
sysLogLoginService.save(log);
throw new RenException(ErrorCode.ACCOUNT_PASSWORD_ERROR);
}
//密码错误
if (!PasswordUtils.matches(login.getPassword(), user.getPassword())) {
log.setStatus(LoginStatusEnum.FAIL.value());
log.setCreator(user.getId());
log.setCreatorName(user.getUsername());
sysLogLoginService.save(log);
throw new RenException(ErrorCode.ACCOUNT_PASSWORD_ERROR);
}
//账号停用
if (user.getStatus() == UserStatusEnum.DISABLE.value()) {
log.setStatus(LoginStatusEnum.LOCK.value());
log.setCreator(user.getId());
log.setCreatorName(user.getUsername());
sysLogLoginService.save(log);
throw new RenException(ErrorCode.ACCOUNT_DISABLE);
}
//登录成功
log.setStatus(LoginStatusEnum.SUCCESS.value());
log.setCreator(user.getId());
log.setCreatorName(user.getUsername());
sysLogLoginService.save(log);
return sysUserTokenService.createToken(user.getId());
}
@PostMapping("logout")
@Operation(summary = "退出")
public Result logout(HttpServletRequest request) {
UserDetail user = SecurityUser.getUser();
//退出
sysUserTokenService.logout(user.getId());
//用户信息
SysLogLoginEntity log = new SysLogLoginEntity();
log.setOperation(LoginOperationEnum.LOGOUT.value());
log.setIp(IpUtils.getIpAddr(request));
log.setUserAgent(request.getHeader(HttpHeaders.USER_AGENT));
log.setIp(IpUtils.getIpAddr(request));
log.setStatus(LoginStatusEnum.SUCCESS.value());
log.setCreator(user.getId());
log.setCreatorName(user.getUsername());
log.setCreateDate(new Date());
sysLogLoginService.save(log);
return new Result();
}
}

View File

@@ -0,0 +1,29 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package io.renren.modules.security.dao;
import io.renren.common.dao.BaseDao;
import io.renren.modules.security.entity.SysUserTokenEntity;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
/**
* 系统用户Token
*
* @author Mark sunlightcs@gmail.com
*/
@Mapper
public interface SysUserTokenDao extends BaseDao<SysUserTokenEntity> {
SysUserTokenEntity getByToken(String token);
SysUserTokenEntity getByUserId(Long userId);
void updateToken(@Param("userId") Long userId, @Param("token") String token);
}

View File

@@ -0,0 +1,43 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package io.renren.modules.security.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import lombok.Data;
import java.io.Serializable;
/**
* 登录表单
*
* @author Mark sunlightcs@gmail.com
*/
@Data
@Schema(title = "登录表单")
public class LoginDTO implements Serializable {
private static final long serialVersionUID = 1L;
@Schema(title = "用户名", required = true)
@NotBlank(message="{sysuser.username.require}")
private String username;
@Schema(title = "密码")
@NotBlank(message="{sysuser.password.require}")
private String password;
@Schema(title = "验证码")
@NotBlank(message="{sysuser.captcha.require}")
private String captcha;
@Schema(title = "唯一标识")
@NotBlank(message="{sysuser.uuid.require}")
private String uuid;
}

View File

@@ -0,0 +1,55 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package io.renren.modules.security.entity;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import io.renren.common.entity.BaseEntity;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
* 系统用户Token
*/
@Data
@TableName("sys_user_token")
public class SysUserTokenEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
* id
*/
@TableId
private Long id;
/**
* 用户ID
*/
private Long userId;
/**
* 用户token
*/
private String token;
/**
* 过期时间
*/
private Date expireDate;
/**
* 更新时间
*/
private Date updateDate;
/**
* 创建时间
*/
@TableField(fill = FieldFill.INSERT)
private Date createDate;
}

View File

@@ -0,0 +1,112 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
* <p>
* https://www.renren.io
* <p>
* 版权所有,侵权必究!
*/
package io.renren.modules.security.oauth2;
import cn.hutool.core.util.StrUtil;
import io.renren.common.constant.Constant;
import io.renren.common.exception.ErrorCode;
import io.renren.common.utils.HttpContextUtils;
import io.renren.common.utils.JsonUtils;
import io.renren.common.utils.Result;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;
import java.io.IOException;
/**
* oauth2过滤器
*
* @author Mark sunlightcs@gmail.com
*/
public class Oauth2Filter extends AuthenticatingFilter {
@Override
protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) throws Exception {
//获取请求token
String token = getRequestToken((HttpServletRequest) request);
if (StrUtil.isBlank(token)) {
return null;
}
return new Oauth2Token(token);
}
@Override
protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
if (((HttpServletRequest) request).getMethod().equals(RequestMethod.OPTIONS.name())) {
return true;
}
return false;
}
@Override
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
//获取请求token如果token不存在直接返回401
String token = getRequestToken((HttpServletRequest) request);
if (StrUtil.isBlank(token)) {
HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.setContentType("application/json;charset=utf-8");
httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
httpResponse.setHeader("Access-Control-Allow-Origin", HttpContextUtils.getOrigin());
String json = JsonUtils.toJsonString(new Result().error(ErrorCode.UNAUTHORIZED));
httpResponse.getWriter().print(json);
return false;
}
return executeLogin(request, response);
}
@Override
protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.setContentType("application/json;charset=utf-8");
httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
httpResponse.setHeader("Access-Control-Allow-Origin", HttpContextUtils.getOrigin());
try {
//处理登录失败的异常
Throwable throwable = e.getCause() == null ? e : e.getCause();
Result r = new Result().error(HttpStatus.UNAUTHORIZED.value(), throwable.getMessage());
String json = JsonUtils.toJsonString(r);
httpResponse.getWriter().print(json);
} catch (IOException e1) {
}
return false;
}
/**
* 获取请求的token
*/
private String getRequestToken(HttpServletRequest httpRequest) {
//从header中获取token
String token = httpRequest.getHeader(Constant.TOKEN_HEADER);
//如果header中不存在token则从参数中获取token
if (StrUtil.isBlank(token)) {
token = httpRequest.getParameter(Constant.TOKEN_HEADER);
}
return token;
}
}

View File

@@ -0,0 +1,92 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
* <p>
* https://www.renren.io
* <p>
* 版权所有,侵权必究!
*/
package io.renren.modules.security.oauth2;
import io.renren.common.exception.ErrorCode;
import io.renren.common.utils.ConvertUtils;
import io.renren.common.utils.MessageUtils;
import io.renren.modules.security.entity.SysUserTokenEntity;
import io.renren.modules.security.service.ShiroService;
import io.renren.modules.security.user.UserDetail;
import io.renren.modules.sys.entity.SysUserEntity;
import lombok.AllArgsConstructor;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Set;
/**
* 认证
*
* @author Mark sunlightcs@gmail.com
*/
@Component
@AllArgsConstructor
public class Oauth2Realm extends AuthorizingRealm {
private final ShiroService shiroService;
@Override
public boolean supports(AuthenticationToken token) {
return token instanceof Oauth2Token;
}
/**
* 授权(验证权限时调用)
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
UserDetail user = (UserDetail) principals.getPrimaryPrincipal();
//用户权限列表
Set<String> permsSet = shiroService.getUserPermissions(user);
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
info.setStringPermissions(permsSet);
return info;
}
/**
* 认证(登录时调用)
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
String accessToken = (String) token.getPrincipal();
//根据accessToken查询用户信息
SysUserTokenEntity tokenEntity = shiroService.getByToken(accessToken);
//token失效
if (tokenEntity == null || tokenEntity.getExpireDate().getTime() < System.currentTimeMillis()) {
throw new IncorrectCredentialsException(MessageUtils.getMessage(ErrorCode.TOKEN_INVALID));
}
//查询用户信息
SysUserEntity userEntity = shiroService.getUser(tokenEntity.getUserId());
//转换成UserDetail对象
UserDetail userDetail = ConvertUtils.sourceToTarget(userEntity, UserDetail.class);
//获取用户对应的部门数据权限
List<Long> deptIdList = shiroService.getDataScopeList(userDetail.getId());
userDetail.setDeptIdList(deptIdList);
//账号锁定
if (userDetail.getStatus() == 0) {
throw new LockedAccountException(MessageUtils.getMessage(ErrorCode.ACCOUNT_LOCK));
}
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(userDetail, accessToken, getName());
return info;
}
}

View File

@@ -0,0 +1,34 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package io.renren.modules.security.oauth2;
import org.apache.shiro.authc.AuthenticationToken;
/**
* token
*
* @author Mark sunlightcs@gmail.com
*/
public class Oauth2Token implements AuthenticationToken {
private String token;
public Oauth2Token(String token){
this.token = token;
}
@Override
public String getPrincipal() {
return token;
}
@Override
public Object getCredentials() {
return token;
}
}

View File

@@ -0,0 +1,52 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package io.renren.modules.security.oauth2;
import io.renren.common.exception.RenException;
import java.security.MessageDigest;
import java.util.UUID;
/**
* 生成token
*
* @author Mark sunlightcs@gmail.com
*/
public class TokenGenerator {
public static String generateValue() {
return generateValue(UUID.randomUUID().toString());
}
private static final char[] HEX_CODE = "0123456789abcdef".toCharArray();
public static String toHexString(byte[] data) {
if(data == null) {
return null;
}
StringBuilder r = new StringBuilder(data.length*2);
for ( byte b : data) {
r.append(HEX_CODE[(b >> 4) & 0xF]);
r.append(HEX_CODE[(b & 0xF)]);
}
return r.toString();
}
public static String generateValue(String param) {
try {
MessageDigest algorithm = MessageDigest.getInstance("MD5");
algorithm.reset();
algorithm.update(param.getBytes());
byte[] messageDigest = algorithm.digest();
return toHexString(messageDigest);
} catch (Exception e) {
throw new RenException("token invalid", e);
}
}
}

View File

@@ -0,0 +1,662 @@
package io.renren.modules.security.password;
import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.security.SecureRandom;
/**
* BCrypt implements OpenBSD-style Blowfish password hashing using the scheme described in
* "A Future-Adaptable Password Scheme" by Niels Provos and David Mazieres.
* <p>
* This password hashing system tries to thwart off-line password cracking using a
* computationally-intensive hashing algorithm, based on Bruce Schneier's Blowfish cipher.
* The work factor of the algorithm is parameterised, so it can be increased as computers
* get faster.
* <p>
* Usage is really simple. To hash a password for the first time, call the hashpw method
* with a random salt, like this:
* <p>
* <code>
* String pw_hash = BCrypt.hashpw(plain_password, BCrypt.gensalt()); <br>
* </code>
* <p>
* To check whether a plaintext password matches one that has been hashed previously, use
* the checkpw method:
* <p>
* <code>
* if (BCrypt.checkpw(candidate_password, stored_hash))<br>
* &nbsp;&nbsp;&nbsp;&nbsp;System.out.println("It matches");<br>
* else<br>
* &nbsp;&nbsp;&nbsp;&nbsp;System.out.println("It does not match");<br>
* </code>
* <p>
* The gensalt() method takes an optional parameter (log_rounds) that determines the
* computational complexity of the hashing:
* <p>
* <code>
* String strong_salt = BCrypt.gensalt(10)<br>
* String stronger_salt = BCrypt.gensalt(12)<br>
* </code>
* <p>
* The amount of work increases exponentially (2**log_rounds), so each increment is twice
* as much work. The default log_rounds is 10, and the valid range is 4 to 31.
*
* @author Damien Miller
*/
public class BCrypt {
// BCrypt parameters
private static final int GENSALT_DEFAULT_LOG2_ROUNDS = 10;
private static final int BCRYPT_SALT_LEN = 16;
// Blowfish parameters
private static final int BLOWFISH_NUM_ROUNDS = 16;
// Initial contents of key schedule
private static final int P_orig[] = { 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344,
0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377,
0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917,
0x9216d5d9, 0x8979fb1b };
private static final int S_orig[] = { 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7,
0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99, 0x24a19947, 0xb3916cf7,
0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e,
0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5,
0x9c30d539, 0x2af26013, 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef,
0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e, 0xd71577c1, 0xbd314b27,
0x78af2fda, 0x55605c60, 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440,
0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993,
0xb3ee1411, 0x636fbc2a, 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e,
0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677, 0x3b8f4898, 0x6b4bb9af,
0xc4bfe81b, 0x66282193, 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032,
0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5,
0x0f6d6ff3, 0x83f44239, 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e,
0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0, 0x6a51a0d2, 0xd8542f68,
0x960fa728, 0xab5133a3, 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98,
0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4,
0x7d84a5c3, 0x3b8b5ebe, 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6,
0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d, 0x37d0d724, 0xd00a1248,
0xdb0fead3, 0x49f1c09b, 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7,
0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4,
0x5e5c9ec2, 0x196a2463, 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f,
0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09, 0xbee3d004, 0xde334afd,
0x660f2807, 0x192e4bb3, 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb,
0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc,
0x8ea5e9f8, 0xdb3222f8, 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab,
0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82, 0x9e5c57bb, 0xca6f8ca0,
0x1a87562e, 0xdf1769db, 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573,
0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8,
0x4afcb56c, 0x2dd1d35b, 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790,
0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8, 0xef20cada, 0x36774c01,
0xd07e9efe, 0x2bf11fb4, 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0,
0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64,
0x8888b812, 0x900df01c, 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad,
0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1, 0xe5a0cc0f, 0xb56f74e8,
0x18acf3d6, 0xce89e299, 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9,
0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86,
0xc75442f5, 0xfb9d35cf, 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49,
0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af, 0x2464369b, 0xf009b91e,
0x5563911d, 0x59dfa6aa, 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5,
0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a,
0x1b510052, 0x9a532915, 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400,
0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915, 0xb6636521, 0xe7b9f9b6,
0xff34052e, 0xc5855664, 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a,
0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d,
0x9cee60b8, 0x8fedb266, 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1,
0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, 0x3f54989a, 0x5b429d65,
0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9,
0x3c971814, 0x6b6a70a1, 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737,
0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, 0xb03ada37, 0xf0500c0d,
0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc,
0xc8b57634, 0x9af3dda7, 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41,
0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, 0x4e548b38, 0x4f6db908,
0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124,
0x501adde6, 0x9f84cd87, 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c,
0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, 0xef1c1847, 0x3215d908,
0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b,
0x3c11183b, 0x5924a509, 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e,
0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, 0x771fe71c, 0x4e3d06fa,
0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d,
0x1939260f, 0x19c27960, 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66,
0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, 0xc332ddef, 0xbe6c5aa5,
0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96,
0x0334fe1e, 0xaa0363cf, 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14,
0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, 0x648b1eaf, 0x19bdf0ca,
0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77,
0x11ed935f, 0x16681281, 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99,
0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, 0xcdb30aeb, 0x532e3054,
0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea,
0xdb6c4f15, 0xfacb4fd0, 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105,
0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, 0xcf62a1f2, 0x5b8d2646,
0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea,
0x1dadf43e, 0x233f7061, 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb,
0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, 0xa6078084, 0x19f8509e,
0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd,
0x675fda79, 0xe3674340, 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20,
0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7, 0xe93d5a68, 0x948140f7,
0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068,
0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, 0x1e39f62e, 0x97244546,
0x14214f74, 0xbf8b8840, 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45,
0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504, 0x96eb27b3, 0x55fd3941,
0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb,
0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, 0x4f3ffea2, 0xe887ad8c,
0xb58ce006, 0x7af4d6b6, 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42,
0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b, 0x1dc9faf7, 0x4b6d1856,
0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb,
0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, 0x55533a3a, 0x20838d87,
0xfe6ba9b7, 0xd096954b, 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33,
0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c, 0xfdf8e802, 0x04272f70,
0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc,
0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, 0x325f51eb, 0xd59bc0d1,
0xf2bcc18f, 0x41113564, 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b,
0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115, 0x6b2395e0, 0x333e92e1,
0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728,
0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, 0x5449a36f, 0x877d48fa,
0xc39dfd27, 0xf33e8d1e, 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37,
0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d, 0xc67b5510, 0x6d672c37,
0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b,
0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, 0xbb132f88, 0x515bad24,
0x7b9479bf, 0x763bd6eb, 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d,
0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c, 0x6a124237, 0xb79251e7,
0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9,
0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, 0x64af674e, 0xda86a85f,
0xbebfe988, 0x64e4c3fe, 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d,
0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc, 0x83426b33, 0xf01eab71,
0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61,
0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, 0x5366f9c3, 0xc8b38e74,
0xb475f255, 0x46fcd9b9, 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2,
0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c, 0xb90bace1, 0xbb8205d0,
0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633,
0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, 0x1ab93d1d, 0x0ba5a4df,
0xa186f20f, 0x2868f169, 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52,
0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027, 0x9af88c27, 0x773f8641,
0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62,
0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, 0xbbcbee56, 0x90bcb6de,
0xebfc7da1, 0xce591d76, 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24,
0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc, 0xed545578, 0x08fca5b5,
0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c,
0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, 0xd79a3234, 0x92638212,
0x670efa8e, 0x406000e0, 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b,
0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe, 0xd5118e9d, 0xbf0f7315,
0xd62d1c7e, 0xc700c47b, 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4,
0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d,
0xd5730a1d, 0x4cd04dc6, 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304,
0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22, 0xc089c2b8, 0x43242ef6,
0xa51e03aa, 0x9cf2d0a4, 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6,
0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da,
0x3f046f69, 0x77fa0a59, 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593,
0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51, 0x96d5ac3a, 0x017da67d,
0xd1cf3ed6, 0x7c7d2d28, 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c,
0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc,
0xf8d56629, 0x79132e28, 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c,
0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd, 0xc3eb9e15, 0x3c9057a2,
0x97271aec, 0xa93a072a, 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319,
0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8,
0xabcc5167, 0xccad925f, 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991,
0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32, 0xa8b6e37e, 0xc3293d46,
0x48de5369, 0x6413e680, 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166,
0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40,
0xccd2017f, 0x6bb4e3bb, 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5,
0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47, 0xd29be463, 0x542f5d9e,
0xaec2771b, 0xf64e6370, 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d,
0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d,
0x06b89fb4, 0xce6ea048, 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8,
0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd, 0xa08839e1, 0x51ce794b,
0x2f32c9b7, 0xa01fbac9, 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7,
0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667,
0x8df9317c, 0xe0b12b4f, 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c,
0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525, 0xfae59361, 0xceb69ceb,
0xc2a86459, 0x12baa8d1, 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442,
0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df,
0xd3a0342b, 0x8971f21e, 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8,
0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d, 0xe54cda54, 0x1edad891,
0xce6279cf, 0xcd3e7e6f, 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299,
0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5,
0x6e163697, 0x88d273cc, 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614,
0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a, 0xc9aa53fd, 0x62a80f00,
0xbb25bfe2, 0x35bdd2f6, 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b,
0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76,
0x77afa1c5, 0x20756060, 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e,
0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9, 0x90d4f869, 0xa65cdea0,
0x3f09252d, 0xc208e69f, 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6 };
// bcrypt IV: "OrpheanBeholderScryDoubt"
static private final int bf_crypt_ciphertext[] = { 0x4f727068, 0x65616e42,
0x65686f6c, 0x64657253, 0x63727944, 0x6f756274 };
// Table for Base64 encoding
static private final char base64_code[] = { '.', '/', 'A', 'B', 'C', 'D', 'E', 'F',
'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U',
'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y',
'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
// Table for Base64 decoding
static private final byte index_64[] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 54, 55,
56, 57, 58, 59, 60, 61, 62, 63, -1, -1, -1, -1, -1, -1, -1, 2, 3, 4, 5, 6, 7,
8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27,
-1, -1, -1, -1, -1, -1, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, -1, -1, -1, -1, -1 };
static final int MIN_LOG_ROUNDS = 4;
static final int MAX_LOG_ROUNDS = 31;
// Expanded Blowfish key
private int P[];
private int S[];
/**
* Encode a byte array using bcrypt's slightly-modified base64 encoding scheme. Note
* that this is <strong>not</strong> compatible with the standard MIME-base64
* encoding.
*
* @param d the byte array to encode
* @param len the number of bytes to encode
* @param rs the destination buffer for the base64-encoded string
* @exception IllegalArgumentException if the length is invalid
*/
static void encode_base64(byte d[], int len, StringBuilder rs)
throws IllegalArgumentException {
int off = 0;
int c1, c2;
if (len <= 0 || len > d.length) {
throw new IllegalArgumentException("Invalid len");
}
while (off < len) {
c1 = d[off++] & 0xff;
rs.append(base64_code[(c1 >> 2) & 0x3f]);
c1 = (c1 & 0x03) << 4;
if (off >= len) {
rs.append(base64_code[c1 & 0x3f]);
break;
}
c2 = d[off++] & 0xff;
c1 |= (c2 >> 4) & 0x0f;
rs.append(base64_code[c1 & 0x3f]);
c1 = (c2 & 0x0f) << 2;
if (off >= len) {
rs.append(base64_code[c1 & 0x3f]);
break;
}
c2 = d[off++] & 0xff;
c1 |= (c2 >> 6) & 0x03;
rs.append(base64_code[c1 & 0x3f]);
rs.append(base64_code[c2 & 0x3f]);
}
}
/**
* Look up the 3 bits base64-encoded by the specified character, range-checking
* against conversion table
* @param x the base64-encoded value
* @return the decoded value of x
*/
private static byte char64(char x) {
if (x > index_64.length) {
return -1;
}
return index_64[x];
}
/**
* Decode a string encoded using bcrypt's base64 scheme to a byte array. Note that
* this is *not* compatible with the standard MIME-base64 encoding.
* @param s the string to decode
* @param maxolen the maximum number of bytes to decode
* @return an array containing the decoded bytes
* @throws IllegalArgumentException if maxolen is invalid
*/
static byte[] decode_base64(String s, int maxolen) throws IllegalArgumentException {
ByteArrayOutputStream out = new ByteArrayOutputStream(maxolen);
int off = 0, slen = s.length(), olen = 0;
byte c1, c2, c3, c4, o;
if (maxolen <= 0) {
throw new IllegalArgumentException("Invalid maxolen");
}
while (off < slen - 1 && olen < maxolen) {
c1 = char64(s.charAt(off++));
c2 = char64(s.charAt(off++));
if (c1 == -1 || c2 == -1) {
break;
}
o = (byte) (c1 << 2);
o |= (c2 & 0x30) >> 4;
out.write(o);
if (++olen >= maxolen || off >= slen) {
break;
}
c3 = char64(s.charAt(off++));
if (c3 == -1) {
break;
}
o = (byte) ((c2 & 0x0f) << 4);
o |= (c3 & 0x3c) >> 2;
out.write(o);
if (++olen >= maxolen || off >= slen) {
break;
}
c4 = char64(s.charAt(off++));
o = (byte) ((c3 & 0x03) << 6);
o |= c4;
out.write(o);
++olen;
}
return out.toByteArray();
}
/**
* Blowfish encipher a single 64-bit block encoded as two 32-bit halves
* @param lr an array containing the two 32-bit half blocks
* @param off the position in the array of the blocks
*/
private final void encipher(int lr[], int off) {
int i, n, l = lr[off], r = lr[off + 1];
l ^= P[0];
for (i = 0; i <= BLOWFISH_NUM_ROUNDS - 2;) {
// Feistel substitution on left word
n = S[(l >> 24) & 0xff];
n += S[0x100 | ((l >> 16) & 0xff)];
n ^= S[0x200 | ((l >> 8) & 0xff)];
n += S[0x300 | (l & 0xff)];
r ^= n ^ P[++i];
// Feistel substitution on right word
n = S[(r >> 24) & 0xff];
n += S[0x100 | ((r >> 16) & 0xff)];
n ^= S[0x200 | ((r >> 8) & 0xff)];
n += S[0x300 | (r & 0xff)];
l ^= n ^ P[++i];
}
lr[off] = r ^ P[BLOWFISH_NUM_ROUNDS + 1];
lr[off + 1] = l;
}
/**
* Cycically extract a word of key material
* @param data the string to extract the data from
* @param offp a "pointer" (as a one-entry array) to the current offset into data
* @return the next word of material from data
*/
private static int streamtoword(byte data[], int offp[]) {
int i;
int word = 0;
int off = offp[0];
for (i = 0; i < 4; i++) {
word = (word << 8) | (data[off] & 0xff);
off = (off + 1) % data.length;
}
offp[0] = off;
return word;
}
/**
* Initialise the Blowfish key schedule
*/
private void init_key() {
P = (int[]) P_orig.clone();
S = (int[]) S_orig.clone();
}
/**
* Key the Blowfish cipher
* @param key an array containing the key
*/
private void key(byte key[]) {
int i;
int koffp[] = { 0 };
int lr[] = { 0, 0 };
int plen = P.length, slen = S.length;
for (i = 0; i < plen; i++) {
P[i] = P[i] ^ streamtoword(key, koffp);
}
for (i = 0; i < plen; i += 2) {
encipher(lr, 0);
P[i] = lr[0];
P[i + 1] = lr[1];
}
for (i = 0; i < slen; i += 2) {
encipher(lr, 0);
S[i] = lr[0];
S[i + 1] = lr[1];
}
}
/**
* Perform the "enhanced key schedule" step described by Provos and Mazieres in
* "A Future-Adaptable Password Scheme" http://www.openbsd.org/papers/bcrypt-paper.ps
* @param data salt information
* @param key password information
*/
private void ekskey(byte data[], byte key[]) {
int i;
int koffp[] = { 0 }, doffp[] = { 0 };
int lr[] = { 0, 0 };
int plen = P.length, slen = S.length;
for (i = 0; i < plen; i++) {
P[i] = P[i] ^ streamtoword(key, koffp);
}
for (i = 0; i < plen; i += 2) {
lr[0] ^= streamtoword(data, doffp);
lr[1] ^= streamtoword(data, doffp);
encipher(lr, 0);
P[i] = lr[0];
P[i + 1] = lr[1];
}
for (i = 0; i < slen; i += 2) {
lr[0] ^= streamtoword(data, doffp);
lr[1] ^= streamtoword(data, doffp);
encipher(lr, 0);
S[i] = lr[0];
S[i + 1] = lr[1];
}
}
static long roundsForLogRounds(int log_rounds) {
if (log_rounds < 4 || log_rounds > 31) {
throw new IllegalArgumentException("Bad number of rounds");
}
return 1L << log_rounds;
}
/**
* Perform the central password hashing step in the bcrypt scheme
* @param password the password to hash
* @param salt the binary salt to hash with the password
* @param log_rounds the binary logarithm of the number of rounds of hashing to apply
* @return an array containing the binary hashed password
*/
private byte[] crypt_raw(byte password[], byte salt[], int log_rounds) {
int cdata[] = (int[]) bf_crypt_ciphertext.clone();
int clen = cdata.length;
byte ret[];
long rounds = roundsForLogRounds(log_rounds);
init_key();
ekskey(salt, password);
for (long i = 0; i < rounds; i++) {
key(password);
key(salt);
}
for (int i = 0; i < 64; i++) {
for (int j = 0; j < (clen >> 1); j++) {
encipher(cdata, j << 1);
}
}
ret = new byte[clen * 4];
for (int i = 0, j = 0; i < clen; i++) {
ret[j++] = (byte) ((cdata[i] >> 24) & 0xff);
ret[j++] = (byte) ((cdata[i] >> 16) & 0xff);
ret[j++] = (byte) ((cdata[i] >> 8) & 0xff);
ret[j++] = (byte) (cdata[i] & 0xff);
}
return ret;
}
/**
* Hash a password using the OpenBSD bcrypt scheme
* @param password the password to hash
* @param salt the salt to hash with (perhaps generated using BCrypt.gensalt)
* @return the hashed password
* @throws IllegalArgumentException if invalid salt is passed
*/
public static String hashpw(String password, String salt) throws IllegalArgumentException {
BCrypt B;
String real_salt;
byte passwordb[], saltb[], hashed[];
char minor = (char) 0;
int rounds, off = 0;
StringBuilder rs = new StringBuilder();
if (salt == null) {
throw new IllegalArgumentException("salt cannot be null");
}
int saltLength = salt.length();
if (saltLength < 28) {
throw new IllegalArgumentException("Invalid salt");
}
if (salt.charAt(0) != '$' || salt.charAt(1) != '2') {
throw new IllegalArgumentException("Invalid salt version");
}
if (salt.charAt(2) == '$') {
off = 3;
}
else {
minor = salt.charAt(2);
if (minor != 'a' || salt.charAt(3) != '$') {
throw new IllegalArgumentException("Invalid salt revision");
}
off = 4;
}
if (saltLength - off < 25) {
throw new IllegalArgumentException("Invalid salt");
}
// Extract number of rounds
if (salt.charAt(off + 2) > '$') {
throw new IllegalArgumentException("Missing salt rounds");
}
rounds = Integer.parseInt(salt.substring(off, off + 2));
real_salt = salt.substring(off + 3, off + 25);
try {
passwordb = (password + (minor >= 'a' ? "\000" : "")).getBytes("UTF-8");
}
catch (UnsupportedEncodingException uee) {
throw new AssertionError("UTF-8 is not supported");
}
saltb = decode_base64(real_salt, BCRYPT_SALT_LEN);
B = new BCrypt();
hashed = B.crypt_raw(passwordb, saltb, rounds);
rs.append("$2");
if (minor >= 'a') {
rs.append(minor);
}
rs.append("$");
if (rounds < 10) {
rs.append("0");
}
rs.append(rounds);
rs.append("$");
encode_base64(saltb, saltb.length, rs);
encode_base64(hashed, bf_crypt_ciphertext.length * 4 - 1, rs);
return rs.toString();
}
/**
* Generate a salt for use with the BCrypt.hashpw() method
* @param log_rounds the log2 of the number of rounds of hashing to apply - the work
* factor therefore increases as 2**log_rounds. Minimum 4, maximum 31.
* @param random an instance of SecureRandom to use
* @return an encoded salt value
*/
public static String gensalt(int log_rounds, SecureRandom random) {
if (log_rounds < MIN_LOG_ROUNDS || log_rounds > MAX_LOG_ROUNDS) {
throw new IllegalArgumentException("Bad number of rounds");
}
StringBuilder rs = new StringBuilder();
byte rnd[] = new byte[BCRYPT_SALT_LEN];
random.nextBytes(rnd);
rs.append("$2a$");
if (log_rounds < 10) {
rs.append("0");
}
rs.append(log_rounds);
rs.append("$");
encode_base64(rnd, rnd.length, rs);
return rs.toString();
}
/**
* Generate a salt for use with the BCrypt.hashpw() method
* @param log_rounds the log2 of the number of rounds of hashing to apply - the work
* factor therefore increases as 2**log_rounds. Minimum 4, maximum 31.
* @return an encoded salt value
*/
public static String gensalt(int log_rounds) {
return gensalt(log_rounds, new SecureRandom());
}
/**
* Generate a salt for use with the BCrypt.hashpw() method, selecting a reasonable
* default for the number of hashing rounds to apply
* @return an encoded salt value
*/
public static String gensalt() {
return gensalt(GENSALT_DEFAULT_LOG2_ROUNDS);
}
/**
* Check that a plaintext password matches a previously hashed one
* @param plaintext the plaintext password to verify
* @param hashed the previously-hashed password
* @return true if the passwords match, false otherwise
*/
public static boolean checkpw(String plaintext, String hashed) {
return equalsNoEarlyReturn(hashed, hashpw(plaintext, hashed));
}
static boolean equalsNoEarlyReturn(String a, String b) {
char[] caa = a.toCharArray();
char[] cab = b.toCharArray();
if (caa.length != cab.length) {
return false;
}
byte ret = 0;
for (int i = 0; i < caa.length; i++) {
ret |= caa[i] ^ cab[i];
}
return ret == 0;
}
}

View File

@@ -0,0 +1,82 @@
package io.renren.modules.security.password;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.security.SecureRandom;
import java.util.regex.Pattern;
/**
* Implementation of PasswordEncoder that uses the BCrypt strong hashing function. Clients
* can optionally supply a "strength" (a.k.a. log rounds in BCrypt) and a SecureRandom
* instance. The larger the strength parameter the more work will have to be done
* (exponentially) to hash the passwords. The default value is 10.
*
* @author Dave Syer
*
*/
public class BCryptPasswordEncoder implements PasswordEncoder {
private Pattern BCRYPT_PATTERN = Pattern
.compile("\\A\\$2a?\\$\\d\\d\\$[./0-9A-Za-z]{53}");
private final Log logger = LogFactory.getLog(getClass());
private final int strength;
private final SecureRandom random;
public BCryptPasswordEncoder() {
this(-1);
}
/**
* @param strength the log rounds to use, between 4 and 31
*/
public BCryptPasswordEncoder(int strength) {
this(strength, null);
}
/**
* @param strength the log rounds to use, between 4 and 31
* @param random the secure random instance to use
*
*/
public BCryptPasswordEncoder(int strength, SecureRandom random) {
if (strength != -1 && (strength < BCrypt.MIN_LOG_ROUNDS || strength > BCrypt.MAX_LOG_ROUNDS)) {
throw new IllegalArgumentException("Bad strength");
}
this.strength = strength;
this.random = random;
}
@Override
public String encode(CharSequence rawPassword) {
String salt;
if (strength > 0) {
if (random != null) {
salt = BCrypt.gensalt(strength, random);
}
else {
salt = BCrypt.gensalt(strength);
}
}
else {
salt = BCrypt.gensalt();
}
return BCrypt.hashpw(rawPassword.toString(), salt);
}
@Override
public boolean matches(CharSequence rawPassword, String encodedPassword) {
if (encodedPassword == null || encodedPassword.length() == 0) {
logger.warn("Empty encoded password");
return false;
}
if (!BCRYPT_PATTERN.matcher(encodedPassword).matches()) {
logger.warn("Encoded password does not look like BCrypt");
return false;
}
return BCrypt.checkpw(rawPassword.toString(), encodedPassword);
}
}

View File

@@ -0,0 +1,30 @@
package io.renren.modules.security.password;
/**
* Service interface for encoding passwords.
*
* The preferred implementation is {@code BCryptPasswordEncoder}.
*
* @author Keith Donald
*/
public interface PasswordEncoder {
/**
* Encode the raw password. Generally, a good encoding algorithm applies a SHA-1 or
* greater hash combined with an 8-byte or greater randomly generated salt.
*/
String encode(CharSequence rawPassword);
/**
* Verify the encoded password obtained from storage matches the submitted raw
* password after it too is encoded. Returns true if the passwords match, false if
* they do not. The stored password itself is never decoded.
*
* @param rawPassword the raw password to encode and match
* @param encodedPassword the encoded password from storage to compare with
* @return true if the raw password, after encoding, matches the encoded password from
* storage
*/
boolean matches(CharSequence rawPassword, String encodedPassword);
}

View File

@@ -0,0 +1,58 @@
/**
* Copyright 2018 人人开源 https://www.renren.io
* <p>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* <p>
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* <p>
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package io.renren.modules.security.password;
/**
* 密码工具类
*
* @author Mark sunlightcs@gmail.com
* @since 1.0.0
*/
public class PasswordUtils {
private static PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
/**
* 加密
* @param str 字符串
* @return 返回加密字符串
*/
public static String encode(String str){
return passwordEncoder.encode(str);
}
/**
* 比较密码是否相等
* @param str 明文密码
* @param password 加密后密码
* @return true成功 false失败
*/
public static boolean matches(String str, String password){
return passwordEncoder.matches(str, password);
}
public static void main(String[] args) {
String str = "admin";
String password = encode(str);
System.out.println(password);
System.out.println(matches(str, password));
}
}

View File

@@ -0,0 +1,34 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package io.renren.modules.security.service;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 验证码
*
* @author Mark sunlightcs@gmail.com
*/
public interface CaptchaService {
/**
* 图片验证码
*/
void create(HttpServletResponse response, String uuid) throws IOException;
/**
* 验证码效验
* @param uuid uuid
* @param code 验证码
* @return true成功 false失败
*/
boolean validate(String uuid, String code);
}

View File

@@ -0,0 +1,43 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package io.renren.modules.security.service;
import io.renren.modules.security.user.UserDetail;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.security.entity.SysUserTokenEntity;
import java.util.List;
import java.util.Set;
/**
* shiro相关接口
*
* @author Mark sunlightcs@gmail.com
*/
public interface ShiroService {
/**
* 获取用户权限列表
*/
Set<String> getUserPermissions(UserDetail user);
SysUserTokenEntity getByToken(String token);
/**
* 根据用户ID查询用户
* @param userId
*/
SysUserEntity getUser(Long userId);
/**
* 获取用户对应的部门数据权限
* @param userId 用户ID
* @return 返回部门ID列表
*/
List<Long> getDataScopeList(Long userId);
}

View File

@@ -0,0 +1,34 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package io.renren.modules.security.service;
import io.renren.common.service.BaseService;
import io.renren.common.utils.Result;
import io.renren.modules.security.entity.SysUserTokenEntity;
/**
* 用户Token
*
* @author Mark sunlightcs@gmail.com
*/
public interface SysUserTokenService extends BaseService<SysUserTokenEntity> {
/**
* 生成token
* @param userId 用户ID
*/
Result createToken(Long userId);
/**
* 退出修改token值
* @param userId 用户ID
*/
void logout(Long userId);
}

View File

@@ -0,0 +1,99 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
* <p>
* https://www.renren.io
* <p>
* 版权所有,侵权必究!
*/
package io.renren.modules.security.service.impl;
import cn.hutool.cache.Cache;
import cn.hutool.cache.CacheUtil;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import io.renren.common.redis.RedisKeys;
import io.renren.common.redis.RedisUtils;
import io.renren.modules.security.service.CaptchaService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.io.IOException;
/**
* 验证码
*
* @author Mark sunlightcs@gmail.com
*/
@Service
public class CaptchaServiceImpl implements CaptchaService {
@Resource
private RedisUtils redisUtils;
@Value("${renren.redis.open: false}")
private boolean open;
/**
* Local Cache 5分钟过期
*/
Cache<String, String> localCache = CacheUtil.newLRUCache(1000, 1000 * 60 * 5);
@Override
public void create(HttpServletResponse response, String uuid) throws IOException {
response.setContentType("image/gif");
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
//生成验证码
SpecCaptcha captcha = new SpecCaptcha(150, 40);
captcha.setLen(5);
captcha.setCharType(Captcha.TYPE_DEFAULT);
captcha.out(response.getOutputStream());
//保存到缓存
setCache(uuid, captcha.text());
}
@Override
public boolean validate(String uuid, String code) {
//获取验证码
String captcha = getCache(uuid);
//效验成功
if (code.equalsIgnoreCase(captcha)) {
return true;
}
return false;
}
private void setCache(String key, String value) {
if (open) {
key = RedisKeys.getCaptchaKey(key);
redisUtils.set(key, value, 300);
} else {
localCache.put(key, value);
}
}
private String getCache(String key) {
if (open) {
key = RedisKeys.getCaptchaKey(key);
String captcha = (String) redisUtils.get(key);
//删除验证码
if (captcha != null) {
redisUtils.delete(key);
}
return captcha;
}
String captcha = localCache.get(key);
//删除验证码
if (captcha != null) {
localCache.remove(key);
}
return captcha;
}
}

View File

@@ -0,0 +1,73 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
* <p>
* https://www.renren.io
* <p>
* 版权所有,侵权必究!
*/
package io.renren.modules.security.service.impl;
import cn.hutool.core.util.StrUtil;
import io.renren.modules.security.dao.SysUserTokenDao;
import io.renren.modules.security.entity.SysUserTokenEntity;
import io.renren.modules.security.service.ShiroService;
import io.renren.modules.security.user.UserDetail;
import io.renren.modules.sys.dao.SysMenuDao;
import io.renren.modules.sys.dao.SysRoleDataScopeDao;
import io.renren.modules.sys.dao.SysUserDao;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.enums.SuperAdminEnum;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@Service
@AllArgsConstructor
public class ShiroServiceImpl implements ShiroService {
private final SysMenuDao sysMenuDao;
private final SysUserDao sysUserDao;
private final SysUserTokenDao sysUserTokenDao;
private final SysRoleDataScopeDao sysRoleDataScopeDao;
@Override
public Set<String> getUserPermissions(UserDetail user) {
//系统管理员,拥有最高权限
List<String> permissionsList;
if (user.getSuperAdmin() == SuperAdminEnum.YES.value()) {
permissionsList = sysMenuDao.getPermissionsList();
} else {
permissionsList = sysMenuDao.getUserPermissionsList(user.getId());
}
//用户权限列表
Set<String> permsSet = new HashSet<>();
for (String permissions : permissionsList) {
if (StrUtil.isBlank(permissions)) {
continue;
}
permsSet.addAll(Arrays.asList(permissions.trim().split(",")));
}
return permsSet;
}
@Override
public SysUserTokenEntity getByToken(String token) {
return sysUserTokenDao.getByToken(token);
}
@Override
public SysUserEntity getUser(Long userId) {
return sysUserDao.selectById(userId);
}
@Override
public List<Long> getDataScopeList(Long userId) {
return sysRoleDataScopeDao.getDataScopeList(userId);
}
}

View File

@@ -0,0 +1,86 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package io.renren.modules.security.service.impl;
import io.renren.common.constant.Constant;
import io.renren.common.service.impl.BaseServiceImpl;
import io.renren.modules.security.oauth2.TokenGenerator;
import io.renren.common.utils.Result;
import io.renren.modules.security.dao.SysUserTokenDao;
import io.renren.modules.security.entity.SysUserTokenEntity;
import io.renren.modules.security.service.SysUserTokenService;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@Service
public class SysUserTokenServiceImpl extends BaseServiceImpl<SysUserTokenDao, SysUserTokenEntity> implements SysUserTokenService {
/**
* 12小时后过期
*/
private final static int EXPIRE = 3600 * 12;
@Override
public Result createToken(Long userId) {
//用户token
String token;
//当前时间
Date now = new Date();
//过期时间
Date expireTime = new Date(now.getTime() + EXPIRE * 1000);
//判断是否生成过token
SysUserTokenEntity tokenEntity = baseDao.getByUserId(userId);
if(tokenEntity == null){
//生成一个token
token = TokenGenerator.generateValue();
tokenEntity = new SysUserTokenEntity();
tokenEntity.setUserId(userId);
tokenEntity.setToken(token);
tokenEntity.setUpdateDate(now);
tokenEntity.setExpireDate(expireTime);
//保存token
this.insert(tokenEntity);
}else{
//判断token是否过期
if(tokenEntity.getExpireDate().getTime() < System.currentTimeMillis()){
//token过期重新生成token
token = TokenGenerator.generateValue();
}else {
token = tokenEntity.getToken();
}
tokenEntity.setToken(token);
tokenEntity.setUpdateDate(now);
tokenEntity.setExpireDate(expireTime);
//更新token
this.updateById(tokenEntity);
}
Map<String, Object> map = new HashMap<>(2);
map.put(Constant.TOKEN_HEADER, token);
map.put("expire", EXPIRE);
return new Result().ok(map);
}
@Override
public void logout(Long userId) {
//生成一个token
String token = TokenGenerator.generateValue();
//修改token
baseDao.updateToken(userId, token);
}
}

View File

@@ -0,0 +1,59 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package io.renren.modules.security.user;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
/**
* 用户
*
* @author Mark sunlightcs@gmail.com
*/
public class SecurityUser {
public static Subject getSubject() {
try {
return SecurityUtils.getSubject();
}catch (Exception e){
return null;
}
}
/**
* 获取用户信息
*/
public static UserDetail getUser() {
Subject subject = getSubject();
if(subject == null){
return new UserDetail();
}
UserDetail user = (UserDetail)subject.getPrincipal();
if(user == null){
return new UserDetail();
}
return user;
}
/**
* 获取用户ID
*/
public static Long getUserId() {
return getUser().getId();
}
/**
* 获取部门ID
*/
public static Long getDeptId() {
return getUser().getDeptId();
}
}

View File

@@ -0,0 +1,41 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package io.renren.modules.security.user;
import lombok.Data;
import java.io.Serializable;
import java.util.List;
/**
* 登录用户信息
*
* @author Mark sunlightcs@gmail.com
*/
@Data
public class UserDetail implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private String username;
private String realName;
private String headUrl;
private Integer gender;
private String email;
private String mobile;
private Long deptId;
private String password;
private Integer status;
private Integer superAdmin;
/**
* 部门数据权限
*/
private List<Long> deptIdList;
}

View File

@@ -0,0 +1,20 @@
package io.renren.modules.sys.controller;
import io.renren.common.utils.Result;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* 首页提示
*
* @author Mark sunlightcs@gmail.com
*/
@RestController
public class IndexController {
@GetMapping("/")
public Result<String> index(){
String tips = "你好renren-admin已启动请启动renren-ui才能访问页面";
return new Result<String>().ok(tips);
}
}

View File

@@ -0,0 +1,98 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
* <p>
* https://www.renren.io
* <p>
* 版权所有,侵权必究!
*/
package io.renren.modules.sys.controller;
import io.renren.common.annotation.LogOperation;
import io.renren.common.utils.Result;
import io.renren.common.validator.AssertUtils;
import io.renren.common.validator.ValidatorUtils;
import io.renren.common.validator.group.AddGroup;
import io.renren.common.validator.group.DefaultGroup;
import io.renren.common.validator.group.UpdateGroup;
import io.renren.modules.sys.dto.SysDeptDTO;
import io.renren.modules.sys.service.SysDeptService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
/**
* 部门管理
*
* @author Mark sunlightcs@gmail.com
*/
@RestController
@RequestMapping("/sys/dept")
@Tag(name = "部门管理")
@AllArgsConstructor
public class SysDeptController {
private final SysDeptService sysDeptService;
@GetMapping("list")
@Operation(summary = "列表")
@RequiresPermissions("sys:dept:list")
public Result<List<SysDeptDTO>> list() {
List<SysDeptDTO> list = sysDeptService.list(new HashMap<>(1));
return new Result<List<SysDeptDTO>>().ok(list);
}
@GetMapping("{id}")
@Operation(summary = "信息")
@RequiresPermissions("sys:dept:info")
public Result<SysDeptDTO> get(@PathVariable("id") Long id) {
SysDeptDTO data = sysDeptService.get(id);
return new Result<SysDeptDTO>().ok(data);
}
@PostMapping
@Operation(summary = "保存")
@LogOperation("保存")
@RequiresPermissions("sys:dept:save")
public Result save(@RequestBody SysDeptDTO dto) {
//效验数据
ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);
sysDeptService.save(dto);
return new Result();
}
@PutMapping
@Operation(summary = "修改")
@LogOperation("修改")
@RequiresPermissions("sys:dept:update")
public Result update(@RequestBody SysDeptDTO dto) {
//效验数据
ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);
sysDeptService.update(dto);
return new Result();
}
@DeleteMapping("{id}")
@Operation(summary = "删除")
@LogOperation("删除")
@RequiresPermissions("sys:dept:delete")
public Result delete(@PathVariable("id") Long id) {
//效验数据
AssertUtils.isNull(id, "id");
sysDeptService.delete(id);
return new Result();
}
}

View File

@@ -0,0 +1,110 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
* <p>
* https://www.renren.io
* <p>
* 版权所有,侵权必究!
*/
package io.renren.modules.sys.controller;
import io.renren.common.annotation.LogOperation;
import io.renren.common.constant.Constant;
import io.renren.common.page.PageData;
import io.renren.common.utils.Result;
import io.renren.common.validator.AssertUtils;
import io.renren.common.validator.ValidatorUtils;
import io.renren.common.validator.group.DefaultGroup;
import io.renren.common.validator.group.UpdateGroup;
import io.renren.modules.sys.dto.SysDictDataDTO;
import io.renren.modules.sys.service.SysDictDataService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
/**
* 字典数据
*
* @author Mark sunlightcs@gmail.com
*/
@RestController
@RequestMapping("sys/dict/data")
@Tag(name = "字典数据")
@AllArgsConstructor
public class SysDictDataController {
private final SysDictDataService sysDictDataService;
@GetMapping("page")
@Operation(summary = "字典数据")
@Parameters({
@Parameter(name = Constant.PAGE, description = "当前页码从1开始", in = ParameterIn.QUERY, required = true, ref = "int"),
@Parameter(name = Constant.LIMIT, description = "每页显示记录数", in = ParameterIn.QUERY, required = true, ref = "int"),
@Parameter(name = Constant.ORDER_FIELD, description = "排序字段", in = ParameterIn.QUERY, ref = "String"),
@Parameter(name = Constant.ORDER, description = "排序方式,可选值(asc、desc)", in = ParameterIn.QUERY, ref = "String"),
@Parameter(name = "dictLabel", description = "字典标签", in = ParameterIn.QUERY, ref = "String"),
@Parameter(name = "dictValue", description = "字典值", in = ParameterIn.QUERY, ref = "String")
})
@RequiresPermissions("sys:dict:page")
public Result<PageData<SysDictDataDTO>> page(@Parameter(hidden = true) @RequestParam Map<String, Object> params) {
//字典类型
PageData<SysDictDataDTO> page = sysDictDataService.page(params);
return new Result<PageData<SysDictDataDTO>>().ok(page);
}
@GetMapping("{id}")
@Operation(summary = "信息")
@RequiresPermissions("sys:dict:info")
public Result<SysDictDataDTO> get(@PathVariable("id") Long id) {
SysDictDataDTO data = sysDictDataService.get(id);
return new Result<SysDictDataDTO>().ok(data);
}
@PostMapping
@Operation(summary = "保存")
@LogOperation("保存")
@RequiresPermissions("sys:dict:save")
public Result save(@RequestBody SysDictDataDTO dto) {
//效验数据
ValidatorUtils.validateEntity(dto, DefaultGroup.class);
sysDictDataService.save(dto);
return new Result();
}
@PutMapping
@Operation(summary = "修改")
@LogOperation("修改")
@RequiresPermissions("sys:dict:update")
public Result update(@RequestBody SysDictDataDTO dto) {
//效验数据
ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);
sysDictDataService.update(dto);
return new Result();
}
@DeleteMapping
@Operation(summary = "删除")
@LogOperation("删除")
@RequiresPermissions("sys:dict:delete")
public Result delete(@RequestBody Long[] ids) {
//效验数据
AssertUtils.isArrayEmpty(ids, "id");
sysDictDataService.delete(ids);
return new Result();
}
}

View File

@@ -0,0 +1,120 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
* <p>
* https://www.renren.io
* <p>
* 版权所有,侵权必究!
*/
package io.renren.modules.sys.controller;
import io.renren.common.annotation.LogOperation;
import io.renren.common.constant.Constant;
import io.renren.common.page.PageData;
import io.renren.common.utils.Result;
import io.renren.common.validator.AssertUtils;
import io.renren.common.validator.ValidatorUtils;
import io.renren.common.validator.group.DefaultGroup;
import io.renren.common.validator.group.UpdateGroup;
import io.renren.modules.sys.dto.SysDictTypeDTO;
import io.renren.modules.sys.entity.DictType;
import io.renren.modules.sys.service.SysDictTypeService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
/**
* 字典类型
*
* @author Mark sunlightcs@gmail.com
*/
@RestController
@RequestMapping("sys/dict/type")
@Tag(name = "字典类型")
@AllArgsConstructor
public class SysDictTypeController {
private final SysDictTypeService sysDictTypeService;
@GetMapping("page")
@Operation(summary = "字典类型")
@Parameters({
@Parameter(name = Constant.PAGE, description = "当前页码从1开始", in = ParameterIn.QUERY, required = true, ref = "int"),
@Parameter(name = Constant.LIMIT, description = "每页显示记录数", in = ParameterIn.QUERY, required = true, ref = "int"),
@Parameter(name = Constant.ORDER_FIELD, description = "排序字段", in = ParameterIn.QUERY, ref = "String"),
@Parameter(name = Constant.ORDER, description = "排序方式,可选值(asc、desc)", in = ParameterIn.QUERY, ref = "String"),
@Parameter(name = "dictType", description = "字典类型", in = ParameterIn.QUERY, ref = "String"),
@Parameter(name = "dictName", description = "字典名称", in = ParameterIn.QUERY, ref = "String")
})
@RequiresPermissions("sys:dict:page")
public Result<PageData<SysDictTypeDTO>> page(@Parameter(hidden = true) @RequestParam Map<String, Object> params) {
//字典类型
PageData<SysDictTypeDTO> page = sysDictTypeService.page(params);
return new Result<PageData<SysDictTypeDTO>>().ok(page);
}
@GetMapping("{id}")
@Operation(summary = "信息")
@RequiresPermissions("sys:dict:info")
public Result<SysDictTypeDTO> get(@PathVariable("id") Long id) {
SysDictTypeDTO data = sysDictTypeService.get(id);
return new Result<SysDictTypeDTO>().ok(data);
}
@PostMapping
@Operation(summary = "保存")
@LogOperation("保存")
@RequiresPermissions("sys:dict:save")
public Result save(@RequestBody SysDictTypeDTO dto) {
//效验数据
ValidatorUtils.validateEntity(dto, DefaultGroup.class);
sysDictTypeService.save(dto);
return new Result();
}
@PutMapping
@Operation(summary = "修改")
@LogOperation("修改")
@RequiresPermissions("sys:dict:update")
public Result update(@RequestBody SysDictTypeDTO dto) {
//效验数据
ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);
sysDictTypeService.update(dto);
return new Result();
}
@DeleteMapping
@Operation(summary = "删除")
@LogOperation("删除")
@RequiresPermissions("sys:dict:delete")
public Result delete(@RequestBody Long[] ids) {
//效验数据
AssertUtils.isArrayEmpty(ids, "id");
sysDictTypeService.delete(ids);
return new Result();
}
@GetMapping("all")
@Operation(summary = "所有字典数据")
public Result<List<DictType>> all() {
List<DictType> list = sysDictTypeService.getAllList();
return new Result<List<DictType>>().ok(list);
}
}

View File

@@ -0,0 +1,138 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
* <p>
* https://www.renren.io
* <p>
* 版权所有,侵权必究!
*/
package io.renren.modules.sys.controller;
import io.renren.common.annotation.LogOperation;
import io.renren.common.exception.ErrorCode;
import io.renren.common.utils.Result;
import io.renren.common.validator.AssertUtils;
import io.renren.common.validator.ValidatorUtils;
import io.renren.common.validator.group.DefaultGroup;
import io.renren.modules.security.service.ShiroService;
import io.renren.modules.security.user.SecurityUser;
import io.renren.modules.security.user.UserDetail;
import io.renren.modules.sys.dto.SysMenuDTO;
import io.renren.modules.sys.enums.MenuTypeEnum;
import io.renren.modules.sys.service.SysMenuService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Set;
/**
* 菜单管理
*
* @author Mark sunlightcs@gmail.com
*/
@RestController
@RequestMapping("/sys/menu")
@Tag(name = "菜单管理")
@AllArgsConstructor
public class SysMenuController {
private final SysMenuService sysMenuService;
private final ShiroService shiroService;
@GetMapping("nav")
@Operation(summary = "导航")
public Result<List<SysMenuDTO>> nav() {
UserDetail user = SecurityUser.getUser();
List<SysMenuDTO> list = sysMenuService.getUserMenuList(user, MenuTypeEnum.MENU.value());
return new Result<List<SysMenuDTO>>().ok(list);
}
@GetMapping("permissions")
@Operation(summary = "权限标识")
public Result<Set<String>> permissions() {
UserDetail user = SecurityUser.getUser();
Set<String> set = shiroService.getUserPermissions(user);
return new Result<Set<String>>().ok(set);
}
@GetMapping("list")
@Operation(summary = "列表")
@Parameter(name = "type", description = "菜单类型 0菜单 1按钮 null全部", in = ParameterIn.QUERY, ref = "int")
@RequiresPermissions("sys:menu:list")
public Result<List<SysMenuDTO>> list(Integer type) {
List<SysMenuDTO> list = sysMenuService.getAllMenuList(type);
return new Result<List<SysMenuDTO>>().ok(list);
}
@GetMapping("{id}")
@Operation(summary = "信息")
@RequiresPermissions("sys:menu:info")
public Result<SysMenuDTO> get(@PathVariable("id") Long id) {
SysMenuDTO data = sysMenuService.get(id);
return new Result<SysMenuDTO>().ok(data);
}
@PostMapping
@Operation(summary = "保存")
@LogOperation("保存")
@RequiresPermissions("sys:menu:save")
public Result save(@RequestBody SysMenuDTO dto) {
//效验数据
ValidatorUtils.validateEntity(dto, DefaultGroup.class);
sysMenuService.save(dto);
return new Result();
}
@PutMapping
@Operation(summary = "修改")
@LogOperation("修改")
@RequiresPermissions("sys:menu:update")
public Result update(@RequestBody SysMenuDTO dto) {
//效验数据
ValidatorUtils.validateEntity(dto, DefaultGroup.class);
sysMenuService.update(dto);
return new Result();
}
@DeleteMapping("{id}")
@Operation(summary = "删除")
@LogOperation("删除")
@RequiresPermissions("sys:menu:delete")
public Result delete(@PathVariable("id") Long id) {
//效验数据
AssertUtils.isNull(id, "id");
//判断是否有子菜单或按钮
List<SysMenuDTO> list = sysMenuService.getListPid(id);
if (list.size() > 0) {
return new Result().error(ErrorCode.SUB_MENU_EXIST);
}
sysMenuService.delete(id);
return new Result();
}
@GetMapping("select")
@Operation(summary = "角色菜单权限")
@RequiresPermissions("sys:menu:select")
public Result<List<SysMenuDTO>> select() {
UserDetail user = SecurityUser.getUser();
List<SysMenuDTO> list = sysMenuService.getUserMenuList(user, null);
return new Result<List<SysMenuDTO>>().ok(list);
}
}

View File

@@ -0,0 +1,126 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
* <p>
* https://www.renren.io
* <p>
* 版权所有,侵权必究!
*/
package io.renren.modules.sys.controller;
import io.renren.common.annotation.LogOperation;
import io.renren.common.constant.Constant;
import io.renren.common.page.PageData;
import io.renren.common.utils.ExcelUtils;
import io.renren.common.utils.Result;
import io.renren.common.validator.AssertUtils;
import io.renren.common.validator.ValidatorUtils;
import io.renren.common.validator.group.AddGroup;
import io.renren.common.validator.group.DefaultGroup;
import io.renren.common.validator.group.UpdateGroup;
import io.renren.modules.sys.dto.SysParamsDTO;
import io.renren.modules.sys.excel.SysParamsExcel;
import io.renren.modules.sys.service.SysParamsService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
/**
* 参数管理
*
* @author Mark sunlightcs@gmail.com
* @since 1.0.0
*/
@RestController
@RequestMapping("sys/params")
@Tag(name = "参数管理")
@AllArgsConstructor
public class SysParamsController {
private final SysParamsService sysParamsService;
@GetMapping("page")
@Operation(summary = "分页")
@Parameters({
@Parameter(name = Constant.PAGE, description = "当前页码从1开始", in = ParameterIn.QUERY, required = true, ref = "int"),
@Parameter(name = Constant.LIMIT, description = "每页显示记录数", in = ParameterIn.QUERY, required = true, ref = "int"),
@Parameter(name = Constant.ORDER_FIELD, description = "排序字段", in = ParameterIn.QUERY, ref = "String"),
@Parameter(name = Constant.ORDER, description = "排序方式,可选值(asc、desc)", in = ParameterIn.QUERY, ref = "String"),
@Parameter(name = "paramCode", description = "参数编码", in = ParameterIn.QUERY, ref = "String")
})
@RequiresPermissions("sys:params:page")
public Result<PageData<SysParamsDTO>> page(@Parameter(hidden = true) @RequestParam Map<String, Object> params) {
PageData<SysParamsDTO> page = sysParamsService.page(params);
return new Result<PageData<SysParamsDTO>>().ok(page);
}
@GetMapping("{id}")
@Operation(summary = "信息")
@RequiresPermissions("sys:params:info")
public Result<SysParamsDTO> get(@PathVariable("id") Long id) {
SysParamsDTO data = sysParamsService.get(id);
return new Result<SysParamsDTO>().ok(data);
}
@PostMapping
@Operation(summary = "保存")
@LogOperation("保存")
@RequiresPermissions("sys:params:save")
public Result save(@RequestBody SysParamsDTO dto) {
//效验数据
ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);
sysParamsService.save(dto);
return new Result();
}
@PutMapping
@Operation(summary = "修改")
@LogOperation("修改")
@RequiresPermissions("sys:params:update")
public Result update(@RequestBody SysParamsDTO dto) {
//效验数据
ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);
sysParamsService.update(dto);
return new Result();
}
@DeleteMapping
@Operation(summary = "删除")
@LogOperation("删除")
@RequiresPermissions("sys:params:delete")
public Result delete(@RequestBody Long[] ids) {
//效验数据
AssertUtils.isArrayEmpty(ids, "id");
sysParamsService.delete(ids);
return new Result();
}
@GetMapping("export")
@Operation(summary = "导出")
@LogOperation("导出")
@RequiresPermissions("sys:params:export")
@Parameter(name = "paramCode", description = "参数编码", in = ParameterIn.QUERY, ref = "String")
public void export(@Parameter(hidden = true) @RequestParam Map<String, Object> params, HttpServletResponse response) throws Exception {
List<SysParamsDTO> list = sysParamsService.list(params);
ExcelUtils.exportExcelToTarget(response, null, "参数管理", list, SysParamsExcel.class);
}
}

View File

@@ -0,0 +1,131 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
* <p>
* https://www.renren.io
* <p>
* 版权所有,侵权必究!
*/
package io.renren.modules.sys.controller;
import io.renren.common.annotation.LogOperation;
import io.renren.common.constant.Constant;
import io.renren.common.page.PageData;
import io.renren.common.utils.Result;
import io.renren.common.validator.AssertUtils;
import io.renren.common.validator.ValidatorUtils;
import io.renren.common.validator.group.AddGroup;
import io.renren.common.validator.group.DefaultGroup;
import io.renren.common.validator.group.UpdateGroup;
import io.renren.modules.sys.dto.SysRoleDTO;
import io.renren.modules.sys.service.SysRoleDataScopeService;
import io.renren.modules.sys.service.SysRoleMenuService;
import io.renren.modules.sys.service.SysRoleService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 角色管理
*
* @author Mark sunlightcs@gmail.com
*/
@RestController
@RequestMapping("/sys/role")
@Tag(name = "角色管理")
@AllArgsConstructor
public class SysRoleController {
private final SysRoleService sysRoleService;
private final SysRoleMenuService sysRoleMenuService;
private final SysRoleDataScopeService sysRoleDataScopeService;
@GetMapping("page")
@Operation(summary = "分页")
@Parameters({
@Parameter(name = Constant.PAGE, description = "当前页码从1开始", in = ParameterIn.QUERY, required = true, ref = "int"),
@Parameter(name = Constant.LIMIT, description = "每页显示记录数", in = ParameterIn.QUERY, required = true, ref = "int"),
@Parameter(name = Constant.ORDER_FIELD, description = "排序字段", in = ParameterIn.QUERY, ref = "String"),
@Parameter(name = Constant.ORDER, description = "排序方式,可选值(asc、desc)", in = ParameterIn.QUERY, ref = "String"),
@Parameter(name = "name", description = "角色名", in = ParameterIn.QUERY, ref = "String")
})
@RequiresPermissions("sys:role:page")
public Result<PageData<SysRoleDTO>> page(@Parameter(hidden = true) @RequestParam Map<String, Object> params) {
PageData<SysRoleDTO> page = sysRoleService.page(params);
return new Result<PageData<SysRoleDTO>>().ok(page);
}
@GetMapping("list")
@Operation(summary = "列表")
@RequiresPermissions("sys:role:list")
public Result<List<SysRoleDTO>> list() {
List<SysRoleDTO> data = sysRoleService.list(new HashMap<>(1));
return new Result<List<SysRoleDTO>>().ok(data);
}
@GetMapping("{id}")
@Operation(summary = "信息")
@RequiresPermissions("sys:role:info")
public Result<SysRoleDTO> get(@PathVariable("id") Long id) {
SysRoleDTO data = sysRoleService.get(id);
//查询角色对应的菜单
List<Long> menuIdList = sysRoleMenuService.getMenuIdList(id);
data.setMenuIdList(menuIdList);
//查询角色对应的数据权限
List<Long> deptIdList = sysRoleDataScopeService.getDeptIdList(id);
data.setDeptIdList(deptIdList);
return new Result<SysRoleDTO>().ok(data);
}
@PostMapping
@Operation(summary = "保存")
@LogOperation("保存")
@RequiresPermissions("sys:role:save")
public Result save(@RequestBody SysRoleDTO dto) {
//效验数据
ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);
sysRoleService.save(dto);
return new Result();
}
@PutMapping
@Operation(summary = "修改")
@LogOperation("修改")
@RequiresPermissions("sys:role:update")
public Result update(@RequestBody SysRoleDTO dto) {
//效验数据
ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);
sysRoleService.update(dto);
return new Result();
}
@DeleteMapping
@Operation(summary = "删除")
@LogOperation("删除")
@RequiresPermissions("sys:role:delete")
public Result delete(@RequestBody Long[] ids) {
//效验数据
AssertUtils.isArrayEmpty(ids, "id");
sysRoleService.delete(ids);
return new Result();
}
}

Some files were not shown because too many files have changed in this diff Show More