issue # 백엔드 서버 재구성

This commit is contained in:
2025-11-13 02:00:11 +00:00
parent d07a8ec65e
commit 8d0329187b
56 changed files with 99 additions and 1335 deletions

22
.env Normal file
View File

@@ -0,0 +1,22 @@
# PostgreSQL 설정
PGHOST=bkdhome.p-e.kr
PGPORT=15454
PGDATABASE=scheduler
PGUSER=baekyangdan
PGPASSWORD=qwas745478!
# Fastify 서버 포트
PORT=3000
# Gmail SMTP 설정
GMAIL_USER=bkd.scheduler@gmail.com
GMAIL_PASS= # 앱 비밀번호 또는 OAuth2 토큰
GMAIL_CLIENT_ID=688417162908-iqvnj4ceb8t1dkbjr70dtcafo27m8kqe.apps.googleusercontent.com
GMAIL_CLIENT_SECRET=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
GMAIL_REFRESH_TOKEN=1//04_pSivNoGpPUCgYIARAAGAQSNwF-L9IrO0Kx6jSzq_eQNjdl65f0O2iqKSNpFeZ3gtIGMhOk0oiZsnKrPfWs8jvuEic1NhUoZ0g
# SMTP 추가 옵션
SMTP_AUTH=true
SMTP_STARTTLS_ENABLE=true
SMTP_STARTTLS_REQUIRED=true
SMTP_AUTH_MECHANISMS=XOAUTH2

3
.gitattributes vendored
View File

@@ -1,3 +0,0 @@
/gradlew text eol=lf
*.bat text eol=crlf
*.jar binary

62
.gitignore vendored
View File

@@ -1,37 +1,33 @@
HELP.md
.gradle
build/
!gradle/wrapper/gradle-wrapper.jar
!**/src/main/**/build/
!**/src/test/**/build/
# Node.js
node_modules/
npm-debug.log*
yarn-error.log*
package-lock.json
yarn.lock
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
bin/
!**/src/main/**/bin/
!**/src/test/**/bin/
# TypeScript
dist/
*.tsbuildinfo
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
out/
!**/src/main/**/out/
!**/src/test/**/out/
# 환경 변수
# .env
# .env.*.local
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
### VS Code ###
# IDE / OS
.vscode/
.idea/
*.suo
*.ntvs*
*.njsproj
*.sln
.DS_Store
Thumbs.db
# PostgreSQL
*.db
*.sqlite
*.sqlite3
# Logs
logs/
*.log

View File

@@ -24,13 +24,6 @@ build: # This job runs in the build stage, which runs first.
tags:
- local-runner
before_script:
- export JAVA_HOME=/usr/lib/jvm/java-21-openjdk-arm64
- export PATH=$JAVA_HOME/bin:$PATH
script:
- echo "Compiling the code..."
- java --version
- chmod +x ./gradlew
- javac --version
- ./gradlew build --no-daemon -Pprofile=prod --refresh-dependencies
- ls
- echo "Compile complete."

View File

@@ -1,57 +0,0 @@
package com.baekyangdan.scheduler.service;
import java.util.Properties;
import org.springframework.stereotype.Service;
import com.google.auth.oauth2.AccessToken;
import com.google.auth.oauth2.UserCredentials;
import jakarta.mail.Message;
import jakarta.mail.Session;
import jakarta.mail.Transport;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeMessage;
@Service
public class MailService {
private static final String CLIENT_ID="688417162908-iqvnj4ceb8t1dkbjr70dtcafo27m8kqe.apps.googleusercontent.com";
private static final String CLIENT_SECRET="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";
private static final String REFRESH_TOKEN="1//04_pSivNoGpPUCgYIARAAGAQSNwF-L9IrO0Kx6jSzq_eQNjdl65f0O2iqKSNpFeZ3gtIGMhOk0oiZsnKrPfWs8jvuEic1NhUoZ0g";
private static final String USER_MAIL="baekyangdan@gmail.com";
public void sendTestMail() throws Exception {
UserCredentials credentials =
UserCredentials.newBuilder()
.setClientId(CLIENT_ID)
.setClientSecret(CLIENT_SECRET)
.setRefreshToken(REFRESH_TOKEN)
.build();
AccessToken accessToken = credentials.refreshAccessToken();
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth.mechanisms", "XOAUTH2");
Session session = Session.getInstance(props);
Transport transport = session.getTransport("smtp");
transport.connect("smtp.gmail.com", USER_MAIL, accessToken.getTokenValue());
Message message = new MimeMessage(session);
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("lapinuit966@gmail.com"));
message.setSubject("test Mail");
message.setText("test mail");
message.setFrom(new InternetAddress(USER_MAIL));
transport.sendMessage(message, message.getAllRecipients());
transport.close();
System.out.println("메일 전송 완료");
}
}

View File

@@ -1,54 +0,0 @@
plugins {
id 'java'
id 'org.springframework.boot' version '3.5.7'
id 'io.spring.dependency-management' version '1.1.7'
}
group = 'com.baekyangdan'
version = '0.0.1-SNAPSHOT'
description = 'Scheduler Service Backend API Server'
java {
toolchain {
// languageVersion = JavaLanguageVersion.of(21)
// vendor = JvmVendorSpec.ADOPTOPENJDK
}
}
tasks.withType(JavaCompile) {
sourceCompatibility = '21'
targetCompatibility = '21'
// 명시적으로 javac 경로 지정
options.fork = true
options.forkOptions.executable = System.getenv("JAVA_HOME") + "/bin/javac"
}
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-data-redis'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.boot:spring-boot-starter-mail'
implementation 'com.google.auth:google-auth-library-oauth2-http:1.40.0'
compileOnly 'org.projectlombok:lombok'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
runtimeOnly 'org.postgresql:postgresql'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
}
tasks.named('test') {
useJUnitPlatform()
}

Binary file not shown.

View File

@@ -1,7 +0,0 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

251
gradlew vendored
View File

@@ -1,251 +0,0 @@
#!/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.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# 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/HEAD/platforms/jvm/plugins-application/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
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# 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="\\\"\\\""
# 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
if ! command -v java >/dev/null 2>&1
then
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
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
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
# 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"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# 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" "$@"

94
gradlew.bat vendored
View File

@@ -1,94 +0,0 @@
@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
@rem SPDX-License-Identifier: Apache-2.0
@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=.
@rem This is normally unused
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% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
set CLASSPATH=
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 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!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

30
package.json Normal file
View File

@@ -0,0 +1,30 @@
{
"name": "fastify",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "ts-node src/server.ts",
"build": "tsc",
"start": "node dist/server.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": "",
"dependencies": {
"dotenv": "^17.2.3",
"fastify": "^5.6.2",
"fastify-postgres": "^3.6.0",
"nodemailer": "^7.0.10",
"pg": "^8.16.3"
},
"devDependencies": {
"@types/dotenv": "^6.1.1",
"@types/node": "^24.10.1",
"@types/nodemailer": "^7.0.3",
"@types/pg": "^8.15.6",
"ts-node": "^10.9.2",
"typescript": "^5.9.3"
}
}

View File

@@ -1 +0,0 @@
rootProject.name = 'scheduler'

View File

@@ -1,13 +0,0 @@
package com.baekyangdan.scheduler;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SchedulerApplication {
public static void main(String[] args) {
SpringApplication.run(SchedulerApplication.class, args);
}
}

View File

@@ -1,22 +0,0 @@
package com.baekyangdan.scheduler.code.user;
public enum SignUpValidationCode {
ID_EMPTY("ID를 입력해주십시오"),
ID_DUPLICATED("중복된 ID가 존재합니다"),
EMAIL_EMPTY("Email을 입력해주십시오"),
EMAIL_FORM_INVALID("Email 형식이 올바르지 않습니다"),
EMAIL_DUPLICATED("중복된 Email이 존재합니다"),
PASSWORD_EMPTY("비밀번호를 입력해주십시오"),
NAME_EMPTY("이름을 입력해주십시오"),
NICKNAME_EMPTY("닉네임을 입력해주십시오");
private String message;
SignUpValidationCode(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
}

View File

@@ -1,21 +0,0 @@
package com.baekyangdan.scheduler.code.user;
import com.fasterxml.jackson.annotation.JsonValue;
public enum UserStatus {
ACTIVE("active"),
WAIT("wait"),
REST("rest"),
WITHDRAW("withdraw");
private final String value;
UserStatus(String value) {
this.value = value;
}
@JsonValue
public String getValue() {
return value;
}
}

View File

@@ -1,18 +0,0 @@
package com.baekyangdan.scheduler.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
public class DisableWebSecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(auth -> auth.anyRequest().permitAll());
return http.build();
}
}

View File

@@ -1,52 +0,0 @@
package com.baekyangdan.scheduler.config;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import com.baekyangdan.scheduler.exception.AuthException;
import com.baekyangdan.scheduler.exception.BusinessException;
import com.baekyangdan.scheduler.exception.ValidationException;
import java.util.HashMap;
import java.util.Map;
@RestControllerAdvice
public class GlobalExceptionHandler {
// 에러 핸들러 목록
// 1. 비즈니스 로직 관련 예외 처리
// ex) 중복 데이터
@ExceptionHandler(BusinessException.class)
public ResponseEntity<Map<String, Object>> handleBusinessException(BusinessException e) {
Map<String, Object> body = new HashMap<>();
body.put("message", e.getMessage());
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(body);
}
// 2. 입력값 유효성 검사 관련 예외 처리
// ex) 데이터 타입 검사
@ExceptionHandler(ValidationException.class)
public ResponseEntity<Map<String, Object>> handleValidationException(ValidationException e) {
Map<String, Object> body = new HashMap<>();
body.put("message", e.getMessage());
return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).body(body);
}
// 3. 권한/인가 관련 예외 처리
// ex) 로그인이 필요한 서비스에 로그인 안 한 사람이 호출
@ExceptionHandler(AuthException.class)
public ResponseEntity<Map<String, Object>> handleAuthException(ValidationException e) {
Map<String, Object> body = new HashMap<>();
body.put("message", e.getMessage());
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(body);
}
// 4. 기타 예외 처리
@ExceptionHandler(Exception.class)
public ResponseEntity<Map<String, Object>> handleDefaultException(Exception e) {
Map<String, Object> body = new HashMap<>();
body.put("message", e.getMessage());
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(body);
}
}

View File

@@ -1,22 +0,0 @@
package com.baekyangdan.scheduler.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import lombok.Getter;
@Getter
@Component
public class MailConfig {
@Value("${spring.mail.username}")
private String username;
@Value("${spring.mail.clientId}")
private String clientId;
@Value("${spring.mail.clientSecret}")
private String clientSecret;
@Value("${spring.mail.refreshToken}")
private String refreshToken;
}

View File

@@ -1,15 +0,0 @@
package com.baekyangdan.scheduler.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
public class SecurityConfig {
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(10);
}
}

View File

@@ -1,17 +0,0 @@
package com.baekyangdan.scheduler.config;
import org.hibernate.boot.model.naming.Identifier;
import org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl;
import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment;
public class SnakeCaseNamingStrategy extends PhysicalNamingStrategyStandardImpl {
@Override
public Identifier toPhysicalColumnName(Identifier name, JdbcEnvironment jdbcEnv) {
String snakeCase = name.getText()
.replaceAll("([a-z])([A-Z])", "$1_$2")
.toLowerCase();
return Identifier.toIdentifier(snakeCase);
}
}

View File

@@ -1,5 +0,0 @@
package com.baekyangdan.scheduler.controller.comment;
public class CommentController {
}

View File

@@ -1,5 +0,0 @@
package com.baekyangdan.scheduler.controller.follow;
public class FollowController {
}

View File

@@ -1,5 +0,0 @@
package com.baekyangdan.scheduler.controller.schedule;
public class ScheduleController {
}

View File

@@ -1,42 +0,0 @@
package com.baekyangdan.scheduler.controller.user;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.baekyangdan.scheduler.repository.user.UserRepository;
import com.baekyangdan.scheduler.request.user.UserRequest;
import com.baekyangdan.scheduler.service.user.UserService;
import com.baekyangdan.scheduler.utils.converter.PasswordConverter;
@RestController
@RequestMapping("/user")
public class UserController {
private final UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
@PostMapping("/signup")
public ResponseEntity<String> signUp(@RequestBody UserRequest.SignUp body) {
try {
userService.signUp(body);
return new ResponseEntity<String> ("회원가입 완료", HttpStatus.OK);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return new ResponseEntity<String> (e.getMessage(), HttpStatus.BAD_REQUEST);
}
}
}

View File

@@ -1,5 +0,0 @@
package com.baekyangdan.scheduler.dto.comment;
public class CommentDto {
}

View File

@@ -1,5 +0,0 @@
package com.baekyangdan.scheduler.dto.follow;
public class FollowDto {
}

View File

@@ -1,5 +0,0 @@
package com.baekyangdan.scheduler.dto.schedule;
public class ScheduleDto {
}

View File

@@ -1,5 +0,0 @@
package com.baekyangdan.scheduler.dto.user;
public class UserDto {
}

View File

@@ -1,67 +0,0 @@
package com.baekyangdan.scheduler.entity.user;
import jakarta.persistence.*;
import lombok.*;
import org.hibernate.annotations.CreationTimestamp;
import com.baekyangdan.scheduler.code.user.UserStatus;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;
/**
* DB 상의 "USER" 테이블에 해당하는 Entity
*/
@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@AllArgsConstructor(access = AccessLevel.PRIVATE)
@Builder
@Entity
@Table(
name = "account",
indexes = @Index(name = "user_pk", columnList = "id")
)
public class UserEntity {
@Id
@GeneratedValue
@org.hibernate.annotations.UuidGenerator
@Column(nullable = false)
private UUID id;
@Column(nullable=false, length=50)
private String accountId;
@Column(nullable = false, length = 50)
private String name;
@Column(nullable = false, length = 100)
private String email;
@Builder.Default
@Column(nullable = false)
private boolean isDeleted = false;
@Column(nullable = false)
private String password;
@Column
private String nickname;
@Column
private LocalDateTime birthday;
@Builder.Default
@Column
private String status = UserStatus.WAIT.getValue();
@CreationTimestamp
@Column(updatable = false)
private LocalDateTime createdAt;
/**
* 사용자가 참여중인 일정들의 id 목록을 가져오는 1대다 매핑 컬럼
*/
// @OneToMany(mappedBy = "participant_id", cascade = CascadeType.ALL)
// private List<String> participatedScheduleList;
}

View File

@@ -1,7 +0,0 @@
package com.baekyangdan.scheduler.exception;
public class AuthException extends RuntimeException {
public AuthException(String message) {
super(message);
}
}

View File

@@ -1,7 +0,0 @@
package com.baekyangdan.scheduler.exception;
public class BusinessException extends RuntimeException {
public BusinessException(String message) {
super(message);
}
}

View File

@@ -1,7 +0,0 @@
package com.baekyangdan.scheduler.exception;
public class ValidationException extends RuntimeException {
public ValidationException(String message) {
super(message);
}
}

View File

@@ -1,5 +0,0 @@
package com.baekyangdan.scheduler.repository.comment;
public class CommentRepository {
}

View File

@@ -1,5 +0,0 @@
package com.baekyangdan.scheduler.repository.follow;
public class FollowRepository {
}

View File

@@ -1,5 +0,0 @@
package com.baekyangdan.scheduler.repository.schedule;
public class ScheduleRepository {
}

View File

@@ -1,22 +0,0 @@
package com.baekyangdan.scheduler.repository.user;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.baekyangdan.scheduler.entity.user.UserEntity;
@Repository
public interface UserRepository extends JpaRepository<UserEntity, String> {
Optional<UserEntity> findByEmail(String email);
@Transactional
@Modifying(clearAutomatically = true)
@Query("UPDATE UserEntity u SET u.password = :password WHERE u.email = :email")
int resetPasswordByEmail(@Param("password") String newPassword, @Param("email") String email);
}

View File

@@ -1,84 +0,0 @@
package com.baekyangdan.scheduler.request.user;
import java.time.LocalDateTime;
import com.baekyangdan.scheduler.code.user.UserStatus;
import lombok.Getter;
import lombok.Setter;
/**
* 회원 관련 요청 데이터 클래스
*/
public class UserRequest {
// 프로그램 실행 순서에 맞춰서 클래스 작성
// 1. 회원 가입
// 1-1. Id 중복 검사 요청 클래스
@Getter
@Setter
public static class CheckIdDuplication {
private String id;
}
// 1-2. 이메일 중복 검사 요청 클래스
@Getter
@Setter
public static class CheckEmailDuplication {
private String email;
}
// 1-3. 회원 가입 요청 클래스
@Getter
@Setter
public static class SignUp {
private String accountId;
private String email;
private String name;
private String nickname;
private String password;
}
// 2. 로그인
// 2-1. 비밀번호 초기화 요청 클래스
@Getter
@Setter
public static class ResetPassword {
private String email;
private String passwordResetCode;
}
// 2-2. 로그인 요청 클래스
@Getter
@Setter
public static class Login {
// identifier: id or email
private String identifier;
private String password;
}
// 3. 회원 정보 수정 요청 클래스
@Getter
@Setter
public static class Update {
private String newId;
private String newName;
private String newEmail;
private String newPassword;
private LocalDateTime newBirthday;
private UserStatus newUserStatus;
}
// 4. 회원 탈퇴 요청 클래스
@Getter
@Setter
public static class Delete {
private String id;
}
// 5. id로 회원 목록 검색 요청 클래스
@Getter
@Setter
public static class FindById {
private String id;
}
}

View File

@@ -1,5 +0,0 @@
package com.baekyangdan.scheduler.service.comment;
public class CommentService {
}

View File

@@ -1,5 +0,0 @@
package com.baekyangdan.scheduler.service.follow;
public class FollowService {
}

View File

@@ -1,57 +0,0 @@
package com.baekyangdan.scheduler.service.mail;
import java.util.Properties;
import org.springframework.stereotype.Service;
import com.google.auth.oauth2.AccessToken;
import com.google.auth.oauth2.UserCredentials;
import jakarta.mail.Message;
import jakarta.mail.Session;
import jakarta.mail.Transport;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeMessage;
@Service
public class MailService {
private static final String CLIENT_ID="688417162908-iqvnj4ceb8t1dkbjr70dtcafo27m8kqe.apps.googleusercontent.com";
private static final String CLIENT_SECRET="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";
private static final String REFRESH_TOKEN="1//04_pSivNoGpPUCgYIARAAGAQSNwF-L9IrO0Kx6jSzq_eQNjdl65f0O2iqKSNpFeZ3gtIGMhOk0oiZsnKrPfWs8jvuEic1NhUoZ0g";
private static final String USER_MAIL="baekyangdan@gmail.com";
public void sendTestMail() throws Exception {
UserCredentials credentials =
UserCredentials.newBuilder()
.setClientId(CLIENT_ID)
.setClientSecret(CLIENT_SECRET)
.setRefreshToken(REFRESH_TOKEN)
.build();
AccessToken accessToken = credentials.refreshAccessToken();
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth.mechanisms", "XOAUTH2");
Session session = Session.getInstance(props);
Transport transport = session.getTransport("smtp");
transport.connect("smtp.gmail.com", USER_MAIL, accessToken.getTokenValue());
Message message = new MimeMessage(session);
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("lapinuit966@gmail.com"));
message.setSubject("test Mail");
message.setText("test mail");
message.setFrom(new InternetAddress(USER_MAIL));
transport.sendMessage(message, message.getAllRecipients());
transport.close();
System.out.println("메일 전송 완료");
}
}

View File

@@ -1,5 +0,0 @@
package com.baekyangdan.scheduler.service.schedule;
public class ScheduleService {
}

View File

@@ -1,46 +0,0 @@
package com.baekyangdan.scheduler.service.user;
import com.baekyangdan.scheduler.code.user.UserStatus;
import com.baekyangdan.scheduler.entity.user.UserEntity;
import com.baekyangdan.scheduler.repository.user.UserRepository;
import com.baekyangdan.scheduler.request.user.UserRequest;
import com.baekyangdan.scheduler.utils.converter.PasswordConverter;
import com.baekyangdan.scheduler.utils.validation.UserValidation;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
@Service
public class UserService {
private final UserRepository userRepository;
private final PasswordConverter passwordConverter;
public UserService(UserRepository userRepository, PasswordConverter passwordConverter) {
this.userRepository = userRepository;
this.passwordConverter = passwordConverter;
}
// 회원가입 로직
public UserEntity signUp(UserRequest.SignUp data) throws Exception {
// 1. 요청받은 데이터가 회원가입 양식을 준수하는지 검사한다.
// 1-1. 회원가입 양식에 맞지 않는 데이터가 있을 경우, validateSignUpForm 함수 내에서 예외를 던져 함수 동작 중단
UserValidation.validateSignUpForm(data);
// 2. data 안의 평문 비밀번호 암호화
String encodedPassword = passwordConverter.encode(data.getPassword());
// 3. data 를 UserEntity 형식으로 build
UserEntity user = UserEntity
.builder()
.accountId(data.getAccountId())
.email(data.getEmail())
.name(data.getName())
.nickname(data.getNickname())
.password(encodedPassword)
.createdAt(LocalDateTime.now())
.build();
// 4. build 된 entity를 UserRepository.save 로 DB에 저장
return userRepository.save(user);
}
}

View File

@@ -1,21 +0,0 @@
package com.baekyangdan.scheduler.utils.converter;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
@Component
public class PasswordConverter {
private final PasswordEncoder passwordEncoder;
public PasswordConverter(PasswordEncoder passwordEncoder) {
this.passwordEncoder = passwordEncoder;
}
public String encode(String rawPassword) {
return passwordEncoder.encode(rawPassword);
}
public boolean matches(String rawPassword, String encodedPassword) {
return passwordEncoder.matches(rawPassword, encodedPassword);
}
}

View File

@@ -1,46 +0,0 @@
package com.baekyangdan.scheduler.utils.generator;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class PasswordGenerator {
private static final String DIGITS = "0123456789";
private static final String LOWER = "abcdefghijklmnopqrstuvwxyz";
private static final String UPPER = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static final String SPECIAL="!@#$";
private static final String ALL = DIGITS + LOWER + UPPER + SPECIAL;
private static final SecureRandom random = new SecureRandom();
public static String generateRandomPassword() {
int length = 10;
List<Character> passwordCharacters = new ArrayList<>(length);
passwordCharacters.add(randomCharFrom(DIGITS));
passwordCharacters.add(randomCharFrom(LOWER));
passwordCharacters.add(randomCharFrom(UPPER));
passwordCharacters.add(randomCharFrom(SPECIAL));
for (int i = 4; i < length; i++) {
passwordCharacters.add(randomCharFrom(ALL));
}
Collections.shuffle(passwordCharacters, random);
StringBuilder sb = new StringBuilder(length);
for (char c : passwordCharacters) {
sb.append(c);
}
return sb.toString();
}
private static char randomCharFrom(String s) {
int idx = random.nextInt(s.length());
return s.charAt(idx);
}
}

View File

@@ -1,35 +0,0 @@
package com.baekyangdan.scheduler.utils.generator;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class RandomCodeGenerator {
private static final String DIGITS = "0123456789";
private static final SecureRandom random = new SecureRandom();
public static String generateRandomCode(int length) {
List<Character> codeCharacters = new ArrayList<>(length);
for (int i = 0; i < length; i++) {
codeCharacters.add(randomChar());
}
Collections.shuffle(codeCharacters, random);
StringBuilder sb = new StringBuilder(length);
for (char c : codeCharacters) {
sb.append(c);
}
return sb.toString();
}
private static char randomChar() {
int idx = random.nextInt(DIGITS.length());
return DIGITS.charAt(idx);
}
}

View File

@@ -1,32 +0,0 @@
package com.baekyangdan.scheduler.utils.validation;
import java.util.regex.Pattern;
public class BaseValidation {
private final static Pattern emailPattern = Pattern.compile("^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{1,}$");
private final static Pattern phoneNumberPattern = Pattern.compile("^010-\\d{4}-\\d{4}$");
protected static boolean matchEmailPattern(String email) {
if (validateStringEmpty(email)) {
return false;
}
return emailPattern.matcher(email).matches();
}
protected static boolean matchPhoneNumberPattern(String phoneNumber) {
if (validateStringEmpty(phoneNumber)) {
return false;
}
return phoneNumberPattern.matcher(phoneNumber).matches();
}
protected static boolean validateStringEmpty(String value) {
if (value == null) {
return true;
}
if (value.trim().isEmpty()) {
return true;
}
return false;
}
}

View File

@@ -1,37 +0,0 @@
package com.baekyangdan.scheduler.utils.validation;
import org.springframework.security.access.method.P;
import com.baekyangdan.scheduler.code.user.SignUpValidationCode;
import com.baekyangdan.scheduler.repository.user.UserRepository;
import com.baekyangdan.scheduler.request.user.UserRequest;
import com.baekyangdan.scheduler.utils.validation.BaseValidation;
public class UserValidation extends BaseValidation {
public static boolean validateSignUpForm(UserRequest.SignUp data) throws Exception {
if (validateStringEmpty(data.getAccountId())) {
throw new Exception(SignUpValidationCode.ID_EMPTY.getMessage());
}
if (validateStringEmpty(data.getEmail())) {
throw new Exception(SignUpValidationCode.EMAIL_EMPTY.getMessage());
}
if (validateStringEmpty(data.getPassword())) {
throw new Exception(SignUpValidationCode.PASSWORD_EMPTY.getMessage());
}
if (validateStringEmpty(data.getName())) {
throw new Exception(SignUpValidationCode.NAME_EMPTY.getMessage());
}
if (validateStringEmpty(data.getNickname())) {
throw new Exception(SignUpValidationCode.NICKNAME_EMPTY.getMessage());
}
return true;
}
}

View File

@@ -1,20 +0,0 @@
spring.datasource.url=jdbc:postgresql://192.168.219.107:5454/scheduler
spring.datasource.username=baekyangdan
spring.datasource.password=qwas745478!
spring.datasource.driver-class-name=org.postgresql.Driver
spring.devtools.restart.enabled=true
spring.devtools.livereload.enabled=true
spring.mail.host=smtp.google.com
spring.mail.port=587
spring.mail.username=bkd.scheduler@gmail.com
spring.mail.protocol=smtp
spring.mail.clientId=688417162908-iqvnj4ceb8t1dkbjr70dtcafo27m8kqe.apps.googleusercontent.com
spring.mail.clientSecret=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
spring.mail.refreshToken=1//04_pSivNoGpPUCgYIARAAGAQSNwF-L9IrO0Kx6jSzq_eQNjdl65f0O2iqKSNpFeZ3gtIGMhOk0oiZsnKrPfWs8jvuEic1NhUoZ0g
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
spring.mail.properties.mail.smtp.auth.mechanisms=XOAUTH2

View File

@@ -1,20 +0,0 @@
spring.datasource.url=jdbc:postgresql://bkdhome.p-e.kr:15454/scheduler
spring.datasource.username=baekyangdan
spring.datasource.password=qwas745478!
spring.datasource.driver-class-name=org.postgresql.Driver
spring.devtools.restart.enabled=true
spring.devtools.livereload.enabled=true
spring.mail.host=smtp.google.com
spring.mail.port=587
spring.mail.username=bkd.scheduler@gmail.com
spring.mail.protocol=smtp
spring.mail.clientId=688417162908-iqvnj4ceb8t1dkbjr70dtcafo27m8kqe.apps.googleusercontent.com
spring.mail.clientSecret=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
spring.mail.refreshToken=1//04_pSivNoGpPUCgYIARAAGAQSNwF-L9IrO0Kx6jSzq_eQNjdl65f0O2iqKSNpFeZ3gtIGMhOk0oiZsnKrPfWs8jvuEic1NhUoZ0g
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
spring.mail.properties.mail.smtp.auth.mechanisms=XOAUTH2

View File

@@ -1,16 +0,0 @@
spring.application.name=scheduler
spring.profiles.active=local
spring.mail.host=smtp.google.com
spring.mail.port=587
spring.mail.username=bkd.scheduler@gmail.com
spring.mail.protocol=smtp
spring.mail.clientId=688417162908-iqvnj4ceb8t1dkbjr70dtcafo27m8kqe.apps.googleusercontent.com
spring.mail.clientSecret=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
spring.mail.refreshToken=1//04_pSivNoGpPUCgYIARAAGAQSNwF-L9IrO0Kx6jSzq_eQNjdl65f0O2iqKSNpFeZ3gtIGMhOk0oiZsnKrPfWs8jvuEic1NhUoZ0g
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
spring.mail.properties.mail.smtp.auth.mechanisms=XOAUTH2

View File

@@ -1,13 +0,0 @@
package com.baekyangdan.scheduler;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class SchedulerApplicationTests {
@Test
void contextLoads() {
}
}

14
tsconfig.json Normal file
View File

@@ -0,0 +1,14 @@
{
"compilerOptions": {
"target": "esnext",
"module": "CommonJS",
"lib": ["ESNext"],
"outDir": "dist",
"rootDir": "src",
"strict": true,
"esModuleInterop": true,
"resolveJsonModule": true,
"forceConsistentCasingInFileNames": true
},
"include": ["src/**/*"]
}