diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..784f24d --- /dev/null +++ b/.editorconfig @@ -0,0 +1,26 @@ +root = true + +[*] +# [encoding-utf8] +charset = utf-8 +end_of_line = lf + +# [newline-eof] +insert_final_newline = true + +[*.bat] +end_of_line = crlf + +[*.java] +# [indentation-tab] +indent_style = tab + +# [4-spaces-tab] +indent_size = 4 +tab_width = 4 + +# [no-trailing-spaces] +trim_trailing_whitespace = true + +[line-length-120] +max_line_length = 120 \ No newline at end of file diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..8bdaa74 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,7 @@ +*.png binary +*.jpg binary +*.jpeg binary +*.gif binary +*.bat text merge=union eol=crlf +* text=auto eol=lf +*.java text eol=lf diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 0000000..6b950dc --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,126 @@ +name: 'People Here Dev Build' + +on: + workflow_call: + inputs: + environment: + type: string + required: true + COMMIT_MESSAGE: + type: string + required: true + API_SERVER: + required: true + type: string + STAGE: + required: true + type: string + FORCE_REBUILD: + required: false + type: boolean + outputs: + APP_VERSION: + value: ${{ jobs.build.outputs.APP_VERSION }} + CACHE_KEY: + value: ${{ jobs.build.outputs.CACHE_KEY }} + +env: + STAGE: ${{ inputs.STAGE }} + API_SERVER: ${{ inputs.API_SERVER}} + CACHE_KEY: ${{ github.ref }}-${{ inputs.environment }}-${{ github.sha }} + +jobs: + build: + name: Build & Test + environment: ${{ inputs.environment }} + runs-on: ubuntu-latest + outputs: + APP_VERSION: ${{ steps.app-version.outputs.APP_VERSION }} + CACHE_KEY: ${{ env.CACHE_KEY }} + steps: + - uses: actions/checkout@v4 + + - name: Start + run: | + echo "\ + ___ __ __ __ + /\_ \ /\ \ /\ \ /\ \ + _____ __ ___ _____ \//\ \ __ \ \ \___ __ _ __ __ \ \ \ \ \ \ + /\ '__`\ /'__`\ / __`\ /\ '__`\ \ \ \ /'__`\ \ \ _ `\ /'__`\ /\`'__\ /'__`\ \ \ \ \ \ \ + \ \ \L\ \/\ __/ /\ \L\ \\ \ \L\ \ \_\ \_ /\ __/ \ \ \ \ \ /\ __/ \ \ \/ /\ __/ \ \_\ \ \_\ + \ \ ,__/\ \____\\ \____/ \ \ ,__/ /\____\\ \____\ \ \_\ \_\\ \____\ \ \_\ \ \____\ \/\_\ \/\_\ + \ \ \/ \/____/ \/___/ \ \ \/ \/____/ \/____/ \/_/\/_/ \/____/ \/_/ \/____/ \/_/ \/_/ + \ \_\ \ \_\ + \/_/ \/_/" + shell: bash + + - name: 버전 세팅 + id: app-version + run: | + BUILD_DATE=$(TZ=Asia/Seoul date +'%Y-%m-%d-%H-%M') + + case ${BRANCH_NAME} in + "main"|"staging"|"develop") + APP_VERSION="${STAGE:0:1}-${BUILD_DATE}" + ;; + "feature/"*) + ISSUE_NAME=$(echo "${BRANCH_NAME}" | sed -n 's/.*\(PH-[0-9]*\).*/\1/p') + APP_VERSION="${ISSUE_NAME}-${BUILD_DATE}" + ;; + *) + APP_VERSION="${STAGE}-${{ github.run_id }}" + ;; + esac + + echo "APP_VERSION=${APP_VERSION}" | tee -a $GITHUB_ENV >> $GITHUB_OUTPUT + echo "BRANCH_NAME=${BRANCH_NAME}" >> $GITHUB_OUTPUT + shell: bash + env: + BRANCH_NAME: ${{ github.ref_name }} + STAGE: ${{ env.STAGE }} + + - name: 캐시 재사용 체크 + uses: actions/cache/restore@v4 + if: inputs.FORCE_REBUILD != true + id: artifact-cache-restore + with: + path: | + .build/jar/*.jar + key: ${{ env.CACHE_KEY }} + + - name: 버전정보 캐시정보 출력 + run: | + echo "# 앱 버전 APP_VERSION [ ${{ env.APP_VERSION }} ]" + if [ "${{ steps.artifact-cache-restore.outputs.cache-hit }}" == "true" ]; then + echo "### 캐시 ✅ (key: ${{ env.CACHE_KEY }})" >> $GITHUB_STEP_SUMMARY + else + echo "### 캐시 없음 ❎ (key: ${{ env.CACHE_KEY }})" >> $GITHUB_STEP_SUMMARY + fi + echo "" >> $GITHUB_STEP_SUMMARY + echo "" >> $GITHUB_STEP_SUMMARY + + # java 셋업 + - name: Set up JDK 21 + if: steps.artifact-cache-restore.outputs.cache-hit != 'true' + uses: actions/setup-java@v3 + with: + distribution: 'corretto' + java-version: '21' + + # gradle caching + - uses: actions/cache@v4 + name: Setup gradle cache + with: + path: | + ~/.gradle/caches + ~/.gradle/wrapper + key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }} + restore-keys: | + ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }} + ${{ runner.os }}-gradle- + + - name: API 빌드 - JAR + if: steps.artifact-cache-restore.outputs.cache-hit != 'true' + uses: gradle/gradle-build-action@v2 + with: + arguments: -i :module-api:build diff --git a/.github/workflows/develop.yml b/.github/workflows/develop.yml new file mode 100644 index 0000000..c996076 --- /dev/null +++ b/.github/workflows/develop.yml @@ -0,0 +1,41 @@ +name: 3. Develop 🚀 + +on: + workflow_dispatch: + inputs: + deploy-api: + description: Develop API 서버 배포 🎉🤣 + type: boolean + required: false + force-rebuild: + description: 강제 빌드 + type: boolean + required: false + + push: + branches: + - develop + # - 'feature/**' + pull_request: + branches: + - develop + +# https://github.com/gradle/gradle-build-action#caching +permissions: + contents: write + +jobs: + build: + name: 빌드 & 테스트 + concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + uses: ./.github/workflows/build.yml + with: + environment: develop + COMMIT_MESSAGE: ${{ github.event.head_commit.message }} + API_SERVER: https://dev.peoplehere.world + STAGE: develop + FORCE_REBUILD: ${{ inputs.force-rebuild == true }} + secrets: inherit + diff --git a/.github/workflows/production.yml b/.github/workflows/production.yml new file mode 100644 index 0000000..2f04316 --- /dev/null +++ b/.github/workflows/production.yml @@ -0,0 +1,56 @@ +name: 1. Production + +on: + workflow_dispatch: + inputs: + deploy-api: + description: Production API 서버 배포 🎉🤣 + type: boolean + required: false + force-rebuild: + description: 강제 빌드 + type: boolean + required: false + version-to-upgrade: + description: 배포 버전 업그레이드 + type: choice + required: true + options: + - major + - minor + - patch + default: patch + + push: + branches: + - main + +# https://github.com/gradle/gradle-build-action#caching +permissions: + contents: write + +jobs: + build: + name: 빌드 & 테스트 + concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + uses: ./.github/workflows/build.yml + with: + environment: production + COMMIT_MESSAGE: ${{ github.event.head_commit.message }} + API_SERVER: https://prod.peoplehere.world + STAGE: production + FORCE_REBUILD: ${{ inputs.force-rebuild == true }} + secrets: inherit + + release: + if: ${{ github.event_name == 'workflow_dispatch' }} + name: 릴리즈 + uses: ./.github/workflows/release.yml + with: + environment: production + STAGE: production + CACHE_KEY: ${{ needs.build.outputs.CACHE_KEY }} + VERSION_TO_UPGRADE: ${{ github.event.inputs.version-to-upgrade }} + secrets: inherit diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..af26451 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,117 @@ +name: 'peoplehere-release' + +on: + workflow_call: + inputs: + environment: + type: string + required: true + STAGE: + type: string + required: true + CACHE_KEY: + type: string + required: true + VERSION_TO_UPGRADE: # major.minor.patch + type: string + required: true + outputs: + APP_VERSION: + value: ${{ jobs.release.outputs.APP_VERSION }} + CACHE_KEY: + value: ${{ jobs.release.outputs.CACHE_KEY }} + +env: + owner: People-Here + repo: people-here-dev + +jobs: + release: + name: Release New Version + environment: ${{ inputs.environment }} + runs-on: ubuntu-latest + outputs: + APP_VERSION: ${{ env.new-version }}-${{ env.release-date }} + CACHE_KEY: ${{ inputs.CACHE_KEY }} + steps: + - uses: actions/checkout@v3 + + - name: 캐시 불러오기 + uses: actions/cache/restore@v3 + id: artifact-cache-restore + with: + path: | + .build/jar/*.jar + key: ${{ inputs.CACHE_KEY }} + + - name: Set Release Date + run: | + echo "release-date=$(TZ=Asia/Seoul date +'%Y-%m-%d')" >> $GITHUB_ENV + + - name: 최신 릴리즈 버전 조회 + id: get-latest-release + env: + GH_TOKEN: ${{ secrets.WORKFLOW_TOKEN }} + run: | + OLD_RELEASE=$(gh api \ + -H "Accept: application/vnd.github+json" \ + -H "X-GitHub-Api-Version: 2022-11-28" \ + /repos/${{ env.owner }}/${{ env.repo }}/releases/latest) + + echo "old-release=${OLD_RELEASE}" >> $GITHUB_ENV + continue-on-error: true + + - name: 릴리즈 버전 조회 실패 시 최초 릴리즈로 간주 + if: ${{ steps.get-latest-release.outcome != 'success' }} + run: | + NEW_VERSION="v1.0.0" + echo "new-version=${NEW_VERSION}" >> $GITHUB_ENV + + - name: 버전업 + if: ${{ steps.get-latest-release.outcome == 'success' }} + run: | + OLD_VERSION=${{ fromJson(env.old-release).tag_name }} + echo "OLD_VERSION: ${OLD_VERSION}" + + MAJOR=$(echo $OLD_VERSION | cut -d. -f1 | sed 's/v//') + MINOR=$(echo $OLD_VERSION | cut -d. -f2) + PATCH=$(echo $OLD_VERSION | cut -d. -f3) + echo "major: $MAJOR, minor: $MINOR, patch: $PATCH" + + INCREMENT_TYPE=${{ inputs.VERSION_TO_UPGRADE }} + if [ "$INCREMENT_TYPE" == "major" ]; then + echo "upgrading major version" + MAJOR=$((++MAJOR)) + MINOR=0 + PATCH=0 + elif [ "$INCREMENT_TYPE" == "minor" ]; then + echo "upgrading minor version" + MINOR=$((++MINOR)) + PATCH=0 + elif [ "$INCREMENT_TYPE" == "patch" ]; then + echo "upgrading patch version" + PATCH=$((++PATCH)) + else + echo "Invalid increment type!" + exit 1 + fi + + echo "NEW_VERSION: v$MAJOR.$MINOR.$PATCH" + NEW_VERSION="v$MAJOR.$MINOR.$PATCH" + echo "new-version=${NEW_VERSION}" >> $GITHUB_ENV + + - name: 버전업 태그 생성 + env: + GH_TOKEN: ${{ secrets.WORKFLOW_TOKEN }} + run: | + NEW_RELEASE=$(gh api \ + --method POST \ + -H "Accept: application/vnd.github+json" \ + -H "X-GitHub-Api-Version: 2022-11-28" \ + /repos/${{ env.owner }}/${{ env.repo }}/releases \ + -f tag_name=${{ env.new-version }} \ + -f target_commitish='main' \ + -f name=${{ env.new-version }} \ + -f body='${{ env.new-version }} release') + + echo "new-release=${NEW_RELEASE}" >> $GITHUB_ENV diff --git a/.github/workflows/staging.yml b/.github/workflows/staging.yml new file mode 100644 index 0000000..13a4303 --- /dev/null +++ b/.github/workflows/staging.yml @@ -0,0 +1,37 @@ +name: 2. Staging 🚀 + +on: + workflow_dispatch: + inputs: + deploy-api: + description: Staging API 서버 배포 🎉🤣 + type: boolean + required: false + force-rebuild: + description: 강제 빌드 + type: boolean + required: false + + push: + branches: + - staging + +# https://github.com/gradle/gradle-build-action#caching +permissions: + contents: write + +jobs: + build: + name: 빌드 & 테스트 + concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + uses: ./.github/workflows/build.yml + with: + environment: staging + COMMIT_MESSAGE: ${{ github.event.head_commit.message }} + API_SERVER: https://stg.peoplehere.world + STAGE: develop + FORCE_REBUILD: ${{ inputs.force-rebuild == true }} + secrets: inherit + diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..e993330 --- /dev/null +++ b/.gitignore @@ -0,0 +1,56 @@ +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +### IntelliJ IDEA ### +.idea +.idea/modules.xml +.idea/jarRepositories.xml +.idea/compiler.xml +.idea/libraries/ +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### Eclipse ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ + +### Mac OS ### +.DS_Store + +.system +.build + +local.properties + +**/src/main/generated +*.pid +*.log +*.http + +module-api/src/main/resources/application-api-local.yml +module-shared/src/main/resources/application-shared-local.yml diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..8a788a7 --- /dev/null +++ b/build.gradle @@ -0,0 +1,225 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '3.2.4' + id 'io.spring.dependency-management' version '1.1.4' + + // checkstyle + id 'checkstyle' + + // jacoco + id 'jacoco' +} + +tasks.named('bootJar') { + enabled = false +} + +tasks.named('jar') { + enabled = false +} + +ext["testcontainersVersion"] = "1.19.6" + +subprojects { + group = 'com.peoplehere' + version = '0.0.1-SNAPSHOT' + sourceCompatibility = '21' + + apply plugin: 'java' + apply plugin: 'java-library' + apply plugin: 'org.springframework.boot' + apply plugin: 'io.spring.dependency-management' + apply plugin: 'checkstyle' + apply plugin: 'jacoco' + + configurations { + compileOnly { + extendsFrom annotationProcessor + } + } + + repositories { + mavenCentral() + } + + // IntelliJ 빌드용 + tasks.register('cleanOut', Delete) { + delete "${projectDir}/out" + } + + clean.finalizedBy(cleanOut) + + // 모든 모듈 공통 의존성 + dependencies { + + // Lombok & Mapstruct + compileOnly 'org.projectlombok:lombok' + implementation 'org.mapstruct:mapstruct:1.5.1.Final' + implementation 'org.projectlombok:lombok-mapstruct-binding:0.2.0' + annotationProcessor "org.projectlombok:lombok-mapstruct-binding:0.2.0" + annotationProcessor 'org.projectlombok:lombok' + annotationProcessor 'org.mapstruct:mapstruct-processor:1.5.1.Final' + + // flyway + implementation 'org.flywaydb:flyway-core' + + // https://mvnrepository.com/artifact/com.vladmihalcea/hibernate-types-60 + implementation 'io.hypersistence:hypersistence-utils-hibernate-60:3.5.1' + + // spring boot + implementation 'org.springframework.boot:spring-boot-starter-data-jpa' + implementation 'org.springframework.boot:spring-boot-starter-security' + implementation 'org.springframework.boot:spring-boot-starter-web' + implementation 'org.springframework.boot:spring-boot-starter-actuator' + implementation 'org.springframework.boot:spring-boot-starter-validation' + implementation 'org.springframework.boot:spring-boot-starter-jdbc' + + // jwt + implementation 'io.jsonwebtoken:jjwt-api:0.12.5' + implementation 'io.jsonwebtoken:jjwt-impl:0.12.5' + implementation 'io.jsonwebtoken:jjwt-jackson:0.12.5' + + // redis + implementation 'org.springframework.boot:spring-boot-starter-data-redis' + + // postgresql + runtimeOnly 'org.postgresql:postgresql' + + testImplementation 'org.springframework.boot:spring-boot-starter-test' + testImplementation 'org.springframework.security:spring-security-test' + testImplementation platform('org.junit:junit-bom:5.9.1') + testImplementation "org.testcontainers:junit-jupiter:${testcontainersVersion}" + + // testContainer + testImplementation "org.testcontainers:testcontainers" + testImplementation 'org.testcontainers:postgresql' + testImplementation 'io.rest-assured:rest-assured' + + } + + dependencyManagement { + imports { + mavenBom "org.testcontainers:testcontainers-bom:${testcontainersVersion}" + } + } + + checkstyle { + maxWarnings = 0 + configFile = file("${rootDir}/lint/naver-checkstyle-rules.xml") + configProperties = ["suppressionFile": "${rootDir}/lint/naver-checkstyle-suppressions.xml"] + toolVersion = "10.13.0" + } + + compileJava.options.encoding = 'UTF-8' + compileTestJava.options.encoding = 'UTF-8' + + tasks.named('test') { + useJUnitPlatform() + finalizedBy 'jacocoTestReport' + } + + def QDomains = [] + for (qPattern in '*.QA'..'*.QZ') { // qPattern = '*.QA', '*.QB', ... '*.QZ' + QDomains.add(qPattern + '*') + } + + jacoco { + toolVersion = '0.8.11' // support jdk 21 + // reportsDir = file("$buildDir/customJacocoReportDir") + } + + jacocoTestReport { + + reports { + html.required = true + xml.required = true + csv.required = false + + // 리포트의 저장 경로 설정 + // layout.buildDirectory를 직접 사용하여 보고서 목적지 지정 + html.destination file("${layout.buildDirectory.dir('reports/jacoco').get().asFile}/index.html") + xml.destination file("${layout.buildDirectory.dir('reports/jacoco').get().asFile}/index.xml") + } + + afterEvaluate { + classDirectories.setFrom( + files(classDirectories.files.collect { + fileTree(dir: it, excludes: [ + // 측정 안하고 싶은 패턴 + "**/*Application*", + "**/*Properties*", + "**/*Config*", + "**/entity/**", + "**/enums/**", + "**/resources/**", + "**/test/**" + ] + QDomains) + }) + ) + } + + finalizedBy 'jacocoTestCoverageVerification' + } + + jacocoTestCoverageVerification { + + violationRules { + + rule { +// enabled = true + enabled = false + element = 'CLASS' + + limit { + counter = 'BRANCH' + value = 'COVEREDRATIO' + minimum = 0.80 + } + + limit { + counter = 'LINE' + value = 'COVEREDRATIO' + minimum = 0.80 + } + + excludes = [ + // 측정 안하고 싶은 패턴 + '*.*Application*', + "*.*Properties*", + '*.*Config*', + "**.test.**", + "**.entity.**", + "**.enums.**", + "**.resources.**" + ] + QDomains + } + } + } + +} + +project(':module-shared') { + + bootJar { enabled = false } + jar { enabled = true } + + dependencies { + } +} + +project(':module-api') { + + bootJar { + enabled = true + destinationDirectory = file("$rootDir/$jarDestDir") + archiveFileName = "api.jar" + } + jar { enabled = false } + + dependencies { + implementation project(':module-shared') + + // mail + implementation 'org.springframework.boot:spring-boot-starter-mail' + } +} diff --git a/docker/docker-compose.yaml b/docker/docker-compose.yaml new file mode 100644 index 0000000..2574760 --- /dev/null +++ b/docker/docker-compose.yaml @@ -0,0 +1,27 @@ +version: "3.8" + +services: + db: + container_name: ph-db + image: postgres:15 + volumes: + - ./.system/docker-data/postgres:/var/lib/postgresql/data + - ./init-db.sh:/docker-entrypoint-initdb.d/init-db.sh + ports: + - "5432:5432" + environment: + - TZ=Asia/Seoul + - POSTGRES_DB=postgres + - POSTGRES_USER=ph + - POSTGRES_PASSWORD=ph + redis: + container_name: ph-redis + image: redis:alpine3.19 + command: redis-server --port 6379 + volumes: + - ./.system/docker-data/redis:/data + labels: + - "name=redis" + - "mode=standalone" + ports: + - 6379:6379 diff --git a/docker/init-db.sh b/docker/init-db.sh new file mode 100644 index 0000000..d6f8f8e --- /dev/null +++ b/docker/init-db.sh @@ -0,0 +1,9 @@ +#!/bin/bash +set -e + +psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" <<-EOSQL + create user sonar; + alter user sonar with password 'sonar' superuser; + create database sonar; + grant all privileges on database sonar to sonar; +EOSQL diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..857e611 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,2 @@ +org.gradle.logging.level=info +jarDestDir=.build/jar/ diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..249e583 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..194b28c --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Sun Mar 03 19:09:53 KST 2024 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.6-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..1b6c787 --- /dev/null +++ b/gradlew @@ -0,0 +1,234 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed 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. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${0##*/} + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +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 + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..107acd3 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,89 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem 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, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/lint/naver-checkstyle-rules.xml b/lint/naver-checkstyle-rules.xml new file mode 100644 index 0000000..2b16050 --- /dev/null +++ b/lint/naver-checkstyle-rules.xml @@ -0,0 +1,439 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/lint/naver-checkstyle-suppressions.xml b/lint/naver-checkstyle-suppressions.xml new file mode 100644 index 0000000..a7b6fd1 --- /dev/null +++ b/lint/naver-checkstyle-suppressions.xml @@ -0,0 +1,7 @@ + + + + + diff --git a/module-api/.gitignore b/module-api/.gitignore new file mode 100644 index 0000000..e69de29 diff --git a/module-api/build.gradle b/module-api/build.gradle new file mode 100644 index 0000000..e69de29 diff --git a/module-api/src/main/java/com/peoplehere/api/ApiApplication.java b/module-api/src/main/java/com/peoplehere/api/ApiApplication.java new file mode 100644 index 0000000..10b0cbd --- /dev/null +++ b/module-api/src/main/java/com/peoplehere/api/ApiApplication.java @@ -0,0 +1,16 @@ +package com.peoplehere.api; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.context.ApplicationPidFileWriter; + +@SpringBootApplication(scanBasePackages = {"com.peoplehere.api", "com.peoplehere.shared"}) +public class ApiApplication { + + public static void main(String[] args) { + var app = new SpringApplication(ApiApplication.class); + app.addListeners(new ApplicationPidFileWriter()); + app.run(args); + + } +} diff --git a/module-api/src/main/java/com/peoplehere/api/common/annotation/CheckEmailVerificationLimit.java b/module-api/src/main/java/com/peoplehere/api/common/annotation/CheckEmailVerificationLimit.java new file mode 100644 index 0000000..90907d7 --- /dev/null +++ b/module-api/src/main/java/com/peoplehere/api/common/annotation/CheckEmailVerificationLimit.java @@ -0,0 +1,11 @@ +package com.peoplehere.api.common.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Target; + +/** + * 이메일 인증 번호 전송에 대한 제한을 체크하는 어노테이션 + */ +@Target({ElementType.METHOD}) +public @interface CheckEmailVerificationLimit { +} diff --git a/module-api/src/main/java/com/peoplehere/api/common/annotation/CheckEmailVerifyLimit.java b/module-api/src/main/java/com/peoplehere/api/common/annotation/CheckEmailVerifyLimit.java new file mode 100644 index 0000000..bbec569 --- /dev/null +++ b/module-api/src/main/java/com/peoplehere/api/common/annotation/CheckEmailVerifyLimit.java @@ -0,0 +1,11 @@ +package com.peoplehere.api.common.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Target; + +/** + * 이메일 인증 번호 검증에 대한 제한을 체크하는 어노테이션 + */ +@Target({ElementType.METHOD}) +public @interface CheckEmailVerifyLimit { +} diff --git a/module-api/src/main/java/com/peoplehere/api/common/annotation/PrivateNetwork.java b/module-api/src/main/java/com/peoplehere/api/common/annotation/PrivateNetwork.java new file mode 100644 index 0000000..a3ab0d4 --- /dev/null +++ b/module-api/src/main/java/com/peoplehere/api/common/annotation/PrivateNetwork.java @@ -0,0 +1,11 @@ +package com.peoplehere.api.common.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target({ElementType.METHOD, ElementType.TYPE}) +@Retention(RetentionPolicy.RUNTIME) +public @interface PrivateNetwork { +} diff --git a/module-api/src/main/java/com/peoplehere/api/common/config/AsyncConfig.java b/module-api/src/main/java/com/peoplehere/api/common/config/AsyncConfig.java new file mode 100644 index 0000000..8faaa93 --- /dev/null +++ b/module-api/src/main/java/com/peoplehere/api/common/config/AsyncConfig.java @@ -0,0 +1,9 @@ +package com.peoplehere.api.common.config; + +/* +@EnableAsync(proxyTargetClass = true) +@Configuration +public class AsyncConfig { + +} +*/ diff --git a/module-api/src/main/java/com/peoplehere/api/common/config/CustomCorsFilter.java b/module-api/src/main/java/com/peoplehere/api/common/config/CustomCorsFilter.java new file mode 100644 index 0000000..c554c81 --- /dev/null +++ b/module-api/src/main/java/com/peoplehere/api/common/config/CustomCorsFilter.java @@ -0,0 +1,88 @@ +package com.peoplehere.api.common.config; + +import static com.peoplehere.api.common.util.RequestUtils.*; +import static java.lang.Boolean.*; +import static org.springframework.data.mapping.Alias.*; +import static org.springframework.http.HttpHeaders.*; +import static org.springframework.http.HttpMethod.*; + +import java.io.IOException; +import java.util.List; + +import org.springframework.core.Ordered; +import org.springframework.core.annotation.Order; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Component; + +import jakarta.servlet.Filter; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import lombok.AllArgsConstructor; +import lombok.extern.slf4j.Slf4j; + +@Slf4j +@Component +@AllArgsConstructor +@Order(Ordered.HIGHEST_PRECEDENCE) +public class CustomCorsFilter implements Filter { + + private final IpAccessManager ipAccessManager; + private static final List ALLOW_ORIGINS = List.of( + ".peoplehere.world", "localhost" + ); + + private static final String ALLOWED_METHODS = "GET, POST, PUT, OPTIONS"; + private static final String ALLOWED_HEADERS = "X-Requested-With,Origin,Content-Type,Accept,Authorization"; + + /** + * 허용된 도메인만 열어주기 + * todo: whitelist(허용된 ip) 도 열어주기 + * @param request + * @param response + * @param chain + * @throws IOException + * @throws ServletException + */ + @Override + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws + IOException, + ServletException { + final HttpServletRequest req = (HttpServletRequest)request; + final HttpServletResponse res = (HttpServletResponse)response; + final String origin = ((HttpServletRequest)request).getHeader(ORIGIN); + + if (ofNullable(origin).isPresent()) { + log.debug("헤더확인: {}", getIp(req)); + + if (ipAccessManager.contains(req) || isAllowOrigin(origin)) { + res.addHeader(ACCESS_CONTROL_ALLOW_ORIGIN, origin); + res.addHeader(ACCESS_CONTROL_ALLOW_CREDENTIALS, TRUE.toString()); + + if (OPTIONS.matches(req.getMethod())) { + res.addHeader(ACCESS_CONTROL_ALLOW_METHODS, ALLOWED_METHODS); + res.addHeader(ACCESS_CONTROL_ALLOW_HEADERS, ALLOWED_HEADERS); + res.setStatus(HttpStatus.OK.value()); + return; + } + } else { + res.setStatus(HttpStatus.FORBIDDEN.value()); + return; + } + } + chain.doFilter(req, res); + + } + + private static boolean isAllowOrigin(String origin) { + for (String allowOrigin : ALLOW_ORIGINS) { + if (origin.contains(allowOrigin)) { + return true; + } + } + return false; + } +} diff --git a/module-api/src/main/java/com/peoplehere/api/common/config/ErrorControllerAdvice.java b/module-api/src/main/java/com/peoplehere/api/common/config/ErrorControllerAdvice.java new file mode 100644 index 0000000..8f77e5a --- /dev/null +++ b/module-api/src/main/java/com/peoplehere/api/common/config/ErrorControllerAdvice.java @@ -0,0 +1,117 @@ +package com.peoplehere.api.common.config; + +import static org.springframework.http.HttpStatus.*; + +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.security.authentication.BadCredentialsException; +import org.springframework.validation.BindException; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; + +import com.peoplehere.api.common.exception.AccountIdNotFoundException; +import com.peoplehere.api.common.exception.ClientBindException; +import com.peoplehere.api.common.exception.DuplicateException; +import com.peoplehere.api.common.exception.ForbiddenException; +import com.peoplehere.shared.common.data.response.ErrorResponseDto; +import com.peoplehere.shared.common.webhook.AlertWebhook; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; + +@Slf4j +@ControllerAdvice +@RequiredArgsConstructor +public class ErrorControllerAdvice { + private final AlertWebhook alertWebhook; + private static final String FORBIDDEN_403_BODY = "접근할 수 없어요!"; + private static final String ERROR_500_BODY = "잠시 후 다시 확인해주세요!"; + + @ExceptionHandler(value = {ForbiddenException.class, AccessDeniedException.class}) + public ResponseEntity redirect403(Exception exception) { + log.debug("403 분석용", exception); + return ResponseEntity.status(FORBIDDEN).body(FORBIDDEN_403_BODY); + } + + @ExceptionHandler(value = DataIntegrityViolationException.class) + public ResponseEntity handle422(Exception exception) { + log.debug("422 에러분석용", exception); + return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).body(ERROR_500_BODY); + } + + /** + * 인증 예외의 핸들링 + * @param exception + * @return + */ + @ExceptionHandler(BadCredentialsException.class) + public ResponseEntity handleAuthenticationException(BadCredentialsException exception) { + log.debug("유효하지 않은 계정정보입니다.", exception); + return ResponseEntity.badRequest().body(new ErrorResponseDto("유효하지않은 계정정보입니다")); + } + + /** + * 클라이언트로부터의 요청 데이터 처리 중 발생한 바인딩 예외의 핸들링 + * 예외 세부 정보를 응답으로 전달하지 않음 + * + * @param exception + * @return + */ + @ExceptionHandler(value = ClientBindException.class) + public ResponseEntity handleClientBindException(ClientBindException exception) { + log.error("바인딩 중 오류 발생", exception); + return ResponseEntity.badRequest().body(new ErrorResponseDto("바인딩 중 오류 발생")); + } + + /** + * 관리자의(백오피스) 내부에서 요청 데이터 처리 중 발생한 바인딩 예외의 핸들링 + * 예외 세부 정보를 응답으로 전달함 + * + * @param exception + * @return + */ + @ExceptionHandler(value = BindException.class) + public ResponseEntity handleBindException(BindException exception) { + log.error("바인딩 중 오류 발생", exception); + ErrorResponseDto response = new ErrorResponseDto("바인딩 중 오류 발생", exception); + return ResponseEntity.badRequest().body(response); + } + + /** + * 중복된 값이 발생했을 때의 핸들링 + * @param exception + * @return + */ + @ExceptionHandler(value = DuplicateException.class) + public ResponseEntity handleDuplicateException(DuplicateException exception) { + log.debug("중복된 값 발생", exception); + ErrorResponseDto response = new ErrorResponseDto(exception); + return ResponseEntity.status(CONFLICT).body(response); + } + + /** + * 계정 아이디를 찾을 수 없을 때의 핸들링(로그인, 이메일 체크 용) + * @param exception + * @return + */ + @ExceptionHandler(value = AccountIdNotFoundException.class) + public ResponseEntity handleAccountIdNotFoundException(AccountIdNotFoundException exception) { + log.debug("계정 아이디를 찾을 수 없음", exception); + ErrorResponseDto response = new ErrorResponseDto(exception); + return ResponseEntity.status(NOT_FOUND).body(response); + } + + /** + * 그 외의 예외의 핸들링 + * @param exception + * @return + */ + @ExceptionHandler(value = Exception.class) + public ResponseEntity handle(Exception exception) { + log.debug("500 에러분석용", exception); + alertWebhook.alertError("500 에러 발생 분석을 하라", exception.getMessage()); + return ResponseEntity.internalServerError().body(ERROR_500_BODY); + } +} diff --git a/module-api/src/main/java/com/peoplehere/api/common/config/IpAccessManager.java b/module-api/src/main/java/com/peoplehere/api/common/config/IpAccessManager.java new file mode 100644 index 0000000..ef6537b --- /dev/null +++ b/module-api/src/main/java/com/peoplehere/api/common/config/IpAccessManager.java @@ -0,0 +1,143 @@ +package com.peoplehere.api.common.config; + +import static com.peoplehere.api.common.util.RequestUtils.*; + +import java.math.BigInteger; +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.util.HashSet; +import java.util.Set; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.security.core.Authentication; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; + +import jakarta.servlet.http.HttpServletRequest; +import lombok.ToString; +import lombok.extern.slf4j.Slf4j; + +@Slf4j +@Component +public class IpAccessManager { + + private final ListRanges privatelistRanges; + private final ListRanges metricsRanges; + private final ListRanges instanceRanges; + + public IpAccessManager( + @Value("#{'${whitelist.private:}'.replaceAll('\\s+', '').split(',')}") Set privateNetworks, + @Value("#{'${whitelist.metrics:}'.replaceAll('\\s+', '').split(',')}") Set metricsNetworks, + @Value("#{'${whitelist.private-instance:}'.replaceAll('\\s+', '').split(',')}") Set privateInstances) + throws UnknownHostException { + + log.info("\nprivate-networks: {}\n", privateNetworks); + log.info("\nmetrics: {}\n", metricsNetworks); + log.info("\nprivate-instance: {}\n", privateInstances); + + this.privatelistRanges = new ListRanges(privateNetworks); + this.metricsRanges = new ListRanges(metricsNetworks); + this.instanceRanges = new ListRanges(privateInstances); + + log.info("IpAccessManager 초기화. whitelist: {}, metrics: {}", privatelistRanges, metricsRanges); + } + + public boolean contains(HttpServletRequest request) { + String ipStr = getIp(request); + + if (ipStr == null) { + return false; + } + + try { + return privatelistRanges.isAllowed(ipStr); + } catch (UnknownHostException e) { + log.error("ip 체크하다 오류 {}", ipStr, e); + return false; + } + } + + public boolean isPrivateNetwork(Authentication authentication, HttpServletRequest request) { + boolean access = contains(request); + + if (!access) { + log.info("제한구역 접근[{}]: [{}] [{}]", getIp(request), request.getRequestURI(), authentication); + } + + return access; + } + + public boolean isMetricNetwork(HttpServletRequest request) { + try { + return metricsRanges.isAllowed(getIp(request)); + } catch (UnknownHostException e) { + log.error("ip 체크하다 오류", e); + return false; + } + } + + public boolean isPrivateInstance(HttpServletRequest request) { + String ip = getIp(request); + return instanceRanges.ipv4List.stream().anyMatch(s -> s.equals(ip) || s.contains(ip)); + } + + @ToString + private static class ListRanges { + private final Set ranges = new HashSet<>(); + private final Set ipv4List = new HashSet<>(); + + public ListRanges(Set list) { + for (String str : list) { + String[] cidr = str.split("/"); + if (cidr.length == 2) { // cidr + String[] ipAddressInArray = cidr[0].split("\\."); + int prefix = Integer.parseInt(cidr[1]); + + BigInteger ipVal = new BigInteger("0"); + for (int i = 0; i < ipAddressInArray.length; i++) { + int power = 3 - i; + int ipAddress = Integer.parseInt(ipAddressInArray[i]); + ipVal = ipVal.add(BigInteger.valueOf(ipAddress).shiftLeft(power * 8)); + } + + BigInteger mask = BigInteger.ZERO.setBit(32).subtract(BigInteger.ONE).shiftRight(prefix); + BigInteger[] range = new BigInteger[] {ipVal, mask}; + ranges.add(range); + } else { + ipv4List.add(str); + } + } + } + + public boolean isAllowed(String ipAddress) throws UnknownHostException { + if (!StringUtils.hasLength(ipAddress)) { + return false; + } + + for (String ipv4 : ipv4List) { + if (ipv4.startsWith(ipAddress)) { + return true; + } + } + + if (!ranges.isEmpty()) { + BigInteger ip = new BigInteger(1, InetAddress.getByName(ipAddress).getAddress()); + for (BigInteger[] range : ranges) { + BigInteger start = range[0]; + BigInteger end = start.add(range[1]); + + if (ip.compareTo(start) >= 0 && ip.compareTo(end) <= 0) { + return true; + } + } + } + + if (log.isDebugEnabled()) { + log.debug("접근금지. ipAddress: [{}]", ipAddress); + } + + return false; + } + } + +} diff --git a/module-api/src/main/java/com/peoplehere/api/common/config/PrivateNetworkInterceptor.java b/module-api/src/main/java/com/peoplehere/api/common/config/PrivateNetworkInterceptor.java new file mode 100644 index 0000000..2c9882d --- /dev/null +++ b/module-api/src/main/java/com/peoplehere/api/common/config/PrivateNetworkInterceptor.java @@ -0,0 +1,41 @@ +package com.peoplehere.api.common.config; + +import static com.peoplehere.api.common.util.RequestUtils.*; + +import org.springframework.stereotype.Component; +import org.springframework.web.method.HandlerMethod; +import org.springframework.web.servlet.HandlerInterceptor; + +import com.peoplehere.api.common.annotation.PrivateNetwork; +import com.peoplehere.api.common.exception.ForbiddenException; + +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import lombok.AllArgsConstructor; +import lombok.extern.slf4j.Slf4j; + +@Slf4j +@Component +@AllArgsConstructor +public class PrivateNetworkInterceptor implements HandlerInterceptor { + + private final IpAccessManager ipAccessManager; + + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { + if (!(handler instanceof HandlerMethod)) { + return true; + } + if (isTarget((HandlerMethod)handler) && !ipAccessManager.contains(request)) { + throw new ForbiddenException(getIp(request), request.getRequestURI()); + } + + return true; + } + + private boolean isTarget(HandlerMethod method) { + return method.hasMethodAnnotation(PrivateNetwork.class) || method.getMethod() + .getDeclaringClass() + .isAnnotationPresent(PrivateNetwork.class); + } +} diff --git a/module-api/src/main/java/com/peoplehere/api/common/config/WebConfig.java b/module-api/src/main/java/com/peoplehere/api/common/config/WebConfig.java new file mode 100644 index 0000000..d0c245e --- /dev/null +++ b/module-api/src/main/java/com/peoplehere/api/common/config/WebConfig.java @@ -0,0 +1,23 @@ +package com.peoplehere.api.common.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; + +@Slf4j +@Configuration +@RequiredArgsConstructor +public class WebConfig implements WebMvcConfigurer { + + private final PrivateNetworkInterceptor privateNetworkInterceptor; + + @Override + public void addInterceptors(InterceptorRegistry registry) { + WebMvcConfigurer.super.addInterceptors(registry); + registry.addInterceptor(privateNetworkInterceptor); + } + +} diff --git a/module-api/src/main/java/com/peoplehere/api/common/config/aspect/RequestLimitAspect.java b/module-api/src/main/java/com/peoplehere/api/common/config/aspect/RequestLimitAspect.java new file mode 100644 index 0000000..e1507ad --- /dev/null +++ b/module-api/src/main/java/com/peoplehere/api/common/config/aspect/RequestLimitAspect.java @@ -0,0 +1,15 @@ +package com.peoplehere.api.common.config.aspect; + +import org.aspectj.lang.annotation.Aspect; +import org.springframework.stereotype.Component; + +import lombok.RequiredArgsConstructor; + +/** + * 요청 전 제한 값들(인증 번호 발급 제한, 유/무료 사용자의 총 요청 제한)을 체크하고 필요한 값을 설정하는 Aspect + */ +@Component +@Aspect +@RequiredArgsConstructor +public class RequestLimitAspect { +} diff --git a/module-api/src/main/java/com/peoplehere/api/common/config/security/AuthorizationFilter.java b/module-api/src/main/java/com/peoplehere/api/common/config/security/AuthorizationFilter.java new file mode 100644 index 0000000..dfa09a5 --- /dev/null +++ b/module-api/src/main/java/com/peoplehere/api/common/config/security/AuthorizationFilter.java @@ -0,0 +1,52 @@ +package com.peoplehere.api.common.config.security; + +import static com.peoplehere.api.common.util.RequestUtils.*; +import static org.springframework.http.HttpHeaders.*; + +import java.io.IOException; + +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; +import org.springframework.web.filter.OncePerRequestFilter; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; + +@Slf4j +@Component +@RequiredArgsConstructor +public class AuthorizationFilter extends OncePerRequestFilter { + + private final TokenProvider tokenProvider; + private final RedisTemplate redisTemplate; + + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, + FilterChain chain) throws ServletException, IOException { + String token = request.getHeader(AUTHORIZATION); + String ip = getIp(request); + String uri = request.getRequestURI(); + + if (!StringUtils.hasText(token)) { + log.debug("토큰 없음, ip: {}, uri: {}", ip, uri); + chain.doFilter(request, response); + return; + } + try { + Authentication authentication = tokenProvider.getAuthenticationFromAcs(token); + SecurityContextHolder.getContext().setAuthentication(authentication); + log.debug("{}: 인증 정보 security context 저장, uri: {}", authentication.getName(), uri); + + } catch (Exception e) { + log.debug("인가 처리 실패 기록 : ip: {}, uri: {} - {}", ip, uri, e.getMessage()); + } + chain.doFilter(request, response); + } +} diff --git a/module-api/src/main/java/com/peoplehere/api/common/config/security/Token.java b/module-api/src/main/java/com/peoplehere/api/common/config/security/Token.java new file mode 100644 index 0000000..3788bb9 --- /dev/null +++ b/module-api/src/main/java/com/peoplehere/api/common/config/security/Token.java @@ -0,0 +1,4 @@ +package com.peoplehere.api.common.config.security; + +public record Token(String accessToken, String refreshToken) { +} diff --git a/module-api/src/main/java/com/peoplehere/api/common/config/security/TokenProperties.java b/module-api/src/main/java/com/peoplehere/api/common/config/security/TokenProperties.java new file mode 100644 index 0000000..022dadd --- /dev/null +++ b/module-api/src/main/java/com/peoplehere/api/common/config/security/TokenProperties.java @@ -0,0 +1,36 @@ +package com.peoplehere.api.common.config.security; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +import jakarta.annotation.PostConstruct; +import lombok.Data; +import lombok.extern.slf4j.Slf4j; + +@Slf4j +@Data +@Component +@ConfigurationProperties(prefix = "token") +public class TokenProperties { + private String accessKey; + + private String refreshKey; + + private long accessTime; + + private long refreshTime; + + @PostConstruct + public void log() { + log.info("access token 만료시간: [{} s]", this.accessTime); + log.info("refresh token 만료시간: [{} s]", this.refreshTime); + } + + public long getExpiredTime(TokenType type) { + if (type == null) { + throw new IllegalArgumentException("Token type must not be null"); + } + return type == TokenType.ACCESS ? this.accessTime : this.refreshTime; + } + +} diff --git a/module-api/src/main/java/com/peoplehere/api/common/config/security/TokenProvider.java b/module-api/src/main/java/com/peoplehere/api/common/config/security/TokenProvider.java new file mode 100644 index 0000000..dd6239b --- /dev/null +++ b/module-api/src/main/java/com/peoplehere/api/common/config/security/TokenProvider.java @@ -0,0 +1,134 @@ +package com.peoplehere.api.common.config.security; + +import static com.peoplehere.api.common.config.security.TokenType.*; +import static java.util.stream.Collectors.*; + +import java.util.Arrays; +import java.util.Collection; +import java.util.Date; +import java.util.stream.Collectors; + +import javax.crypto.SecretKey; + +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.stereotype.Component; + +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.ExpiredJwtException; +import io.jsonwebtoken.Jws; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.MalformedJwtException; +import io.jsonwebtoken.UnsupportedJwtException; +import io.jsonwebtoken.io.Decoders; +import io.jsonwebtoken.security.Keys; +import io.jsonwebtoken.security.SignatureException; +import jakarta.annotation.PostConstruct; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; + +@Slf4j +@Component +@RequiredArgsConstructor +public class TokenProvider { + + private final TokenProperties tokenProperties; + private SecretKey accessKey; + private SecretKey refreshKey; + + private static final String AUTHORITIES_KEY = "auth"; + + @PostConstruct + public void initialize() { + byte[] accessKeyBytes = Decoders.BASE64.decode(tokenProperties.getAccessKey()); + byte[] secretKeyBytes = Decoders.BASE64.decode(tokenProperties.getRefreshKey()); + this.accessKey = Keys.hmacShaKeyFor(accessKeyBytes); + this.refreshKey = Keys.hmacShaKeyFor(secretKeyBytes); + } + + public Token generateToken(Authentication authentication) { + return new Token(buildJwt(ACCESS, authentication), buildJwt(TokenType.REFRESH, authentication)); + } + + public String buildJwt(TokenType type, Authentication authentication) { + String authorities = authentication.getAuthorities().stream() + .map(GrantedAuthority::getAuthority) + .collect(Collectors.joining(",")); + + SecretKey key = getSecretKeyByType(type); + try { + return Jwts.builder() + .subject(authentication.getName()) + .claim(AUTHORITIES_KEY, authorities) + .expiration(new Date(new Date().getTime() + tokenProperties.getExpiredTime(type))) + .signWith(key) + .compact(); + } catch (Exception e) { + log.error("JWT 토큰 생성 실패 - type: [{}], subject: [{}]", type, authentication.getName(), e); + throw new RuntimeException("JWT 토큰 생성 실패", e); + } + } + + public Authentication getAuthenticationFromAcs(String token) { + return getAuthentication(TokenType.ACCESS, token); + } + + public Authentication getAuthenticationFromRef(String token) { + return getAuthentication(TokenType.REFRESH, token); + } + + private Authentication getAuthentication(TokenType type, String token) { + Claims claims = parseJwt(type, token).getPayload(); + + Collection authorities = Arrays.stream( + claims.get(AUTHORITIES_KEY).toString().split(",")) + .map(SimpleGrantedAuthority::new) + .collect(toList()); + + return new UsernamePasswordAuthenticationToken(claims.getSubject(), token, authorities); + } + + public Jws parseJwt(TokenType type, String token) { + try { + SecretKey key = getSecretKeyByType(type); + return Jwts.parser().verifyWith(key).build().parseSignedClaims(token); + } catch (SignatureException e) { + log.error("유효하지 않은 서명의 토큰입니다"); + } catch (MalformedJwtException e) { + log.error("유효하지 않은 JWT입니다."); + } catch (ExpiredJwtException e) { + log.error("만료된 JWT입니다."); + } catch (UnsupportedJwtException e) { + log.error("지원되지 않는 JWT입니다."); + } catch (IllegalArgumentException e) { + log.error("jwt claim is empty"); + } + throw new IllegalArgumentException(); + } + + public boolean isAccessTokenCanBeReissued(String token) { + try { + // 토큰 파싱. 만료되었거나 문제가 있는 경우, 예외 발생 + Jwts.parser().verifyWith(accessKey).build().parseSignedClaims(token); + // 토큰이 유효한 경우: 재발급이 필요하지 않으므로 false를 반환 + return false; + } catch (ExpiredJwtException e) { + // 토큰이 만료된 경우: 재발급이 가능하므로 true를 반환 + return true; + } catch (Exception e) { + // 기타 모든 예외 처리: 재발급이 불가능하므로 false를 반환 + log.error("토큰 재발급 가능 여부 확인 중 오류 발생", e); + return false; + } + } + + private SecretKey getSecretKeyByType(TokenType type) { + if (ACCESS.equals(type)) { + return accessKey; + } + return refreshKey; + } + +} diff --git a/module-api/src/main/java/com/peoplehere/api/common/config/security/TokenType.java b/module-api/src/main/java/com/peoplehere/api/common/config/security/TokenType.java new file mode 100644 index 0000000..fdc1843 --- /dev/null +++ b/module-api/src/main/java/com/peoplehere/api/common/config/security/TokenType.java @@ -0,0 +1,10 @@ +package com.peoplehere.api.common.config.security; + +import lombok.AllArgsConstructor; +import lombok.Getter; + +@Getter +@AllArgsConstructor +public enum TokenType { + ACCESS, REFRESH +} diff --git a/module-api/src/main/java/com/peoplehere/api/common/config/security/VerifyCodeProperties.java b/module-api/src/main/java/com/peoplehere/api/common/config/security/VerifyCodeProperties.java new file mode 100644 index 0000000..9ff6f9f --- /dev/null +++ b/module-api/src/main/java/com/peoplehere/api/common/config/security/VerifyCodeProperties.java @@ -0,0 +1,25 @@ +package com.peoplehere.api.common.config.security; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +import jakarta.annotation.PostConstruct; +import lombok.Data; +import lombok.extern.slf4j.Slf4j; + +@Slf4j +@Data +@Component +@ConfigurationProperties(prefix = "verify") +public class VerifyCodeProperties { + + private int emailTimeout; + + private int phoneTimeout; + + @PostConstruct + public void log() { + log.info("email verify code 만료시간: [{} ms]", this.emailTimeout); + log.info("phone verify code 만료시간: [{} ms]", this.phoneTimeout); + } +} diff --git a/module-api/src/main/java/com/peoplehere/api/common/config/security/WebSecurityConfig.java b/module-api/src/main/java/com/peoplehere/api/common/config/security/WebSecurityConfig.java new file mode 100644 index 0000000..7be290f --- /dev/null +++ b/module-api/src/main/java/com/peoplehere/api/common/config/security/WebSecurityConfig.java @@ -0,0 +1,124 @@ +package com.peoplehere.api.common.config.security; + +import static com.peoplehere.shared.common.enums.AccountRole.*; + +import java.nio.charset.StandardCharsets; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; +import org.springframework.security.authorization.AuthorizationDecision; +import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.access.AccessDeniedHandler; +import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; +import org.springframework.security.web.csrf.CsrfFilter; +import org.springframework.web.filter.CharacterEncodingFilter; + +import com.peoplehere.api.common.config.IpAccessManager; +import com.peoplehere.api.common.config.security.handler.CustomAccessDeniedHandler; +import com.peoplehere.api.common.config.security.handler.CustomAuthenticationEntryPointHandler; + +import lombok.RequiredArgsConstructor; + +@Configuration +@EnableMethodSecurity(prePostEnabled = true) +@EnableWebSecurity +@RequiredArgsConstructor +public class WebSecurityConfig { + + private final CustomAuthenticationEntryPointHandler customAuthenticationEntryPointHandler; + private final AuthorizationFilter authorizationFilter; + private final IpAccessManager ipAccessManager; + + @Profile("!test") + @Bean + public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { + + var filter = new CharacterEncodingFilter(); + filter.setEncoding(StandardCharsets.UTF_8.name()); + filter.setForceEncoding(true); + http + .addFilterBefore(filter, CsrfFilter.class) + .addFilterBefore(authorizationFilter, UsernamePasswordAuthenticationFilter.class); + + // 로그인 방식 설정 + http + .csrf(AbstractHttpConfigurer::disable) + .httpBasic(AbstractHttpConfigurer::disable) + .formLogin(AbstractHttpConfigurer::disable) + .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)); + + // 경로별 접근 제어 설정 + http + .authorizeHttpRequests((authorizeRequests) -> + authorizeRequests + .requestMatchers("/actuator/**", "/error-test") + .access((authentication, object) -> { + // 관리자면서 허용된 ip의 경우만 접근 가능 + var isAdmin = authentication.get() + .getAuthorities() + .stream() + .anyMatch(it -> it.getAuthority().equals(ADMIN.getValue())); + return new AuthorizationDecision( + isAdmin || ipAccessManager.isMetricNetwork(object.getRequest())); + }) + + .requestMatchers("/api/account/alarm") + .authenticated() + + // 로그인 관련 경로 및 특정 uri의 경우 접근 허용 + .requestMatchers("/api/account/**", "/test") + .permitAll() + + // TODO: method annotation 으로 권한을 관리할 api + // .requestMatchers("") + // .permitAll() + + // health check + .requestMatchers("/api/health") + .permitAll() + + // swagger + .requestMatchers("/swagger-ui.html", "/swagger-ui/**", "/v3/api-docs/**", "/swagger-resources/**") + .permitAll() + + // local api 경로 + .requestMatchers("/api/local", "/api/local/**") + .access((authentication, object) -> { + String ip = object.getRequest().getRemoteAddr(); + boolean isLocalIp = "127.0.0.1".equals(ip) || "0:0:0:0:0:0:0:1".equals(ip); + return new AuthorizationDecision( + isLocalIp || ipAccessManager.isPrivateNetwork(authentication.get(), object.getRequest())); + }) + + // 나머지 경로는 인증된 사용자만 접근 가능 + .anyRequest() + .authenticated()); + + // 예외처리 커스터마이징 + http + .exceptionHandling((exceptionConfig) -> + exceptionConfig.authenticationEntryPoint(customAuthenticationEntryPointHandler) + .accessDeniedHandler(accessDeniedHandler())); + + return http.build(); + } + + @Bean + public AccessDeniedHandler accessDeniedHandler() { + return new CustomAccessDeniedHandler(); + } + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } + +} diff --git a/module-api/src/main/java/com/peoplehere/api/common/config/security/handler/CustomAccessDeniedHandler.java b/module-api/src/main/java/com/peoplehere/api/common/config/security/handler/CustomAccessDeniedHandler.java new file mode 100644 index 0000000..3c9e03a --- /dev/null +++ b/module-api/src/main/java/com/peoplehere/api/common/config/security/handler/CustomAccessDeniedHandler.java @@ -0,0 +1,32 @@ +package com.peoplehere.api.common.config.security.handler; + +import static com.peoplehere.api.common.util.RequestUtils.*; + +import java.io.IOException; + +import org.springframework.http.HttpStatus; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.security.web.access.AccessDeniedHandlerImpl; +import org.springframework.stereotype.Component; + +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import lombok.extern.slf4j.Slf4j; + +@Slf4j +@Component +public class CustomAccessDeniedHandler extends AccessDeniedHandlerImpl { + + @Override + public void handle(HttpServletRequest request, HttpServletResponse response, + AccessDeniedException accessDeniedException) throws IOException, ServletException { + super.handle(request, response, accessDeniedException); + + if (log.isDebugEnabled()) { + log.debug("[{}] [{}] [{}] {}", getIp(request), HttpStatus.FORBIDDEN, request.getMethod(), + request.getRequestURI()); + } + } +} + diff --git a/module-api/src/main/java/com/peoplehere/api/common/config/security/handler/CustomAuthenticationEntryPointHandler.java b/module-api/src/main/java/com/peoplehere/api/common/config/security/handler/CustomAuthenticationEntryPointHandler.java new file mode 100644 index 0000000..7436d41 --- /dev/null +++ b/module-api/src/main/java/com/peoplehere/api/common/config/security/handler/CustomAuthenticationEntryPointHandler.java @@ -0,0 +1,38 @@ +package com.peoplehere.api.common.config.security.handler; + +import static com.peoplehere.api.common.util.RequestUtils.*; +import static org.springframework.util.MimeTypeUtils.*; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; + +import org.springframework.http.HttpStatus; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.web.AuthenticationEntryPoint; +import org.springframework.stereotype.Component; + +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; + +@Slf4j +@Component +@RequiredArgsConstructor +public class CustomAuthenticationEntryPointHandler implements AuthenticationEntryPoint { + + @Override + public void commence(HttpServletRequest request, HttpServletResponse response, + AuthenticationException authException) throws IOException, ServletException { + if (log.isDebugEnabled()) { + log.debug("[{}] [{}] [{}] {}", getIp(request), HttpStatus.UNAUTHORIZED, request.getMethod(), + request.getRequestURI()); + } + + response.setStatus(HttpStatus.UNAUTHORIZED.value()); + response.setCharacterEncoding(StandardCharsets.UTF_8.name()); + response.setContentType(APPLICATION_JSON_VALUE); + // todo: 추후 response body에 에러 메시지 필요하다면 추가 + } +} diff --git a/module-api/src/main/java/com/peoplehere/api/common/controller/AccountController.java b/module-api/src/main/java/com/peoplehere/api/common/controller/AccountController.java new file mode 100644 index 0000000..4f5fbc6 --- /dev/null +++ b/module-api/src/main/java/com/peoplehere/api/common/controller/AccountController.java @@ -0,0 +1,182 @@ +package com.peoplehere.api.common.controller; + +import static com.peoplehere.shared.common.util.PatternUtils.*; + +import java.security.Principal; + +import org.springframework.http.ResponseEntity; +import org.springframework.validation.BindException; +import org.springframework.validation.BindingResult; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import com.peoplehere.api.common.annotation.CheckEmailVerificationLimit; +import com.peoplehere.api.common.annotation.CheckEmailVerifyLimit; +import com.peoplehere.api.common.data.request.MailVerificationRequestDto; +import com.peoplehere.api.common.data.request.MailVerifyRequestDto; +import com.peoplehere.api.common.data.response.MailVerificationResponseDto; +import com.peoplehere.api.common.exception.ClientBindException; +import com.peoplehere.api.common.service.AccountService; +import com.peoplehere.api.common.service.VerifyService; +import com.peoplehere.shared.common.data.request.AlarmConsentRequestDto; +import com.peoplehere.shared.common.data.request.PasswordRequestDto; +import com.peoplehere.shared.common.data.request.SignInRequestDto; +import com.peoplehere.shared.common.data.request.SignUpRequestDto; +import com.peoplehere.shared.common.data.request.TokenRequestDto; +import com.peoplehere.shared.common.data.response.AccountResponseDto; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; + +@Slf4j +@RestController +@RequiredArgsConstructor +@RequestMapping("/api/account") +public class AccountController { + + private final AccountService accountService; + private final VerifyService verifyService; + + /** + * client 회원가입 + * @param requestDto 회원가입 요청 정보 + * @param result 바인딩 결과 + * @return + * @throws ClientBindException client 바인딩 오류 + */ + @PostMapping("/sign-up") + public ResponseEntity signUp(@Validated @RequestBody SignUpRequestDto requestDto, + BindingResult result) throws + ClientBindException { + + if (result.hasErrors()) { + throw new ClientBindException(result); + } + accountService.signUp(requestDto); + log.info("client: {} 회원가입 성공", requestDto.getEmail()); + return ResponseEntity.ok().body("success"); + } + + /** + * client 로그인 + * @param requestDto 로그인 요청 정보 + * @param result 바인딩 결과 + * @return 로그인 성공 시 토큰 반환 + * @throws ClientBindException client 바인딩 오류 + */ + @PostMapping("/sign-in") + public ResponseEntity signIn(@Validated @RequestBody SignInRequestDto requestDto, + BindingResult result) throws + BindException { + + if (result.hasErrors()) { + throw new ClientBindException(result); + } + AccountResponseDto responseDto = accountService.signIn(requestDto); + log.debug("client: {} 로그인 성공", requestDto.getEmail()); + return ResponseEntity.ok().body(responseDto); + } + + /** + * 비밀번호 재설정 + * @param requestDto 비밀번호 재설정 요청 정보 + * @param result 바인딩 결과 + * @return + * @throws ClientBindException client 바인딩 오류 + */ + @PutMapping("/password") + public ResponseEntity modifyPassword(@Validated @RequestBody PasswordRequestDto requestDto, + BindingResult result) throws + ClientBindException { + + if (result.hasErrors()) { + throw new ClientBindException(result); + } + accountService.updatePassword(requestDto); + return ResponseEntity.ok().body("success"); + } + + /** + * 이메일 유효성(중복, 패턴) 체크 + * @param email 이메일 + * @return + */ + @GetMapping("/email/check") + public ResponseEntity checkEmail(@RequestParam String email) { + if (!EMAIL_PATTERN.matcher(email).matches()) { + log.error("이메일 형식 오류: {}", email); + return ResponseEntity.badRequest().build(); + } + accountService.checkEmail(email); + return ResponseEntity.ok().body("success"); + } + + /** + * 알람 동의 여부를 저장함 + * @param requestDto 알람 동의 여부 + * @return + */ + @PostMapping("/alarm") + public ResponseEntity modifyAlarmConsent(Principal principal, + @Validated @RequestBody AlarmConsentRequestDto requestDto, BindingResult result) throws BindException { + if (result.hasErrors()) { + throw new BindException(result); + } + accountService.modifyAlarmConsent(principal.getName(), requestDto.isConsent()); + return ResponseEntity.ok().body("success"); + } + + /** + * 토큰 재발급 + * accessToken의 만료 유무 확인 후 만료시 재발급 + * @param requestDto 토큰 재발급 요청 정보 + * @return + */ + @PostMapping("/token") + public ResponseEntity reissueToken(@Validated @RequestBody TokenRequestDto requestDto, + BindingResult result) throws ClientBindException { + if (result.hasErrors()) { + throw new ClientBindException(result); + } + return ResponseEntity.ok( + accountService.reissueToken(requestDto.getAccessToken(), requestDto.getRefreshToken())); + } + + /** + * 이메일 인증 번호 요청 + * @param requestDto 이메일 + * @param result + * @return 인증번호 만료시간 + * @throws ClientBindException + */ + @CheckEmailVerificationLimit + @PostMapping("/email/verification") + public ResponseEntity sendEmailVerificationCode( + @Validated @RequestBody MailVerificationRequestDto requestDto, + BindingResult result) throws ClientBindException { + if (result.hasErrors()) { + throw new ClientBindException(result); + } + long start = System.currentTimeMillis(); + MailVerificationResponseDto responseDto = verifyService.sendEmailVerificationCode(requestDto.email()); + log.info("이메일 인증번호 전송 성공 - {}ms, email: {}", System.currentTimeMillis() - start, requestDto.email()); + return ResponseEntity.ok().body(responseDto); + } + + /** + * 이메일 인증 번호 검증 + * @param requestDto 이메일, 인증번호 + * @return + */ + @CheckEmailVerifyLimit + @PostMapping("/email/verify") + public ResponseEntity checkEmailVerifyCode(@Validated @RequestBody MailVerifyRequestDto requestDto) { + return ResponseEntity.ok().body(verifyService.checkEmailVerifyCode(requestDto)); + } +} diff --git a/module-api/src/main/java/com/peoplehere/api/common/controller/ConstantController.java b/module-api/src/main/java/com/peoplehere/api/common/controller/ConstantController.java new file mode 100644 index 0000000..1e6268f --- /dev/null +++ b/module-api/src/main/java/com/peoplehere/api/common/controller/ConstantController.java @@ -0,0 +1,33 @@ +package com.peoplehere.api.common.controller; + +import static com.peoplehere.shared.common.enums.Region.*; + +import java.util.List; + +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import com.peoplehere.shared.common.data.response.RegionResponseDto; +import com.peoplehere.shared.common.enums.Gender; + +@RestController +@RequestMapping("/api/constants") +public class ConstantController { + + @GetMapping("/genders") + public ResponseEntity getGenderType() { + return ResponseEntity.ok(Gender.VALUES); + } + + /** + * 국가 코드, 영문 이름, 한글 이름, 국제 전화 코드를 반환 + * @return + */ + @GetMapping("/regions") + public ResponseEntity> getRegions() { + return ResponseEntity.ok(REGION_INFO_LIST); + } +} + diff --git a/module-api/src/main/java/com/peoplehere/api/common/controller/StatusController.java b/module-api/src/main/java/com/peoplehere/api/common/controller/StatusController.java new file mode 100644 index 0000000..d30c9a5 --- /dev/null +++ b/module-api/src/main/java/com/peoplehere/api/common/controller/StatusController.java @@ -0,0 +1,60 @@ +package com.peoplehere.api.common.controller; + +import java.util.ArrayList; +import java.util.List; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; + +@Slf4j +@RequiredArgsConstructor +@RestController +public class StatusController { + + @Value("${server.port}") + int port; + + @Value("${app.ip.public:#{null}}") + String publicIp; + + @GetMapping("/api/local/delay") + public ResponseEntity delayGet() throws InterruptedException { + log.info("30초간 작업하는척 "); + + for (int i = 0; i < 30; i++) { + Thread.sleep(1000); + if (i % 5 == 0) { + log.info("{}, {} 초 지남", port, i); + } + } + + return ResponseEntity.ok("success"); + } + + @GetMapping("/api/health") + public ResponseEntity health() { + return ResponseEntity.status(200).body("hello!, im " + publicIp); + } + + /** + * metric 에러로그 수집 테스트 + * @return + */ + @GetMapping("/error-test") + public ResponseEntity errorTest() { + try { + List list = new ArrayList<>(); + list.get(2).toString(); + } catch (Exception e) { + log.error("에러로그 테스트중. 리스트에서 잘못된 접근!", e); + } + + var date = System.currentTimeMillis(); + return ResponseEntity.ok(date); + } +} diff --git a/module-api/src/main/java/com/peoplehere/api/common/data/request/MailVerificationRequestDto.java b/module-api/src/main/java/com/peoplehere/api/common/data/request/MailVerificationRequestDto.java new file mode 100644 index 0000000..76bc92f --- /dev/null +++ b/module-api/src/main/java/com/peoplehere/api/common/data/request/MailVerificationRequestDto.java @@ -0,0 +1,10 @@ +package com.peoplehere.api.common.data.request; + +import jakarta.validation.constraints.Email; + +/** + * 이메일 인증 번호 요청 DTO + * @param email + */ +public record MailVerificationRequestDto(@Email String email) { +} diff --git a/module-api/src/main/java/com/peoplehere/api/common/data/request/MailVerifyRequestDto.java b/module-api/src/main/java/com/peoplehere/api/common/data/request/MailVerifyRequestDto.java new file mode 100644 index 0000000..d59b25a --- /dev/null +++ b/module-api/src/main/java/com/peoplehere/api/common/data/request/MailVerifyRequestDto.java @@ -0,0 +1,10 @@ +package com.peoplehere.api.common.data.request; + +import jakarta.validation.constraints.Email; +import jakarta.validation.constraints.NotBlank; + +/** + * 메일 인증 코드 검증 요청 DTO + */ +public record MailVerifyRequestDto(@Email String email, @NotBlank String code) { +} diff --git a/module-api/src/main/java/com/peoplehere/api/common/data/response/MailVerificationResponseDto.java b/module-api/src/main/java/com/peoplehere/api/common/data/response/MailVerificationResponseDto.java new file mode 100644 index 0000000..192ce50 --- /dev/null +++ b/module-api/src/main/java/com/peoplehere/api/common/data/response/MailVerificationResponseDto.java @@ -0,0 +1,4 @@ +package com.peoplehere.api.common.data.response; + +public record MailVerificationResponseDto(int expireSecondTime) { +} diff --git a/module-api/src/main/java/com/peoplehere/api/common/exception/AccountIdNotFoundException.java b/module-api/src/main/java/com/peoplehere/api/common/exception/AccountIdNotFoundException.java new file mode 100644 index 0000000..e45ff9b --- /dev/null +++ b/module-api/src/main/java/com/peoplehere/api/common/exception/AccountIdNotFoundException.java @@ -0,0 +1,13 @@ +package com.peoplehere.api.common.exception; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +import jakarta.persistence.EntityNotFoundException; + +@ResponseStatus(HttpStatus.NOT_FOUND) +public class AccountIdNotFoundException extends EntityNotFoundException { + public AccountIdNotFoundException(String accountId) { + super("계정 ID (%s)에 해당하는 유저를 찾을 수 없습니다.".formatted(accountId)); + } +} diff --git a/module-api/src/main/java/com/peoplehere/api/common/exception/ClientBindException.java b/module-api/src/main/java/com/peoplehere/api/common/exception/ClientBindException.java new file mode 100644 index 0000000..74c2d14 --- /dev/null +++ b/module-api/src/main/java/com/peoplehere/api/common/exception/ClientBindException.java @@ -0,0 +1,15 @@ +package com.peoplehere.api.common.exception; + +import org.springframework.validation.BindException; +import org.springframework.validation.BindingResult; + +/** + * Bind 예외 중 클라이언트로부터의 요청 처리 중 발생한 예외. + * 클라이언트에게는 예외의 세부 정보를 숨겨야 한다. + * 따라서 별도로 예외처리하기 위해 예외 클래스를 분리 + */ +public class ClientBindException extends BindException { + public ClientBindException(BindingResult bindingResult) { + super(bindingResult); + } +} diff --git a/module-api/src/main/java/com/peoplehere/api/common/exception/DuplicateException.java b/module-api/src/main/java/com/peoplehere/api/common/exception/DuplicateException.java new file mode 100644 index 0000000..ea5b1f3 --- /dev/null +++ b/module-api/src/main/java/com/peoplehere/api/common/exception/DuplicateException.java @@ -0,0 +1,11 @@ +package com.peoplehere.api.common.exception; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +@ResponseStatus(HttpStatus.CONFLICT) +public class DuplicateException extends RuntimeException { + public DuplicateException(String value) { + super("중복된 값: (%s)".formatted(value)); + } +} diff --git a/module-api/src/main/java/com/peoplehere/api/common/exception/ForbiddenException.java b/module-api/src/main/java/com/peoplehere/api/common/exception/ForbiddenException.java new file mode 100644 index 0000000..07c348f --- /dev/null +++ b/module-api/src/main/java/com/peoplehere/api/common/exception/ForbiddenException.java @@ -0,0 +1,11 @@ +package com.peoplehere.api.common.exception; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +@ResponseStatus(HttpStatus.FORBIDDEN) +public class ForbiddenException extends RuntimeException { + public ForbiddenException(String address, String path) { + super("제한구역 접근(%s): [%s]".formatted(address, path)); + } +} diff --git a/module-api/src/main/java/com/peoplehere/api/common/service/AccountService.java b/module-api/src/main/java/com/peoplehere/api/common/service/AccountService.java new file mode 100644 index 0000000..5fd4349 --- /dev/null +++ b/module-api/src/main/java/com/peoplehere/api/common/service/AccountService.java @@ -0,0 +1,117 @@ +package com.peoplehere.api.common.service; + +import static com.peoplehere.shared.common.data.request.SignUpRequestDto.*; + +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.core.Authentication; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import com.peoplehere.api.common.config.security.Token; +import com.peoplehere.api.common.config.security.TokenProvider; +import com.peoplehere.api.common.exception.AccountIdNotFoundException; +import com.peoplehere.api.common.exception.DuplicateException; +import com.peoplehere.shared.common.data.request.PasswordRequestDto; +import com.peoplehere.shared.common.data.request.SignInRequestDto; +import com.peoplehere.shared.common.data.request.SignUpRequestDto; +import com.peoplehere.shared.common.data.response.AccountResponseDto; +import com.peoplehere.shared.common.entity.Account; +import com.peoplehere.shared.common.entity.Consent; +import com.peoplehere.shared.common.repository.AccountRepository; +import com.peoplehere.shared.common.repository.ConsentRepository; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; + +@Slf4j +@Service +@RequiredArgsConstructor +public class AccountService { + + private final AccountRepository accountRepository; + private final ConsentRepository consentRepository; + private final TokenProvider tokenProvider; + private final PasswordEncoder passwordEncoder; + private final AuthenticationManagerBuilder authenticationManagerBuilder; + private final RedisTaskService redisTaskService; + + @Transactional + public void signUp(SignUpRequestDto requestDto) { + if (accountRepository.existsByEmail(requestDto.getEmail())) { + throw new DuplicateException(requestDto.getEmail()); + } + String encodedPassword = passwordEncoder.encode(requestDto.getPassword()); + Account account = accountRepository.save(toClientAccount(requestDto, encodedPassword)); + consentRepository.save(toConsent(requestDto, account)); + } + + /** + * 사용자 로그인을 시도하고, 토큰을 생성 후 redis에 저장하고 반환 + * TODO: 현재는 자동 로그인으로 구현, 추후에 일반 로그인, 자동 로그인으로 분리될 수 있음 + * @param requestDto + * @return + */ + @Transactional + public AccountResponseDto signIn(SignInRequestDto requestDto) { + Authentication authentication = attemptAuthentication(requestDto); + Token token = tokenProvider.generateToken(authentication); + redisTaskService.setRefreshToken(token, authentication.getName()); + return AccountResponseDto.builder() + .accessToken(token.accessToken()) + .refreshToken(token.refreshToken()) + .build(); + } + + @Transactional + public void updatePassword(PasswordRequestDto requestDto) { + Account account = accountRepository.findByEmail(requestDto.getEmail()) + .orElseThrow(() -> new AccountIdNotFoundException(requestDto.getEmail())); + + account.updatePassword(passwordEncoder.encode(requestDto.getNewPassword())); + } + + @Transactional(readOnly = true) + public void checkEmail(String email) { + if (accountRepository.existsByEmail(email)) { + throw new DuplicateException(email); + } + } + + @Transactional + public void modifyAlarmConsent(String userId, boolean alarmConsent) { + Account account = accountRepository.findByEmail(userId) + .orElseThrow(() -> new AccountIdNotFoundException(userId)); + Consent consent = consentRepository.findByAccountId(account.getId()) + .orElseThrow(() -> new AccountIdNotFoundException(userId)); + consent.setAlarmConsent(alarmConsent); + } + + /** + * accessToken의 만료 여부, refreshToken의 유효성을 검사하고, 새로운 accessToken을 발급 + * @param accessToken + * @param refreshToken + * @return + */ + @Transactional + public String reissueToken(String accessToken, String refreshToken) { + if (!tokenProvider.isAccessTokenCanBeReissued(accessToken)) { + throw new IllegalArgumentException("토큰 재발급에 실패하였습니다."); + } + Authentication authentication = tokenProvider.getAuthenticationFromRef(refreshToken); + return tokenProvider.generateToken(authentication).accessToken(); + } + + /** + * 사용자 인증을 시도하고, 인증된 Authentication 객체를 반환 + * @param requestDto 사용자 로그인 요청 정보 + * @return + */ + private Authentication attemptAuthentication(SignInRequestDto requestDto) { + UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken( + requestDto.getEmail(), requestDto.getPassword()); + return authenticationManagerBuilder.getObject().authenticate(authenticationToken); + } + +} diff --git a/module-api/src/main/java/com/peoplehere/api/common/service/PrincipalDetailService.java b/module-api/src/main/java/com/peoplehere/api/common/service/PrincipalDetailService.java new file mode 100644 index 0000000..ed681bc --- /dev/null +++ b/module-api/src/main/java/com/peoplehere/api/common/service/PrincipalDetailService.java @@ -0,0 +1,26 @@ +package com.peoplehere.api.common.service; + +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; + +import com.peoplehere.shared.common.repository.AccountRepository; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; + +@Slf4j +@Service +@RequiredArgsConstructor +public class PrincipalDetailService implements UserDetailsService { + + private final AccountRepository accountRepository; + + @Override + public UserDetails loadUserByUsername(String userId) throws UsernameNotFoundException { + log.debug("{}: LOGIN", userId); + return accountRepository.findByUserId(userId) + .orElseThrow(() -> new UsernameNotFoundException("해당 유저[%s]를 찾을 수 없습니다.".formatted(userId))); + } +} diff --git a/module-api/src/main/java/com/peoplehere/api/common/service/RedisTaskService.java b/module-api/src/main/java/com/peoplehere/api/common/service/RedisTaskService.java new file mode 100644 index 0000000..f532d9b --- /dev/null +++ b/module-api/src/main/java/com/peoplehere/api/common/service/RedisTaskService.java @@ -0,0 +1,92 @@ +package com.peoplehere.api.common.service; + +import static com.peoplehere.shared.common.config.redis.RedisKeyProperties.*; + +import java.util.Objects; +import java.util.concurrent.TimeUnit; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.core.ValueOperations; +import org.springframework.stereotype.Service; + +import com.peoplehere.api.common.config.security.Token; +import com.peoplehere.api.common.config.security.TokenProperties; +import com.peoplehere.api.common.config.security.VerifyCodeProperties; +import com.peoplehere.api.common.data.response.MailVerificationResponseDto; +import com.peoplehere.shared.common.webhook.AlertWebhook; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; + +@Slf4j +@Service +@RequiredArgsConstructor +public class RedisTaskService { + + @Value("${spring.profiles.active:}") + private String stage; + + private final TokenProperties tokenProperties; + private final VerifyCodeProperties verifyCodeProperties; + private final RedisTemplate redisTemplate; + private final AlertWebhook alertWebhook; + + /** + * 사용자의 refresh token을 저장 + * @param token refreshToken + * @param userId 사용자 id + */ + public void setRefreshToken(Token token, String userId) { + String key = generateRefreshTokenKey(stage, userId); + redisTemplate.opsForValue() + .set(key, token.refreshToken(), tokenProperties.getRefreshTime(), TimeUnit.MICROSECONDS); + log.info("refresh token 저장 성공 - userId: {}", userId); + } + + /** + * 이메일 인증 코드 레디스에 저장 + * @param email 이메일 + * @param code 랜덤 인증 코드 + */ + public MailVerificationResponseDto setEmailVerifyCode(String email, String code) { + String key = generateEmailVerifyCodeKey(stage, email); + redisTemplate.opsForValue() + .set(key, code, verifyCodeProperties.getEmailTimeout(), TimeUnit.SECONDS); + log.debug("email verify code 저장 성공 - email: {}", email); + return new MailVerificationResponseDto(verifyCodeProperties.getEmailTimeout()); + } + + /** + * 이메일 인증 코드 레디스에 있는지 확인 + * @param email 이메일 + * @return 인증 코드 + */ + public boolean checkEmailVerifyCode(String email, String code) { + String key = generateEmailVerifyCodeKey(stage, email); + boolean isMatch = checkValueMatch(key, code); + if (isMatch) { + redisTemplate.unlink(key); + log.debug("email verify code 삭제 성공 - email: {}", email); + } + return isMatch; + } + + /** + * key에 해당하는 value가 일치하는지 확인 + * @param key email verify code key + * @param value email verify code + * @return 일치 여부 + */ + private boolean checkValueMatch(String key, String value) { + try { + ValueOperations valueOperations = redisTemplate.opsForValue(); + return Objects.requireNonNull(value).equals(valueOperations.get(key)); + } catch (Exception e) { + log.error("redis에서 값 가져오기 실패 - key: {}", key, e); + alertWebhook.alertError("redis에서 값 가져오기 실패 key - [%s]. 우선은 false 반환 체크 필요".formatted(key), e.getMessage()); + return false; + } + } + +} diff --git a/module-api/src/main/java/com/peoplehere/api/common/service/VerifyService.java b/module-api/src/main/java/com/peoplehere/api/common/service/VerifyService.java new file mode 100644 index 0000000..3cec376 --- /dev/null +++ b/module-api/src/main/java/com/peoplehere/api/common/service/VerifyService.java @@ -0,0 +1,63 @@ +package com.peoplehere.api.common.service; + +import static com.peoplehere.api.common.util.MessageUtils.*; + +import org.springframework.mail.SimpleMailMessage; +import org.springframework.mail.javamail.JavaMailSender; +import org.springframework.stereotype.Service; + +import com.peoplehere.api.common.data.request.MailVerifyRequestDto; +import com.peoplehere.api.common.data.response.MailVerificationResponseDto; +import com.peoplehere.shared.common.webhook.AlertWebhook; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; + +@Slf4j +@Service +@RequiredArgsConstructor +public class VerifyService { + private final JavaMailSender sender; + private final RedisTaskService redisTaskService; + private final AlertWebhook alertWebhook; + + /** + * 이메일 인증 코드 생성 및 전송 + * @param email 이메일 + * @return 인증 코드 만료 시간 + */ + public MailVerificationResponseDto sendEmailVerificationCode(String email) { + try { + long start = System.currentTimeMillis(); + // 1. 이메일 인증 코드 생성 및 전송 + SimpleMailMessage message = new SimpleMailMessage(); + message.setTo(email); + message.setSubject("[PEOPLE-HERE] 이메일 인증을 위한 인증 코드 발송"); + message.setText(generateRandomEmailVerifyCode()); + sender.send(message); + + // 2. redis에 인증 코드 만료시간 포함해서 저장 후 만료시간 반환 + MailVerificationResponseDto dto = redisTaskService.setEmailVerifyCode(email, message.getText()); + + // 3. 이메일 인증 코드 전송 성공 알림 + alertWebhook.alertInfo("이메일 인증 코드 전송 성공", + "이메일: [%s], 소요시간: [%d]ms".formatted(email, System.currentTimeMillis() - start)); + return dto; + } catch (Exception e) { + String errorMessage = "이메일 인증 코드 전송 실패 - email: [%s]".formatted(email); + log.error(errorMessage, e); + alertWebhook.alertError(errorMessage, e.getMessage()); + throw new RuntimeException(errorMessage); + } + } + + /** + * 이메일 인증 코드 검증 + * @param requestDto 이메일 인증 코드 검증 요청 정보 + * @return 인증 성공 여부 + */ + public boolean checkEmailVerifyCode(MailVerifyRequestDto requestDto) { + return redisTaskService.checkEmailVerifyCode(requestDto.email(), requestDto.code()); + } + +} diff --git a/module-api/src/main/java/com/peoplehere/api/common/util/MessageUtils.java b/module-api/src/main/java/com/peoplehere/api/common/util/MessageUtils.java new file mode 100644 index 0000000..543c474 --- /dev/null +++ b/module-api/src/main/java/com/peoplehere/api/common/util/MessageUtils.java @@ -0,0 +1,19 @@ +package com.peoplehere.api.common.util; + +import java.security.SecureRandom; + +import lombok.experimental.UtilityClass; + +@UtilityClass +public class MessageUtils { + private static final SecureRandom random = new SecureRandom(); + + /** + * 메일 인증 번호를 위한 6자리 랜덤 숫자 생성 + * @return + */ + public static String generateRandomEmailVerifyCode() { + int sixDigitNumber = 100_000 + random.nextInt(900_000); + return String.valueOf(sixDigitNumber); + } +} diff --git a/module-api/src/main/java/com/peoplehere/api/common/util/RequestUtils.java b/module-api/src/main/java/com/peoplehere/api/common/util/RequestUtils.java new file mode 100644 index 0000000..234d0d2 --- /dev/null +++ b/module-api/src/main/java/com/peoplehere/api/common/util/RequestUtils.java @@ -0,0 +1,18 @@ +package com.peoplehere.api.common.util; + +import jakarta.servlet.http.HttpServletRequest; +import lombok.experimental.UtilityClass; + +@UtilityClass +public class RequestUtils { + + /** + * @param request + * @return ip 종류 여러개 셋팅되어 올 수 있음 + */ + public static String getIp(HttpServletRequest request) { + return request.getHeader("X-Forwarded-For") != null ? request.getHeader("X-Forwarded-For") : + request.getRemoteAddr(); + } + +} diff --git a/module-api/src/main/resources/application-api-dev.yml b/module-api/src/main/resources/application-api-dev.yml new file mode 100644 index 0000000..0be80a6 --- /dev/null +++ b/module-api/src/main/resources/application-api-dev.yml @@ -0,0 +1,25 @@ +spring.config.activate.on-profile: dev + +spring: + mail: + host: + port: + username: + password: + properties: + mail: + smtp: + auth: + timeout: # read timeout + starttls: + enable: + +token: + access-key: + refresh-key: + access-time: + refresh-time: + +verify: + email-timeout: + phone-timeout: diff --git a/module-api/src/main/resources/application-api-prod.yml b/module-api/src/main/resources/application-api-prod.yml new file mode 100644 index 0000000..40bb3e5 --- /dev/null +++ b/module-api/src/main/resources/application-api-prod.yml @@ -0,0 +1,25 @@ +spring.config.activate.on-profile: prod + +spring: + mail: + host: + port: + username: + password: + properties: + mail: + smtp: + auth: + timeout: # read timeout + starttls: + enable: + +token: + access-key: + refresh-key: + access-time: + refresh-time: + +verify: + email-timeout: + phone-timeout: diff --git a/module-api/src/main/resources/application-api-stg.yml b/module-api/src/main/resources/application-api-stg.yml new file mode 100644 index 0000000..62090ca --- /dev/null +++ b/module-api/src/main/resources/application-api-stg.yml @@ -0,0 +1,25 @@ +spring.config.activate.on-profile: stg + +spring: + mail: + host: + port: + username: + password: + properties: + mail: + smtp: + auth: + timeout: # read timeout + starttls: + enable: + +token: + access-key: + refresh-key: + access-time: + refresh-time: + +verify: + email-timeout: + phone-timeout: diff --git a/module-api/src/main/resources/application-api-test.yml b/module-api/src/main/resources/application-api-test.yml new file mode 100644 index 0000000..41e2191 --- /dev/null +++ b/module-api/src/main/resources/application-api-test.yml @@ -0,0 +1 @@ +spring.config.activate.on-profile: test diff --git a/module-api/src/main/resources/application.yml b/module-api/src/main/resources/application.yml new file mode 100644 index 0000000..cb66c62 --- /dev/null +++ b/module-api/src/main/resources/application.yml @@ -0,0 +1,74 @@ +spring: + profiles: + group: + local: [ "api-local", "shared-local" ] + dev: [ "api-dev", "shared-dev" ] + test: [ "api-test", "shared-test" ] + stg: [ "api-stg", "shared-stg" ] + prod: [ "api-prod", "shared-prod" ] + default: local + + application: + name: api + servlet: + multipart: + file-size-threshold: 2KB # 파일이 디스크에 기록되기 시작하는 임계값 + max-file-size: 10MB # 파일 하나당 최대 사이즈 + max-request-size: 50MB # 요청당 최대 사이즈 + + pid: + file: api.pid + + lifecycle: + timeout-per-shutdown-phase: 35s + + mail: + host: + port: + username: + password: + properties: + mail: + smtp: + auth: + timeout: + starttls: + enable: + +server: + compression: + enabled: true + shutdown: graceful + port: ${API_SERVER_PORT:8080} +app: + version: ${APP_VERSION:} + ip: + public: localhost + local: localhost +management: + endpoint: + health: + show-details: always + endpoints: + web: + exposure: + include: health, info, prometheus, loggers + metrics: + tags: + application: api + app_version: ${app.version} + stage: local + health: + diskspace: + path: / + +whitelist: + metrics: ${API_WHITELIST_METRICS} + private: ${API_WHITELIST_PRIVATE:0:0:0:0:0:0:0:1, localhost, 127.0.0.1} + private-instance: 10.0 + +token: + access-key: + refresh-key: + access-time: + refresh-time: diff --git a/module-api/src/main/resources/github.yml b/module-api/src/main/resources/github.yml new file mode 100644 index 0000000..215760f --- /dev/null +++ b/module-api/src/main/resources/github.yml @@ -0,0 +1,27 @@ +spring: + mail: + host: ${github_mail_host} + port: ${github_mail_port} + username: ${github_mail_username} + password: ${github_mail_password} + properties: + mail: + smtp: + auth: ${github_mail_auth} + timeout: ${github_mail_timeout} # read timeout + starttls: + enable: ${github_mail_starttls} + +whitelist: + metrics: ${API_WHITELIST_METRICS} + private: ${API_WHITELIST_PRIVATE} + +token: + access-key: ${github_access_key} + refresh-key: ${github_refresh_key} + access-time: ${github_access_time} + refresh-time: ${github_refresh_time} + +verify: + email-timeout: ${github_verify_email_timeout} + phone-timeout: ${github_verify_phone_timeout} diff --git a/module-shared/.gitignore b/module-shared/.gitignore new file mode 100644 index 0000000..c2065bc --- /dev/null +++ b/module-shared/.gitignore @@ -0,0 +1,37 @@ +HELP.md +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ diff --git a/module-shared/build.gradle b/module-shared/build.gradle new file mode 100644 index 0000000..e69de29 diff --git a/module-shared/src/main/java/com/peoplehere/shared/SharedApplication.java b/module-shared/src/main/java/com/peoplehere/shared/SharedApplication.java new file mode 100644 index 0000000..0caab82 --- /dev/null +++ b/module-shared/src/main/java/com/peoplehere/shared/SharedApplication.java @@ -0,0 +1,13 @@ +package com.peoplehere.shared; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SharedApplication { + + // 1. 초기화 + public static void main(String[] args) { + SpringApplication.run(SharedApplication.class, args); + } +} diff --git a/module-shared/src/main/java/com/peoplehere/shared/common/config/ObjectMapperConfig.java b/module-shared/src/main/java/com/peoplehere/shared/common/config/ObjectMapperConfig.java new file mode 100644 index 0000000..cb603fb --- /dev/null +++ b/module-shared/src/main/java/com/peoplehere/shared/common/config/ObjectMapperConfig.java @@ -0,0 +1,21 @@ +package com.peoplehere.shared.common.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; + +import lombok.AllArgsConstructor; + +@Configuration +@AllArgsConstructor +public class ObjectMapperConfig { + + @Bean + public ObjectMapper objectMapper() { + ObjectMapper objectMapper = new ObjectMapper(); + objectMapper.registerModule(new JavaTimeModule()); + return objectMapper; + } +} diff --git a/module-shared/src/main/java/com/peoplehere/shared/common/config/PersistenceConfig.java b/module-shared/src/main/java/com/peoplehere/shared/common/config/PersistenceConfig.java new file mode 100644 index 0000000..5946040 --- /dev/null +++ b/module-shared/src/main/java/com/peoplehere/shared/common/config/PersistenceConfig.java @@ -0,0 +1,23 @@ +package com.peoplehere.shared.common.config; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.jpa.repository.config.EnableJpaAuditing; + +import jakarta.annotation.PostConstruct; +import lombok.extern.slf4j.Slf4j; + +@Slf4j +@Configuration +@EnableJpaAuditing +public class PersistenceConfig { + + @Value("${spring.datasource.hikari.schema:}") + private String schema; + + @PostConstruct + public void print() { + log.info("활성화된 DB 스키마: {}", schema); + } + +} diff --git a/module-shared/src/main/java/com/peoplehere/shared/common/config/SharedWebConfig.java b/module-shared/src/main/java/com/peoplehere/shared/common/config/SharedWebConfig.java new file mode 100644 index 0000000..db1769e --- /dev/null +++ b/module-shared/src/main/java/com/peoplehere/shared/common/config/SharedWebConfig.java @@ -0,0 +1,76 @@ +package com.peoplehere.shared.common.config; + +import static org.springframework.http.HttpHeaders.*; +import static org.springframework.http.MediaType.*; + +import javax.sql.DataSource; + +import org.springframework.boot.autoconfigure.flyway.FlywayMigrationStrategy; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.boot.jdbc.DataSourceBuilder; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; +import org.springframework.http.client.SimpleClientHttpRequestFactory; +import org.springframework.web.client.RestClient; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +import com.zaxxer.hikari.HikariDataSource; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; + +@Slf4j +@Configuration +@RequiredArgsConstructor +public class SharedWebConfig implements WebMvcConfigurer { + + /** + * hikariCp 설정을 위한 Config + * @return + */ + @Bean(name = "datasource") + @Profile("!test") + @ConfigurationProperties("spring.datasource.hikari") + public DataSource dataSourceProperties() { + return DataSourceBuilder.create() + .type(HikariDataSource.class) + .build(); + } + + @Profile("!test") + @Bean + public FlywayMigrationStrategy cleanMigrateStrategy() { + return flyway -> { + flyway.repair(); + flyway.migrate(); + }; + } + + @Profile("test") + @Bean + public FlywayMigrationStrategy cleanMigrateStrategyForTest() { + return flyway -> { + flyway.clean(); + flyway.repair(); + flyway.migrate(); + }; + } + + /** + * 기본적인 RestClient timeout 설정 + * 추가적인 설정 필요시 해당 클래스에서 설정 + * @return + */ + @Bean + RestClient restClient() { + SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory(); + factory.setConnectTimeout(10_000); + factory.setReadTimeout(10_000); + return RestClient.builder() + .defaultHeader(CONTENT_TYPE, APPLICATION_JSON_VALUE) + .requestFactory(factory) + .build(); + } + +} diff --git a/module-shared/src/main/java/com/peoplehere/shared/common/config/redis/RedisConfig.java b/module-shared/src/main/java/com/peoplehere/shared/common/config/redis/RedisConfig.java new file mode 100644 index 0000000..3d42bee --- /dev/null +++ b/module-shared/src/main/java/com/peoplehere/shared/common/config/redis/RedisConfig.java @@ -0,0 +1,68 @@ +package com.peoplehere.shared.common.config.redis; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.redis.connection.RedisConnectionFactory; +import org.springframework.data.redis.connection.RedisStandaloneConfiguration; +import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration; +import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer; +import org.springframework.data.redis.serializer.StringRedisSerializer; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import jakarta.annotation.PostConstruct; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; + +@Slf4j +@Configuration +@RequiredArgsConstructor +public class RedisConfig { + + private final ObjectMapper objectMapper; + + private final RedisProperties redisProperties; + + @PostConstruct + public void log() { + log.info("레디스 호스트: {}", redisProperties.getHost()); + log.info("레디스 포트: {}", redisProperties.getPort()); + log.info("SSL 사용 여부: {}", redisProperties.isSslEnabled()); + log.info("레디스 데이터베이스: {}", redisProperties.getDatabase()); + } + + @Bean + public RedisConnectionFactory redisConnectionFactory() { + var redisStandaloneConfiguration = new RedisStandaloneConfiguration(redisProperties.getHost(), + redisProperties.getPort()); + + if (redisProperties.getDatabase() > 0) { + redisStandaloneConfiguration.setDatabase(redisProperties.getDatabase()); + } + + var lettuceClientConfigurationBuilder = LettuceClientConfiguration.builder(); + if (redisProperties.isSslEnabled()) { + lettuceClientConfigurationBuilder.useSsl(); + } + LettuceClientConfiguration lettuceClientConfiguration = lettuceClientConfigurationBuilder.build(); + + return new LettuceConnectionFactory(redisStandaloneConfiguration, lettuceClientConfiguration); + } + + @Bean + public RedisTemplate redisTemplate(RedisConnectionFactory connectionFactory) { + var redisTemplate = new RedisTemplate<>(); + redisTemplate.setConnectionFactory(connectionFactory); + + redisTemplate.setKeySerializer(new StringRedisSerializer()); + redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer(objectMapper)); + + redisTemplate.setHashKeySerializer(new StringRedisSerializer()); + redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer(objectMapper)); + + return redisTemplate; + } + +} diff --git a/module-shared/src/main/java/com/peoplehere/shared/common/config/redis/RedisKeyProperties.java b/module-shared/src/main/java/com/peoplehere/shared/common/config/redis/RedisKeyProperties.java new file mode 100644 index 0000000..2c3f9e5 --- /dev/null +++ b/module-shared/src/main/java/com/peoplehere/shared/common/config/redis/RedisKeyProperties.java @@ -0,0 +1,15 @@ +package com.peoplehere.shared.common.config.redis; + +import lombok.experimental.UtilityClass; + +@UtilityClass +public class RedisKeyProperties { + + public static String generateRefreshTokenKey(String prefix, String identifier) { + return "%s:spring:refresh:token:%s".formatted(prefix, identifier); + } + + public static String generateEmailVerifyCodeKey(String prefix, String email) { + return "%s:spring:email:verify:code:%s".formatted(prefix, email); + } +} diff --git a/module-shared/src/main/java/com/peoplehere/shared/common/config/redis/RedisProperties.java b/module-shared/src/main/java/com/peoplehere/shared/common/config/redis/RedisProperties.java new file mode 100644 index 0000000..28d9a78 --- /dev/null +++ b/module-shared/src/main/java/com/peoplehere/shared/common/config/redis/RedisProperties.java @@ -0,0 +1,19 @@ +package com.peoplehere.shared.common.config.redis; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +import lombok.Data; + +@Data +@Component +@ConfigurationProperties(prefix = "spring.data.redis") +public class RedisProperties { + protected String host; + + protected int port; + + protected boolean sslEnabled; + + protected int database; +} diff --git a/module-shared/src/main/java/com/peoplehere/shared/common/data/request/AlarmConsentRequestDto.java b/module-shared/src/main/java/com/peoplehere/shared/common/data/request/AlarmConsentRequestDto.java new file mode 100644 index 0000000..5e095f1 --- /dev/null +++ b/module-shared/src/main/java/com/peoplehere/shared/common/data/request/AlarmConsentRequestDto.java @@ -0,0 +1,11 @@ +package com.peoplehere.shared.common.data.request; + +import jakarta.validation.constraints.NotNull; +import lombok.Data; + +@Data +public class AlarmConsentRequestDto { + + @NotNull + private boolean consent; +} diff --git a/module-shared/src/main/java/com/peoplehere/shared/common/data/request/PasswordRequestDto.java b/module-shared/src/main/java/com/peoplehere/shared/common/data/request/PasswordRequestDto.java new file mode 100644 index 0000000..b394623 --- /dev/null +++ b/module-shared/src/main/java/com/peoplehere/shared/common/data/request/PasswordRequestDto.java @@ -0,0 +1,21 @@ +package com.peoplehere.shared.common.data.request; + +import static com.peoplehere.shared.common.util.PatternUtils.*; + +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.Pattern; +import lombok.Data; + +// todo: 정규표현식 중복 제거 +@Data +public class PasswordRequestDto { + + @NotBlank + private String email; + + @NotBlank + @Pattern( + regexp = PASSWORD_REGEX, + message = "패스워드 형식을 지켜주세요.") + private String newPassword; +} diff --git a/module-shared/src/main/java/com/peoplehere/shared/common/data/request/SignInRequestDto.java b/module-shared/src/main/java/com/peoplehere/shared/common/data/request/SignInRequestDto.java new file mode 100644 index 0000000..b1c1a1a --- /dev/null +++ b/module-shared/src/main/java/com/peoplehere/shared/common/data/request/SignInRequestDto.java @@ -0,0 +1,13 @@ +package com.peoplehere.shared.common.data.request; + +import jakarta.validation.constraints.NotBlank; +import lombok.Data; + +@Data +public class SignInRequestDto { + + @NotBlank + private String email; + @NotBlank + private String password; +} diff --git a/module-shared/src/main/java/com/peoplehere/shared/common/data/request/SignUpRequestDto.java b/module-shared/src/main/java/com/peoplehere/shared/common/data/request/SignUpRequestDto.java new file mode 100644 index 0000000..d063344 --- /dev/null +++ b/module-shared/src/main/java/com/peoplehere/shared/common/data/request/SignUpRequestDto.java @@ -0,0 +1,73 @@ +package com.peoplehere.shared.common.data.request; + +import static com.peoplehere.shared.common.util.PatternUtils.*; + +import java.time.LocalDate; + +import com.fasterxml.jackson.annotation.JsonFormat; +import com.peoplehere.shared.common.entity.Account; +import com.peoplehere.shared.common.entity.Consent; +import com.peoplehere.shared.common.enums.AccountRole; +import com.peoplehere.shared.common.enums.Gender; +import com.peoplehere.shared.common.enums.Region; + +import jakarta.validation.constraints.Email; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.Pattern; +import lombok.Data; + +@Data +public class SignUpRequestDto { + + @NotBlank + private String firstName; + + @NotBlank + private String lastName; + + @JsonFormat(pattern = "yyyyMMdd") + private LocalDate birthDate; + + private Gender gender; + + @NotBlank + @Email(message = "이메일 형식을 지켜주세요.") + private String email; + + @Pattern( + regexp = PASSWORD_REGEX, + message = "패스워드 형식을 지켜주세요.") + private String password; + + private Region region; + + private String phoneNumber; + + private boolean marketingConsent; + + private boolean privacyConsent; + + public static Account toClientAccount(SignUpRequestDto requestDto, String encodedPassword) { + return Account.builder() + .firstName(requestDto.getFirstName()) + .lastName(requestDto.getLastName()) + .userId(requestDto.getEmail()) + .email(requestDto.getEmail()) + .password(encodedPassword) + .phoneNumber(requestDto.getPhoneNumber()) + .region(requestDto.getRegion()) + .birthDate(requestDto.getBirthDate()) + .gender(requestDto.getGender()) + .role(AccountRole.USER) + .active(true) + .build(); + } + + public static Consent toConsent(SignUpRequestDto requestDto, Account account) { + return Consent.builder() + .accountId(account.getId()) + .privacyConsent(requestDto.isPrivacyConsent()) + .marketingConsent(requestDto.isMarketingConsent()) + .build(); + } +} diff --git a/module-shared/src/main/java/com/peoplehere/shared/common/data/request/TokenRequestDto.java b/module-shared/src/main/java/com/peoplehere/shared/common/data/request/TokenRequestDto.java new file mode 100644 index 0000000..17db346 --- /dev/null +++ b/module-shared/src/main/java/com/peoplehere/shared/common/data/request/TokenRequestDto.java @@ -0,0 +1,9 @@ +package com.peoplehere.shared.common.data.request; + +import lombok.Data; + +@Data +public class TokenRequestDto { + private String accessToken; + private String refreshToken; +} diff --git a/module-shared/src/main/java/com/peoplehere/shared/common/data/response/AccountResponseDto.java b/module-shared/src/main/java/com/peoplehere/shared/common/data/response/AccountResponseDto.java new file mode 100644 index 0000000..8ac6e7b --- /dev/null +++ b/module-shared/src/main/java/com/peoplehere/shared/common/data/response/AccountResponseDto.java @@ -0,0 +1,7 @@ +package com.peoplehere.shared.common.data.response; + +import lombok.Builder; + +@Builder +public record AccountResponseDto(String accessToken, String refreshToken) { +} diff --git a/module-shared/src/main/java/com/peoplehere/shared/common/data/response/ErrorResponseDto.java b/module-shared/src/main/java/com/peoplehere/shared/common/data/response/ErrorResponseDto.java new file mode 100644 index 0000000..39ad6cf --- /dev/null +++ b/module-shared/src/main/java/com/peoplehere/shared/common/data/response/ErrorResponseDto.java @@ -0,0 +1,60 @@ +package com.peoplehere.shared.common.data.response; + +import static java.util.stream.Collectors.*; + +import java.util.List; + +import org.springframework.validation.Errors; +import org.springframework.validation.FieldError; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +public class ErrorResponseDto { + + private String description; + @JsonInclude(JsonInclude.Include.NON_NULL) + @JsonProperty("bindErrors") + private List bindErrors; + + public ErrorResponseDto(String description) { + this.description = description; + } + + public ErrorResponseDto(String description, Errors errors) { + this(description); + setCustomFieldErrors(errors.getFieldErrors()); + } + + public ErrorResponseDto(Exception exception) { + this.description = exception.getMessage(); + } + + private void setCustomFieldErrors(List fieldErrors) { + this.bindErrors = fieldErrors.stream().map(error -> BindErrorResponseDto.builder() + .field(error.getField()) + .input(error.getRejectedValue()) + .message(error.getDefaultMessage()) + .build()) + .collect(toList()); + } + + /** + * 컨트롤러에서 요청 데이터 처리 중 발생한 바인딩 예외의 핸들링을 위한 DTO + */ + @Data + @Builder + @NoArgsConstructor + @AllArgsConstructor + private static class BindErrorResponseDto { + String field; + Object input; + String message; + } +} diff --git a/module-shared/src/main/java/com/peoplehere/shared/common/data/response/RegionResponseDto.java b/module-shared/src/main/java/com/peoplehere/shared/common/data/response/RegionResponseDto.java new file mode 100644 index 0000000..969ede9 --- /dev/null +++ b/module-shared/src/main/java/com/peoplehere/shared/common/data/response/RegionResponseDto.java @@ -0,0 +1,7 @@ +package com.peoplehere.shared.common.data.response; + +import lombok.Builder; + +@Builder +public record RegionResponseDto(String countryCode, String englishName, String koreanName, int dialCode) { +} diff --git a/module-shared/src/main/java/com/peoplehere/shared/common/entity/Account.java b/module-shared/src/main/java/com/peoplehere/shared/common/entity/Account.java new file mode 100644 index 0000000..d5ec5e1 --- /dev/null +++ b/module-shared/src/main/java/com/peoplehere/shared/common/entity/Account.java @@ -0,0 +1,169 @@ +package com.peoplehere.shared.common.entity; + +import java.io.Serial; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.List; + +import org.hibernate.annotations.Comment; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; + +import com.peoplehere.shared.common.enums.AccountAuthority; +import com.peoplehere.shared.common.enums.AccountRole; +import com.peoplehere.shared.common.enums.Gender; +import com.peoplehere.shared.common.enums.Region; + +import io.hypersistence.utils.hibernate.id.Tsid; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.EnumType; +import jakarta.persistence.Enumerated; +import jakarta.persistence.Id; +import jakarta.persistence.Table; +import jakarta.persistence.Transient; +import jakarta.validation.constraints.NotNull; +import lombok.AccessLevel; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.ToString; + +@Getter +@ToString +@Table(name = "account") +@Entity +@Builder +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@AllArgsConstructor +public class Account extends BaseTimeEntity implements UserDetails { + + @Serial + @Transient + private static final long serialVersionUID = 1L; + + @Id + @Tsid + private Long id; + + @Column(name = "first_name") + @Comment("성") + private String firstName; + + @Column(name = "last_name") + @Comment("이름") + private String lastName; + + @NotNull + @Comment("유저 아이디") + @Column(name = "user_id", nullable = false, unique = true) + private String userId; + + @Column + @Comment("비밀번호") + private String password; + + @NotNull + @Column(nullable = false, unique = true) + @Comment("이메일") + private String email; + + @Column(name = "phone_number") + @Comment("전화번호") + private String phoneNumber; + + @Column + @Comment("국가정보") + @Enumerated(EnumType.STRING) + private Region region; + + @Column(name = "birth_date") + @Comment("생년월일") + private LocalDate birthDate; + + @Column + @Enumerated(EnumType.STRING) + @Comment("성별") + private Gender gender; + + @Column + @Enumerated(EnumType.STRING) + @Comment("유저 권한") + AccountRole role; + + @Column + @Comment("유저 활성화 여부") + private boolean active; + + @Column(name = "deleted_at") + LocalDateTime deletedAt; + + @Override + public Collection getAuthorities() { + if (this.role == null) { + return Collections.emptyList(); + } + + List authorityList = new ArrayList<>(); + + authorityList.add(new SimpleGrantedAuthority(this.role.getValue())); + + Arrays.stream(AccountAuthority.values()) + .filter(accountAuthority -> this.role.hasAuthority(accountAuthority)) + .map(accountAuthority -> new SimpleGrantedAuthority(accountAuthority.getValue())) + .forEach(authorityList::add); + + return authorityList; + } + + @Override + public String getUsername() { + return userId; + } + + /** + * 계정이 만료되지 않았는지 리턴 + * @return + */ + @Override + public boolean isAccountNonExpired() { + return this.active; + } + + /** + * 계정이 잠겨있지 않은지 리턴 + * @return + */ + @Override + public boolean isAccountNonLocked() { + return this.active; + } + + /** + * 비밀번호가 만료되지 않았는지 리턴 + * @return + */ + @Override + public boolean isCredentialsNonExpired() { + return this.active; + } + + /** + * 계정이 활성화(사용가능)인지 리턴 + * @return + */ + @Override + public boolean isEnabled() { + return this.active; + } + + public void updatePassword(String encodedPassword) { + this.password = encodedPassword; + } +} diff --git a/module-shared/src/main/java/com/peoplehere/shared/common/entity/BaseTimeEntity.java b/module-shared/src/main/java/com/peoplehere/shared/common/entity/BaseTimeEntity.java new file mode 100644 index 0000000..3425064 --- /dev/null +++ b/module-shared/src/main/java/com/peoplehere/shared/common/entity/BaseTimeEntity.java @@ -0,0 +1,26 @@ +package com.peoplehere.shared.common.entity; + +import java.time.LocalDateTime; + +import org.springframework.data.annotation.CreatedDate; +import org.springframework.data.annotation.LastModifiedDate; +import org.springframework.data.jpa.domain.support.AuditingEntityListener; + +import jakarta.persistence.Column; +import jakarta.persistence.EntityListeners; +import jakarta.persistence.MappedSuperclass; +import lombok.Getter; + +@Getter +@MappedSuperclass +@EntityListeners(AuditingEntityListener.class) +public abstract class BaseTimeEntity { + + @CreatedDate + @Column(updatable = false, name = "created_at") + private LocalDateTime createdAt; + + @LastModifiedDate + @Column(name = "updated_at") + private LocalDateTime updatedAt; +} diff --git a/module-shared/src/main/java/com/peoplehere/shared/common/entity/Consent.java b/module-shared/src/main/java/com/peoplehere/shared/common/entity/Consent.java new file mode 100644 index 0000000..d12a938 --- /dev/null +++ b/module-shared/src/main/java/com/peoplehere/shared/common/entity/Consent.java @@ -0,0 +1,46 @@ +package com.peoplehere.shared.common.entity; + +import org.hibernate.annotations.Comment; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Table; +import jakarta.validation.constraints.NotNull; +import lombok.AccessLevel; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@Table(name = "consent") +@Entity +@Builder +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@AllArgsConstructor +public class Consent extends BaseTimeEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private long id; + + @NotNull + @Column(name = "account_id", nullable = false) + private long accountId; + + @Comment("개인정보 이용 동의") + @Column(name = "privacy_consent") + private Boolean privacyConsent; + + @Comment("마케팅 정보 수신 동의") + @Column(name = "marketing_consent") + private Boolean marketingConsent; + + @Comment("알람 수신 동의") + @Column(name = "alarm_consent") + private Boolean alarmConsent; + +} diff --git a/module-shared/src/main/java/com/peoplehere/shared/common/entity/Language.java b/module-shared/src/main/java/com/peoplehere/shared/common/entity/Language.java new file mode 100644 index 0000000..3672822 --- /dev/null +++ b/module-shared/src/main/java/com/peoplehere/shared/common/entity/Language.java @@ -0,0 +1,33 @@ +package com.peoplehere.shared.common.entity; + +import org.hibernate.annotations.Comment; + +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Table; +import lombok.AccessLevel; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.ToString; + +@Getter +@ToString +@Table(name = "language") +@Entity +@Builder +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@AllArgsConstructor +public class Language { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private int id; + + @Comment("언어명") + private String name; + +} diff --git a/module-shared/src/main/java/com/peoplehere/shared/common/entity/UserLanguage.java b/module-shared/src/main/java/com/peoplehere/shared/common/entity/UserLanguage.java new file mode 100644 index 0000000..ccc6b1b --- /dev/null +++ b/module-shared/src/main/java/com/peoplehere/shared/common/entity/UserLanguage.java @@ -0,0 +1,37 @@ +package com.peoplehere.shared.common.entity; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Table; +import jakarta.validation.constraints.NotNull; +import lombok.AccessLevel; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.ToString; + +@Getter +@ToString +@Table(name = "user_language") +@Entity +@Builder +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@AllArgsConstructor +public class UserLanguage extends BaseTimeEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private long id; + + @NotNull + @Column(name = "language_id", nullable = false) + private int languageId; + + @NotNull + @Column(name = "account_id", nullable = false) + private long accountId; +} diff --git a/module-shared/src/main/java/com/peoplehere/shared/common/enums/AccountAuthority.java b/module-shared/src/main/java/com/peoplehere/shared/common/enums/AccountAuthority.java new file mode 100644 index 0000000..2c9e7b1 --- /dev/null +++ b/module-shared/src/main/java/com/peoplehere/shared/common/enums/AccountAuthority.java @@ -0,0 +1,27 @@ +package com.peoplehere.shared.common.enums; + +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; + +import lombok.AllArgsConstructor; +import lombok.Getter; + +/** + * 유저가 가질 수 있는 권한을 정의한 Enum 클래스 + */ +@Getter +@AllArgsConstructor +public enum AccountAuthority { + + CHANGE_ROLE, + ACTIVE_USER, + READ_TOUR_POST, + CREATE_TOUR; + + public String getValue() { + return this.name(); + } + + private final GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(this.name()); + +} diff --git a/module-shared/src/main/java/com/peoplehere/shared/common/enums/AccountRole.java b/module-shared/src/main/java/com/peoplehere/shared/common/enums/AccountRole.java new file mode 100644 index 0000000..2d9ae4a --- /dev/null +++ b/module-shared/src/main/java/com/peoplehere/shared/common/enums/AccountRole.java @@ -0,0 +1,50 @@ +package com.peoplehere.shared.common.enums; + +import java.util.Arrays; +import java.util.List; + +import lombok.AllArgsConstructor; +import lombok.Getter; + +/** + * 유저의 역할을 정의한 Enum 클래스 + */ +@Getter +@AllArgsConstructor +public enum AccountRole { + + ADMIN("ROLE_ADMIN", Arrays.asList( + AccountAuthority.CHANGE_ROLE, + AccountAuthority.ACTIVE_USER, + AccountAuthority.READ_TOUR_POST, + AccountAuthority.CREATE_TOUR + )), + + USER("ROLE_USER", Arrays.asList( + AccountAuthority.READ_TOUR_POST, + AccountAuthority.CREATE_TOUR + )); + + private final String value; + private final List authorities; + + private static final AccountRole[] VALUES = values(); + + public boolean hasAuthority(AccountAuthority authority) { + return authorities.contains(authority); + } + + public boolean match(String value) { + return this.value.equals(value); + } + + public static AccountRole toAccountRole(String roleName) { + for (var role : VALUES) { + if (role.value.equals(roleName)) { + return role; + } + } + throw new IllegalArgumentException("유효하지 않은 ROLE 이름: " + roleName); + } + +} diff --git a/module-shared/src/main/java/com/peoplehere/shared/common/enums/Gender.java b/module-shared/src/main/java/com/peoplehere/shared/common/enums/Gender.java new file mode 100644 index 0000000..32efae7 --- /dev/null +++ b/module-shared/src/main/java/com/peoplehere/shared/common/enums/Gender.java @@ -0,0 +1,22 @@ +package com.peoplehere.shared.common.enums; + +import com.fasterxml.jackson.annotation.JsonValue; + +import lombok.AllArgsConstructor; +import lombok.Getter; + +@Getter +@AllArgsConstructor +public enum Gender { + + MALE, + FEMALE, + OTHER; + + public static final Gender[] VALUES = values(); + + @JsonValue + public String getGender() { + return this.name(); + } +} diff --git a/module-shared/src/main/java/com/peoplehere/shared/common/enums/Region.java b/module-shared/src/main/java/com/peoplehere/shared/common/enums/Region.java new file mode 100644 index 0000000..d740e8b --- /dev/null +++ b/module-shared/src/main/java/com/peoplehere/shared/common/enums/Region.java @@ -0,0 +1,80 @@ +package com.peoplehere.shared.common.enums; + +import static java.util.stream.Collectors.*; + +import java.util.List; +import java.util.stream.Stream; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.peoplehere.shared.common.data.response.RegionResponseDto; + +import lombok.Getter; + +@Getter +public enum Region { + // 북미 + CA("Canada", "캐나다", 1), + US("United States of America", "미국", 1), + + // 유럽 + AT("Republic of Austria", "오스트리아", 43), + BE("Kingdom of Belgium", "벨기에", 32), + CZ("Czech Republic", "체코", 420), + DK("Kingdom of Denmark", "덴마크", 45), + FI("Republic of Finland", "핀란드", 358), + FR("French Republic", "프랑스", 33), + DE("Federal Republic of Germany", "독일", 49), + IE("Republic of Ireland", "아일랜드", 353), + IT("Italian Republic", "이탈리아", 39), + NL("Kingdom of the Netherlands", "네덜란드", 31), + NO("Kingdom of Norway", "노르웨이", 47), + PL("Republic of Poland", "폴란드", 48), + PT("Portuguese Republic", "포르투갈", 351), + SK("Slovak Republic", "슬로바키아", 421), + ES("Kingdom of Spain", "스페인", 34), + SE("Kingdom of Sweden", "스웨덴", 46), + CH("Swiss Confederation", "스위스", 41), + GB("United Kingdom of Great Britain and Northern Ireland", "영국", 44), + + // 아시아 태평양 + AU("Commonwealth of Australia", "호주", 61), + JP("Japan", "일본", 81), + KR("Republic of Korea", "대한민국", 82), + RU("Russian Federation", "러시아", 7), + TW("Taiwan", "대만", 886); + + private final String englishName; + private final String koreanName; + private final int dialCode; + + public static final Region[] VALUES = values(); + public static final List REGION_INFO_LIST = Stream.of(VALUES) + .map(region -> RegionResponseDto.builder() + .englishName(region.getEnglishName()) + .koreanName(region.getKoreanName()) + .dialCode(region.getDialCode()) + .build()) + .collect(toList()); + + Region(String englishName, String koreanName, int dialCode) { + this.englishName = englishName; + this.koreanName = koreanName; + this.dialCode = dialCode; + } + + @JsonCreator + public static Region findByCode(String code) { + for (Region region : VALUES) { + if (region.name().equalsIgnoreCase(code)) { + return region; + } + } + throw new IllegalArgumentException("Invalid country code: " + code); + } + + @JsonValue + public String getCountryCode() { + return name(); + } +} diff --git a/module-shared/src/main/java/com/peoplehere/shared/common/repository/AccountRepository.java b/module-shared/src/main/java/com/peoplehere/shared/common/repository/AccountRepository.java new file mode 100644 index 0000000..b5e7ffa --- /dev/null +++ b/module-shared/src/main/java/com/peoplehere/shared/common/repository/AccountRepository.java @@ -0,0 +1,18 @@ +package com.peoplehere.shared.common.repository; + +import java.util.Optional; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import com.peoplehere.shared.common.entity.Account; + +@Repository +public interface AccountRepository extends JpaRepository { + Optional findByEmail(String email); + + Optional findByUserId(String userId); + + Boolean existsByEmail(String email); + +} diff --git a/module-shared/src/main/java/com/peoplehere/shared/common/repository/ConsentRepository.java b/module-shared/src/main/java/com/peoplehere/shared/common/repository/ConsentRepository.java new file mode 100644 index 0000000..1b18a95 --- /dev/null +++ b/module-shared/src/main/java/com/peoplehere/shared/common/repository/ConsentRepository.java @@ -0,0 +1,14 @@ +package com.peoplehere.shared.common.repository; + +import java.util.Optional; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import com.peoplehere.shared.common.entity.Consent; + +@Repository +public interface ConsentRepository extends JpaRepository { + + Optional findByAccountId(Long accountId); +} diff --git a/module-shared/src/main/java/com/peoplehere/shared/common/util/PatternUtils.java b/module-shared/src/main/java/com/peoplehere/shared/common/util/PatternUtils.java new file mode 100644 index 0000000..55b0fab --- /dev/null +++ b/module-shared/src/main/java/com/peoplehere/shared/common/util/PatternUtils.java @@ -0,0 +1,14 @@ +package com.peoplehere.shared.common.util; + +import java.util.regex.Pattern; + +import lombok.experimental.UtilityClass; + +@UtilityClass +public class PatternUtils { + + public static final String PASSWORD_REGEX = "^(?=.*[a-z])(?=.*[\\d!@#~^*&%]).{8,}$"; + public static final Pattern EMAIL_PATTERN = Pattern.compile( + "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,6}$" + ); +} diff --git a/module-shared/src/main/java/com/peoplehere/shared/common/webhook/AlertWebhook.java b/module-shared/src/main/java/com/peoplehere/shared/common/webhook/AlertWebhook.java new file mode 100644 index 0000000..58df803 --- /dev/null +++ b/module-shared/src/main/java/com/peoplehere/shared/common/webhook/AlertWebhook.java @@ -0,0 +1,11 @@ +package com.peoplehere.shared.common.webhook; + +/** + * 서버 알림 전송 서비스 - 추후 다양한 모듈에서 사용 및 discord뿐 아니라 slack 등 다양한 서비스 사용 목적 + */ +public interface AlertWebhook { + + void alertInfo(String title, String infoMessage); + + void alertError(String title, String errorMessage); +} diff --git a/module-shared/src/main/java/com/peoplehere/shared/common/webhook/DiscordMessage.java b/module-shared/src/main/java/com/peoplehere/shared/common/webhook/DiscordMessage.java new file mode 100644 index 0000000..39ac535 --- /dev/null +++ b/module-shared/src/main/java/com/peoplehere/shared/common/webhook/DiscordMessage.java @@ -0,0 +1,117 @@ +package com.peoplehere.shared.common.webhook; + +import java.util.ArrayList; +import java.util.List; + +import com.fasterxml.jackson.annotation.JsonProperty; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * Discord Webhook Message + * @see 요청-응답 명세 + */ +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class DiscordMessage { + private String content; + private String username; + @JsonProperty("avatar_url") + private String avatarUrl; + private boolean tts; + @JsonProperty("embeds") + @Builder.Default + private List embedList = new ArrayList<>(); + + public void addEmbed(EmbedObject embed) { + this.embedList.add(embed); + } + + @Data + public static class EmbedObject { + private String title; + private String description; + private String url; + private Integer color; + + private Footer footer; + private Thumbnail thumbnail; + private Image image; + private Author author; + private List fields = new ArrayList<>(); + + public void addField(String name, String value, boolean inline) { + this.fields.add(new Field(name, value, inline)); + } + + @Data + @Builder + @NoArgsConstructor + @AllArgsConstructor + private static class Footer { + private String text; + private String iconUrl; + } + + @Data + @Builder + private static class Thumbnail { + private String url; + } + + @Data + @Builder + private static class Image { + private String url; + } + + @Data + @Builder + @NoArgsConstructor + @AllArgsConstructor + private static class Author { + private String name; + private String url; + @JsonProperty("icon_url") + private String iconUrl; + } + + @Data + @Builder + @NoArgsConstructor + @AllArgsConstructor + public static class Field { + private String name; + private String value; + private boolean inline; + } + } + + static DiscordMessage toMessage(String title, String description, Integer color) { + var message = new DiscordMessage(); + var embedObject = new DiscordMessage.EmbedObject(); + embedObject.setTitle(title); + embedObject.setDescription(description); + embedObject.setColor(color); + message.addEmbed(embedObject); + return message; + } + + static DiscordMessage toMessage(String title, String description, Integer color, List fields) { + var message = new DiscordMessage(); + var embedObject = new DiscordMessage.EmbedObject(); + embedObject.setTitle(title); + embedObject.setDescription(description); + embedObject.setColor(color); + for (var field : fields) { + embedObject.addField(field.name, field.value, field.inline); + } + message.addEmbed(embedObject); + return message; + } +} diff --git a/module-shared/src/main/java/com/peoplehere/shared/common/webhook/DiscordWebhook.java b/module-shared/src/main/java/com/peoplehere/shared/common/webhook/DiscordWebhook.java new file mode 100644 index 0000000..e0684ae --- /dev/null +++ b/module-shared/src/main/java/com/peoplehere/shared/common/webhook/DiscordWebhook.java @@ -0,0 +1,124 @@ +package com.peoplehere.shared.common.webhook; + +import static com.peoplehere.shared.common.webhook.DiscordMessage.*; +import static org.springframework.http.HttpStatus.*; +import static org.springframework.http.MediaType.*; + +import java.lang.management.ManagementFactory; +import java.util.Collections; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.context.event.ApplicationStartedEvent; +import org.springframework.context.event.EventListener; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; +import org.springframework.web.client.RestClient; + +import jakarta.annotation.PostConstruct; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; + +/** + * 디스코드 웹훅의 rate-limit은 초당 5회로 제한됨. + * @see Rate Limits on Discord's API + */ +@Slf4j +@Component +@RequiredArgsConstructor +public class DiscordWebhook implements AlertWebhook { + + @Value("${webhook.discord.channel.alert:#{null}}") + String alertChannel; + @Value("${webhook.discord.channel.status:#{null}}") + String serverStatusChannel; + @Value("${webhook.discord.active:false}") + boolean webhookActive; + + @Value("${spring.application.name:#{null}}") + String appName; + @Value("${app.ip.public:#{null}}") + String publicIp; + @Value("${app.ip.local:#{null}}") + String localIp; + + private final RestClient restClient; + private static boolean isInit = false; + private static final int COLOR_GREEN = 65280; + private static final int COLOR_RED = 16711680; + + @PostConstruct + void init() { + log.info("discord webhook 초기화됨. 기본 알림채널 {}", alertChannel); + log.info("discord webhook 초기화됨. 서버상태 알림채널 {}", serverStatusChannel); + } + + /** + * spring application 시작시 시간 및 ip 기록 + * @param event + */ + @EventListener(ApplicationStartedEvent.class) + public void onStart(final ApplicationStartedEvent event) { + isInit = StringUtils.hasText(alertChannel) && StringUtils.hasText(serverStatusChannel); + + if (isInit) { + String title = "[%s] 모니터링 슬랙채널 활성화".formatted(appName); + String description = "public: %s | local: %s".formatted(publicIp, localIp); + String fieldContent = "%s초".formatted(((double)ManagementFactory.getRuntimeMXBean().getUptime() / 1000)); + DiscordMessage message = toMessage(title, description, COLOR_GREEN, + Collections.singletonList(new EmbedObject.Field("spring start", fieldContent, true))); + sendMessage(serverStatusChannel, message); + } + } + + @Override + public void alertInfo(String title, String infoMessage) { + + String formattedTitle = ":white_check_mark: %s".formatted(title); + String description = "**[알림]**: %s\n**[%s]** **public**: %s | **local**: %s".formatted(infoMessage, appName, + publicIp, localIp); + DiscordMessage message = toMessage(formattedTitle, description, COLOR_GREEN); + sendMessage(alertChannel, message); + } + + @Override + public void alertError(String title, String errorMessage) { + + String formattedTitle = ":warning: %s".formatted(title); + String description = "**[예외]**: %s\n**[%s]** **public**: %s | **local**: %s".formatted(errorMessage, appName, + publicIp, localIp); + DiscordMessage message = toMessage(formattedTitle, description, COLOR_RED); + sendMessage(alertChannel, message); + + } + + /** + * 디스코드 웹훅 전송 + * Todo: 추후 에러 응답이 자주 발생할 경우 retry 로직 추가 및 read timeout 조정 우선은 30초 + * @param channel + * @param message + */ + private void sendMessage(String channel, DiscordMessage message) { + if (!isInit || !webhookActive) { + log.warn("디스코드 웹훅 초기화 안됨. 스킵"); + return; + } + + try { + restClient.post() + .uri(channel) + .contentType(APPLICATION_JSON) + .body(message) + .exchange((request, response) -> { + if (response.getStatusCode().isSameCodeAs(NO_CONTENT)) { + log.info("디스코드 웹훅 전송 완료"); + } + if (response.getStatusCode().isError()) { + log.error("디스코드 웹훅 전송 실패 - code: {}. 우선은 skip", response.getStatusCode()); + } + return response; + }); + } catch (Exception e) { + log.error("디스코드 웹훅 전송 실패 우선은 skip", e); + } + } +} diff --git a/module-shared/src/main/resources/application-shared-dev.yml b/module-shared/src/main/resources/application-shared-dev.yml new file mode 100644 index 0000000..9c29fa1 --- /dev/null +++ b/module-shared/src/main/resources/application-shared-dev.yml @@ -0,0 +1,43 @@ +spring: + datasource: + hikari: + jdbcUrl: ${JDBC_URL:jdbc:postgresql://localhost:5432/postgres} + maximum-pool-size: 10 + username: + password: + driver-class-name: org.postgresql.Driver + schema: + + jpa: + show-sql: false + hibernate: + naming: + physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl + ddl-auto: validate + generate-ddl: false + properties: + hibernate: + format_sql: true + dialect: org.hibernate.dialect.PostgreSQLDialect + + flyway: + locations: classpath:/db/migration + sql-migration-suffixes: sql + baseline-on-migrate: true + baseline-version: 0 + default-schema: public + enabled: true + + data: + redis: + host: localhost + port: 6379 + database: 0 + ssl-enabled: false + +webhook: + discord: + active: true + channel: + alert: + status: diff --git a/module-shared/src/main/resources/application-shared-prod.yml b/module-shared/src/main/resources/application-shared-prod.yml new file mode 100644 index 0000000..9c29fa1 --- /dev/null +++ b/module-shared/src/main/resources/application-shared-prod.yml @@ -0,0 +1,43 @@ +spring: + datasource: + hikari: + jdbcUrl: ${JDBC_URL:jdbc:postgresql://localhost:5432/postgres} + maximum-pool-size: 10 + username: + password: + driver-class-name: org.postgresql.Driver + schema: + + jpa: + show-sql: false + hibernate: + naming: + physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl + ddl-auto: validate + generate-ddl: false + properties: + hibernate: + format_sql: true + dialect: org.hibernate.dialect.PostgreSQLDialect + + flyway: + locations: classpath:/db/migration + sql-migration-suffixes: sql + baseline-on-migrate: true + baseline-version: 0 + default-schema: public + enabled: true + + data: + redis: + host: localhost + port: 6379 + database: 0 + ssl-enabled: false + +webhook: + discord: + active: true + channel: + alert: + status: diff --git a/module-shared/src/main/resources/application-shared-sample.yml b/module-shared/src/main/resources/application-shared-sample.yml new file mode 100644 index 0000000..a4e90b3 --- /dev/null +++ b/module-shared/src/main/resources/application-shared-sample.yml @@ -0,0 +1,37 @@ +spring: + datasource: + hikari: + jdbcUrl: jdbc:postgresql://localhost:5432/postgres + maximum-pool-size: 10 + username: + password: + driver-class-name: org.postgresql.Driver + schema: public + + jpa: + show-sql: false + hibernate: + naming: + physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl + ddl-auto: validate + generate-ddl: false + properties: + hibernate: + format_sql: true + dialect: org.hibernate.dialect.PostgreSQLDialect + + flyway: + locations: classpath:/db/migration + sql-migration-suffixes: sql + baseline-on-migrate: true + baseline-version: 0 + default-schema: public + enabled: true + + data: + redis: + host: localhost + port: 6379 + database: 0 + ssl: + enabled: false diff --git a/module-shared/src/main/resources/application-shared-stg.yml b/module-shared/src/main/resources/application-shared-stg.yml new file mode 100644 index 0000000..9c29fa1 --- /dev/null +++ b/module-shared/src/main/resources/application-shared-stg.yml @@ -0,0 +1,43 @@ +spring: + datasource: + hikari: + jdbcUrl: ${JDBC_URL:jdbc:postgresql://localhost:5432/postgres} + maximum-pool-size: 10 + username: + password: + driver-class-name: org.postgresql.Driver + schema: + + jpa: + show-sql: false + hibernate: + naming: + physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl + ddl-auto: validate + generate-ddl: false + properties: + hibernate: + format_sql: true + dialect: org.hibernate.dialect.PostgreSQLDialect + + flyway: + locations: classpath:/db/migration + sql-migration-suffixes: sql + baseline-on-migrate: true + baseline-version: 0 + default-schema: public + enabled: true + + data: + redis: + host: localhost + port: 6379 + database: 0 + ssl-enabled: false + +webhook: + discord: + active: true + channel: + alert: + status: diff --git a/module-shared/src/main/resources/application-shared-test.yml b/module-shared/src/main/resources/application-shared-test.yml new file mode 100644 index 0000000..432aaf8 --- /dev/null +++ b/module-shared/src/main/resources/application-shared-test.yml @@ -0,0 +1,24 @@ +spring: + config: + activate: + on-profile: test + flyway: + enabled: false + clean-disabled: false + datasource: + hikari: + jdbc-url: + username: sa + password: + # driver-class-name: org.postgresql.Driver + driver-class-name: org.testcontainers.jdbc.ContainerDatabaseDriver + jpa: + # show-sql: true + properties: + hibernate: + # show-sql: true + # format_sql: true + dialect: org.hibernate.dialect.PostgreSQLDialect + # dialect: org.hibernate.dialect.PostgreSQL95Dialect + hibernate: + ddl-auto: create-drop diff --git a/module-shared/src/main/resources/db/migration/V1.1__init.sql b/module-shared/src/main/resources/db/migration/V1.1__init.sql new file mode 100644 index 0000000..be0ac1e --- /dev/null +++ b/module-shared/src/main/resources/db/migration/V1.1__init.sql @@ -0,0 +1,48 @@ +-- 유저 테이블 생성 +CREATE TABLE account +( + id BIGINT PRIMARY KEY, + first_name VARCHAR, + last_name VARCHAR, + user_id VARCHAR UNIQUE NOT NULL, -- 유저 아이디 + email VARCHAR UNIQUE NOT NULL, -- 이메일 + phone_number VARCHAR, + password VARCHAR, + region VARCHAR, + birth_date DATE, + gender VARCHAR, + role VARCHAR, + active BOOLEAN, + created_at TIMESTAMP NOT NULL default NOW(), + updated_at TIMESTAMP NOT NULL default NOW(), -- 수정일 + deleted_at TIMESTAMP NULL +); + +-- 약관 테이블 생성 +CREATE TABLE consent +( + id BIGINT NOT NULL GENERATED ALWAYS AS IDENTITY, + account_id BIGINT NOT NULL, + privacy_consent BOOLEAN NULL, + marketing_consent BOOLEAN NULL, + alarm_consent BOOLEAN NULL, + created_at TIMESTAMP NOT NULL default NOW(), + updated_at TIMESTAMP NOT NULL default NOW() -- 수정일 +); + +-- 언어 테이블 생성 +CREATE TABLE language +( + id INT NOT NULL GENERATED ALWAYS AS IDENTITY, + name VARCHAR +); + +-- 유저-언어 릴레이션 생성 +CREATE TABLE user_language +( + id BIGINT NOT NULL GENERATED ALWAYS AS IDENTITY, + language_id INT NOT NULL, + account_id BIGINT NOT NULL, + created_at TIMESTAMP NOT NULL default NOW(), + updated_at TIMESTAMP NOT NULL default NOW() -- 수정일 +); diff --git a/module-shared/src/main/resources/github.yml b/module-shared/src/main/resources/github.yml new file mode 100644 index 0000000..de6b3d5 --- /dev/null +++ b/module-shared/src/main/resources/github.yml @@ -0,0 +1,19 @@ +spring: + datasource: + hikari: + jdbcUrl: ${github_datasource_jdbc_url} + username: ${github_datasource_username} + password: ${github_datasource_password} + maximum-pool-size: ${github_datasource_maximum_pool_size} + schema: ${github_datasource_schema} + data: + redis: + host: ${github_redis_host} + ssl-enabled: ${github_redis_ssl} + +webhook: + discord: + active: ${github_webhook_discord_active} + channel: + alert: ${github_webhook_discord_channel_alert} + status: ${github_webhook_discord_channel_status} diff --git a/module-shared/src/test/java/com/peoplehere/shared/common/TestConfig.java b/module-shared/src/test/java/com/peoplehere/shared/common/TestConfig.java new file mode 100644 index 0000000..e62b578 --- /dev/null +++ b/module-shared/src/test/java/com/peoplehere/shared/common/TestConfig.java @@ -0,0 +1,26 @@ +package com.peoplehere.shared.common; + +import javax.sql.DataSource; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.jdbc.datasource.DriverManagerDataSource; + +/** + * 테스트 설정중 전역설정으로 포함될 값들을 정의 + */ +@TestConfiguration +public class TestConfig { + @Bean + public DataSource dataSource(@Value("${spring.datasource.hikari.jdbcUrl}") String url, + @Value("${spring.datasource.hikari.username}") String username, + @Value("${spring.datasource.hikari.password}") String password) { + + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setUrl(url); + dataSource.setUsername(username); + dataSource.setPassword(password); + return dataSource; + } +} diff --git a/module-shared/src/test/java/com/peoplehere/shared/common/TestContainerBaseTests.java b/module-shared/src/test/java/com/peoplehere/shared/common/TestContainerBaseTests.java new file mode 100644 index 0000000..26eb6f3 --- /dev/null +++ b/module-shared/src/test/java/com/peoplehere/shared/common/TestContainerBaseTests.java @@ -0,0 +1,23 @@ +package com.peoplehere.shared.common; + +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.Import; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.containers.wait.strategy.Wait; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Import({TestConfig.class}) +@EnableConfigurationProperties +@Testcontainers +public class TestContainerBaseTests { + + static final PostgreSQLContainer postgres; + + static { + postgres = new PostgreSQLContainer<>("postgres:15-alpine") + .withExposedPorts(5432) + .waitingFor(Wait.forLogMessage(".*ready to accept connections.*\\n", 1)); + postgres.start(); + } + +} diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..ab9f5b5 --- /dev/null +++ b/settings.gradle @@ -0,0 +1,3 @@ +rootProject.name = 'peoplehere' +include 'module-api' +include 'module-shared'