최초 커밋!
This commit is contained in:
41
.gitignore
vendored
Normal file
41
.gitignore
vendored
Normal file
@@ -0,0 +1,41 @@
|
||||
HELP.md
|
||||
target/
|
||||
!.mvn/wrapper/maven-wrapper.jar
|
||||
!**/src/main/**/target/
|
||||
!**/src/test/**/target/
|
||||
|
||||
### STS ###
|
||||
.apt_generated
|
||||
.classpath
|
||||
.factorypath
|
||||
.project
|
||||
.settings
|
||||
.springBeans
|
||||
.sts4-cache
|
||||
|
||||
### IntelliJ IDEA ###
|
||||
.idea
|
||||
*.iws
|
||||
*.iml
|
||||
*.ipr
|
||||
|
||||
### NetBeans ###
|
||||
/nbproject/private/
|
||||
/nbbuild/
|
||||
/dist/
|
||||
/nbdist/
|
||||
/.nb-gradle/
|
||||
build/
|
||||
!**/src/main/**/build/
|
||||
!**/src/test/**/build/
|
||||
|
||||
### VS Code ###
|
||||
.vscode/
|
||||
|
||||
upload-dir
|
||||
/.metadata/
|
||||
LOG_PATH_IS_UNDEFINED
|
||||
META-INF
|
||||
.jpd
|
||||
|
||||
*.log
|
||||
33
CHANGELOG.md
Normal file
33
CHANGELOG.md
Normal file
@@ -0,0 +1,33 @@
|
||||
# CHANGELOG
|
||||
|
||||
### Updated - 2025-05-18
|
||||
- core @Entity 객체 이름 일괄 변경
|
||||
- JOIN 테이블은 `with` 에서 `has` 로 변경
|
||||
- 역할, 권한 정보에 `ADMIN_`, `FRONT_` 를 붙여 더 명시적인 이름으로 변경
|
||||
- typesafe 하지 않은 string 속성들 정리
|
||||
|
||||
### Updated - 2025-05-17
|
||||
- recycle-front 카카오 로그인 추가 (로컬 9001포트에서 동작)
|
||||
|
||||
### Updated - 2025-05-14
|
||||
- properties 파일에서 yml 파일 사용으로 전환
|
||||
|
||||
### Updated - 2025-05-12
|
||||
- 전체 패키지 구조 변경
|
||||
- 공용 repository 패키지 생성
|
||||
|
||||
### Added - 2025-05-04
|
||||
- recycle-front 네이버 로그인 추가 (로컬 9001포트에서 동작)
|
||||
- front user - 닉네임 및 회원가입 유형 속성 추가
|
||||
|
||||
### Added - 2025-04-23
|
||||
- recycle-api - Accept-Language 헤더 지원 및 en 다국어 프로퍼티 추가
|
||||
|
||||
### Added - 2025-03-13
|
||||
- recycle-api 모듈 구현
|
||||
|
||||
## [2.0.0] - 2025-02-05
|
||||
### Added
|
||||
- recycle-2 버전 출시.
|
||||
- model mapper 제거 - [model mapper 에서 생성자 패턴으로의 전환](https://code.etribe.co.kr/core-architect/recycle-2/-/blob/main/docs/DOC-000-CHANGELOG-VER2.md?ref_type=heads#model-mapper-%EC%97%90%EC%84%9C-%EC%83%9D%EC%84%B1%EC%9E%90-%ED%8C%A8%ED%84%B4%EC%9C%BC%EB%A1%9C%EC%9D%98-%EC%A0%84%ED%99%98)
|
||||
- JPA Metamodel 도입 - [Typesafe 한 JPA 프로그래밍](https://code.etribe.co.kr/core-architect/recycle-2/-/blob/main/docs/DOC-000-CHANGELOG-VER2.md?ref_type=heads#jpa-metamodel-%EB%8F%84%EC%9E%85)
|
||||
41
Dockerfile
Normal file
41
Dockerfile
Normal file
@@ -0,0 +1,41 @@
|
||||
# 1단계: Maven을 사용하여 빌드
|
||||
FROM maven:3.8-openjdk-17 AS build
|
||||
|
||||
ARG TARGET_MODULE
|
||||
|
||||
# 작업 디렉터리 설정
|
||||
WORKDIR /app
|
||||
|
||||
# 소스 디렉토리를 컨테이너에 복사
|
||||
COPY pom.xml .
|
||||
COPY core ./core
|
||||
COPY aws ./aws
|
||||
COPY admin ./admin
|
||||
COPY front ./front
|
||||
COPY api ./api
|
||||
|
||||
# Maven을 이용해 프로젝트 빌드
|
||||
RUN mvn --projects $TARGET_MODULE --also-make package -Dmaven.test.skip=true
|
||||
|
||||
# 2단계: JAR 파일을 실행할 수 있는 기본 이미지
|
||||
FROM openjdk:17-jdk-slim
|
||||
|
||||
ARG TARGET_MODULE
|
||||
ARG PROFILE
|
||||
ENV SPRING_PROFILE=$PROFILE
|
||||
|
||||
# 타임존 설정
|
||||
ENV TZ=Asia/Seoul
|
||||
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
|
||||
|
||||
# 작업 디렉터리 설정
|
||||
WORKDIR /app
|
||||
|
||||
# 1단계에서 빌드된 JAR 파일을 복사
|
||||
COPY --from=build /app/$TARGET_MODULE/target/*.jar app.jar
|
||||
|
||||
# 포트 노출 (스프링 부트 기본 포트)
|
||||
EXPOSE 8080
|
||||
|
||||
# 커맨드
|
||||
CMD ["sh", "-c", "exec java -Dspring.profiles.active=${SPRING_PROFILE} -jar /app/app.jar"]
|
||||
21
LICENSE
Normal file
21
LICENSE
Normal file
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2023 YoungMok Kim
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
346
README.md
346
README.md
@@ -1,93 +1,309 @@
|
||||
# korea research
|
||||
|
||||
|
||||
|
||||
## Getting started
|
||||
|
||||
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
|
||||
|
||||
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
|
||||
|
||||
## Add your files
|
||||
|
||||
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
|
||||
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
|
||||
|
||||
```
|
||||
cd existing_repo
|
||||
git remote add origin http://code.etribe.co.kr/korea-research/korea-research.git
|
||||
git branch -M main
|
||||
git push -uf origin main
|
||||
┬─┐┌─┐┌─┐┬ ┬┌─┐┬ ┌─┐
|
||||
├┬┘├┤ │ └┬┘│ │ ├┤
|
||||
┴└─└─┘└─┘ ┴ └─┘┴─┘└─┘ - framework for spring developers exploring JPA
|
||||
|
||||
_____\ _______
|
||||
/ \ | /\
|
||||
/_______/ |_____/ \
|
||||
| \ / / /
|
||||
\ \ \/ /
|
||||
\ / \__/_
|
||||
\/ ____ /\
|
||||
/ \ / \
|
||||
/\ \ / /
|
||||
\ \/ /
|
||||
\___\__/
|
||||
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
```
|
||||
|
||||
## Integrate with your tools
|
||||
## Prerequisites
|
||||
|
||||
- [ ] [Set up project integrations](http://code.etribe.co.kr/korea-research/korea-research/-/settings/integrations)
|
||||
* JDK 17+
|
||||
* Maven
|
||||
|
||||
## Collaborate with your team
|
||||
## Structure
|
||||
|
||||
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
|
||||
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
|
||||
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
|
||||
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
|
||||
- [ ] [Set auto-merge](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
|
||||
recycle 은 `core` 모듈을 기반으로 한 `admin`, `front`, `api` 어플리케이션으로 구성되어 있다.
|
||||
|
||||
## Test and Deploy
|
||||
```shell
|
||||
.
|
||||
|-- README.md
|
||||
|-- admin # 관리자 어플리케이션
|
||||
| |-- pom.xml
|
||||
| |-- src
|
||||
| `-- target
|
||||
|-- api # API 모듈 (JWT 토큰 기반 인증)
|
||||
| |-- pom.xml
|
||||
| |-- src
|
||||
| `-- target
|
||||
|-- aws # AWS 서비스 전략(strategy) 모듈
|
||||
| |-- pom.xml
|
||||
| |-- src
|
||||
| `-- target
|
||||
|-- core # 공통 모듈
|
||||
| |-- pom.xml
|
||||
| |-- src
|
||||
| `-- target
|
||||
|-- front # 프론트 어플리케이션
|
||||
| |-- pom.xml
|
||||
| |-- src
|
||||
| `-- target
|
||||
`-- pom.xml
|
||||
```
|
||||
|
||||
Use the built-in continuous integration in GitLab.
|
||||
⚡ AWS S3 업로드를 이용하지 않는다면, pom.xml 에서 `aws`모듈 관련 내용을 삭제하면 된다.
|
||||
⚡ `admin`, `front`, `api` 중 실제 프로젝트에서 사용할 모듈만 남기고 삭제해주세요.
|
||||
|
||||
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
|
||||
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
|
||||
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
|
||||
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
|
||||
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
|
||||
✔️ Dockerfile 과 .gitlab-ci.yml 은 삭제해주세요 : ) recycle demo 용이기에 여려분의 프로젝트에서는 의미가 없습니다.
|
||||
|
||||
***
|
||||
recycle 의 demo 가 궁금하다면 아래 URL 에서 확인 해주세요.
|
||||
- `recycle-admin` - https://recycle-admin.etribe.co.kr 계정정보 (recycle-super/recycle1@#$)
|
||||
- `recycle-api` - https://recycle-api.etribe.co.kr/swagger-ui/index.html
|
||||
- `recycle-front` - https://recycle-front.etribe.co.kr/ 계정정보 (generalUser/generalUser1@#$)
|
||||
|
||||
# Editing this README
|
||||
|
||||
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template.
|
||||
## VM Options
|
||||
|
||||
## Suggestions for a good README
|
||||
프레임워크 실행 시 필요한 자바 VM 옵션은 아래와 같다.
|
||||
|
||||
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
|
||||
| VM 변수 | 설명 | 설정 값 | 필수여부 |
|
||||
|-----------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------|-------------------------|------|
|
||||
| -Dspring.profiles.active | Spring active 프로파일 | local, dev, prod | Y |
|
||||
| **-Dspring.datasource.driver-class-name** (2023-03-25 추가) | JDBC Driver. 없다면 JDBC URL을 기준으로 JPA가 판단한다. | jdbc 드라이버 | Y |
|
||||
| **-Dspring.datasource.url** (2023-03-25 추가) | JDBC URL | jdbc url | N |
|
||||
| **-Dspring.datasource.username** (2023-03-25 추가) | DB Username | DB 사용자 | Y |
|
||||
| **-Dspring.datasource.password** (2023-03-25 추가) | DB Password | DB 패스워드 | Y |
|
||||
| -Dapp.initData.core | 어플리케이션 초기 구동에 필요한 필수 데이터 생성여부 | true, false | N |
|
||||
| -Dspring.jpa.hibernate.ddl-auto | JPA DDL 옵션 | update, create 등등 | Y |
|
||||
| -Dspring.jpa.properties.hibernate.show_sql | JPA SQL 로그 보이기 | true, false | N |
|
||||
| -Dlogging.level.org.hibernate.orm.jdbc.bind | JPA 파라미터 바인딩 로그 보이기 | trace (로그보임), info(숨기기) | N |
|
||||
| -Dpath.upload.public | 파일 업로드 경로 | 기본값 (~/upload/public) | N |
|
||||
| -Dpath.upload.tmpdir | 임시 파일 업로드 경로 | 기본값 (~/upload/tmpdir) | N |
|
||||
| -Dlogging.file.path | 로그 파일 생성 경로 | 기본값 (~/logs) | N |
|
||||
| -Dfile.encoding | JVM 속성 | `UTF-8` | Y |
|
||||
| -Djava.net.preferIPv4Stack | JVM 속성. 클라이언트 IP체크시 IPv4 형식을 사용하기 위함. | true | Y |
|
||||
| -Dcom.amazonaws.sdk.disableEc2Metadata | aws 모듈의 ec2 metadata 전송 끄기 | true | N |
|
||||
| **-Dserver.port** (2023-03-25 추가) | 서버 포트 (없다면 기본 8080) | 원하는 port | N |
|
||||
| **-Dserver.forward-headers-strategy** (2023-03-25 추가) | 프록시 서버(nginx, apache)에 정의된 `X-Forward-For`, `X-Forwarded-Proto` 설정값을 이용하려면 `native` 로 설정해주면 된다. (내장 컨테이너를 사용하는 경우에만 유효) | `native` | N |
|
||||
|
||||
## Name
|
||||
Choose a self-explaining name for your project.
|
||||
### VM Options 예시
|
||||
#### `admin`, `front`, `api` 모두 사용가능합니다.
|
||||
```
|
||||
-Dspring.profiles.active=local
|
||||
-Dapp.initData.core=false
|
||||
-Dspring.jpa.hibernate.ddl-auto=update
|
||||
-Dfile.encoding=UTF-8
|
||||
-Djava.net.preferIPv4Stack=true
|
||||
-Dcom.amazonaws.sdk.disableEc2Metadata=true
|
||||
-Dspring.jpa.properties.hibernate.show_sql=true
|
||||
-Dlogging.level.org.hibernate.orm.jdbc.bind=info
|
||||
-Dserver.port=8080
|
||||
-Dserver.forward-headers-strategy=native
|
||||
-Dlogging.level.org.springframework.security=DEBUG
|
||||
-Dspring.datasource.url=jdbc:h2:~/h2/app-h2;AUTO_SERVER=TRUE
|
||||
-Dspring.datasource.username=sa
|
||||
-Dspring.datasource.password=
|
||||
```
|
||||
|
||||
## Description
|
||||
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
|
||||
## JDBC 및 데이터 핸들링 구성 옵션
|
||||
|
||||
## Badges
|
||||
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
|
||||
### JDBC 연결 설정
|
||||
|
||||
## Visuals
|
||||
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
|
||||
스프링부트의 JDBC 설정 방식을 그대로 이용한다. JDBC 연결을 맺을 DB Vendor 와 JNDI 이용여부 등은 프로젝트 상황에 맞게 설정하면 된다.
|
||||
|
||||
## Installation
|
||||
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
|
||||
recycle 은 `H2`를 기본으로 탑재하고 있다. `H2` 를 이용하면 로컬 개발환경에서 아래와 같은 장점을 얻는다.
|
||||
|
||||
## Usage
|
||||
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
|
||||
* 설치 과정이 필요없다. (Maven dependency 에 기술되어 각자 환경에 이미 탑재됨)
|
||||
* 가볍고 빠르며 JDBC API 를 지원하는 오픈소스이다.
|
||||
* ANSI SQL 을 지원하기에 범용성이 뛰어남.
|
||||
|
||||
## Support
|
||||
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
|
||||
```
|
||||
-Dspring.datasource.url=jdbc:h2:~/h2/app-h2;AUTO_SERVER=TRUE
|
||||
-Dspring.datasource.username=sa
|
||||
-Dspring.datasource.password=
|
||||
```
|
||||
|
||||
## Roadmap
|
||||
If you have ideas for releases in the future, it is a good idea to list them in the README.
|
||||
recycle 이 구동되면서 사용자 홈디렉토리에 밑에 /h2/app-h2.mv 파일을 생성합니다. 생성된 파일을 db 클라이언트 툴에서 접속하는 법은
|
||||
이 [문서](https://javanitto.tistory.com/37) 를 참고하세요.
|
||||
|
||||
## Contributing
|
||||
State if you are open to contributions and what your requirements are for accepting them.
|
||||
⚡️ recycle 은 로컬 개발 환경에서 각자의 DB를 이용한 작업을 지향합니다. 테이블과 데이터를 마음대로 삭제/추가하며 개발할 수 있고, 개발/스테이징/운영 환경 같은 공용 공간에 필요한 정보만 커밋할
|
||||
수 있기
|
||||
때문입니다 : )
|
||||
|
||||
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
|
||||
### ddl-auto
|
||||
|
||||
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
|
||||
```shell
|
||||
-Dspring.jpa.hibernate.ddl-auto=update # update | create | none | validate
|
||||
```
|
||||
|
||||
## Authors and acknowledgment
|
||||
Show your appreciation to those who have contributed to the project.
|
||||
**JPA**가 ddl 을 다루는 방식을 정의한다. 엔티티 변경이 많은 개발 시점에는 `update`, `create`를,
|
||||
엔티티 혹은 데이터가 함부로 변경되서는 안되는 운영 환경에서는 `none`, `validate` 등을 지정해준다. (
|
||||
참고: [ddl-auto 옵션 설명](https://smpark1020.tistory.com/140?category=857916))
|
||||
|
||||
## License
|
||||
For open source projects, say how it is licensed.
|
||||
### show_sql
|
||||
|
||||
```shell
|
||||
-Dspring.jpa.properties.hibernate.show_sql=true # true | false
|
||||
```
|
||||
|
||||
JPA SQL 로그 보이기 여부
|
||||
|
||||
### descriptor.sql
|
||||
|
||||
```shell
|
||||
-Dlogging.level.org.hibernate.orm.jdbc.bind=trace # trace | info | debug and etc
|
||||
```
|
||||
|
||||
JPA 파라미터 바인딩 로그 보이기. trace 일 때 where 조건절 등 바인딩된 파라미터 정보 확인이 가능.
|
||||
|
||||
### app.initData.core
|
||||
|
||||
```shell
|
||||
-Dapp.initData.core=true # true | false
|
||||
```
|
||||
|
||||
어플리케이션 초기 구동에 필요한 필수 데이터 생성여부. 공통코드, 메뉴 정보 및 개발에 필요한 기반 데이터 등이 여기에 해당한다.
|
||||
InitAdminData, InitUriFrontData 등 *ApplicationRunner* 구현체에서 내용을 확인할 수 있다.
|
||||
|
||||
## LOG 생성 옵션
|
||||
|
||||
### logging.file.path
|
||||
|
||||
```shell
|
||||
-Dlogging.file.path=~/logs # 기본값 ${user.home}/logs
|
||||
```
|
||||
|
||||
로그 파일 생성 경로를 지정한다. 지정된 경로에 아래와 같은 로그 파일이 생성된다.
|
||||
|
||||
```shell
|
||||
admin-app.log # 어드민 전체 로그
|
||||
admin-app-ERROR.log # 어드민 로그 중 ERROR 부분 필터링
|
||||
front-app.log # 프론트 전체 로그
|
||||
front-app-ERROR.log # 프론트 로그 중 ERROR 부분 필터링
|
||||
```
|
||||
|
||||
## File 구성 옵션
|
||||
|
||||
### 파일 업로드
|
||||
|
||||
```shell
|
||||
-Dpath.upload.public=~/upload/public # 파일 업로드 경로
|
||||
-Dpath.upload.tmpdir=~/upload/tmpdir # tmp 디렉토리 경로
|
||||
```
|
||||
|
||||
파일 업로드 경로가 지정되면 사용자가 업로드한 파일은 이 경로를 기준으로 `주제`/`년월일` 폴더 아래에 저장됩니다.
|
||||
tmpdir 은 서블릿 컨테이너가 multipart 파일 업로드 시 대용량 처리를 위해 임시파일을 저장하는 공간입니다.
|
||||
|
||||
파일 시스템 외에 AWS S3 로도 업로드해야 한다면, 아래 AWS CLI 를 이용하기 위한 정보를 제공해주어야 합니다.
|
||||
|
||||
```shell
|
||||
-Dapp.aws.s3.accessKey=AKIAZF27HETWNITZBZOF # AMI 에서 발급한 사용자 엑세스 키
|
||||
-Dapp.aws.s3.secretKey=IhnTG0X7Wav8ak3cbYR1l8UAjL+gbnXdWJRM11cx # AMI 에서 발급한 사용자 시크릿 키
|
||||
-Dapp.aws.s3.bucketName=etribe # S3 버킷 이름
|
||||
-Dapp.aws.s3.bucketFolder=/recycle/upload # S3 버킷 디렉토리
|
||||
-Dapp.aws.s3.domain=dixjkmptx5pkm.cloudfront.net # S3 혹은 cloudfront 도메인
|
||||
```
|
||||
|
||||
🔑 위 accessKey 정보는 제가 만든 임시 정보이며, recycle 데모용으로만 사용되니 참고해주세요.
|
||||
|
||||
💡 recycle 은 파일 시스템 업로드와 S3 업로드를 사용 목적에 맞게 선택할 수 있는 유연성을 제공합니다.
|
||||
`FileUploadType`은 파일 업로드가 필요한 주제 도메인들이 정의된 enum 객체입니다. 여기 기술된 `FileStorageType` 속성에 따라 파일 업로드 경로가 결정됩니다.
|
||||
|
||||
### 파일 참조
|
||||
|
||||
업로드된 파일은 참조될 수 있어야 합니다. `fileUrlPortIn`는 파일이 파일 시스템에 있든 S3 에 있든 정확한 참조 URL 을 전달해주는 인터페이스입니다.
|
||||
|
||||
```java
|
||||
// 참조 URL 전달 - inline 방식
|
||||
fileUrlPortIn.getInline(
|
||||
uploadFile.getType().getFileStorageType(),
|
||||
uploadFile.getPath(),
|
||||
uploadFile.getName());
|
||||
|
||||
// 참조 URL 전달 - attachment 방식
|
||||
fileUrlPortIn.getAttachment(
|
||||
uploadFile.getType().getFileStorageType(),
|
||||
uploadFile.getId());
|
||||
```
|
||||
|
||||
`inline` 과 `attachment` 는 응답 헤더의 content-disposition 속성 값을 의미합니다.
|
||||
업로드된 파일은 사용자에게 전달할 때 `inline` 과 `attachment` 두 방식 중 요건에 맞게 사용하면 됩니다.
|
||||
|
||||
## 코드 작성 규칙 (coding conventions)
|
||||
|
||||
기본 패키지 구조는 [포트 앤 어댑터 패턴](https://coco-log.tistory.com/205)에 기반해 구성됩니다.
|
||||
|
||||

|
||||
|
||||
getArticles 라는 주제(subject) 패키지 하부를 구성하는 ports 와 adapters 패키지를 주의깊게 봐주세요.
|
||||
|
||||
```
|
||||
# 주제(subject)
|
||||
getArticles
|
||||
|-- adapters
|
||||
| |-- persistence
|
||||
| | |-- GetArticlesDao.java # 포트아웃 구현체
|
||||
| `-- web
|
||||
| |-- GetArticlesController.java
|
||||
| `-- model
|
||||
| `-- GetArticlesReqVO.java
|
||||
`-- ports
|
||||
|-- GetArticlesPortIn.java # 포트인 인터페이스
|
||||
|-- GetArticlesPortOut.java # 포트아웃 인터페이스
|
||||
`-- application
|
||||
|-- GetArticlesService.java # 포트인 구현체
|
||||
`-- domain
|
||||
|-- GetArticles.java
|
||||
`-- GetArticlesCmd.java
|
||||
```
|
||||
|
||||
* ports 는 비지니스 로직을 담는 application 레이어가 위치한 곳입니다. application 은 `포트인` 인터페이스를 통해 호출되며 `포트아웃` 인터페이스를 호출해 결과를 얻습니다.
|
||||
* application 은 누가 `포트인`을 호출하는지 신경쓰지 않습니다. **자신이 호출하는 `포트아웃`의 구현체에 대해서도 모릅니다.** 이를 통해 application 은 다른 계층(web,
|
||||
persistence)과 관계없는 독립적인 레이어가 됩니다.
|
||||
* adapters/web 은 사용자 요청을 처리하는 controller 레이어가 위치한 곳입니다. `포트인` 인터페이스를 호출하는 클라이언트로 해당 규격을 맞춘 어뎁터(adapter) 이며, *
|
||||
*application 에 종속적입니다.**
|
||||
* adapters/persistence 는 영속화(persistence) 레이어가 위치한 곳입니다. mybatis, jpa 등 다양한 ORM 기술을 이용하여 `포트아웃` 인터페이스를 구현합니다. `포트아웃` 규격을
|
||||
맞춘 어뎁터이며, **application 에 종속적입니다.**
|
||||
|
||||
### 자동화 스캐폴딩 (scaffolding) 도구 소개
|
||||
|
||||
위 패키지 구조와 인터페이스 및 구현체를 일일이 타이핑하며 생성할 필요는 없습니다. [BASC](https://code.etribe.co.kr/core-architect/basc) 스캐폴팅 도구가 자동생성
|
||||
해줍니다.
|
||||
|
||||
### Best Practices
|
||||
|
||||
코드 작성 규칙에 맞게 구현된 가장 좋은 예는 관리자의 **예제 게시판**입니다. 새로운 버전에 맞춰 모든 코드들이 재작성되었고 아래 고민들에 대한 해법이 녹아있습니다.
|
||||
|
||||
1. 패키지 구조 및 클래스 명칭을 어떻게 잡아야 할까?
|
||||
2. 브라우저 history 를 잘 유지하면서 back 버튼 이슈를 발생시키지 않는 구현방식은 무엇일까?
|
||||
3. form submit 과 ajax 호출. 어떤 방식이 더 유용할까?
|
||||
4. 사용자 입력값을 검증하고 문제점을 표현하는 가장 좋은 방법은?
|
||||
5. 어떻게 restfull 한 서비스를 구현할 수 있을까? (GET/POST/PUT/PATCH/DELETE)
|
||||
6. 새로운 파일 업로드 방식.
|
||||
|
||||
## PACKAGING
|
||||
|
||||
배포방식 설정을 위해 두가지 maven 프로파일을 제공한다.
|
||||
|
||||
* `jar` (default)
|
||||
* `war` Jeus, WebLogic, Tomcat 등 별도 외장 컨테이너 이용시 사용
|
||||
|
||||
maven 빌드 시 프로파일을 지정하지 않으면 기본 `jar` 프로파일로 동작하고, `war` 의 경우 명시적인 지정이 필요하다.
|
||||
|
||||
아래는 admin 빌드시 `war` 프로파일을 지정한 예시이다.
|
||||
|
||||
```shell
|
||||
$ mvn --projects admin --also-make clean package -DskipTests -P war
|
||||
|
||||
# 빌드 후, admin/target 디렉토리에 war 가 생성된걸 확인할 수 있다.
|
||||
$ ll admin/target
|
||||
-rw-r--r-- 1 user 197121 94905770 4월 22 09:59 admin-0.0.1-SNAPSHOT.war
|
||||
```
|
||||
|
||||
## Project status
|
||||
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
|
||||
|
||||
33
admin/.gitignore
vendored
Normal file
33
admin/.gitignore
vendored
Normal file
@@ -0,0 +1,33 @@
|
||||
HELP.md
|
||||
target/
|
||||
!.mvn/wrapper/maven-wrapper.jar
|
||||
!**/src/main/**/target/
|
||||
!**/src/test/**/target/
|
||||
|
||||
### STS ###
|
||||
.apt_generated
|
||||
.classpath
|
||||
.factorypath
|
||||
.project
|
||||
.settings
|
||||
.springBeans
|
||||
.sts4-cache
|
||||
|
||||
### IntelliJ IDEA ###
|
||||
.idea
|
||||
*.iws
|
||||
*.iml
|
||||
*.ipr
|
||||
|
||||
### NetBeans ###
|
||||
/nbproject/private/
|
||||
/nbbuild/
|
||||
/dist/
|
||||
/nbdist/
|
||||
/.nb-gradle/
|
||||
build/
|
||||
!**/src/main/**/build/
|
||||
!**/src/test/**/build/
|
||||
|
||||
### VS Code ###
|
||||
.vscode/
|
||||
BIN
admin/.mvn/wrapper/maven-wrapper.jar
vendored
Normal file
BIN
admin/.mvn/wrapper/maven-wrapper.jar
vendored
Normal file
Binary file not shown.
2
admin/.mvn/wrapper/maven-wrapper.properties
vendored
Normal file
2
admin/.mvn/wrapper/maven-wrapper.properties
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.4/apache-maven-3.8.4-bin.zip
|
||||
wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar
|
||||
316
admin/mvnw
vendored
Normal file
316
admin/mvnw
vendored
Normal file
@@ -0,0 +1,316 @@
|
||||
#!/bin/sh
|
||||
# ----------------------------------------------------------------------------
|
||||
# Licensed to the Apache Software Foundation (ASF) under one
|
||||
# or more contributor license agreements. See the NOTICE file
|
||||
# distributed with this work for additional information
|
||||
# regarding copyright ownership. The ASF licenses this file
|
||||
# to you under the Apache License, Version 2.0 (the
|
||||
# "License"); you may not use this file except in compliance
|
||||
# with the License. You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing,
|
||||
# software distributed under the License is distributed on an
|
||||
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
# KIND, either express or implied. See the License for the
|
||||
# specific language governing permissions and limitations
|
||||
# under the License.
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# Maven Start Up Batch script
|
||||
#
|
||||
# Required ENV vars:
|
||||
# ------------------
|
||||
# JAVA_HOME - location of a JDK home dir
|
||||
#
|
||||
# Optional ENV vars
|
||||
# -----------------
|
||||
# M2_HOME - location of maven2's installed home dir
|
||||
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
|
||||
# e.g. to debug Maven itself, use
|
||||
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
|
||||
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
if [ -z "$MAVEN_SKIP_RC" ] ; then
|
||||
|
||||
if [ -f /usr/local/etc/mavenrc ] ; then
|
||||
. /usr/local/etc/mavenrc
|
||||
fi
|
||||
|
||||
if [ -f /etc/mavenrc ] ; then
|
||||
. /etc/mavenrc
|
||||
fi
|
||||
|
||||
if [ -f "$HOME/.mavenrc" ] ; then
|
||||
. "$HOME/.mavenrc"
|
||||
fi
|
||||
|
||||
fi
|
||||
|
||||
# OS specific support. $var _must_ be set to either true or false.
|
||||
cygwin=false;
|
||||
darwin=false;
|
||||
mingw=false
|
||||
case "`uname`" in
|
||||
CYGWIN*) cygwin=true ;;
|
||||
MINGW*) mingw=true;;
|
||||
Darwin*) darwin=true
|
||||
# Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
|
||||
# See https://developer.apple.com/library/mac/qa/qa1170/_index.html
|
||||
if [ -z "$JAVA_HOME" ]; then
|
||||
if [ -x "/usr/libexec/java_home" ]; then
|
||||
export JAVA_HOME="`/usr/libexec/java_home`"
|
||||
else
|
||||
export JAVA_HOME="/Library/Java/Home"
|
||||
fi
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
|
||||
if [ -z "$JAVA_HOME" ] ; then
|
||||
if [ -r /etc/gentoo-release ] ; then
|
||||
JAVA_HOME=`java-config --jre-home`
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ -z "$M2_HOME" ] ; then
|
||||
## resolve links - $0 may be a link to maven's home
|
||||
PRG="$0"
|
||||
|
||||
# need this for relative symlinks
|
||||
while [ -h "$PRG" ] ; do
|
||||
ls=`ls -ld "$PRG"`
|
||||
link=`expr "$ls" : '.*-> \(.*\)$'`
|
||||
if expr "$link" : '/.*' > /dev/null; then
|
||||
PRG="$link"
|
||||
else
|
||||
PRG="`dirname "$PRG"`/$link"
|
||||
fi
|
||||
done
|
||||
|
||||
saveddir=`pwd`
|
||||
|
||||
M2_HOME=`dirname "$PRG"`/..
|
||||
|
||||
# make it fully qualified
|
||||
M2_HOME=`cd "$M2_HOME" && pwd`
|
||||
|
||||
cd "$saveddir"
|
||||
# echo Using m2 at $M2_HOME
|
||||
fi
|
||||
|
||||
# For Cygwin, ensure paths are in UNIX format before anything is touched
|
||||
if $cygwin ; then
|
||||
[ -n "$M2_HOME" ] &&
|
||||
M2_HOME=`cygpath --unix "$M2_HOME"`
|
||||
[ -n "$JAVA_HOME" ] &&
|
||||
JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
|
||||
[ -n "$CLASSPATH" ] &&
|
||||
CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
|
||||
fi
|
||||
|
||||
# For Mingw, ensure paths are in UNIX format before anything is touched
|
||||
if $mingw ; then
|
||||
[ -n "$M2_HOME" ] &&
|
||||
M2_HOME="`(cd "$M2_HOME"; pwd)`"
|
||||
[ -n "$JAVA_HOME" ] &&
|
||||
JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
|
||||
fi
|
||||
|
||||
if [ -z "$JAVA_HOME" ]; then
|
||||
javaExecutable="`which javac`"
|
||||
if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
|
||||
# readlink(1) is not available as standard on Solaris 10.
|
||||
readLink=`which readlink`
|
||||
if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
|
||||
if $darwin ; then
|
||||
javaHome="`dirname \"$javaExecutable\"`"
|
||||
javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
|
||||
else
|
||||
javaExecutable="`readlink -f \"$javaExecutable\"`"
|
||||
fi
|
||||
javaHome="`dirname \"$javaExecutable\"`"
|
||||
javaHome=`expr "$javaHome" : '\(.*\)/bin'`
|
||||
JAVA_HOME="$javaHome"
|
||||
export JAVA_HOME
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ -z "$JAVACMD" ] ; then
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD="$JAVA_HOME/jre/sh/java"
|
||||
else
|
||||
JAVACMD="$JAVA_HOME/bin/java"
|
||||
fi
|
||||
else
|
||||
JAVACMD="`\\unset -f command; \\command -v java`"
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
echo "Error: JAVA_HOME is not defined correctly." >&2
|
||||
echo " We cannot execute $JAVACMD" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ -z "$JAVA_HOME" ] ; then
|
||||
echo "Warning: JAVA_HOME environment variable is not set."
|
||||
fi
|
||||
|
||||
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
|
||||
|
||||
# traverses directory structure from process work directory to filesystem root
|
||||
# first directory with .mvn subdirectory is considered project base directory
|
||||
find_maven_basedir() {
|
||||
|
||||
if [ -z "$1" ]
|
||||
then
|
||||
echo "Path not specified to find_maven_basedir"
|
||||
return 1
|
||||
fi
|
||||
|
||||
basedir="$1"
|
||||
wdir="$1"
|
||||
while [ "$wdir" != '/' ] ; do
|
||||
if [ -d "$wdir"/.mvn ] ; then
|
||||
basedir=$wdir
|
||||
break
|
||||
fi
|
||||
# workaround for JBEAP-8937 (on Solaris 10/Sparc)
|
||||
if [ -d "${wdir}" ]; then
|
||||
wdir=`cd "$wdir/.."; pwd`
|
||||
fi
|
||||
# end of workaround
|
||||
done
|
||||
echo "${basedir}"
|
||||
}
|
||||
|
||||
# concatenates all lines of a file
|
||||
concat_lines() {
|
||||
if [ -f "$1" ]; then
|
||||
echo "$(tr -s '\n' ' ' < "$1")"
|
||||
fi
|
||||
}
|
||||
|
||||
BASE_DIR=`find_maven_basedir "$(pwd)"`
|
||||
if [ -z "$BASE_DIR" ]; then
|
||||
exit 1;
|
||||
fi
|
||||
|
||||
##########################################################################################
|
||||
# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
|
||||
# This allows using the maven wrapper in projects that prohibit checking in binary data.
|
||||
##########################################################################################
|
||||
if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo "Found .mvn/wrapper/maven-wrapper.jar"
|
||||
fi
|
||||
else
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
|
||||
fi
|
||||
if [ -n "$MVNW_REPOURL" ]; then
|
||||
jarUrl="$MVNW_REPOURL/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar"
|
||||
else
|
||||
jarUrl="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar"
|
||||
fi
|
||||
while IFS="=" read key value; do
|
||||
case "$key" in (wrapperUrl) jarUrl="$value"; break ;;
|
||||
esac
|
||||
done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo "Downloading from: $jarUrl"
|
||||
fi
|
||||
wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
|
||||
if $cygwin; then
|
||||
wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"`
|
||||
fi
|
||||
|
||||
if command -v wget > /dev/null; then
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo "Found wget ... using wget"
|
||||
fi
|
||||
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
|
||||
wget "$jarUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath"
|
||||
else
|
||||
wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath"
|
||||
fi
|
||||
elif command -v curl > /dev/null; then
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo "Found curl ... using curl"
|
||||
fi
|
||||
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
|
||||
curl -o "$wrapperJarPath" "$jarUrl" -f
|
||||
else
|
||||
curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f
|
||||
fi
|
||||
|
||||
else
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo "Falling back to using Java to download"
|
||||
fi
|
||||
javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
|
||||
# For Cygwin, switch paths to Windows format before running javac
|
||||
if $cygwin; then
|
||||
javaClass=`cygpath --path --windows "$javaClass"`
|
||||
fi
|
||||
if [ -e "$javaClass" ]; then
|
||||
if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo " - Compiling MavenWrapperDownloader.java ..."
|
||||
fi
|
||||
# Compiling the Java class
|
||||
("$JAVA_HOME/bin/javac" "$javaClass")
|
||||
fi
|
||||
if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
|
||||
# Running the downloader
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo " - Running MavenWrapperDownloader.java ..."
|
||||
fi
|
||||
("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR")
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
##########################################################################################
|
||||
# End of extension
|
||||
##########################################################################################
|
||||
|
||||
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo $MAVEN_PROJECTBASEDIR
|
||||
fi
|
||||
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
|
||||
|
||||
# For Cygwin, switch paths to Windows format before running java
|
||||
if $cygwin; then
|
||||
[ -n "$M2_HOME" ] &&
|
||||
M2_HOME=`cygpath --path --windows "$M2_HOME"`
|
||||
[ -n "$JAVA_HOME" ] &&
|
||||
JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
|
||||
[ -n "$CLASSPATH" ] &&
|
||||
CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
|
||||
[ -n "$MAVEN_PROJECTBASEDIR" ] &&
|
||||
MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
|
||||
fi
|
||||
|
||||
# Provide a "standardized" way to retrieve the CLI args that will
|
||||
# work with both Windows and non-Windows executions.
|
||||
MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@"
|
||||
export MAVEN_CMD_LINE_ARGS
|
||||
|
||||
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
|
||||
|
||||
exec "$JAVACMD" \
|
||||
$MAVEN_OPTS \
|
||||
$MAVEN_DEBUG_OPTS \
|
||||
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
|
||||
"-Dmaven.home=${M2_HOME}" \
|
||||
"-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
|
||||
${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"
|
||||
188
admin/mvnw.cmd
vendored
Normal file
188
admin/mvnw.cmd
vendored
Normal file
@@ -0,0 +1,188 @@
|
||||
@REM ----------------------------------------------------------------------------
|
||||
@REM Licensed to the Apache Software Foundation (ASF) under one
|
||||
@REM or more contributor license agreements. See the NOTICE file
|
||||
@REM distributed with this work for additional information
|
||||
@REM regarding copyright ownership. The ASF licenses this file
|
||||
@REM to you under the Apache License, Version 2.0 (the
|
||||
@REM "License"); you may not use this file except in compliance
|
||||
@REM with the License. You may obtain a copy of the License at
|
||||
@REM
|
||||
@REM https://www.apache.org/licenses/LICENSE-2.0
|
||||
@REM
|
||||
@REM Unless required by applicable law or agreed to in writing,
|
||||
@REM software distributed under the License is distributed on an
|
||||
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
@REM KIND, either express or implied. See the License for the
|
||||
@REM specific language governing permissions and limitations
|
||||
@REM under the License.
|
||||
@REM ----------------------------------------------------------------------------
|
||||
|
||||
@REM ----------------------------------------------------------------------------
|
||||
@REM Maven Start Up Batch script
|
||||
@REM
|
||||
@REM Required ENV vars:
|
||||
@REM JAVA_HOME - location of a JDK home dir
|
||||
@REM
|
||||
@REM Optional ENV vars
|
||||
@REM M2_HOME - location of maven2's installed home dir
|
||||
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
|
||||
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending
|
||||
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
|
||||
@REM e.g. to debug Maven itself, use
|
||||
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
|
||||
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
|
||||
@REM ----------------------------------------------------------------------------
|
||||
|
||||
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
|
||||
@echo off
|
||||
@REM set title of command window
|
||||
title %0
|
||||
@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
|
||||
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
|
||||
|
||||
@REM set %HOME% to equivalent of $HOME
|
||||
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
|
||||
|
||||
@REM Execute a user defined script before this one
|
||||
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
|
||||
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
|
||||
if exist "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %*
|
||||
if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\mavenrc_pre.cmd" %*
|
||||
:skipRcPre
|
||||
|
||||
@setlocal
|
||||
|
||||
set ERROR_CODE=0
|
||||
|
||||
@REM To isolate internal variables from possible post scripts, we use another setlocal
|
||||
@setlocal
|
||||
|
||||
@REM ==== START VALIDATION ====
|
||||
if not "%JAVA_HOME%" == "" goto OkJHome
|
||||
|
||||
echo.
|
||||
echo Error: JAVA_HOME not found in your environment. >&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the >&2
|
||||
echo location of your Java installation. >&2
|
||||
echo.
|
||||
goto error
|
||||
|
||||
:OkJHome
|
||||
if exist "%JAVA_HOME%\bin\java.exe" goto init
|
||||
|
||||
echo.
|
||||
echo Error: JAVA_HOME is set to an invalid directory. >&2
|
||||
echo JAVA_HOME = "%JAVA_HOME%" >&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the >&2
|
||||
echo location of your Java installation. >&2
|
||||
echo.
|
||||
goto error
|
||||
|
||||
@REM ==== END VALIDATION ====
|
||||
|
||||
:init
|
||||
|
||||
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
|
||||
@REM Fallback to current working directory if not found.
|
||||
|
||||
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
|
||||
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
|
||||
|
||||
set EXEC_DIR=%CD%
|
||||
set WDIR=%EXEC_DIR%
|
||||
:findBaseDir
|
||||
IF EXIST "%WDIR%"\.mvn goto baseDirFound
|
||||
cd ..
|
||||
IF "%WDIR%"=="%CD%" goto baseDirNotFound
|
||||
set WDIR=%CD%
|
||||
goto findBaseDir
|
||||
|
||||
:baseDirFound
|
||||
set MAVEN_PROJECTBASEDIR=%WDIR%
|
||||
cd "%EXEC_DIR%"
|
||||
goto endDetectBaseDir
|
||||
|
||||
:baseDirNotFound
|
||||
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
|
||||
cd "%EXEC_DIR%"
|
||||
|
||||
:endDetectBaseDir
|
||||
|
||||
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
|
||||
|
||||
@setlocal EnableExtensions EnableDelayedExpansion
|
||||
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
|
||||
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
|
||||
|
||||
:endReadAdditionalConfig
|
||||
|
||||
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
|
||||
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
|
||||
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
|
||||
|
||||
set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar"
|
||||
|
||||
FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
|
||||
IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
|
||||
)
|
||||
|
||||
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
|
||||
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
|
||||
if exist %WRAPPER_JAR% (
|
||||
if "%MVNW_VERBOSE%" == "true" (
|
||||
echo Found %WRAPPER_JAR%
|
||||
)
|
||||
) else (
|
||||
if not "%MVNW_REPOURL%" == "" (
|
||||
SET DOWNLOAD_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar"
|
||||
)
|
||||
if "%MVNW_VERBOSE%" == "true" (
|
||||
echo Couldn't find %WRAPPER_JAR%, downloading it ...
|
||||
echo Downloading from: %DOWNLOAD_URL%
|
||||
)
|
||||
|
||||
powershell -Command "&{"^
|
||||
"$webclient = new-object System.Net.WebClient;"^
|
||||
"if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
|
||||
"$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
|
||||
"}"^
|
||||
"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^
|
||||
"}"
|
||||
if "%MVNW_VERBOSE%" == "true" (
|
||||
echo Finished downloading %WRAPPER_JAR%
|
||||
)
|
||||
)
|
||||
@REM End of extension
|
||||
|
||||
@REM Provide a "standardized" way to retrieve the CLI args that will
|
||||
@REM work with both Windows and non-Windows executions.
|
||||
set MAVEN_CMD_LINE_ARGS=%*
|
||||
|
||||
%MAVEN_JAVA_EXE% ^
|
||||
%JVM_CONFIG_MAVEN_PROPS% ^
|
||||
%MAVEN_OPTS% ^
|
||||
%MAVEN_DEBUG_OPTS% ^
|
||||
-classpath %WRAPPER_JAR% ^
|
||||
"-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" ^
|
||||
%WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
|
||||
if ERRORLEVEL 1 goto error
|
||||
goto end
|
||||
|
||||
:error
|
||||
set ERROR_CODE=1
|
||||
|
||||
:end
|
||||
@endlocal & set ERROR_CODE=%ERROR_CODE%
|
||||
|
||||
if not "%MAVEN_SKIP_RC%"=="" goto skipRcPost
|
||||
@REM check for post script, once with legacy .bat ending and once with .cmd ending
|
||||
if exist "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat"
|
||||
if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\mavenrc_post.cmd"
|
||||
:skipRcPost
|
||||
|
||||
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
|
||||
if "%MAVEN_BATCH_PAUSE%"=="on" pause
|
||||
|
||||
if "%MAVEN_TERMINATE_CMD%"=="on" exit %ERROR_CODE%
|
||||
|
||||
cmd /C exit /B %ERROR_CODE%
|
||||
43
admin/pom.xml
Normal file
43
admin/pom.xml
Normal file
@@ -0,0 +1,43 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<artifactId>admin</artifactId>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<configuration>
|
||||
<includeSystemScope>true</includeSystemScope>
|
||||
</configuration>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<version>3.4.0</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<artifactId>aws</artifactId>
|
||||
<groupId>app.module</groupId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<artifactId>core</artifactId>
|
||||
<groupId>app.module</groupId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<description>Admin project</description>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<name>admin</name>
|
||||
<packaging>${packaging.type}</packaging>
|
||||
|
||||
<parent>
|
||||
<artifactId>app.module</artifactId>
|
||||
<groupId>app.module</groupId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
|
||||
</project>
|
||||
30
admin/src/main/java/app/module/admin/AdminApplication.java
Normal file
30
admin/src/main/java/app/module/admin/AdminApplication.java
Normal file
@@ -0,0 +1,30 @@
|
||||
package app.module.admin;
|
||||
|
||||
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.cache.annotation.EnableCaching;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
|
||||
@SpringBootApplication
|
||||
@EnableCaching
|
||||
@ComponentScan(basePackages = "app.module")
|
||||
public class AdminApplication extends SpringBootServletInitializer {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(AdminApplication.class, args);
|
||||
}
|
||||
|
||||
/**
|
||||
* maven jar 배포시 필요없지만, war 배포를 선택한 경우 configure 오버라이드가 필요하기에 선언.
|
||||
*
|
||||
* @param builder
|
||||
* @return
|
||||
*/
|
||||
@Override
|
||||
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
|
||||
return builder.sources(AdminApplication.class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package app.module.admin.config.adapters.web.interceptor;
|
||||
|
||||
import app.module.core.config.adapters.web.interceptor.model.URITopTierVO;
|
||||
import app.module.core.config.application.enums.AppType;
|
||||
import app.module.core.config.application.exception.NoMatchingURIException;
|
||||
import app.module.core.config.application.util.CommonUtil;
|
||||
import app.module.core.usecase.uri.ancestry.ports.URIAncestryPortIn;
|
||||
import app.module.core.usecase.uri.currentmatch.ports.URICurrentMatchingPortIn;
|
||||
import app.module.core.usecase.uri.currentmatch.ports.application.domain.URICurrentMatching;
|
||||
import app.module.core.usecase.uri.toptier.ports.URITopTierPortIn;
|
||||
import app.module.core.usecase.uri.toptier.ports.application.domain.URITopTier;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import java.util.stream.Collectors;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.collections4.CollectionUtils;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.servlet.HandlerInterceptor;
|
||||
import org.springframework.web.servlet.ModelAndView;
|
||||
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class AdminURIInterceptor implements HandlerInterceptor {
|
||||
|
||||
private final URICurrentMatchingPortIn uriCurrentMatchingPortIn;
|
||||
private final URIAncestryPortIn uriAncestryPortIn;
|
||||
private final URITopTierPortIn topTierPortIn;
|
||||
|
||||
@Value("${app.aws.s3.domain:null}")
|
||||
private String cloudFrontDomain;
|
||||
|
||||
@Value("${app.aws.s3.bucketFolder:null}")
|
||||
private String bucketFolder;
|
||||
|
||||
@Override
|
||||
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
|
||||
Object handler)
|
||||
throws Exception {
|
||||
String requestURI = request.getRequestURI();
|
||||
|
||||
URICurrentMatching currentURI = uriCurrentMatchingPortIn.connect(AppType.ADMIN, requestURI);
|
||||
if (currentURI == null) {
|
||||
// spring boot 2.6.x 에서는 인터셉터에서 throw exception 이 동작안했기에 아래 코드가 필요했음.
|
||||
// request.setAttribute("message", String.format("매핑되는 않은 URI - %s", requestURI));
|
||||
// request.setAttribute("exception", "NoMatchingURIException");
|
||||
// request.getRequestDispatcher("/error/interceptor").forward(request, response);
|
||||
// return false;
|
||||
|
||||
// spring boot 3.4.x 에서는 throw exception 이 가능!
|
||||
throw new NoMatchingURIException(String.format("매핑되는 않은 URI - %s", requestURI));
|
||||
}
|
||||
|
||||
request.setAttribute("currentURI", currentURI);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void postHandle(
|
||||
HttpServletRequest request,
|
||||
HttpServletResponse response,
|
||||
Object handler,
|
||||
ModelAndView modelAndView)
|
||||
throws Exception {
|
||||
|
||||
if (modelAndView == null) {
|
||||
log.info("POST_HANDLE_END::since modelAndView is null");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!CommonUtil.isAjaxRequest(request)) {
|
||||
URITopTier topTierOutput = topTierPortIn.connect(AppType.ADMIN);
|
||||
modelAndView.addObject("topNode", recursiveMapping(topTierOutput));
|
||||
|
||||
if (modelAndView.getModelMap().getAttribute("currentURI") == null) {
|
||||
modelAndView.addObject("currentURI", request.getAttribute("currentURI"));
|
||||
}
|
||||
|
||||
modelAndView.addObject(
|
||||
"menuHierarchy", uriAncestryPortIn.connect(AppType.ADMIN, request.getRequestURI()));
|
||||
|
||||
if (cloudFrontDomain != null && bucketFolder != null) {
|
||||
modelAndView.addObject("S3URL", "https://" + cloudFrontDomain + bucketFolder);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private URITopTierVO recursiveMapping(URITopTier output) {
|
||||
return new URITopTierVO(
|
||||
output.getId(),
|
||||
output.getText(),
|
||||
output.getUri(),
|
||||
output.getShowOnNavi(),
|
||||
CollectionUtils.emptyIfNull(output.getChildren()).stream()
|
||||
.map(this::recursiveMapping)
|
||||
.collect(Collectors.toList()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package app.module.admin.config.adapters.web.mvc;
|
||||
|
||||
import app.module.admin.config.adapters.web.interceptor.AdminURIInterceptor;
|
||||
import app.module.core.config.adapters.web.interceptor.URIAuthorizeInterceptor;
|
||||
import app.module.core.config.application.enums.PublicAccess;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.stream.Collectors;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.http.converter.HttpMessageConverter;
|
||||
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
|
||||
import org.springframework.web.servlet.LocaleResolver;
|
||||
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
import org.springframework.web.servlet.i18n.CookieLocaleResolver;
|
||||
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
|
||||
|
||||
@Configuration
|
||||
@RequiredArgsConstructor
|
||||
public class AdminWebMvcConfig implements WebMvcConfigurer {
|
||||
|
||||
private final AdminURIInterceptor adminURIInterceptor;
|
||||
private final URIAuthorizeInterceptor uriAuthorizeInterceptor;
|
||||
@Value("${path.upload.public}")
|
||||
private String publicPath;
|
||||
|
||||
@Override
|
||||
public void addInterceptors(InterceptorRegistry registry) {
|
||||
registry
|
||||
.addInterceptor(adminURIInterceptor)
|
||||
.addPathPatterns("/**")
|
||||
.excludePathPatterns(
|
||||
Arrays.stream(PublicAccess.values())
|
||||
.map(PublicAccess::getPath)
|
||||
.collect(Collectors.toList()))
|
||||
.excludePathPatterns("/api/**"); // api 는 menu 정보가 없기에 skip
|
||||
|
||||
registry
|
||||
.addInterceptor(uriAuthorizeInterceptor)
|
||||
.addPathPatterns("/**")
|
||||
.excludePathPatterns(
|
||||
Arrays.stream(PublicAccess.values())
|
||||
.map(PublicAccess::getPath)
|
||||
.collect(Collectors.toList()))
|
||||
.excludePathPatterns("/api/**"); // api 는 menu 정보가 없기에 skip
|
||||
|
||||
registry.addInterceptor(localeChangeInterceptor());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addResourceHandlers(ResourceHandlerRegistry registry) {
|
||||
registry
|
||||
.addResourceHandler("/content-disposition/inline/**")
|
||||
.addResourceLocations("file:///" + publicPath + "/")
|
||||
.setCachePeriod(20);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
|
||||
converters.add(new MappingJackson2HttpMessageConverter());
|
||||
}
|
||||
|
||||
@Bean
|
||||
public LocaleResolver localeResolver() {
|
||||
CookieLocaleResolver slr = new CookieLocaleResolver();
|
||||
slr.setDefaultLocale(Locale.getDefault());
|
||||
slr.setCookieName("lang");
|
||||
return slr;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public LocaleChangeInterceptor localeChangeInterceptor() {
|
||||
LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
|
||||
lci.setParamName("lang");
|
||||
return lci;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package app.module.admin.config.application.aop;
|
||||
|
||||
import app.module.core.config.application.enums.AppType;
|
||||
import app.module.core.config.application.enums.OperationLogType;
|
||||
import app.module.core.config.application.util.CommonUtil;
|
||||
import app.module.core.config.application.util.MessageUtil;
|
||||
import app.module.core.usecase.operationlog.save.application.domain.OperationLogSaveCommand;
|
||||
import app.module.core.usecase.operationlog.save.application.port.in.OperationLogSavePortIn;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.aspectj.lang.JoinPoint;
|
||||
import org.aspectj.lang.annotation.After;
|
||||
import org.aspectj.lang.annotation.Aspect;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Aspect
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class LoginFailAspect {
|
||||
|
||||
private final OperationLogSavePortIn operationLogSavePortIn;
|
||||
private final MessageUtil messageUtil;
|
||||
|
||||
@After("@annotation(app.module.admin.config.application.aop.LoginFailOperateLog)")
|
||||
public void operate(JoinPoint joinPoint) throws Throwable {
|
||||
Object[] args = joinPoint.getArgs();
|
||||
HttpServletRequest request = (HttpServletRequest) args[0];
|
||||
String targetId = request.getParameter("username");
|
||||
|
||||
operationLogSavePortIn.connect(
|
||||
new OperationLogSaveCommand(
|
||||
AppType.ADMIN,
|
||||
OperationLogType.LOGIN_FAIL,
|
||||
targetId,
|
||||
CommonUtil.getClientIP(request),
|
||||
messageUtil.getMessage("operate.login.fail", targetId)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package app.module.admin.config.application.aop;
|
||||
|
||||
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)
|
||||
public @interface LoginFailOperateLog {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package app.module.admin.config.application.aop;
|
||||
|
||||
import app.module.core.config.application.enums.AppType;
|
||||
import app.module.core.config.application.enums.OperationLogType;
|
||||
import app.module.core.config.application.util.CommonUtil;
|
||||
import app.module.core.config.application.util.MessageUtil;
|
||||
import app.module.core.usecase.operationlog.save.application.domain.OperationLogSaveCommand;
|
||||
import app.module.core.usecase.operationlog.save.application.port.in.OperationLogSavePortIn;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.aspectj.lang.JoinPoint;
|
||||
import org.aspectj.lang.annotation.After;
|
||||
import org.aspectj.lang.annotation.Aspect;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Aspect
|
||||
@Component
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
public class LoginSuccessAspect {
|
||||
|
||||
private final OperationLogSavePortIn operationLogSavePortIn;
|
||||
private final MessageUtil messageUtil;
|
||||
|
||||
@After("@annotation(app.module.admin.config.application.aop.LoginSuccessOperateLog)")
|
||||
public void operate(JoinPoint joinPoint) throws Throwable {
|
||||
Object[] args = joinPoint.getArgs();
|
||||
|
||||
HttpServletRequest request = (HttpServletRequest) args[0];
|
||||
Authentication authentication = (Authentication) args[2];
|
||||
|
||||
operationLogSavePortIn.connect(
|
||||
new OperationLogSaveCommand(
|
||||
AppType.ADMIN,
|
||||
OperationLogType.LOGIN_SUCCESS,
|
||||
null,
|
||||
CommonUtil.getClientIP(request),
|
||||
messageUtil.getMessage("operate.login.success", authentication.getName())));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package app.module.admin.config.application.aop;
|
||||
|
||||
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)
|
||||
public @interface LoginSuccessOperateLog {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package app.module.admin.config.application.aop;
|
||||
|
||||
import app.module.core.config.adapters.web.security.domain.CoreRole;
|
||||
import app.module.core.config.application.enums.AppType;
|
||||
import app.module.core.config.application.enums.OperationLogType;
|
||||
import app.module.core.config.application.util.CommonUtil;
|
||||
import app.module.core.usecase.admin.view.ports.AdminViewPortIn;
|
||||
import app.module.core.usecase.admin.view.ports.application.domain.AdminView;
|
||||
import app.module.core.usecase.operationlog.save.application.domain.OperationLogSaveCommand;
|
||||
import app.module.core.usecase.operationlog.save.application.port.in.OperationLogSavePortIn;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.aspectj.lang.ProceedingJoinPoint;
|
||||
import org.aspectj.lang.annotation.Around;
|
||||
import org.aspectj.lang.annotation.Aspect;
|
||||
import org.aspectj.lang.reflect.MethodSignature;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.thymeleaf.util.StringUtils;
|
||||
|
||||
@Aspect
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class RoleUpdateAspect {
|
||||
|
||||
private final AdminViewPortIn adminViewPortIn;
|
||||
private final OperationLogSavePortIn operationLogSavePortIn;
|
||||
|
||||
@Around(
|
||||
"execution(* app.module.core.usecase.admin.saveAdmin.ports.application.SaveAdminService.connect(..))")
|
||||
public Object operate(ProceedingJoinPoint joinPoint) throws Throwable {
|
||||
Object[] args = joinPoint.getArgs();
|
||||
|
||||
String adminId = (String) args[0];
|
||||
List<String> currentRoles = Collections.emptyList();
|
||||
|
||||
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
|
||||
Method method = signature.getMethod();
|
||||
|
||||
for (int i = 0; i < method.getParameters().length; i++) {
|
||||
String parameterName = method.getParameters()[i].getName();
|
||||
if (parameterName.equals("roleIds") && args[i] instanceof List) {
|
||||
currentRoles = (List<String>) args[i];
|
||||
}
|
||||
}
|
||||
|
||||
Optional<AdminView> beforeAdmin = adminViewPortIn.connect(adminId);
|
||||
|
||||
// List<String> currentRoles =
|
||||
// adminId.getWithRoles().stream()
|
||||
// .map(adminUserWithRole -> adminUserWithRole.getRole().getId())
|
||||
// .collect(Collectors.toList());
|
||||
|
||||
boolean createLog = false;
|
||||
|
||||
if (beforeAdmin.isPresent()) {
|
||||
List<String> beforeRoles =
|
||||
beforeAdmin.get().getRoles().stream().map(CoreRole::getId).toList();
|
||||
if (beforeRoles.size() != currentRoles.size()
|
||||
|| currentRoles.stream().anyMatch(item -> !beforeRoles.contains(item))) {
|
||||
createLog = true;
|
||||
}
|
||||
} else if (currentRoles.size() > 0) {
|
||||
createLog = true;
|
||||
}
|
||||
|
||||
if (createLog) {
|
||||
String operatorId = Optional.ofNullable(CommonUtil.getLoginUsername())
|
||||
.orElse("init data");
|
||||
HttpServletRequest request = CommonUtil.getRequest();
|
||||
|
||||
operationLogSavePortIn.connect(
|
||||
new OperationLogSaveCommand(
|
||||
AppType.ADMIN,
|
||||
OperationLogType.ROLE_UPDATE,
|
||||
adminId,
|
||||
request != null ? CommonUtil.getClientIP(request) : null,
|
||||
String.format(
|
||||
"`%s` grants [%s] permissions to `%s`",
|
||||
operatorId, StringUtils.join(currentRoles, ", "), adminId)));
|
||||
}
|
||||
|
||||
return joinPoint.proceed();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package app.module.admin.config.application.aop;
|
||||
|
||||
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)
|
||||
public @interface RoleUpdateOperateLog {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package app.module.admin.config.application.listener;
|
||||
|
||||
import jakarta.servlet.http.HttpSessionEvent;
|
||||
import jakarta.servlet.http.HttpSessionListener;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* Spring Boot 을 이용하지만 내장 Tomcat 이 아닌 외부 WAS 를 이용하는 경우 HttpSessionListener 를 이용해 Session 유효기간을 지정해야
|
||||
* 한다.
|
||||
*/
|
||||
@Component
|
||||
public class SessionListener implements HttpSessionListener {
|
||||
|
||||
@Value("${app.admin.session.validity.period.seconds}")
|
||||
Integer sessionValiditySeconds;
|
||||
|
||||
@Override
|
||||
public void sessionCreated(HttpSessionEvent se) {
|
||||
se.getSession().setMaxInactiveInterval(sessionValiditySeconds);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package app.module.admin.config.application.security;
|
||||
|
||||
import app.module.core.config.application.enums.AppType;
|
||||
import app.module.core.config.application.enums.OperationLogType;
|
||||
import app.module.core.config.application.util.CommonUtil;
|
||||
import app.module.core.config.application.util.MessageUtil;
|
||||
import app.module.core.usecase.admin.status.ports.AdminUpdateAccountLockPortIn;
|
||||
import app.module.core.usecase.admin.status.ports.AdminUpdateLoginFailPortIn;
|
||||
import app.module.core.usecase.admin.view.ports.AdminViewPortIn;
|
||||
import app.module.core.usecase.operationlog.save.application.domain.OperationLogSaveCommand;
|
||||
import app.module.core.usecase.operationlog.save.application.port.in.OperationLogSavePortIn;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import java.util.Optional;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.event.EventListener;
|
||||
import org.springframework.security.authentication.BadCredentialsException;
|
||||
import org.springframework.security.authentication.event.AbstractAuthenticationFailureEvent;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.context.request.RequestContextHolder;
|
||||
import org.springframework.web.context.request.ServletRequestAttributes;
|
||||
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class AdminAuthFailEvent {
|
||||
|
||||
private final AdminViewPortIn adminViewPortIn;
|
||||
private final AdminUpdateLoginFailPortIn updateLoginFailPortIn;
|
||||
private final AdminUpdateAccountLockPortIn updateAccountLockPortIn;
|
||||
private final OperationLogSavePortIn operationLogSavePortIn;
|
||||
private final MessageUtil messageUtil;
|
||||
@Value("${app.admin.auth.fail.permit}")
|
||||
private int failPermit;
|
||||
|
||||
@EventListener
|
||||
public void handleAuthenticationFailureEvent(AbstractAuthenticationFailureEvent event) {
|
||||
HttpServletRequest request =
|
||||
((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
|
||||
|
||||
if (event.getException() instanceof BadCredentialsException) {
|
||||
adminViewPortIn
|
||||
.connect(request.getParameter("username"))
|
||||
.filter(admin -> admin.getAccountLocked() == null || !admin.getAccountLocked())
|
||||
.ifPresent(
|
||||
adminUserViewInfo -> {
|
||||
String adminUserId = adminUserViewInfo.getId();
|
||||
int failCnt =
|
||||
Optional.ofNullable(adminUserViewInfo.getLoginFailCnt()).orElse(0) + 1;
|
||||
updateLoginFailPortIn.connect(adminUserId, failCnt);
|
||||
|
||||
if (failCnt >= failPermit) {
|
||||
// 계정 잠금 처리
|
||||
updateAccountLockPortIn.connect(adminUserId, true);
|
||||
|
||||
// 계정 잠금 메세지 전달
|
||||
CommonUtil.addFlashAlertMessages(
|
||||
request.getSession(),
|
||||
messageUtil.getMessage("security.auth.fail.exceed", failPermit));
|
||||
|
||||
// 계정 잠금 로그 기록
|
||||
operationLogSavePortIn.connect(
|
||||
new OperationLogSaveCommand(
|
||||
AppType.ADMIN,
|
||||
OperationLogType.ACCOUNT_LOCKED,
|
||||
adminUserViewInfo.getId(),
|
||||
CommonUtil.getClientIP(request),
|
||||
messageUtil.getMessage(
|
||||
"operate.account.locked", adminUserViewInfo.getId())));
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
package app.module.admin.config.application.security;
|
||||
|
||||
import app.module.admin.usecase.loggedinuser.save.ports.LoggedInUserSavePortIn;
|
||||
import app.module.admin.usecase.loggedinuser.save.ports.application.domain.LoggedInUserIdSaveCmd;
|
||||
import app.module.admin.usecase.loggedinuser.save.ports.application.domain.LoggedInUserSaveCmd;
|
||||
import app.module.admin.usecase.loggedinuser.view.ports.LoggedInUserViewPortIn;
|
||||
import app.module.admin.usecase.loggedinuser.view.ports.application.domain.LoggedInUserIdCmd;
|
||||
import app.module.admin.usecase.loggedinuser.view.ports.application.domain.LoggedInUserView;
|
||||
import app.module.core.config.application.enums.AppType;
|
||||
import app.module.core.config.application.util.CommonUtil;
|
||||
import app.module.core.config.application.util.MessageUtil;
|
||||
import app.module.core.usecase.admin.status.ports.AdminUpdateLoginFailPortIn;
|
||||
import app.module.core.usecase.admin.view.ports.AdminViewPortIn;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import java.time.LocalDateTime;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.event.EventListener;
|
||||
import org.springframework.security.authentication.event.AbstractAuthenticationFailureEvent;
|
||||
import org.springframework.security.authentication.event.AuthenticationSuccessEvent;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.context.request.RequestContextHolder;
|
||||
import org.springframework.web.context.request.ServletRequestAttributes;
|
||||
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class AdminAuthSuccessEvent {
|
||||
|
||||
private final MessageUtil messageUtil;
|
||||
private final AdminViewPortIn adminViewPortIn;
|
||||
private final AdminUpdateLoginFailPortIn updateLoginFailPortIn;
|
||||
private final LoggedInUserViewPortIn loggedInUserViewPortIn;
|
||||
private final LoggedInUserSavePortIn loggedInUserSavePortIn;
|
||||
@Value("${app.admin.password.validity.period.days}")
|
||||
private long passwordValidPeriodDays;
|
||||
@Value("${app.admin.password.change.notice.period.days}")
|
||||
private long passwordChangeNoticeDays;
|
||||
@Value("${app.admin.session.validity.period.seconds}")
|
||||
private long sessionValidPeriodSeconds;
|
||||
@Value("${app.admin.session.maximum.num}")
|
||||
private Integer maxSessionNum;
|
||||
|
||||
@EventListener
|
||||
public void handleAuthenticationSuccessEvent(AuthenticationSuccessEvent event) {
|
||||
Authentication authentication = event.getAuthentication();
|
||||
AdminUser adminUser = (AdminUser) authentication.getPrincipal();
|
||||
|
||||
HttpServletRequest request =
|
||||
((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
|
||||
|
||||
// 로그인 실패 회수 초기화
|
||||
adminViewPortIn
|
||||
.connect(authentication.getName())
|
||||
.ifPresent(admin -> updateLoginFailPortIn.connect(admin.getId(), 0));
|
||||
|
||||
// 패스워드 변경일 공지
|
||||
if (passwordValidPeriodDays != -1
|
||||
&& adminUser.getRemainPasswordDays() <= passwordChangeNoticeDays) {
|
||||
CommonUtil.addFlashAlertMessages(
|
||||
request.getSession(),
|
||||
messageUtil.getMessage(
|
||||
"security.password.change.notify", adminUser.getRemainPasswordDays()));
|
||||
}
|
||||
|
||||
if (maxSessionNum == 1) {
|
||||
// 동시 접속 (중복 로그인) 여부 판단 후 사용자에게 메세지 보이기
|
||||
if (isAlreadyLoggedInSomewhere(authentication.getName(),
|
||||
CommonUtil.getClientIP(request))) {
|
||||
CommonUtil.addFlashAlertMessages(
|
||||
request.getSession(), messageUtil.getMessage("security.auth.duplicate.login"));
|
||||
}
|
||||
|
||||
// 로그인 활성화 기록 생성
|
||||
loggedInUserSavePortIn.connect(
|
||||
LoggedInUserSaveCmd.builder()
|
||||
.loggedInUserId(
|
||||
LoggedInUserIdSaveCmd.builder()
|
||||
.appType(AppType.ADMIN)
|
||||
.id(authentication.getName())
|
||||
.build())
|
||||
.clientIP(CommonUtil.getClientIP(request))
|
||||
.lastLoggedInAt(LocalDateTime.now())
|
||||
.build());
|
||||
}
|
||||
}
|
||||
|
||||
@EventListener
|
||||
public void handleAuthenticationFailureEvent(AbstractAuthenticationFailureEvent event) {
|
||||
Exception e = event.getException();
|
||||
Authentication authentication = event.getAuthentication();
|
||||
log.warn("Unsuccessful authentication result: {}", authentication, e);
|
||||
}
|
||||
|
||||
/**
|
||||
* 사용자 로그인 여부 확인
|
||||
*/
|
||||
private boolean isAlreadyLoggedInSomewhere(String username, String currentIP) {
|
||||
LoggedInUserView loggedInUser =
|
||||
loggedInUserViewPortIn.connect(new LoggedInUserIdCmd(AppType.ADMIN, username));
|
||||
if (loggedInUser == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
LocalDateTime lastLoggedInAt = loggedInUser.getLastLoggedInAt();
|
||||
|
||||
return lastLoggedInAt.plusSeconds(sessionValidPeriodSeconds).isAfter(LocalDateTime.now())
|
||||
&& !currentIP.equals(loggedInUser.getClientIP());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package app.module.admin.config.application.security;
|
||||
|
||||
import app.module.core.config.adapters.web.security.domain.CorePrivilege;
|
||||
import app.module.core.config.adapters.web.security.domain.CoreRole;
|
||||
import app.module.core.usecase.admin.view.ports.AdminViewPortIn;
|
||||
import app.module.core.usecase.admin.view.ports.application.domain.AdminView;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Collection;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class AdminDetailsService implements UserDetailsService {
|
||||
|
||||
private final AdminViewPortIn adminViewPortIn;
|
||||
|
||||
@Value("${app.admin.password.validity.period.days}")
|
||||
private long passwordValidPeriodDays;
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
|
||||
AdminView adminUser =
|
||||
adminViewPortIn
|
||||
.connect(username)
|
||||
.orElseThrow(() -> new UsernameNotFoundException("Invalid username or password."));
|
||||
|
||||
boolean accountLocked = Optional.ofNullable(adminUser.getAccountLocked()).orElse(false);
|
||||
boolean accountDisabled = Optional.ofNullable(adminUser.getAccountDisabled()).orElse(false);
|
||||
|
||||
return new AdminUser(
|
||||
adminUser.getId(),
|
||||
adminUser.getPassword(),
|
||||
!accountDisabled,
|
||||
true,
|
||||
isCredentialsNonExpired(adminUser.getPasswordUpdatedAt()),
|
||||
!accountLocked,
|
||||
getAuthorities(adminUser.getRoles()),
|
||||
passwordValidPeriodDays - getDaysPassedFrom(adminUser.getPasswordUpdatedAt()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Authorities (Role + Privileges) 합성. Role 과 Privileges 는 1:N 매핑되지만, 이 메서드를 통해 동일한 depth 로 배열에
|
||||
* 담겨 반환된다. 즉, Privilege 는 또다른 종류의 Role 로 볼 수 있다.
|
||||
*
|
||||
* @param roles
|
||||
* @return authorities
|
||||
*/
|
||||
private Collection<? extends GrantedAuthority> getAuthorities(Collection<CoreRole> roles) {
|
||||
return Stream.concat(getRoles(roles), getPrivileges(roles))
|
||||
.map(SimpleGrantedAuthority::new)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
private Stream<String> getRoles(Collection<CoreRole> roles) {
|
||||
return roles.stream().map(CoreRole::getId);
|
||||
}
|
||||
|
||||
private Stream<String> getPrivileges(Collection<CoreRole> roles) {
|
||||
return roles.stream()
|
||||
.flatMap(roleOutput -> roleOutput.getPrivileges().stream())
|
||||
.map(CorePrivilege::getId);
|
||||
}
|
||||
|
||||
// 패스워드 만료 여부체크. 이 기능이 필요하지 않다면 항상 true 를 반환하도록 변경하면 된다.
|
||||
private boolean isCredentialsNonExpired(LocalDateTime passwordUpdatedAt) {
|
||||
// return passwordValidPeriodDays == -1
|
||||
// || getDaysPassedFrom(passwordUpdatedAt) <= passwordValidPeriodDays;
|
||||
return true;
|
||||
}
|
||||
|
||||
// 패스워드 만료일 정보를 반환. 이 기능이 필요하지 않다면 항상 0L 을 반환하도록 변경하면 된다.
|
||||
private long getDaysPassedFrom(LocalDateTime passwordUpdatedAt) {
|
||||
// return Duration.between(passwordUpdatedAt, LocalDateTime.now()).toDays();
|
||||
return 0L;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package app.module.admin.config.application.security;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
|
||||
import org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration;
|
||||
|
||||
@Configuration
|
||||
@EnableGlobalMethodSecurity(jsr250Enabled = true)
|
||||
public class AdminMethodSecurityConfig extends GlobalMethodSecurityConfiguration {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package app.module.admin.config.application.security;
|
||||
|
||||
import app.module.core.config.application.enums.PublicAccess;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import javax.sql.DataSource;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
|
||||
import org.springframework.context.ApplicationEventPublisher;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.authentication.AuthenticationEventPublisher;
|
||||
import org.springframework.security.authentication.DefaultAuthenticationEventPublisher;
|
||||
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
import org.springframework.security.core.session.SessionRegistry;
|
||||
import org.springframework.security.core.session.SessionRegistryImpl;
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
|
||||
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;
|
||||
import org.springframework.security.web.session.HttpSessionEventPublisher;
|
||||
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
|
||||
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
@RequiredArgsConstructor
|
||||
public class AdminSecurityConfig {
|
||||
|
||||
private final AdminDetailsService adminDetailsService;
|
||||
private final DataSource dataSource;
|
||||
private final BCryptPasswordEncoder passwordEncoder;
|
||||
@Value("${app.admin.session.maximum.num}")
|
||||
private Integer maxSessionNum;
|
||||
|
||||
@Bean
|
||||
public DaoAuthenticationProvider authenticationProvider() {
|
||||
DaoAuthenticationProvider auth = new DaoAuthenticationProvider();
|
||||
auth.setUserDetailsService(adminDetailsService);
|
||||
auth.setPasswordEncoder(passwordEncoder);
|
||||
return auth;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public PersistentTokenRepository persistentTokenRepository() {
|
||||
JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
|
||||
jdbcTokenRepository.setDataSource(dataSource);
|
||||
return jdbcTokenRepository;
|
||||
}
|
||||
|
||||
/**
|
||||
* 중복 로그인 방지를 위해 선언
|
||||
*/
|
||||
@Bean
|
||||
public SessionRegistry sessionRegistry() {
|
||||
return new SessionRegistryImpl();
|
||||
}
|
||||
|
||||
/**
|
||||
* 중복 로그인 방지를 위해 선언
|
||||
*/
|
||||
@Bean
|
||||
public ServletListenerRegistrationBean httpSessionEventPublisher() {
|
||||
return new ServletListenerRegistrationBean(new HttpSessionEventPublisher());
|
||||
}
|
||||
|
||||
/**
|
||||
* 인증 성공/실패 이벤트 수신을 위해 선언
|
||||
*/
|
||||
@Bean
|
||||
public AuthenticationEventPublisher authenticationEventPublisher(
|
||||
ApplicationEventPublisher applicationEventPublisher) {
|
||||
return new DefaultAuthenticationEventPublisher(applicationEventPublisher);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
||||
List<String> permitPaths =
|
||||
Arrays.stream(PublicAccess.values())
|
||||
.map(PublicAccess::getPath)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
http.authorizeHttpRequests(
|
||||
(auth) ->
|
||||
auth.requestMatchers(permitPaths.toArray(String[]::new))
|
||||
.permitAll()
|
||||
.anyRequest().hasAuthority("ADMIN_ACCESS"))
|
||||
.formLogin(formLogin -> formLogin.loginPage("/login"))
|
||||
.rememberMe(
|
||||
remMe ->
|
||||
remMe
|
||||
.tokenValiditySeconds(1209600)
|
||||
.userDetailsService(adminDetailsService)
|
||||
.tokenRepository(persistentTokenRepository()))
|
||||
.logout(
|
||||
logout ->
|
||||
logout
|
||||
.invalidateHttpSession(true)
|
||||
.clearAuthentication(true)
|
||||
.logoutRequestMatcher(new AntPathRequestMatcher("/logout")))
|
||||
.sessionManagement(
|
||||
session -> session.maximumSessions(maxSessionNum).maxSessionsPreventsLogin(false));
|
||||
|
||||
return http.build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package app.module.admin.config.application.security;
|
||||
|
||||
import java.util.Collection;
|
||||
import lombok.Getter;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.userdetails.User;
|
||||
|
||||
@Getter
|
||||
public class AdminUser extends User {
|
||||
|
||||
private long remainPasswordDays;
|
||||
|
||||
public AdminUser(
|
||||
String username,
|
||||
String password,
|
||||
boolean enabled,
|
||||
boolean accountNonExpired,
|
||||
boolean credentialsNonExpired,
|
||||
boolean accountNonLocked,
|
||||
Collection<? extends GrantedAuthority> authorities,
|
||||
long remainPasswordDays) {
|
||||
super(
|
||||
username,
|
||||
password,
|
||||
enabled,
|
||||
accountNonExpired,
|
||||
credentialsNonExpired,
|
||||
accountNonLocked,
|
||||
authorities);
|
||||
this.remainPasswordDays = remainPasswordDays;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package app.module.admin.config.application.util;
|
||||
|
||||
import app.module.core.config.adapters.web.interceptor.model.URITopTierVO;
|
||||
import java.util.List;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class AdminUtil {
|
||||
|
||||
public boolean shouldDisplaySubNodes(List<URITopTierVO> uriList) {
|
||||
boolean result = false;
|
||||
if (uriList != null && !uriList.isEmpty()) {
|
||||
for (URITopTierVO uri : uriList) {
|
||||
if (uri.getShowOnNavi()) {
|
||||
result = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package app.module.admin.usecase.admin.getAdmins.adapters.web;
|
||||
|
||||
import app.module.admin.usecase.admin.getAdmins.adapters.web.model.AdminListFilterVO;
|
||||
import app.module.core.config.application.util.ExcelUtil;
|
||||
import app.module.core.usecase.admin.getAdmins.ports.GetAdminsPortIn;
|
||||
import app.module.core.usecase.admin.getAdmins.ports.application.domain.GetAdmins;
|
||||
import app.module.core.usecase.admin.getAdmins.ports.application.domain.GetAdminsCmd;
|
||||
import app.module.core.usecase.admin.getAdmins.ports.application.domain.GetAdminsRole;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Collectors;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.apache.commons.collections4.CollectionUtils;
|
||||
import org.apache.poi.ss.usermodel.Row;
|
||||
import org.apache.poi.ss.usermodel.Sheet;
|
||||
import org.apache.poi.ss.usermodel.Workbook;
|
||||
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.web.PageableDefault;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.ModelAttribute;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
|
||||
@Controller
|
||||
@RequiredArgsConstructor
|
||||
class AdminExcelController {
|
||||
|
||||
private final GetAdminsPortIn getAdminsPortIn;
|
||||
private final ExcelUtil excelUtil;
|
||||
|
||||
@PostMapping(path = "/settings/admins/excel")
|
||||
void excelDownload(
|
||||
HttpServletResponse response,
|
||||
@PageableDefault(sort = "createdAt") Pageable pageable,
|
||||
@ModelAttribute("paramDto") AdminListFilterVO adminListFilterVO) {
|
||||
|
||||
Workbook wb = new XSSFWorkbook();
|
||||
Sheet sheet = wb.createSheet("예제 관리자 목록");
|
||||
|
||||
Page<GetAdmins> listOutput =
|
||||
getAdminsPortIn.connect(
|
||||
pageable,
|
||||
new GetAdminsCmd(
|
||||
adminListFilterVO.getSearchField(),
|
||||
adminListFilterVO.getSearchValue(),
|
||||
adminListFilterVO.getSearchRole()));
|
||||
|
||||
if (CollectionUtils.isNotEmpty(listOutput.getContent())) {
|
||||
// Header
|
||||
Row headerRow = sheet.createRow(sheet.getPhysicalNumberOfRows());
|
||||
excelUtil.createCells(headerRow, "번호", "이메일", "권한", "등록일", "최근 수정일");
|
||||
|
||||
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
|
||||
|
||||
listOutput
|
||||
.getContent()
|
||||
.forEach(
|
||||
item -> {
|
||||
Row row = sheet.createRow(sheet.getPhysicalNumberOfRows());
|
||||
excelUtil.createCells(
|
||||
row,
|
||||
item.getId(),
|
||||
item.getEmail(),
|
||||
item.getRoles().stream()
|
||||
.map(GetAdminsRole::getId)
|
||||
.collect(Collectors.joining(", ")),
|
||||
Optional.ofNullable(item.getCreatedAt())
|
||||
.map(localDateTime -> localDateTime.format(formatter))
|
||||
.orElse(""),
|
||||
Optional.ofNullable(item.getUpdatedAt())
|
||||
.map(localDateTime -> localDateTime.format(formatter))
|
||||
.orElse(""));
|
||||
});
|
||||
}
|
||||
|
||||
excelUtil.generateWithPassword(response, wb, "admin-list");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package app.module.admin.usecase.admin.getAdmins.adapters.web;
|
||||
|
||||
import app.module.admin.usecase.admin.getAdmins.adapters.web.model.AdminListFilterVO;
|
||||
import app.module.core.config.application.enums.AppType;
|
||||
import app.module.core.usecase.admin.getAdmins.ports.GetAdminsPortIn;
|
||||
import app.module.core.usecase.admin.getAdmins.ports.application.domain.GetAdmins;
|
||||
import app.module.core.usecase.admin.getAdmins.ports.application.domain.GetAdminsCmd;
|
||||
import app.module.core.usecase.role.list.ports.RoleListPortIn;
|
||||
import app.module.core.usecase.role.list.ports.application.domain.RoleElement;
|
||||
import app.module.core.usecase.uicode.list.ports.UICodeListPortIn;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.web.PageableDefault;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.ModelAttribute;
|
||||
|
||||
@Controller
|
||||
@RequiredArgsConstructor
|
||||
class AdminListController {
|
||||
|
||||
private final GetAdminsPortIn getAdminsPortIn;
|
||||
private final RoleListPortIn<RoleElement> roleListPortIn;
|
||||
private final UICodeListPortIn uiCodeListPortIn;
|
||||
|
||||
@GetMapping(path = "/settings/admins")
|
||||
String operate(
|
||||
Model model,
|
||||
@PageableDefault(sort = "createdAt") Pageable pageable,
|
||||
@ModelAttribute("listStatus") AdminListFilterVO adminListFilterVO) {
|
||||
|
||||
Page<GetAdmins> listOutput =
|
||||
getAdminsPortIn.connect(
|
||||
pageable,
|
||||
new GetAdminsCmd(
|
||||
adminListFilterVO.getSearchField(),
|
||||
adminListFilterVO.getSearchValue(),
|
||||
adminListFilterVO.getSearchRole()));
|
||||
|
||||
model.addAttribute("listOutput", listOutput);
|
||||
model.addAttribute("roles", roleListPortIn.connect(AppType.ADMIN));
|
||||
model.addAttribute("pageRows", uiCodeListPortIn.connect("code.pageable.rows"));
|
||||
|
||||
return "admin/adminList";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package app.module.admin.usecase.admin.getAdmins.adapters.web.model;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@AllArgsConstructor
|
||||
public class AdminListFilterVO {
|
||||
|
||||
private String searchField;
|
||||
private String searchValue;
|
||||
private String searchRole;
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package app.module.admin.usecase.admin.removeAdmins.adapters.web;
|
||||
|
||||
import app.module.core.config.application.util.MessageUtil;
|
||||
import app.module.core.usecase.admin.removeAdmin.ports.RemoveAdminPortIn;
|
||||
import java.util.List;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.apache.commons.collections4.CollectionUtils;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
|
||||
|
||||
@Controller
|
||||
@RequiredArgsConstructor
|
||||
class AdminRemoveController {
|
||||
|
||||
private final MessageUtil messageUtil;
|
||||
private final RemoveAdminPortIn removeAdminPortIn;
|
||||
|
||||
@PostMapping(path = "/settings/admins/delete")
|
||||
String operate(RedirectAttributes redirectAttributes, @RequestParam List<String> checkedIds) {
|
||||
|
||||
if (CollectionUtils.isNotEmpty(checkedIds)) {
|
||||
removeAdminPortIn.connect(checkedIds);
|
||||
redirectAttributes.addFlashAttribute(
|
||||
"operationMessage", messageUtil.getMessage("operation.settings.admin.removed"));
|
||||
}
|
||||
|
||||
return "redirect:/settings/admins";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package app.module.admin.usecase.admin.removeAdmins.adapters.web;
|
||||
|
||||
import app.module.admin.usecase.admin.removeAdmins.adapters.web.model.RemoveAdminsReqVO;
|
||||
import app.module.core.config.application.util.MessageUtil;
|
||||
import app.module.core.usecase.admin.removeAdmin.ports.RemoveAdminPortIn;
|
||||
import jakarta.validation.Valid;
|
||||
import java.util.List;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.apache.commons.collections4.CollectionUtils;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.validation.BindingResult;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
|
||||
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
class RemoveAdminsController {
|
||||
|
||||
private final RemoveAdminPortIn removeAdminPortIn;
|
||||
|
||||
@DeleteMapping(path = "/api/settings/admin/remove")
|
||||
ResponseEntity<?> operate(@Valid RemoveAdminsReqVO reqVO, BindingResult bindingResult) {
|
||||
if (bindingResult.hasErrors()) {
|
||||
return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY)
|
||||
.body(bindingResult.getFieldErrors());
|
||||
}
|
||||
|
||||
if (CollectionUtils.isNotEmpty(reqVO.getCheckedIds())) {
|
||||
removeAdminPortIn.connect(reqVO.getCheckedIds());
|
||||
}
|
||||
|
||||
return ResponseEntity.status(HttpStatus.OK).body(reqVO);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package app.module.admin.usecase.admin.removeAdmins.adapters.web.model;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@AllArgsConstructor
|
||||
@EqualsAndHashCode
|
||||
public class RemoveAdminsReqVO {
|
||||
List<String> checkedIds;
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package app.module.admin.usecase.admin.saveAdmin.adapters.web;
|
||||
|
||||
import app.module.admin.usecase.admin.saveAdmin.adapters.web.model.AdminCreateBindingVO;
|
||||
import app.module.core.config.application.enums.AppType;
|
||||
import app.module.core.usecase.role.list.ports.RoleListPortIn;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.ModelAttribute;
|
||||
|
||||
@Controller
|
||||
@RequiredArgsConstructor
|
||||
public class AdminCreateGetController {
|
||||
|
||||
private final RoleListPortIn roleListPortIn;
|
||||
|
||||
@GetMapping(path = "/settings/admins/create")
|
||||
String operate(Model model, @ModelAttribute("bindingVO") AdminCreateBindingVO bindingVO) {
|
||||
model.addAttribute("roles", roleListPortIn.connect(AppType.ADMIN));
|
||||
return "admin/adminCreateForm";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package app.module.admin.usecase.admin.saveAdmin.adapters.web;
|
||||
|
||||
import app.module.admin.usecase.admin.saveAdmin.adapters.web.model.AdminCreateBindingVO;
|
||||
import app.module.admin.usecase.admin.saveAdmin.adapters.web.validator.AdminCreateValidator;
|
||||
import app.module.core.config.application.enums.AppType;
|
||||
import app.module.core.config.application.util.MessageUtil;
|
||||
import app.module.core.usecase.admin.saveAdmin.ports.SaveAdminPortIn;
|
||||
import app.module.core.usecase.role.list.ports.RoleListPortIn;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.validation.BindingResult;
|
||||
import org.springframework.web.bind.annotation.ModelAttribute;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
|
||||
|
||||
@Controller
|
||||
@RequiredArgsConstructor
|
||||
public class AdminCreatePostController {
|
||||
|
||||
private final RoleListPortIn roleListPortIn;
|
||||
private final MessageUtil messageUtil;
|
||||
private final SaveAdminPortIn savePortIn;
|
||||
private final AdminCreateValidator adminCreateValidator;
|
||||
|
||||
@PostMapping(path = "/settings/admins/create")
|
||||
String operate(
|
||||
RedirectAttributes redirectAttributes,
|
||||
Model model,
|
||||
@Valid @ModelAttribute("bindingVO") AdminCreateBindingVO bindingVO,
|
||||
BindingResult bindingResult) {
|
||||
|
||||
adminCreateValidator.validate(bindingVO, bindingResult);
|
||||
if (bindingResult.hasErrors()) {
|
||||
model.addAttribute("roles", roleListPortIn.connect(AppType.ADMIN));
|
||||
return "admin/adminCreateForm";
|
||||
}
|
||||
|
||||
savePortIn.connect(
|
||||
bindingVO.getId(),
|
||||
bindingVO.getPassword(),
|
||||
bindingVO.getEmail(),
|
||||
bindingVO.getAccountDisabled(),
|
||||
bindingVO.getAccountLocked(),
|
||||
bindingVO.getRoleIds());
|
||||
|
||||
redirectAttributes.addFlashAttribute(
|
||||
"operationMessage",
|
||||
messageUtil.getMessage("operation.settings.admin.created", bindingVO.getId()));
|
||||
|
||||
return "redirect:/settings/admins";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package app.module.admin.usecase.admin.saveAdmin.adapters.web;
|
||||
|
||||
import app.module.admin.usecase.admin.getAdmins.adapters.web.model.AdminListFilterVO;
|
||||
import app.module.admin.usecase.admin.saveAdmin.adapters.web.model.AdminUpdateBindingVO;
|
||||
import app.module.core.config.adapters.web.security.domain.CoreRole;
|
||||
import app.module.core.config.application.component.ListPageableInfo;
|
||||
import app.module.core.config.application.enums.AppType;
|
||||
import app.module.core.config.application.util.MessageUtil;
|
||||
import app.module.core.usecase.admin.view.ports.AdminViewPortIn;
|
||||
import app.module.core.usecase.admin.view.ports.application.domain.AdminView;
|
||||
import app.module.core.usecase.role.list.ports.RoleListPortIn;
|
||||
import java.util.NoSuchElementException;
|
||||
import java.util.stream.Collectors;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.ModelAttribute;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
|
||||
@Controller
|
||||
@RequiredArgsConstructor
|
||||
class AdminUpdateGetController {
|
||||
|
||||
private final AdminViewPortIn adminViewPortIn;
|
||||
private final RoleListPortIn roleListPortIn;
|
||||
private final MessageUtil messageUtil;
|
||||
|
||||
@GetMapping(path = "/settings/admins/update/{adminId}")
|
||||
String operate(
|
||||
Model model,
|
||||
@PathVariable String adminId,
|
||||
@ModelAttribute("pageable") final ListPageableInfo pageable,
|
||||
@ModelAttribute("listStatus") AdminListFilterVO listStatus) {
|
||||
|
||||
AdminView output =
|
||||
adminViewPortIn
|
||||
.connect(adminId)
|
||||
.orElseThrow(
|
||||
() ->
|
||||
new NoSuchElementException(
|
||||
messageUtil.getMessage("exception.noSuchElement", adminId,
|
||||
"Admin ID")));
|
||||
|
||||
AdminUpdateBindingVO bindingVO =
|
||||
new AdminUpdateBindingVO(
|
||||
output.getCreatedBy(),
|
||||
output.getCreatedAt(),
|
||||
output.getUpdatedBy(),
|
||||
output.getUpdatedAt(),
|
||||
output.getId(),
|
||||
null,
|
||||
output.getEmail(),
|
||||
output.getPasswordUpdatedAt(),
|
||||
output.getAccountDisabled(),
|
||||
output.getLoginFailCnt(),
|
||||
output.getAccountLocked(),
|
||||
output.getRoles().stream().map(CoreRole::getId).collect(Collectors.toList()));
|
||||
|
||||
model.addAttribute("bindingVO", bindingVO);
|
||||
model.addAttribute("roles", roleListPortIn.connect(AppType.ADMIN));
|
||||
|
||||
return "admin/adminUpdateForm";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package app.module.admin.usecase.admin.saveAdmin.adapters.web;
|
||||
|
||||
import app.module.admin.usecase.admin.saveAdmin.adapters.web.model.AdminUpdateBindingVO;
|
||||
import app.module.admin.usecase.admin.saveAdmin.adapters.web.validator.AdminUpdateValidator;
|
||||
import app.module.core.config.application.enums.AppType;
|
||||
import app.module.core.config.application.util.MessageUtil;
|
||||
import app.module.core.usecase.admin.saveAdmin.ports.SaveAdminPortIn;
|
||||
import app.module.core.usecase.role.list.ports.RoleListPortIn;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.validation.BindingResult;
|
||||
import org.springframework.web.bind.annotation.ModelAttribute;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
|
||||
|
||||
@Controller
|
||||
@RequiredArgsConstructor
|
||||
class AdminUpdatePostController {
|
||||
|
||||
private final AdminUpdateValidator adminUpdateValidator;
|
||||
private final RoleListPortIn roleListPortIn;
|
||||
private final SaveAdminPortIn saveAdminPortIn;
|
||||
private final MessageUtil messageUtil;
|
||||
|
||||
@PostMapping(path = "/settings/admins/update/{id}")
|
||||
String operate(
|
||||
Model model,
|
||||
RedirectAttributes redirectAttributes,
|
||||
@Valid @ModelAttribute("bindingVO") AdminUpdateBindingVO bindingVO,
|
||||
BindingResult bindingResult) {
|
||||
|
||||
adminUpdateValidator.validate(bindingVO, bindingResult);
|
||||
if (bindingResult.hasErrors()) {
|
||||
model.addAttribute("roles", roleListPortIn.connect(AppType.ADMIN));
|
||||
return "admin/adminUpdateForm";
|
||||
}
|
||||
|
||||
saveAdminPortIn.connect(
|
||||
bindingVO.getId(),
|
||||
bindingVO.getUpdatePassword(),
|
||||
bindingVO.getEmail(),
|
||||
bindingVO.getAccountDisabled(),
|
||||
bindingVO.getAccountLocked(),
|
||||
bindingVO.getRoleIds());
|
||||
|
||||
redirectAttributes.addFlashAttribute(
|
||||
"operationMessage",
|
||||
messageUtil.getMessage("operation.settings.admin.updated", bindingVO.getId()));
|
||||
|
||||
return "redirect:/settings/admins";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package app.module.admin.usecase.admin.saveAdmin.adapters.web.model;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Pattern;
|
||||
import java.util.List;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@AllArgsConstructor
|
||||
public class AdminCreateBindingVO {
|
||||
|
||||
private String id;
|
||||
private String password;
|
||||
|
||||
@NotBlank(message = "{valid.common.required}")
|
||||
@Pattern(
|
||||
regexp =
|
||||
"^[\\w!#$%&’*+/=?`{|}~^-]+(?:\\.[\\w!#$%&’*+/=?`{|}~^-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,6}$",
|
||||
message = "{valid.common.email.wrong}")
|
||||
private String email;
|
||||
|
||||
private Boolean accountDisabled;
|
||||
private Boolean accountLocked;
|
||||
private List<String> roleIds;
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package app.module.admin.usecase.admin.saveAdmin.adapters.web.model;
|
||||
|
||||
import app.module.core.config.application.component.AuditOutput;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Pattern;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@AllArgsConstructor
|
||||
public class AdminUpdateBindingVO implements AuditOutput {
|
||||
|
||||
private final String createdBy;
|
||||
|
||||
private final LocalDateTime createdAt;
|
||||
|
||||
private final String updatedBy;
|
||||
|
||||
private final LocalDateTime updatedAt;
|
||||
|
||||
private String id;
|
||||
private String updatePassword;
|
||||
|
||||
@NotBlank(message = "{valid.common.required}")
|
||||
@Pattern(
|
||||
regexp =
|
||||
"^[\\w!#$%&’*+/=?`{|}~^-]+(?:\\.[\\w!#$%&’*+/=?`{|}~^-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,6}$",
|
||||
message = "{valid.common.email.wrong}")
|
||||
private String email;
|
||||
|
||||
private LocalDateTime passwordUpdatedAt;
|
||||
private Boolean accountDisabled;
|
||||
private Integer loginFailCnt;
|
||||
private Boolean accountLocked;
|
||||
private List<String> roleIds;
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package app.module.admin.usecase.admin.saveAdmin.adapters.web.validator;
|
||||
|
||||
import app.module.admin.usecase.admin.saveAdmin.adapters.web.model.AdminCreateBindingVO;
|
||||
import java.util.Optional;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.validation.Errors;
|
||||
import org.springframework.validation.ValidationUtils;
|
||||
import org.springframework.validation.Validator;
|
||||
|
||||
@Component
|
||||
public class AdminCreateValidator implements Validator {
|
||||
|
||||
private final String PASSWORD_REGEX = "^((?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%_\\-])\\S{6,15})$";
|
||||
|
||||
@Override
|
||||
public boolean supports(Class<?> clazz) {
|
||||
return AdminCreateBindingVO.class.equals(clazz);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void validate(Object target, Errors errors) {
|
||||
AdminCreateBindingVO vo = (AdminCreateBindingVO) target;
|
||||
|
||||
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "valid.common.required");
|
||||
|
||||
Optional.ofNullable(vo.getPassword())
|
||||
.filter(password -> !password.matches(PASSWORD_REGEX))
|
||||
.ifPresent(password -> errors.rejectValue("password", "valid.common.password.wrong"));
|
||||
|
||||
Optional.ofNullable(vo.getRoleIds())
|
||||
.filter(ids -> ids.size() < 1)
|
||||
.ifPresent(
|
||||
ids ->
|
||||
errors.rejectValue(
|
||||
"roleIds", "valid.common.required.size.min", new Object[]{1}, ""));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package app.module.admin.usecase.admin.saveAdmin.adapters.web.validator;
|
||||
|
||||
import app.module.admin.usecase.admin.saveAdmin.adapters.web.model.AdminUpdateBindingVO;
|
||||
import java.util.Optional;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.validation.Errors;
|
||||
import org.springframework.validation.Validator;
|
||||
|
||||
@Component
|
||||
public class AdminUpdateValidator implements Validator {
|
||||
|
||||
private final String PASSWORD_REGEX = "^((?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%_\\-])\\S{6,15})$";
|
||||
|
||||
@Override
|
||||
public boolean supports(Class<?> clazz) {
|
||||
return AdminUpdateBindingVO.class.equals(clazz);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void validate(Object target, Errors errors) {
|
||||
AdminUpdateBindingVO vo = (AdminUpdateBindingVO) target;
|
||||
|
||||
Optional.ofNullable(vo.getRoleIds())
|
||||
.filter(ids -> ids.size() < 1)
|
||||
.ifPresent(
|
||||
ids ->
|
||||
errors.rejectValue(
|
||||
"roleIds", "valid.common.required.size.min", new Object[]{1}, ""));
|
||||
|
||||
Optional.ofNullable(vo.getUpdatePassword())
|
||||
.filter(s -> !s.trim().isEmpty() && !s.matches(PASSWORD_REGEX))
|
||||
.ifPresent(s -> errors.rejectValue("updatePassword", "valid.common.password.wrong"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package app.module.admin.usecase.article.createArticle.adapters.web;
|
||||
|
||||
import app.module.admin.usecase.article.createArticle.adapters.web.model.CreateArticleReqVO;
|
||||
import app.module.admin.usecase.article.createArticle.adapters.web.validator.CreateArticleValidator;
|
||||
import app.module.core.usecase.article.createArticle.ports.CreateArticlePortIn;
|
||||
import app.module.core.usecase.article.createArticle.ports.application.domain.CreateArticle;
|
||||
import app.module.core.usecase.article.createArticle.ports.application.domain.CreateArticleCmd;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.validation.BindingResult;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
class CreateArticleController {
|
||||
|
||||
private final CreateArticlePortIn createArticlePortIn;
|
||||
private final CreateArticleValidator createArticleValidator;
|
||||
|
||||
@PostMapping(path = "/api/board/articles/create")
|
||||
ResponseEntity<?> operate(@Valid CreateArticleReqVO reqVO, BindingResult bindingResult) {
|
||||
|
||||
createArticleValidator.validate(reqVO, bindingResult);
|
||||
|
||||
if (bindingResult.hasErrors()) {
|
||||
return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY)
|
||||
.body(bindingResult.getFieldErrors());
|
||||
}
|
||||
|
||||
CreateArticle article =
|
||||
createArticlePortIn
|
||||
.operate(
|
||||
new CreateArticleCmd(
|
||||
reqVO.getTitle(),
|
||||
reqVO.getContent(),
|
||||
reqVO.getVisible(),
|
||||
reqVO.getStartDate(),
|
||||
reqVO.getEndDate(),
|
||||
reqVO.getFileMappingId()))
|
||||
.orElseThrow();
|
||||
|
||||
return ResponseEntity.status(HttpStatus.OK).body(article);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package app.module.admin.usecase.article.createArticle.adapters.web.model;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import org.apache.commons.text.StringEscapeUtils;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@AllArgsConstructor
|
||||
@EqualsAndHashCode
|
||||
public class CreateArticleReqVO {
|
||||
|
||||
@NotBlank(message = "{valid.common.required}")
|
||||
private String title;
|
||||
|
||||
@NotBlank(message = "{valid.common.required}")
|
||||
private String content;
|
||||
|
||||
@NotNull(message = "{valid.common.required}")
|
||||
private Boolean visible;
|
||||
|
||||
@NotNull(message = "{valid.common.required}")
|
||||
private LocalDateTime startDate;
|
||||
|
||||
@NotNull(message = "{valid.common.required}")
|
||||
private LocalDateTime endDate;
|
||||
|
||||
private List<String> fileMappingId;
|
||||
|
||||
public String getTitle() {
|
||||
return StringEscapeUtils.escapeHtml4(title);
|
||||
}
|
||||
|
||||
public String getContent() {
|
||||
return StringEscapeUtils.escapeHtml4(content);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package app.module.admin.usecase.article.createArticle.adapters.web.validator;
|
||||
|
||||
import app.module.admin.usecase.article.createArticle.adapters.web.model.CreateArticleReqVO;
|
||||
import app.module.core.config.application.util.MessageUtil;
|
||||
import java.time.LocalDateTime;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.validation.Errors;
|
||||
import org.springframework.validation.Validator;
|
||||
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class CreateArticleValidator implements Validator {
|
||||
|
||||
private final MessageUtil messageUtil;
|
||||
|
||||
@Override
|
||||
public boolean supports(Class<?> clazz) {
|
||||
return CreateArticleReqVO.class.equals(clazz);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void validate(Object target, Errors errors) {
|
||||
CreateArticleReqVO vo = (CreateArticleReqVO) target;
|
||||
|
||||
LocalDateTime startDate = vo.getStartDate();
|
||||
LocalDateTime endDate = vo.getEndDate();
|
||||
|
||||
// 게시일 날짜 체크
|
||||
if (startDate == null) {
|
||||
errors.rejectValue(
|
||||
"startDate", "valid.common.required",
|
||||
messageUtil.getMessage("valid.common.required"));
|
||||
}
|
||||
|
||||
if (endDate == null) {
|
||||
errors.rejectValue(
|
||||
"endDate", "valid.common.required",
|
||||
messageUtil.getMessage("valid.common.required"));
|
||||
}
|
||||
|
||||
if (startDate != null && endDate != null) {
|
||||
if (!startDate.isBefore(endDate)) {
|
||||
errors.rejectValue(
|
||||
"startDate",
|
||||
"valid.common.date.invalid",
|
||||
messageUtil.getMessage("valid.common.date.invalid"));
|
||||
errors.rejectValue(
|
||||
"endDate",
|
||||
"valid.common.date.invalid",
|
||||
messageUtil.getMessage("valid.common.date.invalid"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package app.module.admin.usecase.article.getArticle.adapters.web;
|
||||
|
||||
import app.module.core.usecase.article.getArticle.ports.GetArticlePortIn;
|
||||
import app.module.core.usecase.article.getArticle.ports.application.domain.GetArticleCmd;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
class GetArticleController {
|
||||
|
||||
private final GetArticlePortIn getArticlePortIn;
|
||||
|
||||
@GetMapping(path = "/api/board/articles/{id}")
|
||||
ResponseEntity<?> operate(@PathVariable Long id) {
|
||||
return ResponseEntity.status(HttpStatus.OK)
|
||||
.body(getArticlePortIn.operate(new GetArticleCmd(id)).orElseThrow());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package app.module.admin.usecase.article.getArticleCreateUI.adapters.web;
|
||||
|
||||
import app.module.admin.usecase.article.getArticleCreateUI.adapters.web.model.CreateArticleUIReqVO;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.ModelAttribute;
|
||||
|
||||
@Controller
|
||||
@RequiredArgsConstructor
|
||||
class CreateArticleUIController {
|
||||
|
||||
@GetMapping(path = "/board/articles/create")
|
||||
String operate(
|
||||
Model model,
|
||||
@ModelAttribute("reqVO") CreateArticleUIReqVO reqVO) {
|
||||
|
||||
return "board/articles/create";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package app.module.admin.usecase.article.getArticleCreateUI.adapters.web.model;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@AllArgsConstructor
|
||||
@EqualsAndHashCode
|
||||
public class CreateArticleUIReqVO {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package app.module.admin.usecase.article.getArticleUpdateUI.adapters.web;
|
||||
|
||||
import app.module.admin.usecase.article.getArticleUpdateUI.adapters.web.model.GetArticleUpdateUIReqVO;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.ModelAttribute;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
|
||||
@Controller
|
||||
@RequiredArgsConstructor
|
||||
class GetArticleUpdateUIController {
|
||||
|
||||
@GetMapping(path = "/board/articles/{id}")
|
||||
String operate(
|
||||
Model model,
|
||||
@PathVariable @ModelAttribute("id") Long id,
|
||||
@ModelAttribute("reqVO") GetArticleUpdateUIReqVO reqVO) {
|
||||
|
||||
return "board/articles/{id}";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package app.module.admin.usecase.article.getArticleUpdateUI.adapters.web.model;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@AllArgsConstructor
|
||||
@EqualsAndHashCode
|
||||
public class GetArticleUpdateUIReqVO {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package app.module.admin.usecase.article.getArticles.adapters.web;
|
||||
|
||||
import app.module.admin.usecase.article.getArticles.adapters.web.model.GetArticlesReqVO;
|
||||
import app.module.core.usecase.article.getArticles.ports.GetArticlesPortIn;
|
||||
import app.module.core.usecase.article.getArticles.ports.application.domain.GetArticles;
|
||||
import app.module.core.usecase.article.getArticles.ports.application.domain.GetArticlesCmd;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.web.PageableDefault;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
class GetArticlesController {
|
||||
|
||||
private final GetArticlesPortIn getArticlesPortIn;
|
||||
|
||||
@GetMapping(path = "/api/board/articles")
|
||||
ResponseEntity<?> operate(@PageableDefault Pageable pageable, GetArticlesReqVO reqVO) {
|
||||
Page<GetArticles> articles =
|
||||
getArticlesPortIn.operate(
|
||||
pageable,
|
||||
new GetArticlesCmd(
|
||||
reqVO.getSearchField(), reqVO.getSearchValue(), reqVO.getSearchOpen()));
|
||||
|
||||
return ResponseEntity.status(HttpStatus.OK).body(articles);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package app.module.admin.usecase.article.getArticles.adapters.web.model;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@AllArgsConstructor
|
||||
@EqualsAndHashCode
|
||||
public class GetArticlesReqVO {
|
||||
|
||||
private String searchField;
|
||||
private String searchValue;
|
||||
private String searchOpen;
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
package app.module.admin.usecase.article.getArticlesExcel.adapters.web;
|
||||
|
||||
import app.module.admin.usecase.article.getArticlesExcel.adapters.web.model.GetArticlesExcelReqVO;
|
||||
import app.module.core.usecase.article.getArticles.ports.GetArticlesPortIn;
|
||||
import app.module.core.usecase.article.getArticles.ports.application.domain.GetArticles;
|
||||
import app.module.core.usecase.article.getArticles.ports.application.domain.GetArticlesCmd;
|
||||
import app.module.core.usecase.excel.createCell.ports.CreateCellPortIn;
|
||||
import app.module.core.usecase.excel.createCell.ports.application.model.CellConfig;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.Calendar;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.apache.poi.ss.usermodel.CellType;
|
||||
import org.apache.poi.ss.usermodel.HorizontalAlignment;
|
||||
import org.apache.poi.ss.util.CellRangeAddress;
|
||||
import org.apache.poi.xssf.streaming.SXSSFSheet;
|
||||
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.web.PageableDefault;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
class GetArticlesExcelController {
|
||||
|
||||
private final GetArticlesPortIn getArticlesPortIn;
|
||||
private final CreateCellPortIn createCellPortIn;
|
||||
|
||||
@GetMapping(path = "/api/board/articles/excel")
|
||||
void operate(
|
||||
@PageableDefault(size = Integer.MAX_VALUE) Pageable pageable,
|
||||
GetArticlesExcelReqVO reqVO,
|
||||
HttpServletResponse response)
|
||||
throws IOException {
|
||||
|
||||
String title = "예제 게시판 목록";
|
||||
|
||||
Page<GetArticles> output =
|
||||
getArticlesPortIn.operate(
|
||||
pageable,
|
||||
new GetArticlesCmd(
|
||||
reqVO.getSearchField(), reqVO.getSearchValue(), reqVO.getSearchOpen()));
|
||||
|
||||
if (!output.getContent().isEmpty()) {
|
||||
|
||||
// 1000 개 로우가 넘으면 디스크에 기록한다.
|
||||
try (SXSSFWorkbook wb = new SXSSFWorkbook(1000)) {
|
||||
SXSSFSheet sheet = wb.createSheet(title);
|
||||
sheet.trackAllColumnsForAutoSizing();
|
||||
|
||||
AtomicInteger colNo = new AtomicInteger(0);
|
||||
|
||||
// 상단 Header 생성 및 필터 적용
|
||||
createCellPortIn.operate(
|
||||
// 상단 Header 의 Row 목록 - 2개 이상이면 병합이 가능해진다.
|
||||
List.of(sheet.createRow(sheet.getPhysicalNumberOfRows())),
|
||||
// 상단 Header Row 를 구성하는 col 목록
|
||||
List.of(
|
||||
new CellConfig(
|
||||
0,
|
||||
colNo.getAndIncrement(),
|
||||
null,
|
||||
CellType.STRING,
|
||||
"제목",
|
||||
createCellPortIn.getDefaultHeaderStyle(wb, HorizontalAlignment.CENTER),
|
||||
null),
|
||||
new CellConfig(
|
||||
0,
|
||||
colNo.getAndIncrement(),
|
||||
null,
|
||||
CellType.STRING,
|
||||
"공개여부",
|
||||
createCellPortIn.getDefaultHeaderStyle(wb, HorizontalAlignment.CENTER),
|
||||
null),
|
||||
new CellConfig(
|
||||
0,
|
||||
colNo.getAndIncrement(),
|
||||
null,
|
||||
CellType.STRING,
|
||||
"게시일",
|
||||
createCellPortIn.getDefaultHeaderStyle(wb, HorizontalAlignment.CENTER),
|
||||
null),
|
||||
new CellConfig(
|
||||
0,
|
||||
colNo.getAndIncrement(),
|
||||
null,
|
||||
CellType.STRING,
|
||||
"종료일",
|
||||
createCellPortIn.getDefaultHeaderStyle(wb, HorizontalAlignment.CENTER),
|
||||
null),
|
||||
new CellConfig(
|
||||
0,
|
||||
colNo.getAndIncrement(),
|
||||
null,
|
||||
CellType.STRING,
|
||||
"최근 수정자",
|
||||
createCellPortIn.getDefaultHeaderStyle(wb, HorizontalAlignment.CENTER),
|
||||
null),
|
||||
new CellConfig(
|
||||
0,
|
||||
colNo.getAndIncrement(),
|
||||
null,
|
||||
CellType.STRING,
|
||||
"최근 수정일",
|
||||
createCellPortIn.getDefaultHeaderStyle(wb, HorizontalAlignment.CENTER),
|
||||
null)));
|
||||
sheet.setAutoFilter(new CellRangeAddress(0, 0, 0, colNo.get() - 1));
|
||||
|
||||
// 본문 데이터
|
||||
output
|
||||
.getContent()
|
||||
.forEach(
|
||||
item -> {
|
||||
colNo.set(0);
|
||||
createCellPortIn.operate(
|
||||
List.of(sheet.createRow(sheet.getPhysicalNumberOfRows())),
|
||||
List.of(
|
||||
new CellConfig(
|
||||
0,
|
||||
colNo.getAndIncrement(),
|
||||
null,
|
||||
CellType.STRING,
|
||||
item.getTitle(),
|
||||
createCellPortIn.getDefaultDataStyle(wb,
|
||||
HorizontalAlignment.CENTER),
|
||||
null),
|
||||
new CellConfig(
|
||||
0,
|
||||
colNo.getAndIncrement(),
|
||||
null,
|
||||
CellType.STRING,
|
||||
item.getVisible() ? "Y" : "N",
|
||||
createCellPortIn.getDefaultDataStyle(wb,
|
||||
HorizontalAlignment.CENTER),
|
||||
null),
|
||||
new CellConfig(
|
||||
0,
|
||||
colNo.getAndIncrement(),
|
||||
null,
|
||||
CellType.STRING,
|
||||
item.getStartDate()
|
||||
.format(
|
||||
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")),
|
||||
createCellPortIn.getDefaultDataStyle(wb,
|
||||
HorizontalAlignment.CENTER),
|
||||
null),
|
||||
new CellConfig(
|
||||
0,
|
||||
colNo.getAndIncrement(),
|
||||
null,
|
||||
CellType.STRING,
|
||||
item.getEndDate()
|
||||
.format(
|
||||
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")),
|
||||
createCellPortIn.getDefaultDataStyle(wb,
|
||||
HorizontalAlignment.CENTER),
|
||||
null),
|
||||
new CellConfig(
|
||||
0,
|
||||
colNo.getAndIncrement(),
|
||||
null,
|
||||
CellType.STRING,
|
||||
item.getUpdatedBy(),
|
||||
createCellPortIn.getDefaultDataStyle(wb,
|
||||
HorizontalAlignment.CENTER),
|
||||
null),
|
||||
new CellConfig(
|
||||
0,
|
||||
colNo.getAndIncrement(),
|
||||
null,
|
||||
CellType.STRING,
|
||||
item.getUpdatedAt()
|
||||
.format(
|
||||
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")),
|
||||
createCellPortIn.getDefaultDataStyle(wb,
|
||||
HorizontalAlignment.CENTER),
|
||||
null)));
|
||||
});
|
||||
|
||||
// 한글 파일명 처리를 위해 URLEncoder 필요
|
||||
String filename =
|
||||
URLEncoder.encode(
|
||||
String.format(
|
||||
"%s-%s.xlsx",
|
||||
title,
|
||||
new SimpleDateFormat("yyyyMMdd").format(
|
||||
Calendar.getInstance().getTime())),
|
||||
StandardCharsets.UTF_8);
|
||||
|
||||
response.setHeader(
|
||||
HttpHeaders.CONTENT_DISPOSITION,
|
||||
String.format("attachment; filename=\"%s\"", filename));
|
||||
|
||||
wb.write(response.getOutputStream());
|
||||
|
||||
// 디스크에 기록한 임시 파일 제거
|
||||
wb.dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package app.module.admin.usecase.article.getArticlesExcel.adapters.web.model;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@AllArgsConstructor
|
||||
@EqualsAndHashCode
|
||||
public class GetArticlesExcelReqVO {
|
||||
|
||||
private String searchField;
|
||||
private String searchValue;
|
||||
private String searchOpen;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package app.module.admin.usecase.article.getArticlesUI.adapters.web;
|
||||
|
||||
import app.module.admin.usecase.article.getArticlesUI.adapters.web.model.GetArticlesUIReqVO;
|
||||
import app.module.core.usecase.uicode.list.ports.UICodeListPortIn;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.ModelAttribute;
|
||||
|
||||
@Controller
|
||||
@RequiredArgsConstructor
|
||||
class GetArticlesUIController {
|
||||
|
||||
private final UICodeListPortIn uiCodeListPortIn;
|
||||
|
||||
@GetMapping(path = "/board/articles")
|
||||
String operate(@ModelAttribute("reqVO") GetArticlesUIReqVO reqVO, Model model) {
|
||||
|
||||
model.addAttribute("pageRows", uiCodeListPortIn.connect("code.pageable.rows"));
|
||||
|
||||
return "board/articles";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package app.module.admin.usecase.article.getArticlesUI.adapters.web.model;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import org.thymeleaf.util.StringUtils;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@AllArgsConstructor
|
||||
@EqualsAndHashCode
|
||||
public class GetArticlesUIReqVO {
|
||||
|
||||
private Integer page;
|
||||
private String sort;
|
||||
private Integer size;
|
||||
private String searchField;
|
||||
private String searchValue;
|
||||
private String searchOpen;
|
||||
|
||||
public Integer getPage() {
|
||||
// 요청 페이지 넘버 - 초기값 `0`
|
||||
return page != null ? page : 0;
|
||||
}
|
||||
|
||||
public String getSort() {
|
||||
// 정렬 값 - 초기값 `orderNo 내림차순`
|
||||
return StringUtils.isEmpty(sort) ? "orderNo,DESC" : sort;
|
||||
}
|
||||
|
||||
public Integer getSize() {
|
||||
// 페이지 당 아이템 수 - 초기값 `10`
|
||||
return size != null ? size : 10;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package app.module.admin.usecase.article.removeArticles.adapters.web;
|
||||
|
||||
import app.module.admin.usecase.article.removeArticles.adapters.web.model.RemoveArticlesReqVO;
|
||||
import app.module.core.usecase.article.removeArticles.ports.RemoveArticlesPortIn;
|
||||
import app.module.core.usecase.article.removeArticles.ports.application.domain.RemoveArticlesCmd;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.validation.BindingResult;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
class RemoveArticlesController {
|
||||
|
||||
private final RemoveArticlesPortIn removeArticlesPortIn;
|
||||
|
||||
@DeleteMapping(path = "/api/board/articles/remove")
|
||||
ResponseEntity<?> operate(@Valid RemoveArticlesReqVO reqVO, BindingResult bindingResult) {
|
||||
if (bindingResult.hasErrors()) {
|
||||
return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY)
|
||||
.body(bindingResult.getFieldErrors());
|
||||
}
|
||||
|
||||
removeArticlesPortIn.operate(new RemoveArticlesCmd(reqVO.getSelectIds()));
|
||||
|
||||
return ResponseEntity.status(HttpStatus.OK).body(reqVO);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package app.module.admin.usecase.article.removeArticles.adapters.web.model;
|
||||
|
||||
import java.util.Set;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@AllArgsConstructor
|
||||
@EqualsAndHashCode
|
||||
public class RemoveArticlesReqVO {
|
||||
|
||||
private Set<Long> selectIds;
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package app.module.admin.usecase.article.sortArticles.adapters.web;
|
||||
|
||||
import app.module.admin.usecase.article.sortArticles.adapters.web.model.SortArticlesReqVO;
|
||||
import app.module.core.usecase.article.sortArticles.ports.SortArticlesPortIn;
|
||||
import app.module.core.usecase.article.sortArticles.ports.application.domain.SortArticlesCmd;
|
||||
import jakarta.validation.Valid;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.validation.BindingResult;
|
||||
import org.springframework.web.bind.annotation.PatchMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
class SortArticlesController {
|
||||
|
||||
private final SortArticlesPortIn sortArticlesPortIn;
|
||||
|
||||
@PatchMapping(path = "/api/board/articles/sort")
|
||||
ResponseEntity<?> operate(
|
||||
@Valid @RequestBody List<SortArticlesReqVO> reqVO, BindingResult bindingResult) {
|
||||
if (bindingResult.hasErrors()) {
|
||||
return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).body(bindingResult);
|
||||
}
|
||||
|
||||
sortArticlesPortIn.operate(
|
||||
reqVO.stream()
|
||||
.map(
|
||||
sortArticlesReqVO ->
|
||||
new SortArticlesCmd(sortArticlesReqVO.getId(),
|
||||
sortArticlesReqVO.getOrderNo()))
|
||||
.collect(Collectors.toList()));
|
||||
|
||||
return ResponseEntity.status(HttpStatus.OK).body(reqVO);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package app.module.admin.usecase.article.sortArticles.adapters.web.model;
|
||||
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@EqualsAndHashCode
|
||||
public class SortArticlesReqVO {
|
||||
|
||||
@NotNull(message = "{valid.common.required}")
|
||||
private Long id;
|
||||
|
||||
@NotNull(message = "{valid.common.required}")
|
||||
private Integer orderNo;
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package app.module.admin.usecase.article.updateArticle.adapters.web;
|
||||
|
||||
import app.module.admin.usecase.article.updateArticle.adapters.web.model.UpdateArticleReqVO;
|
||||
import app.module.admin.usecase.article.updateArticle.adapters.web.validator.UpdateArticleValidator;
|
||||
import app.module.core.usecase.article.updateArticle.ports.UpdateArticlePortIn;
|
||||
import app.module.core.usecase.article.updateArticle.ports.application.domain.UpdateArticleCmd;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.validation.BindingResult;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
class UpdateArticleController {
|
||||
|
||||
private final UpdateArticlePortIn updateArticlePortIn;
|
||||
private final UpdateArticleValidator updateArticleValidator;
|
||||
|
||||
@PutMapping(path = "/api/board/articles/update")
|
||||
ResponseEntity<?> operate(@Valid UpdateArticleReqVO reqVO, BindingResult bindingResult) {
|
||||
|
||||
updateArticleValidator.validate(reqVO, bindingResult);
|
||||
|
||||
if (bindingResult.hasErrors()) {
|
||||
return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY)
|
||||
.body(bindingResult.getFieldErrors());
|
||||
}
|
||||
|
||||
updateArticlePortIn.operate(
|
||||
new UpdateArticleCmd(
|
||||
reqVO.getId(),
|
||||
reqVO.getTitle(),
|
||||
reqVO.getContent(),
|
||||
reqVO.getVisible(),
|
||||
reqVO.getOrderNo(),
|
||||
reqVO.getStartDate(),
|
||||
reqVO.getEndDate(),
|
||||
reqVO.getFileMappingId()));
|
||||
|
||||
return ResponseEntity.status(HttpStatus.OK).body(reqVO);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package app.module.admin.usecase.article.updateArticle.adapters.web.model;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
import org.apache.commons.text.StringEscapeUtils;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@EqualsAndHashCode
|
||||
public class UpdateArticleReqVO {
|
||||
|
||||
@NotNull(message = "{valid.common.required}")
|
||||
private Long id;
|
||||
|
||||
@NotBlank(message = "{valid.common.required}")
|
||||
private String title;
|
||||
|
||||
@NotBlank(message = "{valid.common.required}")
|
||||
private String content;
|
||||
|
||||
@NotNull(message = "{valid.common.required}")
|
||||
private Boolean visible;
|
||||
|
||||
@NotNull(message = "{valid.common.required}")
|
||||
private Integer orderNo;
|
||||
|
||||
@NotNull(message = "{valid.common.required}")
|
||||
private LocalDateTime startDate;
|
||||
|
||||
@NotNull(message = "{valid.common.required}")
|
||||
private LocalDateTime endDate;
|
||||
|
||||
private List<String> fileMappingId;
|
||||
|
||||
public String getTitle() {
|
||||
return StringEscapeUtils.escapeHtml4(title);
|
||||
}
|
||||
|
||||
public String getContent() {
|
||||
return StringEscapeUtils.escapeHtml4(content);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package app.module.admin.usecase.article.updateArticle.adapters.web.validator;
|
||||
|
||||
import app.module.admin.usecase.article.updateArticle.adapters.web.model.UpdateArticleReqVO;
|
||||
import app.module.core.config.application.util.MessageUtil;
|
||||
import java.time.LocalDateTime;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.validation.Errors;
|
||||
import org.springframework.validation.Validator;
|
||||
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class UpdateArticleValidator implements Validator {
|
||||
|
||||
private final MessageUtil messageUtil;
|
||||
|
||||
@Override
|
||||
public boolean supports(Class<?> clazz) {
|
||||
return UpdateArticleReqVO.class.equals(clazz);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void validate(Object target, Errors errors) {
|
||||
UpdateArticleReqVO vo = (UpdateArticleReqVO) target;
|
||||
|
||||
LocalDateTime startDate = vo.getStartDate();
|
||||
LocalDateTime endDate = vo.getEndDate();
|
||||
|
||||
// 게시일 날짜 체크
|
||||
if (startDate == null) {
|
||||
errors.rejectValue(
|
||||
"startDate", "valid.common.required",
|
||||
messageUtil.getMessage("valid.common.required"));
|
||||
}
|
||||
|
||||
if (endDate == null) {
|
||||
errors.rejectValue(
|
||||
"endDate", "valid.common.required",
|
||||
messageUtil.getMessage("valid.common.required"));
|
||||
}
|
||||
|
||||
if (startDate != null && endDate != null) {
|
||||
if (!startDate.isBefore(endDate)) {
|
||||
errors.rejectValue(
|
||||
"startDate",
|
||||
"valid.common.date.invalid",
|
||||
messageUtil.getMessage("valid.common.date.invalid"));
|
||||
errors.rejectValue(
|
||||
"endDate",
|
||||
"valid.common.date.invalid",
|
||||
messageUtil.getMessage("valid.common.date.invalid"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package app.module.admin.usecase.editor.adapters.web;
|
||||
|
||||
import app.module.core.config.application.enums.FileUploadType;
|
||||
import app.module.core.usecase.file.saveToStorage.ports.SaveToStoragePortIn;
|
||||
import app.module.core.usecase.file.saveToStorage.ports.application.domain.SaveToStorage;
|
||||
import app.module.core.usecase.file.url.application.port.in.FileUrlPortIn;
|
||||
import java.io.IOException;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
@Controller
|
||||
@RequiredArgsConstructor
|
||||
public class EditorImageUploadController {
|
||||
|
||||
private final SaveToStoragePortIn saveToStoragePortIn;
|
||||
private final FileUrlPortIn fileUrlPortIn;
|
||||
|
||||
@PostMapping(path = "/api/editorImage/upload")
|
||||
ResponseEntity<?> editorImageUpload(MultipartFile editorImage) throws IOException {
|
||||
SaveToStorage saveToStorage =
|
||||
saveToStoragePortIn.operate(FileUploadType.EDITOR_IMAGE, editorImage).orElseThrow();
|
||||
|
||||
return ResponseEntity.status(HttpStatus.OK)
|
||||
.body(
|
||||
fileUrlPortIn.getInline(
|
||||
saveToStorage.getType().getFileStorageType(),
|
||||
saveToStorage.getPath(),
|
||||
saveToStorage.getName()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package app.module.admin.usecase.email.send.adapters.web;
|
||||
|
||||
import app.module.admin.usecase.email.send.adapters.web.model.EmailVO;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.ModelAttribute;
|
||||
|
||||
@Controller
|
||||
@RequiredArgsConstructor
|
||||
public class EmailController {
|
||||
|
||||
@GetMapping(path = "/addons/email/form")
|
||||
public String emailForm(@ModelAttribute("formDto") EmailVO emailVO) {
|
||||
return "email/emailForm";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package app.module.admin.usecase.email.send.adapters.web;
|
||||
|
||||
import app.module.admin.usecase.email.send.adapters.web.model.EmailVO;
|
||||
import app.module.admin.usecase.email.send.ports.EmailSendPortIn;
|
||||
import app.module.admin.usecase.email.send.ports.application.domain.Email;
|
||||
import app.module.core.config.application.util.MessageUtil;
|
||||
import jakarta.mail.MessagingException;
|
||||
import jakarta.validation.Valid;
|
||||
import java.io.IOException;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.validation.BindingResult;
|
||||
import org.springframework.web.bind.annotation.ModelAttribute;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
|
||||
|
||||
@Controller
|
||||
@RequiredArgsConstructor
|
||||
public class EmailSendController {
|
||||
|
||||
private final EmailSendPortIn emailSendPortIn;
|
||||
private final MessageUtil messageUtil;
|
||||
|
||||
@PostMapping(path = "/addons/email/form")
|
||||
public String sendEmail(
|
||||
RedirectAttributes redirectAttributes,
|
||||
@Valid @ModelAttribute("formDto") EmailVO emailVO,
|
||||
BindingResult bindingResult)
|
||||
throws IOException, MessagingException {
|
||||
|
||||
if (bindingResult.hasErrors()) {
|
||||
return "email/emailForm";
|
||||
}
|
||||
|
||||
emailSendPortIn.connect(
|
||||
new Email(
|
||||
emailVO.getTo(),
|
||||
null,
|
||||
emailVO.getSubject(),
|
||||
emailVO.getMsgType(),
|
||||
emailVO.getMessage(),
|
||||
emailVO.getMultipartFiles()));
|
||||
|
||||
redirectAttributes.addFlashAttribute(
|
||||
"operationMessage",
|
||||
messageUtil.getMessage("operation.common.email.to", emailVO.getTo()));
|
||||
|
||||
return "redirect:/addons/email/form";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package app.module.admin.usecase.email.send.adapters.web.model;
|
||||
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import java.util.List;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
public class EmailVO {
|
||||
|
||||
@NotEmpty(message = "{valid.common.required}")
|
||||
private String to;
|
||||
|
||||
@NotEmpty(message = "{valid.common.required}")
|
||||
private String subject;
|
||||
|
||||
private String msgType;
|
||||
|
||||
@NotEmpty(message = "{valid.common.required}")
|
||||
private String message;
|
||||
|
||||
private List<MultipartFile> multipartFiles;
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package app.module.admin.usecase.email.send.ports;
|
||||
|
||||
import app.module.admin.usecase.email.send.ports.application.domain.Email;
|
||||
import jakarta.mail.MessagingException;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
|
||||
public interface EmailSendPortIn {
|
||||
|
||||
void connect(Email email) throws MessagingException, UnsupportedEncodingException;
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package app.module.admin.usecase.email.send.ports.application;
|
||||
|
||||
import app.module.admin.usecase.email.send.ports.EmailSendPortIn;
|
||||
import app.module.admin.usecase.email.send.ports.application.domain.Email;
|
||||
import jakarta.mail.MessagingException;
|
||||
import jakarta.mail.internet.MimeMessage;
|
||||
import jakarta.mail.internet.MimeUtility;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.util.Objects;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.mail.javamail.JavaMailSender;
|
||||
import org.springframework.mail.javamail.MimeMessageHelper;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
class EmailSendService implements EmailSendPortIn {
|
||||
|
||||
private final JavaMailSender mailSender;
|
||||
|
||||
@Value("${spring.mail.username}")
|
||||
private String mailUsername;
|
||||
|
||||
@Override
|
||||
public void connect(Email email) throws MessagingException, UnsupportedEncodingException {
|
||||
MimeMessage mimeMessage = mailSender.createMimeMessage();
|
||||
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
|
||||
mimeMessageHelper.setTo(email.getTo());
|
||||
mimeMessageHelper.setFrom(email.getFrom() != null ? email.getFrom() : mailUsername);
|
||||
mimeMessageHelper.setSubject(MimeUtility.encodeText(email.getSubject(), "UTF-8", "B"));
|
||||
mimeMessageHelper.setText(email.getMessage(), "HTML".equals(email.getMsgType()));
|
||||
|
||||
if (email.getMultipartFiles() != null) {
|
||||
for (MultipartFile multipartFile : email.getMultipartFiles()) {
|
||||
if (!multipartFile.isEmpty()) {
|
||||
mimeMessageHelper.addAttachment(
|
||||
Objects.requireNonNull(multipartFile.getOriginalFilename()), multipartFile);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
mailSender.send(mimeMessage);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package app.module.admin.usecase.email.send.ports.application.domain;
|
||||
|
||||
import java.util.List;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class Email {
|
||||
|
||||
private String to;
|
||||
private String from;
|
||||
private String subject;
|
||||
private String msgType;
|
||||
private String message;
|
||||
private List<MultipartFile> multipartFiles;
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package app.module.admin.usecase.home.adapters.web;
|
||||
|
||||
import app.module.core.usecase.admin.view.ports.AdminViewPortIn;
|
||||
import java.security.Principal;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
|
||||
@Controller
|
||||
@RequestMapping("/")
|
||||
@RequiredArgsConstructor
|
||||
public class HomeController {
|
||||
|
||||
private final AdminViewPortIn adminViewPortIn;
|
||||
|
||||
@GetMapping
|
||||
public String home(Principal principal, Model model) {
|
||||
adminViewPortIn
|
||||
.connect(principal.getName())
|
||||
.ifPresent(
|
||||
loginUser -> {
|
||||
model.addAttribute("loginUser", loginUser);
|
||||
model.addAttribute("loginUserRoles", loginUser.getRoles());
|
||||
});
|
||||
|
||||
return "home";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package app.module.admin.usecase.loggedinuser.remove.adapters.persistence;
|
||||
|
||||
import app.module.admin.usecase.loggedinuser.remove.adapters.persistence.model.LoggedInUserRemoveParam;
|
||||
import app.module.admin.usecase.loggedinuser.remove.ports.LoggedInUserRemovePortOut;
|
||||
import app.module.admin.usecase.loggedinuser.remove.ports.application.domain.LoggedInUserRemoveCmd;
|
||||
import app.module.core.config.application.util.CommonUtil;
|
||||
import java.time.LocalDateTime;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@Repository
|
||||
@RequiredArgsConstructor
|
||||
public class LoggedInUserRemoveDao implements LoggedInUserRemovePortOut {
|
||||
|
||||
private final LoggedInUserRemoveMapper mapper;
|
||||
|
||||
@Override
|
||||
public void connect(LoggedInUserRemoveCmd removeCommand) {
|
||||
mapper.deleteByCompositeId(new LoggedInUserRemoveParam(
|
||||
removeCommand.getAppType(),
|
||||
removeCommand.getId(),
|
||||
LocalDateTime.now(),
|
||||
CommonUtil.getLoginUsername(),
|
||||
LocalDateTime.now(),
|
||||
CommonUtil.getLoginUsername(),
|
||||
false
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package app.module.admin.usecase.loggedinuser.remove.adapters.persistence;
|
||||
|
||||
|
||||
import app.module.admin.usecase.loggedinuser.remove.adapters.persistence.model.LoggedInUserRemoveParam;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
|
||||
@Mapper
|
||||
public interface LoggedInUserRemoveMapper {
|
||||
void deleteByCompositeId(LoggedInUserRemoveParam param);
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package app.module.admin.usecase.loggedinuser.remove.adapters.persistence.model;
|
||||
|
||||
import app.module.core.config.application.enums.AppType;
|
||||
import java.time.LocalDateTime;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@AllArgsConstructor
|
||||
public class LoggedInUserRemoveParam {
|
||||
private AppType appType;
|
||||
private String id;
|
||||
private LocalDateTime updatedAt;
|
||||
private String updatedBy;
|
||||
private LocalDateTime deletedAt;
|
||||
private String deletedBy;
|
||||
private Boolean isDeleted;
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package app.module.admin.usecase.loggedinuser.remove.ports;
|
||||
|
||||
import app.module.admin.usecase.loggedinuser.remove.ports.application.domain.LoggedInUserRemoveCmd;
|
||||
|
||||
public interface LoggedInUserRemovePortIn {
|
||||
|
||||
void connect(LoggedInUserRemoveCmd loggedInUserId);
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package app.module.admin.usecase.loggedinuser.remove.ports;
|
||||
|
||||
import app.module.admin.usecase.loggedinuser.remove.ports.application.domain.LoggedInUserRemoveCmd;
|
||||
|
||||
public interface LoggedInUserRemovePortOut {
|
||||
|
||||
void connect(LoggedInUserRemoveCmd removeCommand);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package app.module.admin.usecase.loggedinuser.remove.ports.application;
|
||||
|
||||
import app.module.admin.usecase.loggedinuser.remove.ports.LoggedInUserRemovePortIn;
|
||||
import app.module.admin.usecase.loggedinuser.remove.ports.LoggedInUserRemovePortOut;
|
||||
import app.module.admin.usecase.loggedinuser.remove.ports.application.domain.LoggedInUserRemoveCmd;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class LoggedInUserRemoveService implements LoggedInUserRemovePortIn {
|
||||
|
||||
private final LoggedInUserRemovePortOut portOut;
|
||||
|
||||
@Override
|
||||
public void connect(LoggedInUserRemoveCmd removeCommand) {
|
||||
portOut.connect(removeCommand);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package app.module.admin.usecase.loggedinuser.remove.ports.application.domain;
|
||||
|
||||
import app.module.core.config.application.enums.AppType;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class LoggedInUserRemoveCmd {
|
||||
private AppType appType;
|
||||
private String id;
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package app.module.admin.usecase.loggedinuser.save.adapter.persistence;
|
||||
|
||||
import app.module.admin.usecase.loggedinuser.save.ports.LoggedInUserSavePortOut;
|
||||
import app.module.admin.usecase.loggedinuser.save.ports.application.domain.LoggedInUserSaveCmd;
|
||||
import app.module.admin.usecase.loggedinuser.view.adapters.persistence.LoggedInUserViewMapper;
|
||||
import app.module.admin.usecase.loggedinuser.view.adapters.persistence.model.LoggedInUserDto;
|
||||
import app.module.core.config.adapters.persistence.entity.LoggedInUser;
|
||||
import java.util.Optional;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@Repository
|
||||
@RequiredArgsConstructor
|
||||
public class LoggedInUserSaveDao implements LoggedInUserSavePortOut {
|
||||
|
||||
private final LoggedInUserSaveMapper mapper;
|
||||
private final LoggedInUserViewMapper viewMapper;
|
||||
|
||||
@Override
|
||||
public void connect(LoggedInUserSaveCmd saveCommand) {
|
||||
|
||||
Optional<LoggedInUserDto> existedLoggedInUser =
|
||||
viewMapper.findByCompositeKey(
|
||||
saveCommand.getLoggedInUserId().getAppType(),
|
||||
saveCommand.getLoggedInUserId().getId());
|
||||
|
||||
LoggedInUser loggedInUser = new LoggedInUser(
|
||||
saveCommand.getLoggedInUserId().getAppType(),
|
||||
saveCommand.getLoggedInUserId().getId(),
|
||||
saveCommand.getClientIP(),
|
||||
saveCommand.getLastLoggedInAt()
|
||||
);
|
||||
|
||||
if (existedLoggedInUser.isPresent()) {
|
||||
mapper.update(loggedInUser);
|
||||
} else {
|
||||
mapper.insert(loggedInUser);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package app.module.admin.usecase.loggedinuser.save.adapter.persistence;
|
||||
|
||||
import app.module.core.config.adapters.persistence.entity.LoggedInUser;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
|
||||
@Mapper
|
||||
public interface LoggedInUserSaveMapper {
|
||||
void insert(LoggedInUser loggedInUser);
|
||||
void update(LoggedInUser loggedInUser);
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package app.module.admin.usecase.loggedinuser.save.ports;
|
||||
|
||||
import app.module.admin.usecase.loggedinuser.save.ports.application.domain.LoggedInUserSaveCmd;
|
||||
|
||||
public interface LoggedInUserSavePortIn {
|
||||
|
||||
void connect(LoggedInUserSaveCmd loggedInUserSaveCmd);
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package app.module.admin.usecase.loggedinuser.save.ports;
|
||||
|
||||
import app.module.admin.usecase.loggedinuser.save.ports.application.domain.LoggedInUserSaveCmd;
|
||||
|
||||
public interface LoggedInUserSavePortOut {
|
||||
|
||||
void connect(LoggedInUserSaveCmd loggedInUser);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package app.module.admin.usecase.loggedinuser.save.ports.application;
|
||||
|
||||
import app.module.admin.usecase.loggedinuser.save.ports.LoggedInUserSavePortIn;
|
||||
import app.module.admin.usecase.loggedinuser.save.ports.LoggedInUserSavePortOut;
|
||||
import app.module.admin.usecase.loggedinuser.save.ports.application.domain.LoggedInUserSaveCmd;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class LoggedInUserSaveService implements LoggedInUserSavePortIn {
|
||||
|
||||
private final LoggedInUserSavePortOut portOut;
|
||||
|
||||
@Override
|
||||
public void connect(LoggedInUserSaveCmd loggedInUserSaveCmd) {
|
||||
portOut.connect(loggedInUserSaveCmd);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package app.module.admin.usecase.loggedinuser.save.ports.application.domain;
|
||||
|
||||
import app.module.core.config.application.enums.AppType;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class LoggedInUserIdSaveCmd {
|
||||
private AppType appType;
|
||||
private String id;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
package app.module.admin.usecase.loggedinuser.save.ports.application.domain;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
@Builder
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class LoggedInUserSaveCmd {
|
||||
private LoggedInUserIdSaveCmd loggedInUserId;
|
||||
private String clientIP;
|
||||
private LocalDateTime lastLoggedInAt;
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package app.module.admin.usecase.loggedinuser.view.adapters.persistence;
|
||||
|
||||
import app.module.admin.usecase.loggedinuser.view.adapters.persistence.model.LoggedInUserDto;
|
||||
import app.module.admin.usecase.loggedinuser.view.ports.LoggedInUserViewPortOut;
|
||||
import app.module.admin.usecase.loggedinuser.view.ports.application.domain.LoggedInUserIdCmd;
|
||||
import app.module.admin.usecase.loggedinuser.view.ports.application.domain.LoggedInUserView;
|
||||
import java.util.Optional;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@Repository
|
||||
@RequiredArgsConstructor
|
||||
public class LoggedInUserViewDao implements LoggedInUserViewPortOut {
|
||||
|
||||
private final LoggedInUserViewMapper mapper;
|
||||
|
||||
@Override
|
||||
public LoggedInUserView connect(LoggedInUserIdCmd userCommand) {
|
||||
return mapper.findByCompositeKey(userCommand.getAppType(), userCommand.getId())
|
||||
.map(d -> new LoggedInUserView(
|
||||
new LoggedInUserIdCmd(d.getAppType(), d.getId()),
|
||||
d.getClientIP(),
|
||||
d.getLastLoggedInAt()
|
||||
)).orElse(null);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package app.module.admin.usecase.loggedinuser.view.adapters.persistence;
|
||||
|
||||
import app.module.admin.usecase.loggedinuser.view.adapters.persistence.model.LoggedInUserDto;
|
||||
import app.module.core.config.application.enums.AppType;
|
||||
import java.util.Optional;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
|
||||
@Mapper
|
||||
public interface LoggedInUserViewMapper {
|
||||
Optional<LoggedInUserDto> findByCompositeKey(AppType appType, String id);
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package app.module.admin.usecase.loggedinuser.view.adapters.persistence.model;
|
||||
|
||||
import app.module.core.config.application.enums.AppType;
|
||||
import java.time.LocalDateTime;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@AllArgsConstructor
|
||||
public class LoggedInUserDto {
|
||||
private AppType appType;
|
||||
private String id;
|
||||
private String clientIP;
|
||||
private LocalDateTime lastLoggedInAt;
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package app.module.admin.usecase.loggedinuser.view.ports;
|
||||
|
||||
import app.module.admin.usecase.loggedinuser.view.ports.application.domain.LoggedInUserIdCmd;
|
||||
import app.module.admin.usecase.loggedinuser.view.ports.application.domain.LoggedInUserView;
|
||||
|
||||
public interface LoggedInUserViewPortIn {
|
||||
|
||||
LoggedInUserView connect(LoggedInUserIdCmd userCommand);
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package app.module.admin.usecase.loggedinuser.view.ports;
|
||||
|
||||
import app.module.admin.usecase.loggedinuser.view.ports.application.domain.LoggedInUserIdCmd;
|
||||
import app.module.admin.usecase.loggedinuser.view.ports.application.domain.LoggedInUserView;
|
||||
|
||||
public interface LoggedInUserViewPortOut {
|
||||
|
||||
LoggedInUserView connect(LoggedInUserIdCmd userCommand);
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package app.module.admin.usecase.loggedinuser.view.ports.application;
|
||||
|
||||
import app.module.admin.usecase.loggedinuser.view.ports.LoggedInUserViewPortIn;
|
||||
import app.module.admin.usecase.loggedinuser.view.ports.LoggedInUserViewPortOut;
|
||||
import app.module.admin.usecase.loggedinuser.view.ports.application.domain.LoggedInUserIdCmd;
|
||||
import app.module.admin.usecase.loggedinuser.view.ports.application.domain.LoggedInUserView;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class LoggedInUserViewService implements LoggedInUserViewPortIn {
|
||||
|
||||
private final LoggedInUserViewPortOut portOut;
|
||||
|
||||
@Override
|
||||
public LoggedInUserView connect(LoggedInUserIdCmd userCommand) {
|
||||
return portOut.connect(userCommand);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package app.module.admin.usecase.loggedinuser.view.ports.application.domain;
|
||||
|
||||
import app.module.core.config.application.enums.AppType;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@Builder
|
||||
@AllArgsConstructor
|
||||
public class LoggedInUserIdCmd {
|
||||
private AppType appType;
|
||||
private String id;
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package app.module.admin.usecase.loggedinuser.view.ports.application.domain;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@AllArgsConstructor
|
||||
public class LoggedInUserView {
|
||||
private LoggedInUserIdCmd loggedInUserId;
|
||||
private String clientIP;
|
||||
private LocalDateTime lastLoggedInAt;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package app.module.admin.usecase.login.adapters.web;
|
||||
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
|
||||
@Controller
|
||||
public class LoginController {
|
||||
|
||||
@GetMapping("/login")
|
||||
public String login() {
|
||||
return "security/login";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package app.module.admin.usecase.operationlog.list.adapters.web;
|
||||
|
||||
import app.module.admin.usecase.operationlog.list.adapters.web.model.OperationLogListFilterVO;
|
||||
import app.module.core.usecase.operationlog.list.application.domain.OperationLogElement;
|
||||
import app.module.core.usecase.operationlog.list.application.domain.OperationLogListFilterCommand;
|
||||
import app.module.core.usecase.operationlog.list.application.port.in.OperationLogListPortIn;
|
||||
import app.module.core.usecase.uicode.list.ports.UICodeListPortIn;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.domain.Sort.Direction;
|
||||
import org.springframework.data.web.PageableDefault;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.ModelAttribute;
|
||||
|
||||
@Controller
|
||||
@RequiredArgsConstructor
|
||||
public class OperationLogListController {
|
||||
|
||||
private final OperationLogListPortIn operationLogListPortIn;
|
||||
private final UICodeListPortIn uiCodeListPortIn;
|
||||
|
||||
@GetMapping("/analysis/operationlog")
|
||||
String operate(
|
||||
Model model,
|
||||
@PageableDefault(sort = "createdAt", direction = Direction.DESC) Pageable pageable,
|
||||
@ModelAttribute("paramDto") OperationLogListFilterVO statusVO) {
|
||||
|
||||
Page<OperationLogElement> listOutput =
|
||||
operationLogListPortIn.connect(
|
||||
pageable,
|
||||
new OperationLogListFilterCommand(
|
||||
statusVO.getSearchField(),
|
||||
statusVO.getSearchValue(),
|
||||
statusVO.getSearchAppType(),
|
||||
statusVO.getSearchOperationType()));
|
||||
|
||||
model.addAttribute("listOutput", listOutput);
|
||||
model.addAttribute("pageRows", uiCodeListPortIn.connect("code.pageable.rows"));
|
||||
|
||||
return "operationLog/operationLogList";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package app.module.admin.usecase.operationlog.list.adapters.web;
|
||||
|
||||
import app.module.admin.usecase.operationlog.list.adapters.web.model.OperationLogListFilterVO;
|
||||
import app.module.core.config.application.util.ExcelUtil;
|
||||
import app.module.core.usecase.operationlog.list.application.domain.OperationLogElement;
|
||||
import app.module.core.usecase.operationlog.list.application.domain.OperationLogListFilterCommand;
|
||||
import app.module.core.usecase.operationlog.list.application.port.in.OperationLogListPortIn;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.Optional;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.apache.commons.collections4.CollectionUtils;
|
||||
import org.apache.poi.ss.usermodel.Row;
|
||||
import org.apache.poi.ss.usermodel.Sheet;
|
||||
import org.apache.poi.ss.usermodel.Workbook;
|
||||
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.domain.Sort.Direction;
|
||||
import org.springframework.data.web.PageableDefault;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.ModelAttribute;
|
||||
|
||||
@Controller
|
||||
@RequiredArgsConstructor
|
||||
public class OperationLogListExcelController {
|
||||
|
||||
private final ExcelUtil excelUtil;
|
||||
private final OperationLogListPortIn operationLogListPortIn;
|
||||
|
||||
@GetMapping("/analysis/operationlog/excel")
|
||||
public void operate(
|
||||
HttpServletResponse response,
|
||||
@PageableDefault(sort = "createdAt", direction = Direction.DESC) Pageable pageable,
|
||||
@ModelAttribute("paramDto") OperationLogListFilterVO statusVO) {
|
||||
Workbook wb = new XSSFWorkbook();
|
||||
Sheet sheet = wb.createSheet("수행로그 목록");
|
||||
|
||||
Page<OperationLogElement> listOutput =
|
||||
operationLogListPortIn.connect(
|
||||
pageable,
|
||||
new OperationLogListFilterCommand(
|
||||
statusVO.getSearchField(),
|
||||
statusVO.getSearchValue(),
|
||||
statusVO.getSearchAppType(),
|
||||
statusVO.getSearchOperationType()));
|
||||
|
||||
if (CollectionUtils.isNotEmpty(listOutput.getContent())) {
|
||||
// Header
|
||||
Row headerRow = sheet.createRow(sheet.getPhysicalNumberOfRows());
|
||||
excelUtil.createCells(
|
||||
headerRow, "로그 ID", "App Type", "Operation Type", "IP", "수행일", "수행자", "피수행자",
|
||||
"수행 내용");
|
||||
|
||||
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
|
||||
|
||||
listOutput
|
||||
.getContent()
|
||||
.forEach(
|
||||
item -> {
|
||||
Row row = sheet.createRow(sheet.getPhysicalNumberOfRows());
|
||||
|
||||
excelUtil.createCells(
|
||||
row,
|
||||
item.getId(),
|
||||
item.getAppType().name(),
|
||||
item.getOperationLogType().name(),
|
||||
item.getIp(),
|
||||
Optional.ofNullable(item.getCreatedAt())
|
||||
.map(localDateTime -> localDateTime.format(formatter))
|
||||
.orElse(""),
|
||||
item.getCreatedBy(),
|
||||
item.getTargetId(),
|
||||
item.getTaskDesc());
|
||||
});
|
||||
}
|
||||
|
||||
excelUtil.generateWithPassword(response, wb, "operation-logs");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package app.module.admin.usecase.operationlog.list.adapters.web.model;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@AllArgsConstructor
|
||||
public class OperationLogListFilterVO {
|
||||
|
||||
private String searchField;
|
||||
private String searchValue;
|
||||
private String searchAppType;
|
||||
private String searchOperationType;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package app.module.admin.usecase.privileges.index.adapters.web;
|
||||
|
||||
import app.module.core.config.application.enums.AppType;
|
||||
import groovy.util.logging.Slf4j;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
|
||||
@Controller
|
||||
@RequiredArgsConstructor
|
||||
@RequestMapping("/settings/adminPrivilege")
|
||||
@Slf4j
|
||||
class PrivilegeIndexController {
|
||||
|
||||
@GetMapping
|
||||
String intro(Model model) {
|
||||
model.addAttribute("appType", AppType.ADMIN);
|
||||
return "privilege/privilegeList";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package app.module.admin.usecase.privileges.list.adapters.web;
|
||||
|
||||
import app.module.admin.usecase.privileges.list.adapters.web.model.PrivilegeElementVO;
|
||||
import app.module.core.config.adapters.web.rest.response.RestResponse;
|
||||
import app.module.core.config.application.enums.AppType;
|
||||
import app.module.core.usecase.privilege.list.ports.PrivilegeListPortIn;
|
||||
import app.module.core.usecase.privilege.list.ports.application.domain.PrivilegeElement;
|
||||
import java.util.stream.Collectors;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
class PrivilegeListRestController {
|
||||
|
||||
private final PrivilegeListPortIn<PrivilegeElement> listPortIn;
|
||||
|
||||
@GetMapping("/api/adminPrivilege/get/recursiveItems")
|
||||
ResponseEntity<?> operate() {
|
||||
return ResponseEntity.status(HttpStatus.OK)
|
||||
.body(
|
||||
RestResponse.<PrivilegeElementVO>builder()
|
||||
.items(
|
||||
listPortIn.connect(AppType.ADMIN).stream()
|
||||
.map(
|
||||
p ->
|
||||
new PrivilegeElementVO(
|
||||
p.getCreatedBy(),
|
||||
p.getCreatedAt(),
|
||||
p.getUpdatedBy(),
|
||||
p.getUpdatedAt(),
|
||||
p.getId(),
|
||||
p.getDescription(),
|
||||
p.getOrderNo()))
|
||||
.collect(Collectors.toList()))
|
||||
.build());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package app.module.admin.usecase.privileges.list.adapters.web.model;
|
||||
|
||||
import app.module.core.config.application.converter.CustomLocalDateTimeSerializer;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
|
||||
import java.time.LocalDateTime;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@AllArgsConstructor
|
||||
public class PrivilegeElementVO {
|
||||
|
||||
private final String createdBy;
|
||||
|
||||
@JsonSerialize(using = CustomLocalDateTimeSerializer.class)
|
||||
@JsonDeserialize(using = LocalDateTimeDeserializer.class)
|
||||
private final LocalDateTime createdAt;
|
||||
|
||||
private final String updatedBy;
|
||||
|
||||
@JsonSerialize(using = CustomLocalDateTimeSerializer.class)
|
||||
@JsonDeserialize(using = LocalDateTimeDeserializer.class)
|
||||
private final LocalDateTime updatedAt;
|
||||
|
||||
private final String id;
|
||||
private final String description;
|
||||
private final Integer orderNo;
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user