This commit is contained in:
闵宪瑞 2025-05-22 17:32:03 +08:00
parent 795a0d0c4b
commit e6227f4d92
359 changed files with 34361 additions and 19 deletions

174
.gitignore vendored
View File

@ -1,26 +1,162 @@
# ---> Java
# Compiled class file
*.class
# ---> Python
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
.idea
# C extensions
*.so
# Log file
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# BlueJ files
*.ctxt
# Flask stuff:
instance/
.webassets-cache
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Scrapy stuff:
.scrapy
# Package Files #
*.jar
*.war
*.nar
*.ear
*.zip
*.tar.gz
*.rar
# Sphinx documentation
docs/_build/
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
replay_pid*
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock
# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/#use-with-ide
.pdm.toml
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/

200
admin/admin.iml Normal file
View File

@ -0,0 +1,200 @@
<?xml version="1.0" encoding="UTF-8"?>
<module org.jetbrains.idea.maven.project.MavenProjectsManager.isMavenModule="true" type="JAVA_MODULE" version="4">
<component name="FacetManager">
<facet type="web" name="Web">
<configuration>
<webroots />
</configuration>
</facet>
<facet type="Spring" name="Spring">
<configuration />
</facet>
</component>
<component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_17">
<output url="file://$MODULE_DIR$/target/classes" />
<output-test url="file://$MODULE_DIR$/target/test-classes" />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />
<excludeFolder url="file://$MODULE_DIR$/target" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="module" module-name="common" />
<orderEntry type="library" name="Maven: org.apache.shiro:shiro-spring:jakarta:1.12.0" level="project" />
<orderEntry type="library" name="Maven: org.apache.shiro:shiro-core:jakarta:1.12.0" level="project" />
<orderEntry type="library" name="Maven: org.apache.shiro:shiro-lang:1.12.0" level="project" />
<orderEntry type="library" name="Maven: org.apache.shiro:shiro-cache:1.12.0" level="project" />
<orderEntry type="library" name="Maven: org.apache.shiro:shiro-crypto-hash:1.12.0" level="project" />
<orderEntry type="library" name="Maven: org.apache.shiro:shiro-crypto-core:1.12.0" level="project" />
<orderEntry type="library" name="Maven: org.apache.shiro:shiro-crypto-cipher:1.12.0" level="project" />
<orderEntry type="library" name="Maven: org.apache.shiro:shiro-config-core:1.12.0" level="project" />
<orderEntry type="library" name="Maven: org.apache.shiro:shiro-config-ogdl:1.12.0" level="project" />
<orderEntry type="library" name="Maven: commons-beanutils:commons-beanutils:1.9.4" level="project" />
<orderEntry type="library" name="Maven: commons-collections:commons-collections:3.2.2" level="project" />
<orderEntry type="library" name="Maven: org.apache.shiro:shiro-event:1.12.0" level="project" />
<orderEntry type="library" name="Maven: org.apache.shiro:shiro-web:jakarta:1.12.0" level="project" />
<orderEntry type="library" name="Maven: org.owasp.encoder:encoder:1.2.3" level="project" />
<orderEntry type="library" name="Maven: com.github.whvcse:easy-captcha:1.6.2" level="project" />
<orderEntry type="library" name="Maven: com.alibaba:easyexcel:3.2.1" level="project" />
<orderEntry type="library" name="Maven: com.alibaba:easyexcel-core:3.2.1" level="project" />
<orderEntry type="library" name="Maven: com.alibaba:easyexcel-support:3.2.1" level="project" />
<orderEntry type="library" name="Maven: org.apache.poi:poi:4.1.2" level="project" />
<orderEntry type="library" name="Maven: org.apache.commons:commons-collections4:4.4" level="project" />
<orderEntry type="library" name="Maven: org.apache.commons:commons-math3:3.6.1" level="project" />
<orderEntry type="library" name="Maven: com.zaxxer:SparseBitSet:1.2" level="project" />
<orderEntry type="library" name="Maven: org.apache.poi:poi-ooxml:4.1.2" level="project" />
<orderEntry type="library" name="Maven: org.apache.commons:commons-compress:1.19" level="project" />
<orderEntry type="library" name="Maven: com.github.virtuald:curvesapi:1.06" level="project" />
<orderEntry type="library" name="Maven: org.apache.poi:poi-ooxml-schemas:4.1.2" level="project" />
<orderEntry type="library" name="Maven: org.apache.xmlbeans:xmlbeans:3.1.0" level="project" />
<orderEntry type="library" name="Maven: org.apache.commons:commons-csv:1.8" level="project" />
<orderEntry type="library" name="Maven: org.ehcache:ehcache:3.10.8" level="project" />
<orderEntry type="library" name="Maven: javax.cache:cache-api:1.1.1" level="project" />
<orderEntry type="library" scope="RUNTIME" name="Maven: org.glassfish.jaxb:jaxb-runtime:4.0.5" level="project" />
<orderEntry type="library" scope="RUNTIME" name="Maven: org.glassfish.jaxb:jaxb-core:4.0.5" level="project" />
<orderEntry type="library" scope="RUNTIME" name="Maven: org.eclipse.angus:angus-activation:2.0.2" level="project" />
<orderEntry type="library" scope="RUNTIME" name="Maven: org.glassfish.jaxb:txw2:4.0.5" level="project" />
<orderEntry type="library" scope="RUNTIME" name="Maven: com.sun.istack:istack-commons-runtime:4.1.2" level="project" />
<orderEntry type="library" name="Maven: org.slf4j:slf4j-api:2.0.13" level="project" />
<orderEntry type="library" name="Maven: com.qiniu:qiniu-java-sdk:7.2.27" level="project" />
<orderEntry type="library" scope="RUNTIME" name="Maven: com.squareup.okhttp3:okhttp:4.12.0" level="project" />
<orderEntry type="library" scope="RUNTIME" name="Maven: com.squareup.okio:okio:3.6.0" level="project" />
<orderEntry type="library" scope="RUNTIME" name="Maven: com.squareup.okio:okio-jvm:3.6.0" level="project" />
<orderEntry type="library" scope="RUNTIME" name="Maven: org.jetbrains.kotlin:kotlin-stdlib-common:1.9.24" level="project" />
<orderEntry type="library" scope="RUNTIME" name="Maven: org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.9.24" level="project" />
<orderEntry type="library" scope="RUNTIME" name="Maven: org.jetbrains.kotlin:kotlin-stdlib:1.9.24" level="project" />
<orderEntry type="library" scope="RUNTIME" name="Maven: org.jetbrains:annotations:13.0" level="project" />
<orderEntry type="library" scope="RUNTIME" name="Maven: org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.9.24" level="project" />
<orderEntry type="library" scope="RUNTIME" name="Maven: com.google.code.gson:gson:2.10.1" level="project" />
<orderEntry type="library" name="Maven: com.aliyun.oss:aliyun-sdk-oss:2.8.3" level="project" />
<orderEntry type="library" name="Maven: org.apache.httpcomponents:httpclient:4.4.1" level="project" />
<orderEntry type="library" name="Maven: org.apache.httpcomponents:httpcore:4.4.16" level="project" />
<orderEntry type="library" name="Maven: commons-logging:commons-logging:1.2" level="project" />
<orderEntry type="library" name="Maven: org.jdom:jdom:1.1" level="project" />
<orderEntry type="library" name="Maven: com.aliyun:aliyun-java-sdk-core:3.2.2" level="project" />
<orderEntry type="library" name="Maven: com.qcloud:cos_api:5.4.4" level="project" />
<orderEntry type="library" name="Maven: commons-codec:commons-codec:1.16.1" level="project" />
<orderEntry type="library" name="Maven: joda-time:joda-time:2.9.6" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.core:jackson-databind:2.15.4" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.core:jackson-annotations:2.15.4" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.core:jackson-core:2.15.4" level="project" />
<orderEntry type="library" name="Maven: junit:junit:4.13.2" level="project" />
<orderEntry type="library" name="Maven: org.hamcrest:hamcrest-core:2.2" level="project" />
<orderEntry type="library" name="Maven: org.bouncycastle:bcprov-jdk15on:1.59" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.springframework.boot:spring-boot-starter-test:3.2.6" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter:3.2.6" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot:3.2.6" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-logging:3.2.6" level="project" />
<orderEntry type="library" name="Maven: ch.qos.logback:logback-classic:1.4.14" level="project" />
<orderEntry type="library" name="Maven: ch.qos.logback:logback-core:1.4.14" level="project" />
<orderEntry type="library" name="Maven: org.apache.logging.log4j:log4j-to-slf4j:2.21.1" level="project" />
<orderEntry type="library" name="Maven: org.apache.logging.log4j:log4j-api:2.21.1" level="project" />
<orderEntry type="library" name="Maven: org.slf4j:jul-to-slf4j:2.0.13" level="project" />
<orderEntry type="library" name="Maven: jakarta.annotation:jakarta.annotation-api:2.1.1" level="project" />
<orderEntry type="library" name="Maven: org.yaml:snakeyaml:2.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.springframework.boot:spring-boot-test:3.2.6" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.springframework.boot:spring-boot-test-autoconfigure:3.2.6" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: com.jayway.jsonpath:json-path:2.9.0" level="project" />
<orderEntry type="library" name="Maven: jakarta.xml.bind:jakarta.xml.bind-api:4.0.2" level="project" />
<orderEntry type="library" name="Maven: jakarta.activation:jakarta.activation-api:2.1.3" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: net.minidev:json-smart:2.5.1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: net.minidev:accessors-smart:2.5.1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.ow2.asm:asm:9.6" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.assertj:assertj-core:3.24.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: net.bytebuddy:byte-buddy:1.14.16" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.awaitility:awaitility:4.2.1" level="project" />
<orderEntry type="library" name="Maven: org.hamcrest:hamcrest:2.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.junit.jupiter:junit-jupiter:5.10.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.junit.jupiter:junit-jupiter-api:5.10.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.opentest4j:opentest4j:1.3.0" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.junit.platform:junit-platform-commons:1.10.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apiguardian:apiguardian-api:1.1.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.junit.jupiter:junit-jupiter-params:5.10.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.junit.jupiter:junit-jupiter-engine:5.10.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.junit.platform:junit-platform-engine:1.10.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.mockito:mockito-core:5.7.0" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: net.bytebuddy:byte-buddy-agent:1.14.16" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.objenesis:objenesis:3.3" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.mockito:mockito-junit-jupiter:5.7.0" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.skyscreamer:jsonassert:1.5.1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: com.vaadin.external.google:android-json:0.0.20131108.vaadin1" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-core:6.1.8" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-jcl:6.1.8" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.springframework:spring-test:6.1.8" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.xmlunit:xmlunit-core:2.9.1" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-web:3.2.6" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-json:3.2.6" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.datatype:jackson-datatype-jdk8:2.15.4" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.15.4" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.module:jackson-module-parameter-names:2.15.4" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-tomcat:3.2.6" level="project" />
<orderEntry type="library" name="Maven: org.apache.tomcat.embed:tomcat-embed-core:10.1.24" level="project" />
<orderEntry type="library" name="Maven: org.apache.tomcat.embed:tomcat-embed-websocket:10.1.24" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-web:6.1.8" level="project" />
<orderEntry type="library" name="Maven: io.micrometer:micrometer-observation:1.12.6" level="project" />
<orderEntry type="library" name="Maven: io.micrometer:micrometer-commons:1.12.6" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-webmvc:6.1.8" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-expression:6.1.8" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-aop:3.2.6" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-aop:6.1.8" level="project" />
<orderEntry type="library" name="Maven: org.aspectj:aspectjweaver:1.9.22" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-validation:3.2.6" level="project" />
<orderEntry type="library" name="Maven: org.apache.tomcat.embed:tomcat-embed-el:10.1.24" level="project" />
<orderEntry type="library" name="Maven: org.hibernate.validator:hibernate-validator:8.0.1.Final" level="project" />
<orderEntry type="library" name="Maven: jakarta.validation:jakarta.validation-api:3.0.2" level="project" />
<orderEntry type="library" name="Maven: org.jboss.logging:jboss-logging:3.5.3.Final" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml:classmate:1.6.0" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-context-support:6.1.8" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-beans:6.1.8" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-context:6.1.8" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-data-redis:3.2.6" level="project" />
<orderEntry type="library" name="Maven: io.lettuce:lettuce-core:6.3.2.RELEASE" level="project" />
<orderEntry type="library" name="Maven: io.netty:netty-common:4.1.110.Final" level="project" />
<orderEntry type="library" name="Maven: io.netty:netty-handler:4.1.110.Final" level="project" />
<orderEntry type="library" name="Maven: io.netty:netty-resolver:4.1.110.Final" level="project" />
<orderEntry type="library" name="Maven: io.netty:netty-buffer:4.1.110.Final" level="project" />
<orderEntry type="library" name="Maven: io.netty:netty-transport-native-unix-common:4.1.110.Final" level="project" />
<orderEntry type="library" name="Maven: io.netty:netty-codec:4.1.110.Final" level="project" />
<orderEntry type="library" name="Maven: io.netty:netty-transport:4.1.110.Final" level="project" />
<orderEntry type="library" name="Maven: io.projectreactor:reactor-core:3.6.6" level="project" />
<orderEntry type="library" name="Maven: org.reactivestreams:reactive-streams:1.0.4" level="project" />
<orderEntry type="library" name="Maven: org.springframework.data:spring-data-redis:3.2.6" level="project" />
<orderEntry type="library" name="Maven: org.springframework.data:spring-data-keyvalue:3.2.6" level="project" />
<orderEntry type="library" name="Maven: org.springframework.data:spring-data-commons:3.2.6" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-tx:6.1.8" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-oxm:6.1.8" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-configuration-processor:3.2.6" level="project" />
<orderEntry type="library" name="Maven: com.mysql:mysql-connector-j:8.3.0" level="project" />
<orderEntry type="library" name="Maven: com.alibaba:druid-spring-boot-3-starter:1.2.21" level="project" />
<orderEntry type="library" name="Maven: com.alibaba:druid:1.2.21" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-autoconfigure:3.2.6" level="project" />
<orderEntry type="library" name="Maven: com.baomidou:mybatis-plus-boot-starter:3.5.5" level="project" />
<orderEntry type="library" name="Maven: com.baomidou:mybatis-plus:3.5.5" level="project" />
<orderEntry type="library" name="Maven: com.baomidou:mybatis-plus-core:3.5.5" level="project" />
<orderEntry type="library" name="Maven: com.baomidou:mybatis-plus-annotation:3.5.5" level="project" />
<orderEntry type="library" name="Maven: com.baomidou:mybatis-plus-extension:3.5.5" level="project" />
<orderEntry type="library" name="Maven: org.mybatis:mybatis:3.5.15" level="project" />
<orderEntry type="library" name="Maven: com.github.jsqlparser:jsqlparser:4.6" level="project" />
<orderEntry type="library" name="Maven: com.baomidou:mybatis-plus-spring-boot-autoconfigure:3.5.5" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-jdbc:3.2.6" level="project" />
<orderEntry type="library" name="Maven: com.zaxxer:HikariCP:5.0.1" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-jdbc:6.1.8" level="project" />
<orderEntry type="library" name="Maven: org.mybatis:mybatis-spring:3.0.3" level="project" />
<orderEntry type="library" name="Maven: cn.hutool:hutool-all:5.8.29" level="project" />
<orderEntry type="library" name="Maven: org.jsoup:jsoup:1.15.3" level="project" />
<orderEntry type="library" name="Maven: com.github.xiaoymin:knife4j-openapi3-jakarta-spring-boot-starter:4.5.0" level="project" />
<orderEntry type="library" name="Maven: com.github.xiaoymin:knife4j-core:4.5.0" level="project" />
<orderEntry type="library" name="Maven: com.github.xiaoymin:knife4j-openapi3-ui:4.5.0" level="project" />
<orderEntry type="library" name="Maven: org.springdoc:springdoc-openapi-starter-webmvc-ui:2.3.0" level="project" />
<orderEntry type="library" name="Maven: org.springdoc:springdoc-openapi-starter-webmvc-api:2.3.0" level="project" />
<orderEntry type="library" name="Maven: org.springdoc:springdoc-openapi-starter-common:2.3.0" level="project" />
<orderEntry type="library" name="Maven: io.swagger.core.v3:swagger-core-jakarta:2.2.19" level="project" />
<orderEntry type="library" name="Maven: org.apache.commons:commons-lang3:3.13.0" level="project" />
<orderEntry type="library" name="Maven: io.swagger.core.v3:swagger-annotations-jakarta:2.2.19" level="project" />
<orderEntry type="library" name="Maven: io.swagger.core.v3:swagger-models-jakarta:2.2.19" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:2.15.4" level="project" />
<orderEntry type="library" name="Maven: org.webjars:swagger-ui:5.10.3" level="project" />
<orderEntry type="library" name="Maven: org.projectlombok:lombok:1.18.24" level="project" />
</component>
</module>

119
admin/pom.xml Normal file
View File

@ -0,0 +1,119 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>io.renren</groupId>
<artifactId>block-chaincopyright</artifactId>
<version>5.4.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>admin</artifactId>
<packaging>jar</packaging>
<description>admin</description>
<properties>
<quartz.version>2.3.2</quartz.version>
<shiro.version>1.12.0</shiro.version>
<captcha.version>1.6.2</captcha.version>
<easyexcel.version>3.2.1</easyexcel.version>
<qiniu.version>7.2.27</qiniu.version>
<aliyun.oss.version>2.8.3</aliyun.oss.version>
<aliyun.core.version>3.2.2</aliyun.core.version>
<qcloud.cos.version>5.4.4</qcloud.cos.version>
</properties>
<dependencies>
<dependency>
<groupId>io.renren</groupId>
<artifactId>common</artifactId>
<version>5.4.0</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<classifier>jakarta</classifier>
<version>${shiro.version}</version>
<!-- 排除仍使用了javax.servlet的依赖 -->
<exclusions>
<exclusion>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-web</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- 引入适配jakarta的依赖包 -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<classifier>jakarta</classifier>
<version>${shiro.version}</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-web</artifactId>
<classifier>jakarta</classifier>
<version>${shiro.version}</version>
<exclusions>
<exclusion>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.github.whvcse</groupId>
<artifactId>easy-captcha</artifactId>
<version>${captcha.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>${easyexcel.version}</version>
</dependency>
<dependency>
<groupId>com.qiniu</groupId>
<artifactId>qiniu-java-sdk</artifactId>
<version>${qiniu.version}</version>
</dependency>
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>${aliyun.oss.version}</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>${aliyun.core.version}</version>
</dependency>
<dependency>
<groupId>com.qcloud</groupId>
<artifactId>cos_api</artifactId>
<version>${qcloud.cos.version}</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<skipTests>true</skipTests>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,21 @@
package io;
import org.mybatis.spring.annotation.MapperScan;
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;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@ComponentScan(basePackages = {"io.modules","io.modules","io.common"}) // 扫描多个包
@MapperScan(basePackages = {"io.modules.**.dao","io.common.modules.**.dao"})
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,30 @@
package io.common.annotation;
import java.lang.annotation.*;
/**
* 数据过滤注解
*
*/
@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,22 @@
package io.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;
/**
* 操作日志注解
*
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface LogOperation {
String value() default "";
}

View File

@ -0,0 +1,90 @@
package io.common.aspect;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.qiniu.util.StringUtils;
import io.common.annotation.DataFilter;
import io.common.interceptor.DataScope;
import io.common.constant.Constant;
import io.common.exception.ErrorCode;
import io.common.exception.RenException;
import io.modules.security.user.SecurityUser;
import io.modules.security.user.UserDetail;
import io.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;
/**
* 数据过滤切面处理类
*
*/
@Aspect
@Component
public class DataFilterAspect {
@Pointcut("@annotation(io.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("日期参数错误!");
}
/**
* 获取数据过滤的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,72 @@
package io.common.aspect;
import io.common.annotation.LogOperation;
import io.common.utils.HttpContextUtils;
import io.common.utils.JsonUtils;
import io.modules.security.user.SecurityUser;
import io.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;
/**
* 操作日志切面处理类
*
*/
@Aspect
@Component
@AllArgsConstructor
public class LogOperationAspect {
@Pointcut("@annotation(io.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;
return result;
} catch (Exception e) {
//执行时长(毫秒)
long time = System.currentTimeMillis() - beginTime;
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);
//登录用户信息
UserDetail user = SecurityUser.getUser();
//请求相关信息
HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
//请求参数
Object[] args = joinPoint.getArgs();
try {
String params = JsonUtils.toJsonString(args[0]);
} catch (Exception e) {
}
}
}

View File

@ -0,0 +1,34 @@
package io.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.common.interceptor.DataFilterInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* mybatis-plus配置
*/
@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,41 @@
package io.common.config;
import io.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配置
*
*/
@Configuration
public class SwaggerConfig {
@Bean
public OpenAPI createRestApi() {
return new OpenAPI()
.info(apiInfo())
.security(security());
}
private Info apiInfo() {
return new Info()
.title("系统")
.description("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,65 @@
package io.common.exception;
import cn.hutool.core.map.MapUtil;
import io.common.utils.HttpContextUtils;
import io.common.utils.IpUtils;
import io.common.utils.JsonUtils;
import io.common.utils.Result;
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;
/**
* 异常处理器
*/
@Slf4j
@RestControllerAdvice
@AllArgsConstructor
public class RenExceptionHandler {
/**
* 处理自定义异常
*/
@ExceptionHandler(RenException.class)
public Result handleRenException(RenException ex) {
System.out.println("自定义捕捉异常!");
Result result = new Result();
result.error(500, ex.getMsg());
return result;
}
@ExceptionHandler(DuplicateKeyException.class)
public Result handleDuplicateKeyException(DuplicateKeyException ex) {
Result result = new Result();
result.error("数据库中已存在该记录!");
return result;
}
@ExceptionHandler(Exception.class)
public Result handleException(Exception ex) {
System.out.println("全局捕捉异常!");
log.error(ex.getMessage(), ex);
saveLog(ex);
return new Result().error(ex.getMessage());
}
/**
* 保存异常日志
*/
private void saveLog(Exception ex) {
//请求相关信息
HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
Map<String, String> params = HttpContextUtils.getParameterMap(request);
}
}

View File

@ -0,0 +1,49 @@
package io.common.handler;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import io.modules.security.user.SecurityUser;
import io.modules.security.user.UserDetail;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import java.util.Date;
/**
* 公共字段自动填充值
*
*/
@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,82 @@
package io.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;
/**
* 数据过滤
*
*/
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,27 @@
package io.common.interceptor;
/**
* 数据范围
*/
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,64 @@
package io.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工具类
*/
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,84 @@
package io.modules.security.config;
import io.modules.security.oauth2.Oauth2Filter;
import io.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的配置文件
*
*/
@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,67 @@
package io.modules.security.config;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import io.common.utils.DateUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.ByteArrayHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.ResourceHttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.TimeZone;
@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);
}
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(new ByteArrayHttpMessageConverter());
converters.add(new StringHttpMessageConverter());
converters.add(new ResourceHttpMessageConverter());
converters.add(new AllEncompassingFormHttpMessageConverter());
converters.add(new StringHttpMessageConverter());
converters.add(jackson2HttpMessageConverter());
}
@Bean
public MappingJackson2HttpMessageConverter jackson2HttpMessageConverter() {
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
ObjectMapper mapper = new ObjectMapper();
//日期格式转换
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.setDateFormat(new SimpleDateFormat(DateUtils.DATE_TIME_PATTERN));
mapper.setTimeZone(TimeZone.getTimeZone("GMT+8"));
//Long类型转String类型
SimpleModule simpleModule = new SimpleModule();
simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
mapper.registerModule(simpleModule);
converter.setObjectMapper(mapper);
return converter;
}
}

View File

@ -0,0 +1,88 @@
package io.modules.security.controller;
import io.common.exception.RenException;
import io.common.utils.IpUtils;
import io.common.utils.Result;
import io.common.validator.AssertUtils;
import io.common.validator.ValidatorUtils;
import io.modules.security.dto.LoginDTO;
import io.modules.security.password.PasswordUtils;
import io.modules.security.service.CaptchaService;
import io.modules.security.service.SysUserTokenService;
import io.modules.security.user.SecurityUser;
import io.modules.security.user.UserDetail;
import io.modules.sys.dto.SysUserDTO;
import io.modules.sys.enums.UserStatusEnum;
import io.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.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;
/**
* 登录
*/
@RestController
@Tag(name = "登录管理")
@AllArgsConstructor
public class LoginController {
private final SysUserService sysUserService;
private final SysUserTokenService sysUserTokenService;
private final CaptchaService captchaService;
@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, "UUID不能为空~");
//生成验证码
captchaService.create(response, uuid);
}
@PostMapping("login")
@Operation(summary = "登录")
public Result login(@RequestBody LoginDTO login) {
//效验数据
// ValidatorUtils.validateEntity(login);
//验证码是否正确
// boolean flag = captchaService.validate(login.getUuid(), login.getCaptcha());
// if (!flag) {
// return new Result().error("验证码不正确~");
// }
//用户信息
SysUserDTO user = sysUserService.getByUsername(login.getUsername());
//用户不存在
if (user == null) {
throw new RenException("用户不存在~");
}
//密码错误
if (!PasswordUtils.matches(login.getPassword(), user.getPassword())) {
throw new RenException("密码错误~");
}
//账号停用
if (user.getStatus() == UserStatusEnum.DISABLE.value()) {
throw new RenException("账号停用~");
}
//登录成功
return sysUserTokenService.createToken(user.getId());
}
@PostMapping("logout")
@Operation(summary = "退出")
public Result logout(HttpServletRequest request) {
UserDetail user = SecurityUser.getUser();
//退出
sysUserTokenService.logout(user.getId());
return new Result();
}
}

View File

@ -0,0 +1,23 @@
package io.modules.security.dao;
import io.modules.security.entity.SysUserTokenEntity;
import io.common.dao.BaseDao;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
/**
* 系统用户Token
*
*/
@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,37 @@
package io.modules.security.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import lombok.Data;
import java.io.Serializable;
/**
* 登录表单
*
*/
@Data
@Schema(title = "登录表单")
public class LoginDTO implements Serializable {
private static final long serialVersionUID = 1L;
@Schema(title = "用户名", required = true)
@NotBlank(message="用户名不能为空~")
private String username;
@Schema(title = "密码")
@NotBlank(message="密码不能为空")
private String password;
// @Schema(title = "验证码")
// @NotBlank(message="验证不能为空")
// private String captcha;
@Schema(title = "唯一标识")
@NotBlank(message="唯一标识不能为空")
private String uuid;
}

View File

@ -0,0 +1,48 @@
package io.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 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,96 @@
package io.modules.security.oauth2;
import cn.hutool.core.util.StrUtil;
import io.common.constant.Constant;
import io.common.exception.ErrorCode;
import io.common.utils.HttpContextUtils;
import io.common.utils.JsonUtils;
import io.common.utils.Result;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.http.HttpStatus;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.springframework.web.bind.annotation.RequestMethod;
import java.io.IOException;
/**
* oauth2过滤器
*
*/
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("未授权访问!"));
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.SC_UNAUTHORIZED, 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,74 @@
package io.modules.security.oauth2;
import io.modules.security.service.ShiroService;
import io.common.exception.ErrorCode;
import io.common.utils.ConvertUtils;
import io.modules.security.entity.SysUserTokenEntity;
import io.modules.security.user.UserDetail;
import io.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;
/**
* 认证
*
*/
@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("登录失效,请重新登录!");
}
//查询用户信息
SysUserEntity userEntity = shiroService.getUser(tokenEntity.getUserId());
//转换成UserDetail对象
UserDetail userDetail = ConvertUtils.sourceToTarget(userEntity, UserDetail.class);
//账号锁定
if (userDetail.getStatus() == 0) {
throw new LockedAccountException("账号已被锁定!");
}
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(userDetail, accessToken, getName());
return info;
}
}

View File

@ -0,0 +1,27 @@
package io.modules.security.oauth2;
import org.apache.shiro.authc.AuthenticationToken;
/**
* token
*
*/
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,45 @@
package io.modules.security.oauth2;
import io.common.exception.RenException;
import java.security.MessageDigest;
import java.util.UUID;
/**
* 生成token
*
*/
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,623 @@
package io.modules.security.password;
import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.security.SecureRandom;
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,73 @@
package io.modules.security.password;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.security.SecureRandom;
import java.util.regex.Pattern;
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.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,41 @@
package io.modules.security.password;
/**
* 密码工具类
*
* @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,28 @@
package io.modules.security.service;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 验证码
*
*/
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,32 @@
package io.modules.security.service;
import io.modules.security.user.UserDetail;
import io.modules.sys.entity.SysUserEntity;
import io.modules.security.entity.SysUserTokenEntity;
import java.util.List;
import java.util.Set;
/**
* shiro相关接口
*
*/
public interface ShiroService {
/**
* 获取用户权限列表
*/
Set<String> getUserPermissions(UserDetail user);
SysUserTokenEntity getByToken(String token);
/**
* 根据用户ID查询用户
* @param userId
*/
SysUserEntity getUser(Long userId);
}

View File

@ -0,0 +1,28 @@
package io.modules.security.service;
import io.common.service.BaseService;
import io.common.utils.Result;
import io.modules.security.entity.SysUserTokenEntity;
/**
* 用户Token
*
*/
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,62 @@
package io.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.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;
/**
* 验证码
*
*/
@Service
public class CaptchaServiceImpl implements CaptchaService {
/**
* 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) {
localCache.put(key, value);
}
private String getCache(String key) {
String captcha = localCache.get(key);
//删除验证码
if (captcha != null) {
localCache.remove(key);
}
return captcha;
}
}

View File

@ -0,0 +1,45 @@
package io.modules.security.service.impl;
import cn.hutool.core.util.StrUtil;
import io.modules.security.dao.SysUserTokenDao;
import io.modules.security.entity.SysUserTokenEntity;
import io.modules.security.service.ShiroService;
import io.modules.security.user.UserDetail;
import io.modules.sys.dao.SysUserDao;
import io.modules.sys.entity.SysUserEntity;
import io.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 SysUserDao sysUserDao;
private final SysUserTokenDao sysUserTokenDao;
@Override
public Set<String> getUserPermissions(UserDetail user) {
//用户权限列表
Set<String> permsSet = new HashSet<>();
return permsSet;
}
@Override
public SysUserTokenEntity getByToken(String token) {
return sysUserTokenDao.getByToken(token);
}
@Override
public SysUserEntity getUser(Long userId) {
return sysUserDao.selectById(userId);
}
}

View File

@ -0,0 +1,80 @@
package io.modules.security.service.impl;
import io.common.constant.Constant;
import io.common.service.impl.BaseServiceImpl;
import io.modules.security.oauth2.TokenGenerator;
import io.common.utils.Result;
import io.modules.security.dao.SysUserTokenDao;
import io.modules.security.entity.SysUserTokenEntity;
import io.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,53 @@
package io.modules.security.user;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
/**
* 用户
*
*/
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,35 @@
package io.modules.security.user;
import lombok.Data;
import java.io.Serializable;
import java.util.List;
/**
* 登录用户信息
*
*/
@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,82 @@
package io.modules.sys.controller;
import io.common.constant.Constant;
import io.common.page.PageData;
import io.common.utils.Result;
import io.common.validator.AssertUtils;
import io.common.validator.ValidatorUtils;
import io.common.validator.group.AddGroup;
import io.common.validator.group.DefaultGroup;
import io.common.validator.group.UpdateGroup;
import io.modules.item.dto.AddressDTO;
import io.modules.item.service.AddressService;
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 org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
/**
* 收货地址表
*/
@RestController
@RequestMapping("sys/address")
@Tag(name="收货地址表")
public class AddressController {
@Autowired
private AddressService addressService;
@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")
})
public Result<PageData<AddressDTO>> page(@Parameter(hidden = true) @RequestParam Map<String, Object> params){
PageData<AddressDTO> page = addressService.page(params);
return new Result<PageData<AddressDTO>>().ok(page);
}
@GetMapping("{id}")
@Operation(summary = "信息")
public Result<AddressDTO> get(@PathVariable("id") Long id){
AddressDTO data = addressService.get(id);
return new Result<AddressDTO>().ok(data);
}
@PostMapping
@Operation(summary = "保存")
public Result save(@RequestBody AddressDTO dto){
//效验数据
ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);
addressService.save(dto);
return new Result();
}
@PutMapping
@Operation(summary = "修改")
public Result update(@RequestBody AddressDTO dto){
//效验数据
ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);
addressService.update(dto);
return new Result();
}
@DeleteMapping("{id}")
@Operation(summary = "删除")
public Result delete(@PathVariable Long id) {
Long[] ids = new Long[]{id};
//效验数据
AssertUtils.isArrayEmpty(ids, "id");
addressService.delete(ids);
return new Result();
}
}

View File

@ -0,0 +1,107 @@
package io.modules.sys.controller;
import io.common.annotation.LogOperation;
import io.common.constant.Constant;
import io.modules.item.dto.ArticleDTO;
import io.modules.item.service.ArticleService;
import io.common.page.PageData;
import io.common.utils.Result;
import io.common.validator.AssertUtils;
import io.common.validator.ValidatorUtils;
import io.common.validator.group.AddGroup;
import io.common.validator.group.DefaultGroup;
import io.common.validator.group.UpdateGroup;
import io.modules.item.service.DictService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import java.util.List;
import java.util.Map;
/**
* 文章表
*/
@RestController
@RequestMapping("item/article")
@Tag(name="文章表")
public class ArticleController {
@Autowired
private ArticleService articleService;
@Autowired
private DictService dictService;
@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 = "type", description = "类型", in = ParameterIn.QUERY, ref="String")
})
@RequiresPermissions("item:article:page")
public Result<PageData<ArticleDTO>> page(@Parameter(hidden = true) @RequestParam Map<String, Object> params){
PageData<ArticleDTO> page = articleService.page(params);
return new Result<PageData<ArticleDTO>>().ok(page);
}
@GetMapping("{id}")
@Operation(summary = "信息")
@RequiresPermissions("item:article:info")
public Result<ArticleDTO> get(@PathVariable("id") Long id){
ArticleDTO data = articleService.get(id);
return new Result<ArticleDTO>().ok(data);
}
@PostMapping
@Operation(summary = "保存")
@LogOperation("保存")
@RequiresPermissions("item:article:save")
public Result save(@RequestBody ArticleDTO dto){
//效验数据
ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);
List<String> existsList = dictService.isExistsList(dto.getIntroduction());
if (!existsList.isEmpty()){
return new Result().error("简介出现敏感词:"+existsList);
}
List<String> contentExistsList = dictService.isExistsList(dto.getContent());
if (!contentExistsList.isEmpty()){
return new Result().error("发布内容出现敏感词:"+ contentExistsList);
}
articleService.save(dto);
return new Result();
}
@PutMapping
@Operation(summary = "修改")
@LogOperation("修改")
@RequiresPermissions("item:article:update")
public Result update(@RequestBody ArticleDTO dto){
//效验数据
ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);
articleService.update(dto);
return new Result();
}
@DeleteMapping
@Operation(summary = "删除")
@LogOperation("删除")
@RequiresPermissions("item:article:delete")
public Result delete(@RequestBody Long[] ids){
//效验数据
AssertUtils.isArrayEmpty(ids, "id");
articleService.delete(ids);
return new Result();
}
}

View File

@ -0,0 +1,100 @@
package io.modules.sys.controller;
import io.common.annotation.LogOperation;
import io.common.constant.Constant;
import io.common.page.PageData;
import io.common.utils.ExcelUtils;
import io.common.utils.Result;
import io.common.validator.AssertUtils;
import io.common.validator.ValidatorUtils;
import io.common.validator.group.AddGroup;
import io.common.validator.group.DefaultGroup;
import io.common.validator.group.UpdateGroup;
import io.modules.item.dto.CategoriesDTO;
import io.modules.item.service.CategoriesService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import jakarta.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
/**
* 商品分类表
*
* @author Mark #
* @since 1.0.0 2025-02-13
*/
@RestController
@RequestMapping("sys/categories")
@Tag(name="商品分类表")
public class CategoriesController {
@Autowired
private CategoriesService categoriesService;
@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")
})
public Result<PageData<CategoriesDTO>> page(@Parameter(hidden = true) @RequestParam Map<String, Object> params){
PageData<CategoriesDTO> page = categoriesService.page(params);
return new Result<PageData<CategoriesDTO>>().ok(page);
}
@GetMapping("{id}")
public Result<CategoriesDTO> get(@PathVariable("id") Long id){
CategoriesDTO data = categoriesService.get(id);
return new Result<CategoriesDTO>().ok(data);
}
@PostMapping
@Operation(summary = "保存")
public Result save(@RequestBody CategoriesDTO dto){
//效验数据
ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);
categoriesService.save(dto);
return new Result();
}
@PutMapping
@Operation(summary = "修改")
public Result update(@RequestBody CategoriesDTO dto){
//效验数据
ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);
categoriesService.update(dto);
return new Result();
}
@DeleteMapping("{id}")
@Operation(summary = "删除")
@LogOperation("删除")
public Result delete(@PathVariable Long id){
Long[] ids = new Long[] { id };
//效验数据
AssertUtils.isArrayEmpty(ids, "id");
categoriesService.delete(ids);
return new Result();
}
}

View File

@ -0,0 +1,93 @@
package io.modules.sys.controller;
import io.common.annotation.LogOperation;
import io.common.constant.Constant;
import io.common.page.PageData;
import io.common.utils.Result;
import io.common.validator.AssertUtils;
import io.modules.item.dto.CommentDTO;
import io.modules.item.dto.HouseDTO;
import io.modules.item.dto.UserDTO;
import io.modules.item.service.CommentService;
import io.modules.item.service.HouseService;
import io.modules.item.service.UserService;
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 org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* 评论表
*/
@RestController
@RequestMapping("/sys/comment")
@Tag(name="评论表")
@CrossOrigin
public class CommentController {
@Autowired
private CommentService commentService;
@Autowired
private UserService userService;
@Autowired
private HouseService itemService;
@Value("${upload.url}")
private String uploadUrl;
@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 = "itemId", description = "关联编号", in = ParameterIn.QUERY, ref="String")
})
public Result<PageData<CommentDTO>> page(@Parameter(hidden = true) @RequestParam Map<String, Object> params){
PageData<CommentDTO> page = commentService.page(params);
List<CommentDTO> updatedPage = page.getList().stream()
.map(comment -> {
Long userId = comment.getUserId();
// 如果缓存中已经存在该用户的信息直接使用
UserDTO user = userService.get(userId);
if (user != null) {
// 否则调用 userService 获取用户信息并缓存
comment.setNickName(user.getNickName()); // 设置昵称
}
Long itemId = comment.getItemId();
HouseDTO itemDTO = itemService.get(itemId);
if (itemDTO != null){
itemDTO.setImage(uploadUrl + itemDTO.getImage());;
}
comment.setItemDTO(itemDTO);
return comment;
})
.collect(Collectors.toList());
page.setList(updatedPage);
return new Result<PageData<CommentDTO>>().ok(page);
}
@DeleteMapping("{id}")
@Operation(summary = "删除")
@LogOperation("删除")
public Result delete(@PathVariable Long id){
Long[] ids = new Long[] { id };
//效验数据
AssertUtils.isArrayEmpty(ids, "id");
commentService.delete(ids);
return new Result();
}
}

View File

@ -0,0 +1,105 @@
package io.modules.sys.controller;
import io.common.annotation.LogOperation;
import io.common.constant.Constant;
import io.common.page.PageData;
import io.common.utils.ExcelUtils;
import io.common.utils.Result;
import io.common.validator.AssertUtils;
import io.common.validator.ValidatorUtils;
import io.common.validator.group.AddGroup;
import io.common.validator.group.DefaultGroup;
import io.common.validator.group.UpdateGroup;
import io.modules.item.dto.DictDTO;
import io.modules.item.service.DictService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import java.util.List;
import java.util.Map;
/**
* 敏感词
*/
@RestController
@RequestMapping("item/dict")
@Tag(name="敏感词")
public class DictController {
@Autowired
private DictService dictService;
@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("item:dict:page")
public Result<PageData<DictDTO>> page(@Parameter(hidden = true) @RequestParam Map<String, Object> params){
PageData<DictDTO> page = dictService.page(params);
return new Result<PageData<DictDTO>>().ok(page);
}
@GetMapping("{id}")
@Operation(summary = "信息")
@RequiresPermissions("item:dict:info")
public Result<DictDTO> get(@PathVariable("id") Long id){
DictDTO data = dictService.get(id);
return new Result<DictDTO>().ok(data);
}
@PostMapping
@Operation(summary = "保存")
@LogOperation("保存")
@RequiresPermissions("item:dict:save")
public Result save(@RequestBody DictDTO dto){
//效验数据
ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);
dictService.save(dto);
return new Result();
}
@PutMapping
@Operation(summary = "修改")
@LogOperation("修改")
@RequiresPermissions("item:dict:update")
public Result update(@RequestBody DictDTO dto){
//效验数据
ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);
dictService.update(dto);
return new Result();
}
@DeleteMapping
@Operation(summary = "删除")
@LogOperation("删除")
@RequiresPermissions("item:dict:delete")
public Result delete(@RequestBody Long[] ids){
//效验数据
AssertUtils.isArrayEmpty(ids, "id");
dictService.delete(ids);
return new Result();
}
}

View File

@ -0,0 +1,113 @@
package io.modules.sys.controller;
import io.common.annotation.LogOperation;
import io.common.constant.Constant;
import io.common.page.PageData;
import io.common.utils.Result;
import io.common.validator.AssertUtils;
import io.common.validator.ValidatorUtils;
import io.common.validator.group.AddGroup;
import io.common.validator.group.DefaultGroup;
import io.common.validator.group.UpdateGroup;
import io.modules.item.dto.CategoriesDTO;
import io.modules.item.dto.HouseDTO;
import io.modules.item.entity.ViewEntity;
import io.modules.item.service.CategoriesService;
import io.modules.item.service.HouseService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* 主表
*/
@CrossOrigin
@RestController
@RequestMapping("sys/house")
@Tag(name = "主表")
public class HouseController {
@Autowired
private HouseService itemService;
@GetMapping("query")
@Operation(summary = "首页顶部展示")
public Result<List<Object>> page() {
List<Object> res = itemService.query();
return new Result<List<Object>>().ok(res);
}
@GetMapping("view1")
@Operation(summary = "首页分析1")
public Result<List<ViewEntity>> view1() {
List<ViewEntity> res = itemService.view1();
return new Result<List<ViewEntity>>().ok(res);
}
@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 = "排序方式,可选值(asc、desc)", in = ParameterIn.QUERY, ref = "String")
})
public Result<PageData<HouseDTO>> page(@Parameter(hidden = true) @RequestParam Map<String, Object> params) {
PageData<HouseDTO> page = itemService.page(params);
List<HouseDTO> list = page.getList().stream().map(e -> {
return e;
}).collect(Collectors.toList());
page.setList(list);
return new Result<PageData<HouseDTO>>().ok(page);
}
@GetMapping("{id}")
@Operation(summary = "信息")
public Result<HouseDTO> get(@PathVariable("id") Long id) {
HouseDTO data = itemService.get(id);
return new Result<HouseDTO>().ok(data);
}
@PostMapping
@Operation(summary = "保存")
public Result save(@RequestBody HouseDTO dto) {
//效验数据
ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);
itemService.save(dto);
return new Result();
}
@PutMapping
@Operation(summary = "修改")
public Result update(@RequestBody HouseDTO dto) { //效验数据
ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);
itemService.update(dto);
return new Result();
}
@DeleteMapping("{id}")
@Operation(summary = "删除")
@LogOperation("删除")
public Result delete(@PathVariable Long id) {
Long[] ids = new Long[]{id};
//效验数据
AssertUtils.isArrayEmpty(ids, "id");
itemService.delete(ids);
return new Result();
}
}

View File

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

View File

@ -0,0 +1,120 @@
package io.modules.sys.controller;
import io.common.constant.Constant;
import io.common.page.PageData;
import io.common.utils.Result;
import io.common.validator.AssertUtils;
import io.common.validator.ValidatorUtils;
import io.common.validator.group.AddGroup;
import io.common.validator.group.DefaultGroup;
import io.common.validator.group.UpdateGroup;
import io.modules.item.dao.FrontUserDao;
import io.modules.item.dto.AddressDTO;
import io.modules.item.dto.HouseDTO;
import io.modules.item.dto.OrderDTO;
import io.modules.item.entity.FrontUserEntity;
import io.modules.item.service.AddressService;
import io.modules.item.service.HouseService;
import io.modules.item.service.OrderService;
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 org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* 订单表
*
* @author Mark #
* @since 1.0.0 2025-02-14
*/
@RestController
@RequestMapping("sys/order")
@Tag(name="订单表")
@CrossOrigin
public class OrderController {
@Autowired
private OrderService orderService;
@Autowired
private HouseService itemService;
@Autowired
private FrontUserDao frontUserDao;
@Value("${upload.url}")
private String uploadUrl;
@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")
})
public Result<PageData<OrderDTO>> page(@Parameter(hidden = true) @RequestParam Map<String, Object> params){
PageData<OrderDTO> page = orderService.page(params);
List<OrderDTO> collect = page.getList().stream().map(e -> {
HouseDTO item = itemService.get(e.getItemId());
if(item != null){
item.setImage(uploadUrl + item.getImage());
}
e.setItem(item);
FrontUserEntity frontUserEntity = frontUserDao.selectById(e.getUserId());
e.setUserEntity(frontUserEntity);
return e;
}).collect(Collectors.toList());
page.setList(collect);
return new Result<PageData<OrderDTO>>().ok(page);
}
@GetMapping("{id}")
@Operation(summary = "信息")
public Result<OrderDTO> get(@PathVariable("id") Long id){
OrderDTO data = orderService.get(id);
return new Result<OrderDTO>().ok(data);
}
@PostMapping
@Operation(summary = "保存")
public Result save(@RequestBody OrderDTO dto){
//效验数据
ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);
orderService.save(dto);
return new Result();
}
@PutMapping
@Operation(summary = "修改")
public Result update(@RequestBody OrderDTO dto){
//效验数据
ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);
orderService.update(dto);
return new Result();
}
@DeleteMapping
@Operation(summary = "删除")
public Result delete(@RequestBody Long[] ids){
//效验数据
AssertUtils.isArrayEmpty(ids, "id");
orderService.delete(ids);
return new Result();
}
}

View File

@ -0,0 +1,107 @@
package io.modules.sys.controller;
import io.common.annotation.LogOperation;
import io.common.constant.Constant;
import io.modules.item.dto.SlidesDTO;
import io.modules.item.service.SlidesService;
import io.common.page.PageData;
import io.common.utils.Result;
import io.common.validator.AssertUtils;
import io.common.validator.ValidatorUtils;
import io.common.validator.group.AddGroup;
import io.common.validator.group.DefaultGroup;
import io.common.validator.group.UpdateGroup;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* 轮播图
*/
@RestController
@RequestMapping("sys/slides")
@Tag(name= "轮播图")
public class SlidesController {
@Autowired
private SlidesService slidesService;
@Value("${upload.url}")
private String uploadUrl;
@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")
})
public Result<PageData<SlidesDTO>> page(@Parameter(hidden = true) @RequestParam Map<String, Object> params){
PageData<SlidesDTO> page = slidesService.page(params);
List<SlidesDTO> list = page.getList().stream().map(e -> {
e.setPath(uploadUrl + e.getPath());
return e;
}).collect(Collectors.toList());
page.setList(list);
return new Result<PageData<SlidesDTO>>().ok(page);
}
@GetMapping("{id}")
@Operation(summary = "信息")
public Result<SlidesDTO> get(@PathVariable("id") Long id){
SlidesDTO data = slidesService.get(id);
return new Result<SlidesDTO>().ok(data);
}
@PostMapping
@Operation(summary = "保存")
@LogOperation("保存")
public Result save(@RequestBody SlidesDTO dto){
//效验数据
ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);
dto.setPath(dto.getPath().replace(uploadUrl ,""));
slidesService.save(dto);
return new Result();
}
@PutMapping
@Operation(summary = "修改")
@LogOperation("修改")
public Result update(@RequestBody SlidesDTO dto){
//效验数据
ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);
dto.setPath(dto.getPath().replace(uploadUrl ,""));
slidesService.update(dto);
return new Result();
}
@DeleteMapping("{id}")
@Operation(summary = "删除")
@LogOperation("删除")
public Result delete(@PathVariable Long id){
Long[] ids = new Long[] { id };
//效验数据
AssertUtils.isArrayEmpty(ids, "id");
slidesService.delete(ids);
return new Result();
}
}

View File

@ -0,0 +1,126 @@
package io.modules.sys.controller;
import io.modules.security.password.PasswordUtils;
import io.modules.security.user.SecurityUser;
import io.modules.security.user.UserDetail;
import io.common.annotation.LogOperation;
import io.common.constant.Constant;
import io.common.page.PageData;
import io.common.utils.ConvertUtils;
import io.common.utils.ExcelUtils;
import io.common.utils.Result;
import io.common.validator.AssertUtils;
import io.common.validator.ValidatorUtils;
import io.common.validator.group.AddGroup;
import io.common.validator.group.DefaultGroup;
import io.common.validator.group.UpdateGroup;
import io.modules.sys.dto.PasswordDTO;
import io.modules.sys.dto.SysUserDTO;
import io.modules.sys.service.SysUserService;
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.Arrays;
import java.util.List;
import java.util.Map;
/**
* 用户管理
*
*/
@RestController
@RequestMapping("/sys/user")
@Tag(name = "用户管理")
@AllArgsConstructor
public class SysUserController {
private final SysUserService sysUserService;
@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 = "username", description = "用户名", in = ParameterIn.QUERY, ref = "String"),
@Parameter(name = "gender", description = "性别", in = ParameterIn.QUERY, ref = "String"),
@Parameter(name = "deptId", description = "部门ID", in = ParameterIn.QUERY, ref = "String")
})
@RequiresPermissions("sys:user:page")
public Result<PageData<SysUserDTO>> page(@Parameter(hidden = true) @RequestParam Map<String, Object> params) {
PageData<SysUserDTO> page = sysUserService.page(params);
return new Result<PageData<SysUserDTO>>().ok(page);
}
@GetMapping("{id}")
@Operation(summary = "信息")
@RequiresPermissions("sys:user:info")
public Result<SysUserDTO> get(@PathVariable("id") Long id) {
SysUserDTO data = sysUserService.get(id);
return new Result<SysUserDTO>().ok(data);
}
@GetMapping("info")
@Operation(summary = "登录用户信息")
public Result<SysUserDTO> info() {
SysUserDTO data = ConvertUtils.sourceToTarget(SecurityUser.getUser(), SysUserDTO.class);
return new Result<SysUserDTO>().ok(data);
}
@PutMapping("password")
@Operation(summary = "修改密码")
@LogOperation("修改密码")
public Result password(@RequestBody PasswordDTO dto) {
//效验数据
ValidatorUtils.validateEntity(dto);
UserDetail user = SecurityUser.getUser();
//原密码不正确
if (!PasswordUtils.matches(dto.getPassword(), user.getPassword())) {
return new Result().error("原密码不正确!");
}
sysUserService.updatePassword(user.getId(), dto.getNewPassword());
return new Result();
}
@PostMapping
@Operation(summary = "保存")
@LogOperation("保存")
@RequiresPermissions("sys:user:save")
public Result save(@RequestBody SysUserDTO dto) {
//效验数据
ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);
sysUserService.save(dto);
return new Result();
}
@PutMapping
@Operation(summary = "修改")
@LogOperation("修改")
@RequiresPermissions("sys:user:update")
public Result update(@RequestBody SysUserDTO dto) {
//效验数据
ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);
sysUserService.update(dto);
return new Result();
}
@DeleteMapping
@Operation(summary = "删除")
@LogOperation("删除")
@RequiresPermissions("sys:user:delete")
public Result delete(@RequestBody Long[] ids) {
//效验数据
AssertUtils.isArrayEmpty(ids, "id");
sysUserService.deleteBatchIds(Arrays.asList(ids));
return new Result();
}
}

View File

@ -0,0 +1,96 @@
package io.modules.sys.controller;
import cn.hutool.crypto.digest.DigestUtil;
import io.common.annotation.LogOperation;
import io.common.constant.Constant;
import io.common.page.PageData;
import io.common.utils.ExcelUtils;
import io.common.utils.Result;
import io.common.validator.AssertUtils;
import io.common.validator.ValidatorUtils;
import io.common.validator.group.AddGroup;
import io.common.validator.group.DefaultGroup;
import io.common.validator.group.UpdateGroup;
import io.modules.item.dto.UserDTO;
import io.modules.item.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import jakarta.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
/**
* 用户
*/
@RestController
@RequestMapping("/sys/user-front")
@Tag(name="用户")
public class UserController {
@Autowired
private UserService userService;
@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")
})
public Result<PageData<UserDTO>> page(@Parameter(hidden = true) @RequestParam Map<String, Object> params){
PageData<UserDTO> page = userService.page(params);
return new Result<PageData<UserDTO>>().ok(page);
}
@GetMapping("{id}")
@Operation(summary = "信息")
public Result<UserDTO> get(@PathVariable("id") Long id){
UserDTO data = userService.get(id);
return new Result<UserDTO>().ok(data);
}
@PostMapping
@Operation(summary = "保存")
@LogOperation("保存")
public Result save(@RequestBody UserDTO dto){
//效验数据
ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);
if (StringUtils.isNotBlank(dto.getPassword())){
dto.setPassword(DigestUtil.sha256Hex(dto.getPassword()));
}
userService.save(dto);
return new Result();
}
@PutMapping
@Operation(summary = "修改")
@LogOperation("修改")
public Result update(@RequestBody UserDTO dto){
//效验数据
ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);
if (StringUtils.isNotBlank(dto.getPassword())){
dto.setPassword(DigestUtil.sha256Hex(dto.getPassword()));
}
userService.update(dto);
return new Result();
}
@DeleteMapping("{id}")
@Operation(summary = "删除")
@LogOperation("删除")
public Result delete(@PathVariable Long id){
Long[] ids = new Long[] { id };
//效验数据
AssertUtils.isArrayEmpty(ids, "id");
userService.delete(ids);
return new Result();
}
}

View File

@ -0,0 +1,103 @@
package io.modules.sys.controller;
import io.common.annotation.LogOperation;
import io.common.constant.Constant;
import io.common.page.PageData;
import io.common.utils.Result;
import io.common.validator.AssertUtils;
import io.common.validator.ValidatorUtils;
import io.common.validator.group.AddGroup;
import io.common.validator.group.DefaultGroup;
import io.common.validator.group.UpdateGroup;
import io.modules.item.dto.BookDTO;
import io.modules.item.service.BookService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import java.util.Map;
/**
* 吐槽墙
*
* @author Mark #
* @since 1.0.0 2024-12-12
*/
@RestController
@RequestMapping("item/wall")
@Tag(name="吐槽墙")
public class WallController {
@Autowired
private BookService wallService;
@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("item:wall:page")
public Result<PageData<BookDTO>> page(@Parameter(hidden = true) @RequestParam Map<String, Object> params){
PageData<BookDTO> page = wallService.page(params);
return new Result<PageData<BookDTO>>().ok(page);
}
@GetMapping("{id}")
@Operation(summary = "信息")
@RequiresPermissions("item:wall:info")
public Result<BookDTO> get(@PathVariable("id") Long id){
BookDTO data = wallService.get(id);
return new Result<BookDTO>().ok(data);
}
@PostMapping
@Operation(summary = "保存")
@LogOperation("保存")
@RequiresPermissions("item:wall:save")
public Result save(@RequestBody BookDTO dto){
//效验数据
ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);
wallService.save(dto);
return new Result();
}
@PutMapping
@Operation(summary = "修改")
@LogOperation("修改")
@RequiresPermissions("item:wall:update")
public Result update(@RequestBody BookDTO dto){
//效验数据
ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);
wallService.update(dto);
return new Result();
}
@DeleteMapping
@Operation(summary = "删除")
@LogOperation("删除")
@RequiresPermissions("item:wall:delete")
public Result delete(@RequestBody Long[] ids){
//效验数据
AssertUtils.isArrayEmpty(ids, "id");
wallService.delete(ids);
return new Result();
}
}

View File

@ -0,0 +1,38 @@
package io.modules.sys.dao;
import io.modules.sys.entity.SysUserEntity;
import io.common.dao.BaseDao;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
/**
* 系统用户
*
*/
@Mapper
public interface SysUserDao extends BaseDao<SysUserEntity> {
List<SysUserEntity> getList(Map<String, Object> params);
SysUserEntity getById(Long id);
SysUserEntity getByUsername(String username);
int updatePassword(@Param("id") Long id, @Param("newPassword") String newPassword);
/**
* 根据部门ID查询用户数
*/
int getCountByDeptId(Long deptId);
/**
* 根据部门ID,查询用户ID列表
*/
List<Long> getUserIdListByDeptId(List<Long> deptIdList);
}

View File

@ -0,0 +1,30 @@
package io.modules.sys.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import lombok.Data;
import java.io.Serializable;
/**
* 修改密码
*
* @since 1.0.0
*/
@Data
@Schema(title = "修改密码")
public class PasswordDTO implements Serializable {
private static final long serialVersionUID = 1L;
@Schema(title = "原密码")
@NotBlank(message="{sysuser.password.require}")
private String password;
@Schema(title = "新密码")
@NotBlank(message="{sysuser.password.require}")
private String newPassword;
}

View File

@ -0,0 +1,76 @@
package io.modules.sys.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.common.utils.TreeNode;
import io.common.validator.group.AddGroup;
import io.common.validator.group.DefaultGroup;
import io.common.validator.group.UpdateGroup;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Null;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.io.Serializable;
import java.util.Date;
/**
* 部门管理
*
* @since 1.0.0
*/
@Data
@EqualsAndHashCode(callSuper = true)
@Schema(title = "部门管理")
public class SysDeptDTO extends TreeNode implements Serializable {
private static final long serialVersionUID = 1L;
@Schema(title = "id")
@Null(message="ID必须为空", groups = AddGroup.class)
@NotNull(message="{id.require}", groups = UpdateGroup.class)
private Long id;
@Schema(title = "上级ID")
@NotNull(message="{sysdept.pid.require}", groups = DefaultGroup.class)
private Long pid;
@Schema(title = "部门名称")
@NotBlank(message="{sysdept.name.require}", groups = DefaultGroup.class)
private String name;
@Schema(title = "排序")
@Min(value = 0, message = "{sort.number}", groups = DefaultGroup.class)
private Integer sort;
@Schema(title = "创建时间")
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private Date createDate;
@Schema(title = "上级部门名称")
private String parentName;
@Override
public Long getId() {
return id;
}
@Override
public void setId(Long id) {
this.id = id;
}
@Override
public Long getPid() {
return pid;
}
@Override
public void setPid(Long pid) {
this.pid = pid;
}
}

View File

@ -0,0 +1,59 @@
package io.modules.sys.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.common.validator.group.AddGroup;
import io.common.validator.group.DefaultGroup;
import io.common.validator.group.UpdateGroup;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Null;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
* 字典数据
*
*/
@Data
@Schema(title = "字典数据")
public class SysDictDataDTO implements Serializable {
private static final long serialVersionUID = 1L;
@Schema(title = "id")
@Null(message="ID必须为空", groups = AddGroup.class)
@NotNull(message="{id.require}", groups = UpdateGroup.class)
private Long id;
@Schema(title = "字典类型ID")
@NotNull(message="{sysdict.type.require}", groups = DefaultGroup.class)
private Long dictTypeId;
@Schema(title = "字典标签")
@NotBlank(message="{sysdict.label.require}", groups = DefaultGroup.class)
private String dictLabel;
@Schema(title = "字典值")
private String dictValue;
@Schema(title = "备注")
private String remark;
@Schema(title = "排序")
@Min(value = 0, message = "{sort.number}", groups = DefaultGroup.class)
private Integer sort;
@Schema(title = "创建时间")
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private Date createDate;
@Schema(title = "更新时间")
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private Date updateDate;
}

View File

@ -0,0 +1,56 @@
package io.modules.sys.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.common.validator.group.AddGroup;
import io.common.validator.group.DefaultGroup;
import io.common.validator.group.UpdateGroup;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Null;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
* 字典类型
*
*/
@Data
@Schema(title = "字典类型")
public class SysDictTypeDTO implements Serializable {
private static final long serialVersionUID = 1L;
@Schema(title = "id")
@Null(message="ID必须为空", groups = AddGroup.class)
@NotNull(message="{id.require}", groups = UpdateGroup.class)
private Long id;
@Schema(title = "字典类型")
@NotBlank(message="{sysdict.type.require}", groups = DefaultGroup.class)
private String dictType;
@Schema(title = "字典名称")
@NotBlank(message="{sysdict.name.require}", groups = DefaultGroup.class)
private String dictName;
@Schema(title = "备注")
private String remark;
@Schema(title = "排序")
@Min(value = 0, message = "{sort.number}", groups = DefaultGroup.class)
private Integer sort;
@Schema(title = "创建时间")
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private Date createDate;
@Schema(title = "更新时间")
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private Date updateDate;
}

View File

@ -0,0 +1,91 @@
package io.modules.sys.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.common.utils.TreeNode;
import io.common.validator.group.AddGroup;
import io.common.validator.group.DefaultGroup;
import io.common.validator.group.UpdateGroup;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Null;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.hibernate.validator.constraints.Range;
import java.io.Serializable;
import java.util.Date;
/**
* 菜单管理
*
* @since 1.0.0
*/
@Data
@EqualsAndHashCode(callSuper = true)
@Schema(title = "菜单管理")
public class SysMenuDTO extends TreeNode<SysMenuDTO> implements Serializable {
private static final long serialVersionUID = 1L;
@Schema(title = "id")
@Null(message="ID必须为空", groups = AddGroup.class)
@NotNull(message="{id.require}", groups = UpdateGroup.class)
private Long id;
@Schema(title = "上级ID")
@NotNull(message="{sysmenu.pid.require}", groups = DefaultGroup.class)
private Long pid;
@Schema(title = "菜单名称")
@NotBlank(message="菜单名称不能为空", groups = DefaultGroup.class)
private String name;
@Schema(title = "菜单URL")
private String url;
@Schema(title = "类型 0菜单 1按钮")
@Range(min=0, max=1, message = "{sysmenu.type.range}", groups = DefaultGroup.class)
private Integer menuType;
@Schema(title = "菜单图标")
private String icon;
@Schema(title = "授权(多个用逗号分隔sys:user:list,sys:user:save)")
private String permissions;
@Schema(title = "排序")
@Min(value = 0, message = "{sort.number}", groups = DefaultGroup.class)
private Integer sort;
@Schema(title = "创建时间")
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private Date createDate;
@Schema(title = "上级菜单名称")
private String parentName;
@Override
public Long getId() {
return id;
}
@Override
public void setId(Long id) {
this.id = id;
}
@Override
public Long getPid() {
return pid;
}
@Override
public void setPid(Long pid) {
this.pid = pid;
}
}

View File

@ -0,0 +1,53 @@
package io.modules.sys.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.common.validator.group.AddGroup;
import io.common.validator.group.DefaultGroup;
import io.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 java.io.Serializable;
import java.util.Date;
/**
* 参数管理
*
* @since 1.0.0
*/
@Data
@Schema(title = "参数管理")
public class SysParamsDTO implements Serializable {
private static final long serialVersionUID = 1L;
@Schema(title = "id")
@Null(message="ID必须为空", groups = AddGroup.class)
@NotNull(message="{id.require}", groups = UpdateGroup.class)
private Long id;
@Schema(title = "参数编码")
@NotBlank(message="{sysparams.paramcode.require}", groups = DefaultGroup.class)
private String paramCode;
@Schema(title = "参数值")
@NotBlank(message="{sysparams.paramvalue.require}", groups = DefaultGroup.class)
private String paramValue;
@Schema(title = "备注")
private String remark;
@Schema(title = "创建时间")
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private Date createDate;
@Schema(title = "更新时间")
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private Date updateDate;
}

View File

@ -0,0 +1,52 @@
package io.modules.sys.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.common.validator.group.AddGroup;
import io.common.validator.group.DefaultGroup;
import io.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 java.io.Serializable;
import java.util.Date;
import java.util.List;
/**
* 角色管理
*
* @since 1.0.0
*/
@Data
@Schema(title = "角色管理")
public class SysRoleDTO implements Serializable {
private static final long serialVersionUID = 1L;
@Schema(title = "id")
@Null(message="ID必须为空", groups = AddGroup.class)
@NotNull(message="{id.require}", groups = UpdateGroup.class)
private Long id;
@Schema(title = "角色名称")
@NotBlank(message="{sysrole.name.require}", groups = DefaultGroup.class)
private String name;
@Schema(title = "备注")
private String remark;
@Schema(title = "创建时间")
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private Date createDate;
@Schema(title = "菜单ID列表")
private List<Long> menuIdList;
@Schema(title = "部门ID列表")
private List<Long> deptIdList;
}

View File

@ -0,0 +1,86 @@
package io.modules.sys.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.common.validator.group.AddGroup;
import io.common.validator.group.DefaultGroup;
import io.common.validator.group.UpdateGroup;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.Email;
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;
import java.util.List;
/**
* 用户管理
*
* @since 1.0.0
*/
@Data
@Schema(title = "用户管理")
public class SysUserDTO implements Serializable {
private static final long serialVersionUID = 1L;
@Schema(title = "id")
@Null(message="ID必须为空", groups = AddGroup.class)
@NotNull(message="{id.require}", groups = UpdateGroup.class)
private Long id;
@Schema(title = "用户名", required = true)
@NotBlank(message="{sysuser.username.require}", groups = DefaultGroup.class)
private String username;
@Schema(title = "密码")
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
@NotBlank(message="{sysuser.password.require}", groups = AddGroup.class)
private String password;
@Schema(title = "姓名", requiredMode = Schema.RequiredMode.REQUIRED)
@NotBlank(message="{sysuser.realName.require}", groups = DefaultGroup.class)
private String realName;
@Schema(title = "头像")
private String headUrl;
@Schema(title = "性别 0男 1女 2保密", required = true)
@Range(min=0, max=2, message = "{sysuser.gender.range}", groups = DefaultGroup.class)
private Integer gender;
@Schema(title = "邮箱")
@Email(message="{sysuser.email.error}", groups = DefaultGroup.class)
private String email;
@Schema(title = "手机号")
private String mobile;
@Schema(title = "部门ID", required = true)
@NotNull(message="{sysuser.deptId.require}", groups = DefaultGroup.class)
private Long deptId;
@Schema(title = "状态 0停用 1正常", required = true)
@Range(min=0, max=1, message = "{sysuser.status.range}", groups = DefaultGroup.class)
private Integer status;
@Schema(title = "创建时间")
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private Date createDate;
@Schema(title = "超级管理员 0否 1")
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private Integer superAdmin;
@Schema(title = "角色ID列表")
private List<Long> roleIdList;
@Schema(title = "部门名称")
private String deptName;
}

View File

@ -0,0 +1,42 @@
package io.modules.sys.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.io.Serializable;
import java.math.BigDecimal;
/**
* 系统数据
*
* @since 1.0.0
*/
@Data
@Schema(title = "系统数据")
public class SystemDTO implements Serializable {
private static final long serialVersionUID = 1L;
private Long sysTime;
private String osName;
private String osArch;
private String osVersion;
private String userLanguage;
private String userDir;
private Long totalPhysical;
private Long freePhysical;
private BigDecimal memoryRate;
private Integer processors;
private String jvmName;
private String javaVersion;
private String javaHome;
private Long javaTotalMemory;
private Long javaFreeMemory;
private Long javaMaxMemory;
private String userName;
private BigDecimal systemCpuLoad;
private String userTimezone;
}

View File

@ -0,0 +1,80 @@
package io.modules.sys.entity;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import io.common.entity.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.util.Date;
/**
* 系统用户
*
*/
@Data
@EqualsAndHashCode(callSuper=false)
@TableName("sys_user")
public class SysUserEntity extends BaseEntity {
private static final long serialVersionUID = 1L;
/**
* 用户名
*/
private String username;
/**
* 密码
*/
private String password;
/**
* 姓名
*/
private String realName;
/**
* 头像
*/
private String headUrl;
/**
* 性别 0 1 2保密
*/
private Integer gender;
/**
* 邮箱
*/
private String email;
/**
* 手机号
*/
private String mobile;
/**
* 部门ID
*/
private Long deptId;
/**
* 超级管理员 0 1
*/
private Integer superAdmin;
/**
* 状态 0停用 1正常
*/
private Integer status;
/**
* 更新者
*/
@TableField(fill = FieldFill.INSERT_UPDATE)
private Long updater;
/**
* 更新时间
*/
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateDate;
/**
* 部门名称
*/
@TableField(exist=false)
private String deptName;
}

View File

@ -0,0 +1,30 @@
package io.modules.sys.enums;
/**
* 菜单类型枚举
*
* @since 1.0.0
*/
public enum MenuTypeEnum {
/**
* 菜单
*/
MENU(0),
/**
* 按钮
*/
BUTTON(1);
private int value;
MenuTypeEnum(int value) {
this.value = value;
}
public int value() {
return this.value;
}
}

View File

@ -0,0 +1,24 @@
package io.modules.sys.enums;
/**
* 超级管理员枚举
*
* @since 1.0.0
*/
public enum SuperAdminEnum {
YES(1),
NO(0);
private int value;
SuperAdminEnum(int value) {
this.value = value;
}
public int value() {
return this.value;
}
}

View File

@ -0,0 +1,24 @@
package io.modules.sys.enums;
/**
* 用户状态
*
* @since 1.0.0
*/
public enum UserStatusEnum {
DISABLE(0),
ENABLED(1);
private int value;
UserStatusEnum(int value) {
this.value = value;
}
public int value() {
return this.value;
}
}

View File

@ -0,0 +1,52 @@
package io.modules.sys.service;
import io.common.page.PageData;
import io.common.service.BaseService;
import io.modules.sys.dto.SysUserDTO;
import io.modules.sys.entity.SysUserEntity;
import java.util.List;
import java.util.Map;
/**
* 系统用户
*
*/
public interface SysUserService extends BaseService<SysUserEntity> {
PageData<SysUserDTO> page(Map<String, Object> params);
List<SysUserDTO> list(Map<String, Object> params);
SysUserDTO get(Long id);
SysUserDTO getByUsername(String username);
void save(SysUserDTO dto);
void update(SysUserDTO dto);
void delete(Long[] ids);
/**
* 修改密码
* @param id 用户ID
* @param newPassword 新密码
*/
void updatePassword(Long id, String newPassword);
/**
* 根据部门ID查询用户数
*/
int getCountByDeptId(Long deptId);
/**
* 根据部门ID,查询用户Id列表
*/
List<Long> getUserIdListByDeptId(List<Long> deptIdList);
}

View File

@ -0,0 +1,129 @@
package io.modules.sys.service.impl;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.modules.security.password.PasswordUtils;
import io.modules.security.user.SecurityUser;
import io.modules.security.user.UserDetail;
import io.common.constant.Constant;
import io.common.page.PageData;
import io.common.service.impl.BaseServiceImpl;
import io.common.utils.ConvertUtils;
import io.modules.sys.dao.SysUserDao;
import io.modules.sys.dto.SysUserDTO;
import io.modules.sys.entity.SysUserEntity;
import io.modules.sys.enums.SuperAdminEnum;
import io.modules.sys.service.SysUserService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
/**
* 系统用户
*
*/
@Service
@AllArgsConstructor
public class SysUserServiceImpl extends BaseServiceImpl<SysUserDao, SysUserEntity> implements SysUserService {
@Override
public PageData<SysUserDTO> page(Map<String, Object> params) {
//转换成like
paramsToLike(params, "username");
//分页
IPage<SysUserEntity> page = getPage(params, Constant.CREATE_DATE, false);
//普通管理员只能查询所属部门及子部门的数据
UserDetail user = SecurityUser.getUser();
//查询
List<SysUserEntity> list = baseDao.getList(params);
return getPageData(list, page.getTotal(), SysUserDTO.class);
}
@Override
public List<SysUserDTO> list(Map<String, Object> params) {
//普通管理员只能查询所属部门及子部门的数据
UserDetail user = SecurityUser.getUser();
List<SysUserEntity> entityList = baseDao.getList(params);
return ConvertUtils.sourceToTarget(entityList, SysUserDTO.class);
}
@Override
public SysUserDTO get(Long id) {
SysUserEntity entity = baseDao.getById(id);
return ConvertUtils.sourceToTarget(entity, SysUserDTO.class);
}
@Override
public SysUserDTO getByUsername(String username) {
SysUserEntity entity = baseDao.getByUsername(username);
return ConvertUtils.sourceToTarget(entity, SysUserDTO.class);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void save(SysUserDTO dto) {
SysUserEntity entity = ConvertUtils.sourceToTarget(dto, SysUserEntity.class);
//密码加密
String password = PasswordUtils.encode(entity.getPassword());
entity.setPassword(password);
//保存用户
entity.setSuperAdmin(SuperAdminEnum.NO.value());
insert(entity);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void update(SysUserDTO dto) {
SysUserEntity entity = ConvertUtils.sourceToTarget(dto, SysUserEntity.class);
//密码加密
if (StrUtil.isBlank(dto.getPassword())) {
entity.setPassword(null);
} else {
String password = PasswordUtils.encode(entity.getPassword());
entity.setPassword(password);
}
//更新用户
updateById(entity);
}
@Override
public void delete(Long[] ids) {
//删除用户
baseDao.deleteBatchIds(Arrays.asList(ids));
}
@Override
@Transactional(rollbackFor = Exception.class)
public void updatePassword(Long id, String newPassword) {
newPassword = PasswordUtils.encode(newPassword);
baseDao.updatePassword(id, newPassword);
}
@Override
public int getCountByDeptId(Long deptId) {
return baseDao.getCountByDeptId(deptId);
}
@Override
public List<Long> getUserIdListByDeptId(List<Long> deptIdList) {
return baseDao.getUserIdListByDeptId(deptIdList);
}
}

View File

@ -0,0 +1,41 @@
spring:
datasource:
druid:
#MySQL
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:33060/block_house?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&nullCatalogMeansCurrent=true
username: root
password: 123456
initial-size: 10
max-active: 100
min-idle: 10
max-wait: 6000
pool-prepared-statements: true
max-pool-prepared-statement-per-connection-size: 20
time-between-eviction-runs-millis: 60000
min-evictable-idle-time-millis: 300000
test-while-idle: true
test-on-borrow: false
test-on-return: false
stat-view-servlet:
enabled: true
url-pattern: /druid/*
mybatis-plus:
mapper-locations: classpath*:/mapper/**/*.xml
typeAliasesPackage: io.modules.*.entity,io.modules.*.entity
global-config:
db-config:
id-type: AUTO
banner: false
configuration:
map-underscore-to-camel-case: true
cache-enabled: false
call-setters-on-nulls: true
jdbc-type-for-null: 'null'
configuration-properties:
prefix:
blobType: BLOB
boolValue: TRUE
upload:
path: D:\\code\\security\\upload\\
url: http://localhost:18081/

View File

@ -0,0 +1,57 @@
# Tomcat
server:
tomcat:
uri-encoding: UTF-8
threads:
max: 1000
min-spare: 30
port: 18080
servlet:
context-path: /
session:
cookie:
http-only: true
knife4j:
enable: true
basic:
enable: false
username: admin
password: admin
setting:
enableFooter: false
spring:
profiles:
active: dev
messages:
encoding: UTF-8
basename: i18n/messages
mvc:
pathmatch:
matching-strategy: ANT_PATH_MATCHER
servlet:
multipart:
max-file-size: 100MB
max-request-size: 100MB
enabled: true
#mybatis
mybatis-plus:
mapper-locations: classpath*:/mapper/**/*.xml
typeAliasesPackage: io.modules.*.entity
global-config:
db-config:
id-type: AUTO
banner: false
configuration:
map-underscore-to-camel-case: true
cache-enabled: false
call-setters-on-nulls: true
jdbc-type-for-null: 'null'
configuration-properties:
prefix:
blobType: BLOB
boolValue: TRUE

View File

@ -0,0 +1,21 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<include resource="org/springframework/boot/logging/logback/base.xml" />
<logger name="org.springframework.web" level="INFO"/>
<logger name="org.springboot.sample" level="TRACE" />
<!-- 开发、测试环境 -->
<springProfile name="dev,test">
<logger name="org.springframework.web" level="INFO"/>
<logger name="org.springboot.sample" level="INFO" />
<logger name="io.renren" level="DEBUG" />
</springProfile>
<!-- 生产环境 -->
<springProfile name="prod">
<logger name="org.springframework.web" level="ERROR"/>
<logger name="org.springboot.sample" level="ERROR" />
<logger name="io.renren" level="ERROR" />
</springProfile>
</configuration>

View File

@ -0,0 +1,50 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="io.modules.sys.dao.SysUserDao">
<select id="getList" resultType="io.modules.sys.entity.SysUserEntity">
select t1.*, (select t2.name from sys_dept t2 where t2.id=t1.dept_id) deptName from sys_user t1
where t1.super_admin = 0
<if test="username != null and username.trim() != ''">
and t1.username like #{username}
</if>
<if test="deptId != null and deptId.trim() != ''">
and t1.dept_id = #{deptId}
</if>
<if test="gender != null and gender.trim() != ''">
and t1.gender = #{gender}
</if>
<if test="deptIdList != null">
and t1.dept_id in
<foreach item="id" collection="deptIdList" open="(" separator="," close=")">
#{id}
</foreach>
</if>
</select>
<select id="getById" resultType="io.modules.sys.entity.SysUserEntity">
select t1.*, (select t2.name from sys_dept t2 where t2.id=t1.dept_id) deptName from sys_user t1
where t1.id = #{value}
</select>
<select id="getByUsername" resultType="io.modules.sys.entity.SysUserEntity">
select * from sys_user where username = #{value}
</select>
<update id="updatePassword">
update sys_user set password = #{newPassword} where id = #{id}
</update>
<select id="getCountByDeptId" resultType="int">
select count(*) from sys_user where dept_id = #{value}
</select>
<select id="getUserIdListByDeptId" resultType="Long">
select id from sys_user where dept_id in
<foreach item="deptId" collection="list" open="(" separator="," close=")">
#{deptId}
</foreach>
</select>
</mapper>

View File

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="io.modules.security.dao.SysUserTokenDao">
<select id="getByToken" resultType="io.modules.security.entity.SysUserTokenEntity">
select * from sys_user_token where token = #{value}
</select>
<select id="getByUserId" resultType="io.modules.security.entity.SysUserTokenEntity">
select * from sys_user_token where user_id = #{value}
</select>
<update id="updateToken">
update sys_user_token set token = #{token} where user_id = #{userId}
</update>
</mapper>

141
common/common.iml Normal file
View File

@ -0,0 +1,141 @@
<?xml version="1.0" encoding="UTF-8"?>
<module org.jetbrains.idea.maven.project.MavenProjectsManager.isMavenModule="true" type="JAVA_MODULE" version="4">
<component name="FacetManager">
<facet type="web" name="Web">
<configuration>
<webroots />
</configuration>
</facet>
<facet type="Spring" name="Spring">
<configuration />
</facet>
</component>
<component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_17">
<output url="file://$MODULE_DIR$/target/classes" />
<output-test url="file://$MODULE_DIR$/target/test-classes" />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
<excludeFolder url="file://$MODULE_DIR$/target" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" scope="TEST" name="Maven: org.springframework.boot:spring-boot-starter-test:3.2.6" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter:3.2.6" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot:3.2.6" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-logging:3.2.6" level="project" />
<orderEntry type="library" name="Maven: ch.qos.logback:logback-classic:1.4.14" level="project" />
<orderEntry type="library" name="Maven: ch.qos.logback:logback-core:1.4.14" level="project" />
<orderEntry type="library" name="Maven: org.apache.logging.log4j:log4j-to-slf4j:2.21.1" level="project" />
<orderEntry type="library" name="Maven: org.apache.logging.log4j:log4j-api:2.21.1" level="project" />
<orderEntry type="library" name="Maven: org.slf4j:jul-to-slf4j:2.0.13" level="project" />
<orderEntry type="library" name="Maven: jakarta.annotation:jakarta.annotation-api:2.1.1" level="project" />
<orderEntry type="library" name="Maven: org.yaml:snakeyaml:2.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.springframework.boot:spring-boot-test:3.2.6" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.springframework.boot:spring-boot-test-autoconfigure:3.2.6" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: com.jayway.jsonpath:json-path:2.9.0" level="project" />
<orderEntry type="library" name="Maven: jakarta.xml.bind:jakarta.xml.bind-api:4.0.2" level="project" />
<orderEntry type="library" name="Maven: jakarta.activation:jakarta.activation-api:2.1.3" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: net.minidev:json-smart:2.5.1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: net.minidev:accessors-smart:2.5.1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.ow2.asm:asm:9.6" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.assertj:assertj-core:3.24.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: net.bytebuddy:byte-buddy:1.14.16" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.awaitility:awaitility:4.2.1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.hamcrest:hamcrest:2.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.junit.jupiter:junit-jupiter:5.10.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.junit.jupiter:junit-jupiter-api:5.10.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.opentest4j:opentest4j:1.3.0" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.junit.platform:junit-platform-commons:1.10.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apiguardian:apiguardian-api:1.1.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.junit.jupiter:junit-jupiter-params:5.10.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.junit.jupiter:junit-jupiter-engine:5.10.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.junit.platform:junit-platform-engine:1.10.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.mockito:mockito-core:5.7.0" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: net.bytebuddy:byte-buddy-agent:1.14.16" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.objenesis:objenesis:3.3" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.mockito:mockito-junit-jupiter:5.7.0" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.skyscreamer:jsonassert:1.5.1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: com.vaadin.external.google:android-json:0.0.20131108.vaadin1" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-core:6.1.8" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-jcl:6.1.8" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.springframework:spring-test:6.1.8" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.xmlunit:xmlunit-core:2.9.1" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-web:3.2.6" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-json:3.2.6" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.core:jackson-databind:2.15.4" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.core:jackson-annotations:2.15.4" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.core:jackson-core:2.15.4" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.datatype:jackson-datatype-jdk8:2.15.4" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.15.4" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.module:jackson-module-parameter-names:2.15.4" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-tomcat:3.2.6" level="project" />
<orderEntry type="library" name="Maven: org.apache.tomcat.embed:tomcat-embed-core:10.1.24" level="project" />
<orderEntry type="library" name="Maven: org.apache.tomcat.embed:tomcat-embed-websocket:10.1.24" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-web:6.1.8" level="project" />
<orderEntry type="library" name="Maven: io.micrometer:micrometer-observation:1.12.6" level="project" />
<orderEntry type="library" name="Maven: io.micrometer:micrometer-commons:1.12.6" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-webmvc:6.1.8" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-expression:6.1.8" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-aop:3.2.6" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-aop:6.1.8" level="project" />
<orderEntry type="library" name="Maven: org.aspectj:aspectjweaver:1.9.22" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-validation:3.2.6" level="project" />
<orderEntry type="library" name="Maven: org.apache.tomcat.embed:tomcat-embed-el:10.1.24" level="project" />
<orderEntry type="library" name="Maven: org.hibernate.validator:hibernate-validator:8.0.1.Final" level="project" />
<orderEntry type="library" name="Maven: jakarta.validation:jakarta.validation-api:3.0.2" level="project" />
<orderEntry type="library" name="Maven: org.jboss.logging:jboss-logging:3.5.3.Final" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml:classmate:1.6.0" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-context-support:6.1.8" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-beans:6.1.8" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-context:6.1.8" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-data-redis:3.2.6" level="project" />
<orderEntry type="library" name="Maven: io.lettuce:lettuce-core:6.3.2.RELEASE" level="project" />
<orderEntry type="library" name="Maven: io.netty:netty-common:4.1.110.Final" level="project" />
<orderEntry type="library" name="Maven: io.netty:netty-handler:4.1.110.Final" level="project" />
<orderEntry type="library" name="Maven: io.netty:netty-resolver:4.1.110.Final" level="project" />
<orderEntry type="library" name="Maven: io.netty:netty-buffer:4.1.110.Final" level="project" />
<orderEntry type="library" name="Maven: io.netty:netty-transport-native-unix-common:4.1.110.Final" level="project" />
<orderEntry type="library" name="Maven: io.netty:netty-codec:4.1.110.Final" level="project" />
<orderEntry type="library" name="Maven: io.netty:netty-transport:4.1.110.Final" level="project" />
<orderEntry type="library" name="Maven: io.projectreactor:reactor-core:3.6.6" level="project" />
<orderEntry type="library" name="Maven: org.reactivestreams:reactive-streams:1.0.4" level="project" />
<orderEntry type="library" name="Maven: org.springframework.data:spring-data-redis:3.2.6" level="project" />
<orderEntry type="library" name="Maven: org.springframework.data:spring-data-keyvalue:3.2.6" level="project" />
<orderEntry type="library" name="Maven: org.springframework.data:spring-data-commons:3.2.6" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-tx:6.1.8" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-oxm:6.1.8" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-configuration-processor:3.2.6" level="project" />
<orderEntry type="library" name="Maven: com.mysql:mysql-connector-j:8.3.0" level="project" />
<orderEntry type="library" name="Maven: com.alibaba:druid-spring-boot-3-starter:1.2.21" level="project" />
<orderEntry type="library" name="Maven: com.alibaba:druid:1.2.21" level="project" />
<orderEntry type="library" name="Maven: org.slf4j:slf4j-api:2.0.13" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-autoconfigure:3.2.6" level="project" />
<orderEntry type="library" name="Maven: com.baomidou:mybatis-plus-boot-starter:3.5.5" level="project" />
<orderEntry type="library" name="Maven: com.baomidou:mybatis-plus:3.5.5" level="project" />
<orderEntry type="library" name="Maven: com.baomidou:mybatis-plus-core:3.5.5" level="project" />
<orderEntry type="library" name="Maven: com.baomidou:mybatis-plus-annotation:3.5.5" level="project" />
<orderEntry type="library" name="Maven: com.baomidou:mybatis-plus-extension:3.5.5" level="project" />
<orderEntry type="library" name="Maven: org.mybatis:mybatis:3.5.15" level="project" />
<orderEntry type="library" name="Maven: com.github.jsqlparser:jsqlparser:4.6" level="project" />
<orderEntry type="library" name="Maven: com.baomidou:mybatis-plus-spring-boot-autoconfigure:3.5.5" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-jdbc:3.2.6" level="project" />
<orderEntry type="library" name="Maven: com.zaxxer:HikariCP:5.0.1" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-jdbc:6.1.8" level="project" />
<orderEntry type="library" name="Maven: org.mybatis:mybatis-spring:3.0.3" level="project" />
<orderEntry type="library" name="Maven: cn.hutool:hutool-all:5.8.29" level="project" />
<orderEntry type="library" name="Maven: org.jsoup:jsoup:1.15.3" level="project" />
<orderEntry type="library" name="Maven: com.github.xiaoymin:knife4j-openapi3-jakarta-spring-boot-starter:4.5.0" level="project" />
<orderEntry type="library" name="Maven: com.github.xiaoymin:knife4j-core:4.5.0" level="project" />
<orderEntry type="library" name="Maven: com.github.xiaoymin:knife4j-openapi3-ui:4.5.0" level="project" />
<orderEntry type="library" name="Maven: org.springdoc:springdoc-openapi-starter-webmvc-ui:2.3.0" level="project" />
<orderEntry type="library" name="Maven: org.springdoc:springdoc-openapi-starter-webmvc-api:2.3.0" level="project" />
<orderEntry type="library" name="Maven: org.springdoc:springdoc-openapi-starter-common:2.3.0" level="project" />
<orderEntry type="library" name="Maven: io.swagger.core.v3:swagger-core-jakarta:2.2.19" level="project" />
<orderEntry type="library" name="Maven: org.apache.commons:commons-lang3:3.13.0" level="project" />
<orderEntry type="library" name="Maven: io.swagger.core.v3:swagger-annotations-jakarta:2.2.19" level="project" />
<orderEntry type="library" name="Maven: io.swagger.core.v3:swagger-models-jakarta:2.2.19" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:2.15.4" level="project" />
<orderEntry type="library" name="Maven: org.webjars:swagger-ui:5.10.3" level="project" />
<orderEntry type="library" name="Maven: org.projectlombok:lombok:1.18.24" level="project" />
</component>
</module>

16
common/pom.xml Normal file
View File

@ -0,0 +1,16 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>io.renren</groupId>
<artifactId>block-chaincopyright</artifactId>
<version>5.4.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>common</artifactId>
<packaging>jar</packaging>
<description>common</description>
<build>
<finalName>${project.artifactId}</finalName>
</build>
</project>

View File

@ -0,0 +1,119 @@
package io.common.constant;
/**
* 常量
*
*/
public interface Constant {
/**
* 成功
*/
int SUCCESS = 1;
/**
* 失败
*/
int FAIL = 0;
/**
* 菜单根节点标识
*/
Long MENU_ROOT = 0L;
/**
* 部门根节点标识
*/
Long DEPT_ROOT = 0L;
/**
* 升序
*/
String ASC = "asc";
/**
* 降序
*/
String DESC = "desc";
/**
* 创建时间字段名
*/
String CREATE_DATE = "create_date";
/**
* 数据权限过滤
*/
String SQL_FILTER = "sqlFilter";
/**
* 当前页码
*/
String PAGE = "page";
/**
* 每页显示记录数
*/
String LIMIT = "limit";
/**
* 排序字段
*/
String ORDER_FIELD = "orderField";
/**
* 排序方式
*/
String ORDER = "order";
/**
* token header
*/
String TOKEN_HEADER = "token";
/**
* 云存储配置KEY
*/
String CLOUD_STORAGE_CONFIG_KEY = "CLOUD_STORAGE_CONFIG_KEY";
/**
* 定时任务状态
*/
enum ScheduleStatus {
/**
* 暂停
*/
PAUSE(0),
/**
* 正常
*/
NORMAL(1);
private int value;
ScheduleStatus(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
/**
* 云服务商
*/
enum CloudService {
/**
* 七牛云
*/
QINIU(1),
/**
* 阿里云
*/
ALIYUN(2),
/**
* 腾讯云
*/
QCLOUD(3);
private int value;
CloudService(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
}

View File

@ -0,0 +1,70 @@
package io.common.convert;
import cn.hutool.core.util.StrUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* 日期转换
*/
@Component
public class DateConverter implements Converter<String, Date> {
private static final Logger logger = LoggerFactory.getLogger(DateConverter.class);
private static final List<String> formatList = new ArrayList<>(5);
static {
formatList.add("yyyy-MM");
formatList.add("yyyy-MM-dd");
formatList.add("yyyy-MM-dd HH:mm");
formatList.add("yyyy-MM-dd HH:mm:ss");
formatList.add("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
}
@Override
public Date convert(String source) {
String value = source.trim();
if (StrUtil.isEmpty(value)) {
return null;
}
if (source.matches("^\\d{4}-\\d{1,2}$")) {
return parseDate(source, formatList.get(0));
} else if (source.matches("^\\d{4}-\\d{1,2}-\\d{1,2}$")) {
return parseDate(source, formatList.get(1));
} else if (source.matches("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}$")) {
return parseDate(source, formatList.get(2));
} else if (source.matches("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}:\\d{1,2}$")) {
return parseDate(source, formatList.get(3));
} else if (source.matches("^\\d{4}-\\d{1,2}-\\d{1,2}.*T.*\\d{1,2}:\\d{1,2}:\\d{1,2}.*..*$")) {
return parseDate(source, formatList.get(4));
} else {
throw new IllegalArgumentException("Invalid boolean value '" + source + "'");
}
}
/**
* 格式化日期
* @param dateStr String 字符型日期
* @param format String 格式
* @return Date 日期
*/
public Date parseDate(String dateStr, String format) {
Date date = null;
try {
DateFormat dateFormat = new SimpleDateFormat(format);
date = dateFormat.parse(dateStr);
} catch (Exception e) {
logger.error("Formatted date with date: {} and format : {} ", dateStr, format);
}
return date;
}
}

View File

@ -0,0 +1,10 @@
package io.common.dao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* 基础Dao
*/
public interface BaseDao<T> extends BaseMapper<T> {
}

View File

@ -0,0 +1,33 @@
package io.common.entity;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
* 基础实体类所有实体都需要继承
*/
@Data
public abstract class BaseEntity implements Serializable {
/**
* id
*/
@TableId
private Long id;
/**
* 创建者
*/
@TableField(fill = FieldFill.INSERT)
private Long creator;
/**
* 创建时间
*/
@TableField(fill = FieldFill.INSERT)
private Date createDate;
}

View File

@ -0,0 +1,18 @@
package io.common.exception;
/**
* 错误编码由5位数字组成前2位为模块编码后3位为业务编码
* <p>
* 1000110代表系统模块001代表业务代码
* </p>
*/
public interface ErrorCode {
int INTERNAL_SERVER_ERROR = 500;
int UNAUTHORIZED = 401;
int NOT_NULL = 500;
int ACCOUNT_PASSWORD_ERROR = 10004;
int IDENTIFIER_NOT_NULL = 10006;
}

View File

@ -0,0 +1,43 @@
package io.common.exception;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
/**
* Exception工具类
*/
public class ExceptionUtils {
/**
* 获取异常信息
* @param ex 异常
* @return 返回异常信息
*/
public static String getErrorStackTrace(Exception ex){
StringWriter sw = null;
PrintWriter pw = null;
try {
sw = new StringWriter();
pw = new PrintWriter(sw, true);
ex.printStackTrace(pw);
}finally {
try {
if(pw != null) {
pw.close();
}
} catch (Exception e) {
}
try {
if(sw != null) {
sw.close();
}
} catch (IOException e) {
}
}
return sw.toString();
}
}

View File

@ -0,0 +1,46 @@
package io.common.exception;
import java.util.Arrays;
/**
* 自定义异常
*
*/
public class RenException extends RuntimeException {
private static final long serialVersionUID = 1L;
private int code;
private String msg;
public RenException(int code, String... params) {
this.code = code;
this.msg = Arrays.toString(params);
}
public RenException(String msg) {
super(msg);
this.code = 500;
this.msg = msg;
}
public RenException(String msg, Throwable e) {
super(msg, e);
this.code = ErrorCode.INTERNAL_SERVER_ERROR;
this.msg = msg;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
}

View File

@ -0,0 +1,32 @@
package io.common.page;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.io.Serializable;
import java.util.List;
/**
* 分页工具类
*/
@Data
@Schema(title = "分页数据")
public class PageData<T> implements Serializable {
private static final long serialVersionUID = 1L;
@Schema(title = "总记录数")
private int total;
@Schema(title = "列表数据")
private List<T> list;
/**
* 分页
* @param list 列表数据
* @param total 总记录数
*/
public PageData(List<T> list, long total) {
this.list = list;
this.total = (int)total;
}
}

View File

@ -0,0 +1,106 @@
package io.common.service;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import java.io.Serializable;
import java.util.Collection;
/**
* 基础服务接口所有Service接口都要继承
*/
public interface BaseService<T> {
Class<T> currentModelClass();
/**
* <p>
* 插入一条记录选择字段策略插入
* </p>
*
* @param entity 实体对象
*/
boolean insert(T entity);
/**
* <p>
* 插入批量该方法不支持 OracleSQL Server
* </p>
*
* @param entityList 实体对象集合
*/
boolean insertBatch(Collection<T> entityList);
/**
* <p>
* 插入批量该方法不支持 OracleSQL Server
* </p>
*
* @param entityList 实体对象集合
* @param batchSize 插入批次数量
*/
boolean insertBatch(Collection<T> entityList, int batchSize);
/**
* <p>
* 根据 ID 选择修改
* </p>
*
* @param entity 实体对象
*/
boolean updateById(T entity);
/**
* <p>
* 根据 whereEntity 条件更新记录
* </p>
*
* @param entity 实体对象
* @param updateWrapper 实体对象封装操作类 {@link com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper}
*/
boolean update(T entity, Wrapper<T> updateWrapper);
/**
* <p>
* 根据ID 批量更新
* </p>
*
* @param entityList 实体对象集合
*/
boolean updateBatchById(Collection<T> entityList);
/**
* <p>
* 根据ID 批量更新
* </p>
*
* @param entityList 实体对象集合
* @param batchSize 更新批次数量
*/
boolean updateBatchById(Collection<T> entityList, int batchSize);
/**
* <p>
* 根据 ID 查询
* </p>
*
* @param id 主键ID
*/
T selectById(Serializable id);
/**
* <p>
* 根据 ID 删除
* </p>
*
* @param id 主键ID
*/
boolean deleteById(Serializable id);
/**
* <p>
* 删除根据ID 批量删除
* </p>
*
* @param idList 主键ID列表
*/
boolean deleteBatchIds(Collection<? extends Serializable> idList);
}

View File

@ -0,0 +1,25 @@
package io.common.service;
import io.common.page.PageData;
import java.util.List;
import java.util.Map;
/**
* CRUD基础服务接口
*/
public interface CrudService<T, D> extends BaseService<T> {
PageData<D> page(Map<String, Object> params);
List<D> list(Map<String, Object> params);
D get(Long id);
void save(D dto);
void update(D dto);
void delete(Long[] ids);
}

View File

@ -0,0 +1,213 @@
package io.common.service.impl;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.enums.SqlMethod;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.baomidou.mybatisplus.core.toolkit.ReflectionKit;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import io.common.constant.Constant;
import io.common.page.PageData;
import io.common.service.BaseService;
import io.common.utils.ConvertUtils;
import org.apache.ibatis.binding.MapperMethod;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.logging.LogFactory;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.function.BiConsumer;
/**
* 基础服务类所有Service都要继承
*
*/
public abstract class BaseServiceImpl<M extends BaseMapper<T>, T> implements BaseService<T> {
@Autowired
protected M baseDao;
protected Log log = LogFactory.getLog(getClass());
/**
* 获取分页对象
* @param params 分页查询参数
* @param defaultOrderField 默认排序字段
* @param isAsc 排序方式
*/
protected IPage<T> getPage(Map<String, Object> params, String defaultOrderField, boolean isAsc) {
//分页参数
long curPage = 1;
long limit = 10;
if (params.get(Constant.PAGE) != null) {
curPage = Long.parseLong((String) params.get(Constant.PAGE));
}
if (params.get(Constant.LIMIT) != null) {
limit = Long.parseLong((String) params.get(Constant.LIMIT));
}
//分页对象
Page<T> page = new Page<>(curPage, limit);
//分页参数
params.put(Constant.PAGE, page);
//排序字段
String orderField = (String) params.get(Constant.ORDER_FIELD);
String order = (String) params.get(Constant.ORDER);
//前端字段排序
if (StrUtil.isNotBlank(orderField) && StrUtil.isNotBlank(order)) {
if (Constant.ASC.equalsIgnoreCase(order)) {
return page.addOrder(OrderItem.asc(orderField));
} else {
return page.addOrder(OrderItem.desc(orderField));
}
}
//没有排序字段则不排序
if (StrUtil.isBlank(defaultOrderField)) {
return page;
}
//默认排序
if (isAsc) {
page.addOrder(OrderItem.asc(defaultOrderField));
} else {
page.addOrder(OrderItem.desc(defaultOrderField));
}
return page;
}
protected <T> PageData<T> getPageData(List<?> list, long total, Class<T> target) {
List<T> targetList = ConvertUtils.sourceToTarget(list, target);
return new PageData<>(targetList, total);
}
protected <T> PageData<T> getPageData(IPage page, Class<T> target) {
return getPageData(page.getRecords(), page.getTotal(), target);
}
protected void paramsToLike(Map<String, Object> params, String... likes) {
for (String like : likes) {
String val = (String) params.get(like);
if (StrUtil.isNotBlank(val)) {
params.put(like, "%" + val + "%");
} else {
params.put(like, null);
}
}
}
/**
* <p>
* 判断数据库操作是否成功
* </p>
* <p>
* 注意 该方法为 Integer 判断不可传入 int 基本类型
* </p>
*
* @param result 数据库操作返回影响条数
* @return boolean
*/
protected static boolean retBool(Integer result) {
return SqlHelper.retBool(result);
}
protected Class<M> currentMapperClass() {
return (Class<M>) ReflectionKit.getSuperClassGenericType(this.getClass(), BaseServiceImpl.class, 0);
}
@Override
public Class<T> currentModelClass() {
return (Class<T>) ReflectionKit.getSuperClassGenericType(this.getClass(), BaseServiceImpl.class, 1);
}
protected String getSqlStatement(SqlMethod sqlMethod) {
return SqlHelper.getSqlStatement(this.currentMapperClass(), sqlMethod);
}
@Override
public boolean insert(T entity) {
return BaseServiceImpl.retBool(baseDao.insert(entity));
}
@Override
@Transactional(rollbackFor = Exception.class)
public boolean insertBatch(Collection<T> entityList) {
return insertBatch(entityList, 100);
}
/**
* 批量插入
*/
@Override
@Transactional(rollbackFor = Exception.class)
public boolean insertBatch(Collection<T> entityList, int batchSize) {
String sqlStatement = getSqlStatement(SqlMethod.INSERT_ONE);
return executeBatch(entityList, batchSize, (sqlSession, entity) -> sqlSession.insert(sqlStatement, entity));
}
/**
* 执行批量操作
*/
protected <E> boolean executeBatch(Collection<E> list, int batchSize, BiConsumer<SqlSession, E> consumer) {
return SqlHelper.executeBatch(this.currentModelClass(), this.log, list, batchSize, consumer);
}
@Override
public boolean updateById(T entity) {
return BaseServiceImpl.retBool(baseDao.updateById(entity));
}
@Override
public boolean update(T entity, Wrapper<T> updateWrapper) {
return BaseServiceImpl.retBool(baseDao.update(entity, updateWrapper));
}
@Override
@Transactional(rollbackFor = Exception.class)
public boolean updateBatchById(Collection<T> entityList) {
return updateBatchById(entityList, 30);
}
@Override
@Transactional(rollbackFor = Exception.class)
public boolean updateBatchById(Collection<T> entityList, int batchSize) {
String sqlStatement = getSqlStatement(SqlMethod.UPDATE_BY_ID);
return executeBatch(entityList, batchSize, (sqlSession, entity) -> {
MapperMethod.ParamMap<T> param = new MapperMethod.ParamMap<>();
param.put(Constants.ENTITY, entity);
sqlSession.update(sqlStatement, param);
});
}
@Override
public T selectById(Serializable id) {
return baseDao.selectById(id);
}
@Override
public boolean deleteById(Serializable id) {
return SqlHelper.retBool(baseDao.deleteById(id));
}
@Override
public boolean deleteBatchIds(Collection<? extends Serializable> idList) {
return SqlHelper.retBool(baseDao.deleteBatchIds(idList));
}
}

View File

@ -0,0 +1,74 @@
package io.common.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ReflectionKit;
import io.common.page.PageData;
import io.common.service.CrudService;
import io.common.utils.ConvertUtils;
import org.springframework.beans.BeanUtils;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
/**
* CRUD基础服务类
*
*/
public abstract class CrudServiceImpl<M extends BaseMapper<T>, T, D> extends BaseServiceImpl<M, T> implements CrudService<T, D> {
protected Class<D> currentDtoClass() {
return (Class<D>)ReflectionKit.getSuperClassGenericType(getClass(), CrudServiceImpl.class, 2);
}
@Override
public PageData<D> page(Map<String, Object> params) {
IPage<T> page = baseDao.selectPage(
getPage(params, null, false),
getWrapper(params)
);
return getPageData(page, currentDtoClass());
}
@Override
public List<D> list(Map<String, Object> params) {
List<T> entityList = baseDao.selectList(getWrapper(params));
return ConvertUtils.sourceToTarget(entityList, currentDtoClass());
}
public abstract QueryWrapper<T> getWrapper(Map<String, Object> params);
@Override
public D get(Long id) {
T entity = baseDao.selectById(id);
return ConvertUtils.sourceToTarget(entity, currentDtoClass());
}
@Override
public void save(D dto) {
T entity = ConvertUtils.sourceToTarget(dto, currentModelClass());
insert(entity);
//copy主键值到dto
BeanUtils.copyProperties(entity, dto);
}
@Override
public void update(D dto) {
T entity = ConvertUtils.sourceToTarget(dto, currentModelClass());
updateById(entity);
}
@Override
public void delete(Long[] ids) {
baseDao.deleteBatchIds(Arrays.asList(ids));
}
}

View File

@ -0,0 +1,51 @@
package io.common.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* 转换工具类
*
*/
public class ConvertUtils {
private static Logger logger = LoggerFactory.getLogger(ConvertUtils.class);
public static <T> T sourceToTarget(Object source, Class<T> target){
if(source == null){
return null;
}
T targetObject = null;
try {
targetObject = target.newInstance();
BeanUtils.copyProperties(source, targetObject);
} catch (Exception e) {
logger.error("convert error ", e);
}
return targetObject;
}
public static <T> List<T> sourceToTarget(Collection<?> sourceList, Class<T> target){
if(sourceList == null){
return null;
}
List targetList = new ArrayList<>(sourceList.size());
try {
for(Object source : sourceList){
T targetObject = target.newInstance();
BeanUtils.copyProperties(source, targetObject);
targetList.add(targetObject);
}
}catch (Exception e){
logger.error("convert error ", e);
}
return targetList;
}
}

View File

@ -0,0 +1,55 @@
package io.common.utils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 日期处理
*
*/
public class DateUtils {
/** 时间格式(yyyy-MM-dd) */
public final static String DATE_PATTERN = "yyyy-MM-dd";
/** 时间格式(yyyy-MM-dd HH:mm:ss) */
public final static String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
/**
* 日期格式化 日期格式为yyyy-MM-dd
* @param date 日期
* @return 返回yyyy-MM-dd格式日期
*/
public static String format(Date date) {
return format(date, DATE_PATTERN);
}
/**
* 日期格式化 日期格式为yyyy-MM-dd
* @param date 日期
* @param pattern 格式DateUtils.DATE_TIME_PATTERN
* @return 返回yyyy-MM-dd格式日期
*/
public static String format(Date date, String pattern) {
if (date != null) {
SimpleDateFormat df = new SimpleDateFormat(pattern);
return df.format(date);
}
return null;
}
/**
* 日期解析
* @param date 日期
* @param pattern 格式DateUtils.DATE_TIME_PATTERN
* @return 返回Date
*/
public static Date parse(String date, String pattern) {
try {
return new SimpleDateFormat(pattern).parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
}

View File

@ -0,0 +1,55 @@
package io.common.utils;
import cn.hutool.core.util.StrUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.HttpHeaders;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
/**
* Http
*
*/
public class HttpContextUtils {
public static HttpServletRequest getHttpServletRequest() {
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
if(requestAttributes == null){
return null;
}
return ((ServletRequestAttributes) requestAttributes).getRequest();
}
public static Map<String, String> getParameterMap(HttpServletRequest request) {
Enumeration<String> parameters = request.getParameterNames();
Map<String, String> params = new HashMap<>();
while (parameters.hasMoreElements()) {
String parameter = parameters.nextElement();
String value = request.getParameter(parameter);
if (StrUtil.isNotBlank(value)) {
params.put(parameter, value);
}
}
return params;
}
public static String getDomain(){
HttpServletRequest request = getHttpServletRequest();
StringBuffer url = request.getRequestURL();
return url.delete(url.length() - request.getRequestURI().length(), url.length()).toString();
}
public static String getOrigin(){
HttpServletRequest request = getHttpServletRequest();
return request.getHeader(HttpHeaders.ORIGIN);
}
}

View File

@ -0,0 +1,50 @@
package io.common.utils;
import cn.hutool.core.util.StrUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* IP地址
*
*/
public class IpUtils {
private static Logger logger = LoggerFactory.getLogger(IpUtils.class);
/**
* 获取IP地址
*
* 使用Nginx等反向代理软件 则不能通过request.getRemoteAddr()获取IP地址
* 如果使用了多级反向代理的话X-Forwarded-For的值并不止一个而是一串IP地址X-Forwarded-For中第一个非unknown的有效IP字符串则为真实IP地址
*/
public static String getIpAddr(HttpServletRequest request) {
String unknown = "unknown";
String ip = null;
try {
ip = request.getHeader("x-forwarded-for");
if (StrUtil.isEmpty(ip) || unknown.equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (StrUtil.isEmpty(ip) || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (StrUtil.isEmpty(ip) || unknown.equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (StrUtil.isEmpty(ip) || unknown.equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (StrUtil.isEmpty(ip) || unknown.equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
} catch (Exception e) {
logger.error("IPUtils ERROR ", e);
}
return ip;
}
}

View File

@ -0,0 +1,68 @@
package io.common.utils;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.ArrayList;
import java.util.List;
/**
* JSON 工具类
*
*/
public class JsonUtils {
private static final ObjectMapper objectMapper = new ObjectMapper();
public static String toJsonString(Object object) {
try {
return objectMapper.writeValueAsString(object);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static <T> T parseObject(String text, Class<T> clazz) {
if (StrUtil.isEmpty(text)) {
return null;
}
try {
return objectMapper.readValue(text, clazz);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static <T> T parseObject(byte[] bytes, Class<T> clazz) {
if (ArrayUtil.isEmpty(bytes)) {
return null;
}
try {
return objectMapper.readValue(bytes, clazz);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static <T> T parseObject(String text, TypeReference<T> typeReference) {
try {
return objectMapper.readValue(text, typeReference);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static <T> List<T> parseArray(String text, Class<T> clazz) {
if (StrUtil.isEmpty(text)) {
return new ArrayList<>();
}
try {
return objectMapper.readValue(text, objectMapper.getTypeFactory().constructCollectionType(List.class, clazz));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}

View File

@ -0,0 +1,76 @@
package io.common.utils;
import io.common.exception.ErrorCode;
import io.swagger.v3.oas.annotations.media.Schema;
import java.io.Serializable;
/**
* 响应数据
*
* @since 1.0.0
*/
@Schema(title = "响应")
public class Result<T> implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 编码0表示成功其他值表示失败
*/
@Schema(title = "编码0表示成功其他值表示失败")
private int code = 0;
/**
* 消息内容
*/
@Schema(title = "消息内容")
private String msg = "success";
/**
* 响应数据
*/
@Schema(title = "响应数据")
private T data;
public Result<T> ok(T data) {
this.setData(data);
return this;
}
public boolean success(){
return code == 0;
}
public Result<T> error(int code, String msg) {
this.code = code;
this.msg = msg;
return this;
}
public Result<T> error(String msg) {
this.code = ErrorCode.INTERNAL_SERVER_ERROR;
this.msg = msg;
return this;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}

View File

@ -0,0 +1,47 @@
package io.common.utils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
* Spring Context 工具类
*
*/
@Component
public class SpringContextUtils implements ApplicationContextAware {
public static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
SpringContextUtils.applicationContext = applicationContext;
}
public static Object getBean(String name) {
return applicationContext.getBean(name);
}
public static <T> T getBean(Class<T> requiredType) {
return applicationContext.getBean(requiredType);
}
public static <T> T getBean(String name, Class<T> requiredType) {
return applicationContext.getBean(name, requiredType);
}
public static boolean containsBean(String name) {
return applicationContext.containsBean(name);
}
public static boolean isSingleton(String name) {
return applicationContext.isSingleton(name);
}
public static Class<? extends Object> getType(String name) {
return applicationContext.getType(name);
}
}

View File

@ -0,0 +1,26 @@
package io.common.utils;
import lombok.Data;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* 树节点所有需要实现树节点的都需要继承该类
*/
@Data
public class TreeNode<T> implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键
*/
private Long id;
/**
* 上级ID
*/
private Long pid;
/**
* 子节点列表
*/
private List<T> children = new ArrayList<>();
}

View File

@ -0,0 +1,72 @@
package io.common.utils;
import io.common.validator.AssertUtils;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* 树形结构工具类菜单部门等
*
* @since 1.0.0
*/
public class TreeUtils {
/**
* 根据pid构建树节点
*/
public static <T extends TreeNode> List<T> build(List<T> treeNodes, Long pid) {
//pid不能为空
AssertUtils.isNull(pid, "pid");
List<T> treeList = new ArrayList<>();
for(T treeNode : treeNodes) {
if (pid.equals(treeNode.getPid())) {
treeList.add(findChildren(treeNodes, treeNode));
}
}
return treeList;
}
/**
* 查找子节点
*/
private static <T extends TreeNode> T findChildren(List<T> treeNodes, T rootNode) {
for(T treeNode : treeNodes) {
if(rootNode.getId().equals(treeNode.getPid())) {
rootNode.getChildren().add(findChildren(treeNodes, treeNode));
}
}
return rootNode;
}
/**
* 构建树节点
*/
public static <T extends TreeNode> List<T> build(List<T> treeNodes) {
List<T> result = new ArrayList<>();
//list转map
Map<Long, T> nodeMap = new LinkedHashMap<>(treeNodes.size());
for(T treeNode : treeNodes){
nodeMap.put(treeNode.getId(), treeNode);
}
for(T node : nodeMap.values()) {
T parent = nodeMap.get(node.getPid());
if(parent != null && !(node.getId().equals(parent.getId()))){
parent.getChildren().add(node);
continue;
}
result.add(node);
}
return result;
}
}

View File

@ -0,0 +1,90 @@
package io.common.validator;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ArrayUtil;
import io.common.exception.ErrorCode;
import io.common.exception.RenException;
import cn.hutool.core.util.StrUtil;
import java.util.List;
import java.util.Map;
/**
* 校验工具类
*
* @since 1.0.0
*/
public class AssertUtils {
public static void isBlank(String str, String... params) {
isBlank(str, ErrorCode.NOT_NULL, params);
}
public static void isBlank(String str, Integer code, String... params) {
if(code == null){
throw new RenException(ErrorCode.NOT_NULL, "code");
}
if (StrUtil.isBlank(str)) {
throw new RenException(code, params);
}
}
public static void isNull(Object object, String... params) {
isNull(object, ErrorCode.NOT_NULL, params);
}
public static void isNull(Object object, Integer code, String... params) {
if(code == null){
throw new RenException(ErrorCode.NOT_NULL, "code");
}
if (object == null) {
throw new RenException(code, params);
}
}
public static void isArrayEmpty(Object[] array, String... params) {
isArrayEmpty(array, ErrorCode.NOT_NULL, params);
}
public static void isArrayEmpty(Object[] array, Integer code, String... params) {
if(code == null){
throw new RenException(ErrorCode.NOT_NULL, "code");
}
if(ArrayUtil.isEmpty(array)){
throw new RenException(code, params);
}
}
public static void isListEmpty(List<?> list, String... params) {
isListEmpty(list, ErrorCode.NOT_NULL, params);
}
public static void isListEmpty(List<?> list, Integer code, String... params) {
if(code == null){
throw new RenException(ErrorCode.NOT_NULL, "code");
}
if(CollUtil.isEmpty(list)){
throw new RenException(code, params);
}
}
public static void isMapEmpty(Map map, String... params) {
isMapEmpty(map, ErrorCode.NOT_NULL, params);
}
public static void isMapEmpty(Map map, Integer code, String... params) {
if(code == null){
throw new RenException(ErrorCode.NOT_NULL, "code");
}
if(MapUtil.isEmpty(map)){
throw new RenException(code, params);
}
}
}

View File

@ -0,0 +1,47 @@
package io.common.validator;
import io.common.exception.RenException;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.validation.beanvalidation.MessageSourceResourceBundleLocator;
import java.util.Locale;
import java.util.Set;
/**
* hibernate-validator校验工具类
* 参考文档http://docs.jboss.org/hibernate/validator/6.0/reference/en-US/html_single/
* @since 1.0.0
*/
public class ValidatorUtils {
private static ResourceBundleMessageSource getMessageSource() {
ResourceBundleMessageSource bundleMessageSource = new ResourceBundleMessageSource();
bundleMessageSource.setDefaultEncoding("UTF-8");
bundleMessageSource.setBasenames("i18n/validation");
return bundleMessageSource;
}
/**
* 校验对象
* @param object 待校验对象
* @param groups 待校验的组
*/
public static void validateEntity(Object object, Class<?>... groups)
throws RenException {
Locale.setDefault(LocaleContextHolder.getLocale());
Validator validator = Validation.byDefaultProvider().configure().messageInterpolator(
new ResourceBundleMessageInterpolator(new MessageSourceResourceBundleLocator(getMessageSource())))
.buildValidatorFactory().getValidator();
Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
if (!constraintViolations.isEmpty()) {
ConstraintViolation<Object> constraint = constraintViolations.iterator().next();
throw new RenException(constraint.getMessage());
}
}
}

View File

@ -0,0 +1,8 @@
package io.common.validator.group;
/**
* 新增 Group
*/
public interface AddGroup {
}

View File

@ -0,0 +1,11 @@
package io.common.validator.group;
/**
* 默认 Group
*
* @since 1.0.0
*/
public interface DefaultGroup {
}

View File

@ -0,0 +1,15 @@
package io.common.validator.group;
import jakarta.validation.GroupSequence;
/**
* 定义校验顺序如果AddGroup组失败则UpdateGroup组不会再校验
*
* @since 1.0.0
*/
@GroupSequence({AddGroup.class, UpdateGroup.class})
public interface Group {
}

View File

@ -0,0 +1,11 @@
package io.common.validator.group;
/**
* 修改 Group
*
* @since 1.0.0
*/
public interface UpdateGroup {
}

View File

@ -0,0 +1,29 @@
package io.common.xss;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import java.io.IOException;
/**
* XSS过滤
*/
public class XssFilter implements Filter {
@Override
public void init(FilterConfig config) {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
XssHttpServletRequestWrapper xssRequest = new XssHttpServletRequestWrapper(
(HttpServletRequest) request);
chain.doFilter(xssRequest, response);
}
@Override
public void destroy() {
}
}

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