├── .github ├── CODEOWNERS ├── PULL_REQUEST_TEMPLATE.md ├── workflows │ ├── pr-labeler.yml │ └── build-and-deploy.yaml └── labeler.yml ├── settings.gradle.kts ├── src ├── main │ ├── kotlin │ │ └── com │ │ │ └── depromeet │ │ │ └── makers │ │ │ ├── domain │ │ │ ├── vo │ │ │ │ ├── Age.kt │ │ │ │ ├── Image.kt │ │ │ │ ├── TeamHistory.kt │ │ │ │ ├── TokenPair.kt │ │ │ │ ├── MemberLink.kt │ │ │ │ ├── SessionPlace.kt │ │ │ │ └── Code.kt │ │ │ ├── enums │ │ │ │ ├── MemberRole.kt │ │ │ │ ├── MemberStatus.kt │ │ │ │ ├── SocialCredentialsProvider.kt │ │ │ │ ├── WebsiteType.kt │ │ │ │ ├── MemberPosition.kt │ │ │ │ └── SessionType.kt │ │ │ ├── exception │ │ │ │ ├── DomainException.kt │ │ │ │ └── ErrorCode.kt │ │ │ ├── SocialCredentials.kt │ │ │ ├── Member.kt │ │ │ └── Session.kt │ │ │ ├── presentation │ │ │ └── web │ │ │ │ ├── dto │ │ │ │ ├── response │ │ │ │ │ ├── DefaultResponse.kt │ │ │ │ │ ├── ErrorResponse.kt │ │ │ │ │ ├── AppleKeyResponse.kt │ │ │ │ │ ├── AuthenticationResponse.kt │ │ │ │ │ ├── KakaoAccountResponse.kt │ │ │ │ │ └── SessionResponse.kt │ │ │ │ └── request │ │ │ │ │ ├── AppleLoginRequest.kt │ │ │ │ │ ├── KakaoLoginRequest.kt │ │ │ │ │ ├── RefreshTokenRequest.kt │ │ │ │ │ ├── TestLoginRequest.kt │ │ │ │ │ └── SessionRequest.kt │ │ │ │ ├── SessionController.kt │ │ │ │ ├── AuthController.kt │ │ │ │ └── AdminSessionController.kt │ │ │ ├── util │ │ │ ├── Logger.kt │ │ │ └── AuthenticationUtil.kt │ │ │ ├── repository │ │ │ ├── MemberRepository.kt │ │ │ ├── SocialCredentialsRepository.kt │ │ │ ├── client │ │ │ │ ├── AppleAuthClient.kt │ │ │ │ └── KakaoAuthClient.kt │ │ │ └── SessionRepository.kt │ │ │ ├── DepromeetMakersBeApplication.kt │ │ │ ├── config │ │ │ ├── properties │ │ │ │ └── AppProperties.kt │ │ │ ├── MongoConfig.kt │ │ │ ├── SwaggerConfig.kt │ │ │ ├── WebExceptionHandler.kt │ │ │ ├── WebConfig.kt │ │ │ ├── filters │ │ │ │ └── JWTAuthenticationFilter.kt │ │ │ └── WebSecurityConfig.kt │ │ │ ├── components │ │ │ ├── SocialLoginProvider.kt │ │ │ └── JWTTokenProvider.kt │ │ │ └── service │ │ │ ├── SessionService.kt │ │ │ └── AuthService.kt │ └── resources │ │ └── application.yaml └── test │ └── kotlin │ └── com │ └── depromeet │ └── makers │ └── DepromeetMakersBeApplicationTests.kt ├── gradle └── wrapper │ └── gradle-wrapper.properties ├── .gitignore ├── .jpb └── jpb-settings.xml ├── HELP.md ├── gradlew.bat └── gradlew /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | * @CChuYong @ddingmin -------------------------------------------------------------------------------- /settings.gradle.kts: -------------------------------------------------------------------------------- 1 | rootProject.name = "depromeet-makers-be" 2 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | # 💡 기능 2 | 3 | # 🔎 기타 4 | 5 | 6 | -------------------------------------------------------------------------------- /src/main/kotlin/com/depromeet/makers/domain/vo/Age.kt: -------------------------------------------------------------------------------- 1 | package com.depromeet.makers.domain.vo 2 | 3 | @JvmInline 4 | value class Age( 5 | val age: Int 6 | ) 7 | -------------------------------------------------------------------------------- /src/main/kotlin/com/depromeet/makers/domain/enums/MemberRole.kt: -------------------------------------------------------------------------------- 1 | package com.depromeet.makers.domain.enums 2 | 3 | enum class MemberRole { 4 | ADMIN, 5 | USER, 6 | } 7 | -------------------------------------------------------------------------------- /src/main/kotlin/com/depromeet/makers/presentation/web/dto/response/DefaultResponse.kt: -------------------------------------------------------------------------------- 1 | package com.depromeet.makers.presentation.web.dto.response 2 | 3 | class DefaultResponse 4 | -------------------------------------------------------------------------------- /src/main/kotlin/com/depromeet/makers/domain/vo/Image.kt: -------------------------------------------------------------------------------- 1 | package com.depromeet.makers.domain.vo 2 | 3 | data class Image( 4 | val url: String, 5 | val revision: Long, 6 | ) 7 | -------------------------------------------------------------------------------- /src/main/kotlin/com/depromeet/makers/domain/vo/TeamHistory.kt: -------------------------------------------------------------------------------- 1 | package com.depromeet.makers.domain.vo 2 | 3 | data class TeamHistory( 4 | val generation: Int, 5 | val team: Int?, 6 | ) 7 | -------------------------------------------------------------------------------- /src/main/kotlin/com/depromeet/makers/domain/vo/TokenPair.kt: -------------------------------------------------------------------------------- 1 | package com.depromeet.makers.domain.vo 2 | 3 | data class TokenPair( 4 | val accessToken: String, 5 | val refreshToken: String, 6 | ) 7 | -------------------------------------------------------------------------------- /src/main/kotlin/com/depromeet/makers/domain/enums/MemberStatus.kt: -------------------------------------------------------------------------------- 1 | package com.depromeet.makers.domain.enums 2 | 3 | enum class MemberStatus { 4 | REGISTERED, 5 | UNREGISTERED, 6 | PENDING, 7 | } 8 | -------------------------------------------------------------------------------- /src/main/kotlin/com/depromeet/makers/domain/exception/DomainException.kt: -------------------------------------------------------------------------------- 1 | package com.depromeet.makers.domain.exception 2 | 3 | class DomainException( 4 | val errorCode: ErrorCode, 5 | ) : RuntimeException() 6 | -------------------------------------------------------------------------------- /src/main/kotlin/com/depromeet/makers/util/Logger.kt: -------------------------------------------------------------------------------- 1 | package com.depromeet.makers.util 2 | 3 | import org.slf4j.LoggerFactory 4 | 5 | inline fun T.logger() = LoggerFactory.getLogger(T::class.java)!! 6 | -------------------------------------------------------------------------------- /src/main/kotlin/com/depromeet/makers/domain/enums/SocialCredentialsProvider.kt: -------------------------------------------------------------------------------- 1 | package com.depromeet.makers.domain.enums 2 | 3 | enum class SocialCredentialsProvider { 4 | KAKAO, 5 | APPLE, 6 | TEST 7 | } 8 | -------------------------------------------------------------------------------- /src/main/kotlin/com/depromeet/makers/presentation/web/dto/request/AppleLoginRequest.kt: -------------------------------------------------------------------------------- 1 | package com.depromeet.makers.presentation.web.dto.request 2 | 3 | data class AppleLoginRequest( 4 | val identityToken: String, 5 | ) 6 | -------------------------------------------------------------------------------- /src/main/kotlin/com/depromeet/makers/presentation/web/dto/request/KakaoLoginRequest.kt: -------------------------------------------------------------------------------- 1 | package com.depromeet.makers.presentation.web.dto.request 2 | 3 | data class KakaoLoginRequest( 4 | val accessToken: String, 5 | ) 6 | -------------------------------------------------------------------------------- /src/main/kotlin/com/depromeet/makers/presentation/web/dto/request/RefreshTokenRequest.kt: -------------------------------------------------------------------------------- 1 | package com.depromeet.makers.presentation.web.dto.request 2 | 3 | data class RefreshTokenRequest( 4 | val refreshToken: String, 5 | ) 6 | -------------------------------------------------------------------------------- /src/main/kotlin/com/depromeet/makers/presentation/web/dto/request/TestLoginRequest.kt: -------------------------------------------------------------------------------- 1 | package com.depromeet.makers.presentation.web.dto.request 2 | 3 | data class TestLoginRequest( 4 | val externalIdentifier: String, 5 | ) 6 | -------------------------------------------------------------------------------- /src/main/kotlin/com/depromeet/makers/domain/enums/WebsiteType.kt: -------------------------------------------------------------------------------- 1 | package com.depromeet.makers.domain.enums 2 | 3 | enum class WebsiteType { 4 | GITHUB, 5 | BLOG, 6 | LINKEDIN, 7 | BEHANCE, 8 | ETC, 9 | } 10 | -------------------------------------------------------------------------------- /src/main/kotlin/com/depromeet/makers/domain/enums/MemberPosition.kt: -------------------------------------------------------------------------------- 1 | package com.depromeet.makers.domain.enums 2 | 3 | enum class MemberPosition { 4 | DESIGN, 5 | WEB, 6 | ANDROID, 7 | IOS, 8 | SERVER, 9 | } 10 | -------------------------------------------------------------------------------- /src/main/kotlin/com/depromeet/makers/presentation/web/dto/response/ErrorResponse.kt: -------------------------------------------------------------------------------- 1 | package com.depromeet.makers.presentation.web.dto.response 2 | 3 | data class ErrorResponse( 4 | val code: Int, 5 | val message: String, 6 | ) 7 | -------------------------------------------------------------------------------- /src/main/kotlin/com/depromeet/makers/domain/vo/MemberLink.kt: -------------------------------------------------------------------------------- 1 | package com.depromeet.makers.domain.vo 2 | 3 | import com.depromeet.makers.domain.enums.WebsiteType 4 | 5 | data class MemberLink( 6 | val website: WebsiteType, 7 | val link: String, 8 | ) 9 | -------------------------------------------------------------------------------- /src/main/kotlin/com/depromeet/makers/domain/vo/SessionPlace.kt: -------------------------------------------------------------------------------- 1 | package com.depromeet.makers.domain.vo 2 | 3 | data class SessionPlace( 4 | val id: String, 5 | val title: String, 6 | val address: String, 7 | val latitude: Double, 8 | val longitude: Double, 9 | ) 10 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.12.1-bin.zip 4 | networkTimeout=10000 5 | validateDistributionUrl=true 6 | zipStoreBase=GRADLE_USER_HOME 7 | zipStorePath=wrapper/dists 8 | -------------------------------------------------------------------------------- /src/main/kotlin/com/depromeet/makers/repository/MemberRepository.kt: -------------------------------------------------------------------------------- 1 | package com.depromeet.makers.repository 2 | 3 | import com.depromeet.makers.domain.Member 4 | import org.bson.types.ObjectId 5 | import org.springframework.data.mongodb.repository.MongoRepository 6 | 7 | interface MemberRepository : MongoRepository 8 | -------------------------------------------------------------------------------- /src/test/kotlin/com/depromeet/makers/DepromeetMakersBeApplicationTests.kt: -------------------------------------------------------------------------------- 1 | package com.depromeet.makers 2 | 3 | import org.junit.jupiter.api.Test 4 | import org.springframework.boot.test.context.SpringBootTest 5 | 6 | @SpringBootTest 7 | class DepromeetMakersBeApplicationTests { 8 | 9 | @Test 10 | fun contextLoads() { 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/kotlin/com/depromeet/makers/repository/SocialCredentialsRepository.kt: -------------------------------------------------------------------------------- 1 | package com.depromeet.makers.repository 2 | 3 | import com.depromeet.makers.domain.SocialCredentials 4 | import com.depromeet.makers.domain.SocialCredentialsKey 5 | import org.springframework.data.mongodb.repository.MongoRepository 6 | 7 | interface SocialCredentialsRepository : MongoRepository 8 | -------------------------------------------------------------------------------- /src/main/kotlin/com/depromeet/makers/repository/client/AppleAuthClient.kt: -------------------------------------------------------------------------------- 1 | package com.depromeet.makers.repository.client 2 | 3 | import com.depromeet.makers.presentation.web.dto.response.AppleKeyListResponse 4 | import org.springframework.web.service.annotation.GetExchange 5 | 6 | interface AppleAuthClient { 7 | @GetExchange("https://appleid.apple.com/auth/keys") 8 | fun getApplyKeys(): AppleKeyListResponse 9 | } 10 | -------------------------------------------------------------------------------- /src/main/kotlin/com/depromeet/makers/util/AuthenticationUtil.kt: -------------------------------------------------------------------------------- 1 | package com.depromeet.makers.util 2 | 3 | import org.springframework.security.core.Authentication 4 | import org.springframework.security.core.authority.SimpleGrantedAuthority 5 | 6 | object AuthenticationUtil { 7 | fun Authentication.isAdmin(): Boolean { 8 | return this.authorities.contains(SimpleGrantedAuthority("ROLE_ADMIN")) 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/main/kotlin/com/depromeet/makers/presentation/web/dto/response/AppleKeyResponse.kt: -------------------------------------------------------------------------------- 1 | package com.depromeet.makers.presentation.web.dto.response 2 | 3 | data class AppleKeyResponse( 4 | val kty: String, 5 | val kid: String, 6 | val use: String, 7 | val alg: String, 8 | val n: String, 9 | val e: String, 10 | ) 11 | 12 | data class AppleKeyListResponse( 13 | val keys: List, 14 | ) 15 | -------------------------------------------------------------------------------- /.github/workflows/pr-labeler.yml: -------------------------------------------------------------------------------- 1 | name: PR labeler 2 | 3 | on: 4 | pull_request: 5 | types: [ opened ] 6 | 7 | jobs: 8 | labeler: 9 | runs-on: ubuntu-latest 10 | permissions: 11 | contents: read 12 | pull-requests: write 13 | steps: 14 | - name: Check Labels 15 | id: labeler 16 | uses: jimschubert/labeler-action@v1 17 | with: 18 | GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}} 19 | -------------------------------------------------------------------------------- /src/main/kotlin/com/depromeet/makers/domain/vo/Code.kt: -------------------------------------------------------------------------------- 1 | package com.depromeet.makers.domain.vo 2 | 3 | import kotlin.random.Random 4 | 5 | @JvmInline 6 | value class Code( 7 | val code: String, 8 | ) { 9 | fun mask(): Code { 10 | return Code("******") 11 | } 12 | 13 | companion object { 14 | fun generate(): Code { 15 | return Random.nextInt(100_000, 1_000_000).toString().let { Code(it) } 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/kotlin/com/depromeet/makers/domain/enums/SessionType.kt: -------------------------------------------------------------------------------- 1 | package com.depromeet.makers.domain.enums 2 | 3 | import com.depromeet.makers.domain.Session 4 | 5 | enum class SessionType { 6 | ONLINE, 7 | OFFLINE, 8 | ; 9 | 10 | companion object { 11 | fun of(session: Session): SessionType { 12 | return when (session.place) { 13 | null -> ONLINE 14 | else -> OFFLINE 15 | } 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled class file 2 | *.class 3 | 4 | # Log file 5 | *.log 6 | 7 | # BlueJ files 8 | *.ctxt 9 | 10 | # Mobile Tools for Java (J2ME) 11 | .mtj.tmp/ 12 | 13 | # Package Files # 14 | *.jar 15 | *.war 16 | *.nar 17 | *.ear 18 | *.zip 19 | *.tar.gz 20 | *.rar 21 | 22 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 23 | hs_err_pid* 24 | replay_pid* 25 | 26 | build/ 27 | .idea/ 28 | *.iml 29 | .gradle/ 30 | /out/ 31 | 32 | application-local.yaml 33 | -------------------------------------------------------------------------------- /src/main/kotlin/com/depromeet/makers/DepromeetMakersBeApplication.kt: -------------------------------------------------------------------------------- 1 | package com.depromeet.makers 2 | 3 | import org.springframework.boot.autoconfigure.SpringBootApplication 4 | import org.springframework.boot.context.properties.ConfigurationPropertiesScan 5 | import org.springframework.boot.runApplication 6 | 7 | @ConfigurationPropertiesScan 8 | @SpringBootApplication 9 | class DepromeetMakersBeApplication 10 | 11 | fun main(args: Array) { 12 | runApplication(*args) 13 | } 14 | -------------------------------------------------------------------------------- /src/main/kotlin/com/depromeet/makers/repository/SessionRepository.kt: -------------------------------------------------------------------------------- 1 | package com.depromeet.makers.repository 2 | 3 | import com.depromeet.makers.domain.Session 4 | import org.bson.types.ObjectId 5 | import org.springframework.data.mongodb.repository.MongoRepository 6 | 7 | interface SessionRepository : MongoRepository { 8 | fun findByGeneration(generation: Int): List 9 | 10 | fun findByGenerationAndWeek(generation: Int, week: Int): Session? 11 | 12 | fun deleteAllByGeneration(generation: Int) 13 | } 14 | -------------------------------------------------------------------------------- /.jpb/jpb-settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /src/main/kotlin/com/depromeet/makers/presentation/web/dto/response/AuthenticationResponse.kt: -------------------------------------------------------------------------------- 1 | package com.depromeet.makers.presentation.web.dto.response 2 | 3 | import com.depromeet.makers.domain.vo.TokenPair 4 | 5 | data class AuthenticationResponse( 6 | val accessToken: String, 7 | val refreshToken: String, 8 | ) { 9 | companion object { 10 | fun from(tokenPair: TokenPair) = AuthenticationResponse( 11 | accessToken = tokenPair.accessToken, 12 | refreshToken = tokenPair.refreshToken, 13 | ) 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/resources/application.yaml: -------------------------------------------------------------------------------- 1 | spring: 2 | application: 3 | name: depromeet-makers-be 4 | data: 5 | mongodb: 6 | host: ${MONGO_HOST} 7 | port: ${MONGO_PORT} 8 | username: ${MONGO_USER} 9 | password: ${MONGO_PASSWORD} 10 | database: ${MONGO_DB} 11 | field-naming-strategy: org.springframework.data.mapping.model.SnakeCaseFieldNamingStrategy 12 | app: 13 | token: 14 | secretKey: ${TOKEN_SECRET_KEY} 15 | expiration: 16 | access: 86400 17 | refresh: 2592000 18 | depromeet: 19 | generation: 15 20 | -------------------------------------------------------------------------------- /src/main/kotlin/com/depromeet/makers/repository/client/KakaoAuthClient.kt: -------------------------------------------------------------------------------- 1 | package com.depromeet.makers.repository.client 2 | 3 | import com.depromeet.makers.presentation.web.dto.response.KakaoAccountResponse 4 | import org.springframework.web.bind.annotation.RequestHeader 5 | import org.springframework.web.service.annotation.PostExchange 6 | 7 | interface KakaoAuthClient { 8 | @PostExchange(url = "https://kapi.kakao.com/v2/user/me", contentType = "application/x-www-form-urlencoded;charset=utf-8") 9 | fun getKakaoAccount(@RequestHeader headers: Map): KakaoAccountResponse 10 | } 11 | -------------------------------------------------------------------------------- /.github/labeler.yml: -------------------------------------------------------------------------------- 1 | enable: 2 | issues: true 3 | prs: true 4 | 5 | comments: 6 | prs: | 7 | Auto labels applied based on the title of the PR. 8 | 9 | # 레이블 10 | labels: 11 | 'bug': 12 | include: 13 | - '\bfix\b' 14 | 'test': 15 | include: 16 | - '\btest\b' 17 | 'feature': 18 | include: 19 | - '\bfeat\b' 20 | 'documentation': 21 | include: 22 | - '\bdocs\b' 23 | 'refactor': 24 | include: 25 | - '\brefactor\b' 26 | 'chore': 27 | include: 28 | - '\bchore\b' 29 | 'fix': 30 | include: 31 | - '\bfix\b' 32 | 'release': 33 | include: 34 | - '\release\b' 35 | 36 | -------------------------------------------------------------------------------- /src/main/kotlin/com/depromeet/makers/domain/SocialCredentials.kt: -------------------------------------------------------------------------------- 1 | package com.depromeet.makers.domain 2 | 3 | import com.depromeet.makers.domain.enums.SocialCredentialsProvider 4 | import org.springframework.data.annotation.Id 5 | import org.springframework.data.mongodb.core.mapping.DBRef 6 | import org.springframework.data.mongodb.core.mapping.Document 7 | 8 | @Document(collection = "socialCredentials") 9 | class SocialCredentials( 10 | @Id 11 | val key: SocialCredentialsKey, 12 | @DBRef 13 | val member: Member, 14 | ) 15 | 16 | data class SocialCredentialsKey( 17 | val provider: SocialCredentialsProvider, 18 | val externalIdentifier: String, 19 | ) 20 | -------------------------------------------------------------------------------- /src/main/kotlin/com/depromeet/makers/config/properties/AppProperties.kt: -------------------------------------------------------------------------------- 1 | package com.depromeet.makers.config.properties 2 | 3 | import org.springframework.boot.context.properties.ConfigurationProperties 4 | 5 | @ConfigurationProperties(prefix = "app") 6 | data class AppProperties( 7 | val token: TokenProperties, 8 | val depromeet: DepromeetProperties, 9 | ) { 10 | data class TokenProperties( 11 | val secretKey: String, 12 | val expiration: Expiration 13 | ) { 14 | data class Expiration( 15 | val access: Long, 16 | val refresh: Long, 17 | ) 18 | } 19 | 20 | data class DepromeetProperties( 21 | val generation: Int, 22 | ) 23 | } 24 | 25 | -------------------------------------------------------------------------------- /src/main/kotlin/com/depromeet/makers/presentation/web/dto/request/SessionRequest.kt: -------------------------------------------------------------------------------- 1 | package com.depromeet.makers.presentation.web.dto.request 2 | 3 | import com.depromeet.makers.domain.vo.SessionPlace 4 | import java.time.LocalDateTime 5 | 6 | data class SessionRequest( 7 | val generation: Int, 8 | val week: Int, 9 | val title: String, 10 | val description: String, 11 | val place: SessionPlace?, 12 | val startTime: LocalDateTime, 13 | val endTime: LocalDateTime, 14 | ) { 15 | init { 16 | require(generation > 0) { "generation must be greater than 0" } 17 | require(week > 0) { "week must be greater than 0" } 18 | } 19 | } 20 | 21 | data class SessionGenerationRequest( 22 | val generation: Int, 23 | ) 24 | -------------------------------------------------------------------------------- /src/main/kotlin/com/depromeet/makers/domain/exception/ErrorCode.kt: -------------------------------------------------------------------------------- 1 | package com.depromeet.makers.domain.exception 2 | 3 | import org.springframework.http.HttpStatus 4 | 5 | enum class ErrorCode( 6 | val httpStatus: HttpStatus, 7 | val code: Int, 8 | val message: String, 9 | ) { 10 | INTERNAL_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, 50000, "알 수 없는 오류가 발생했어요"), 11 | 12 | NOT_FOUND(HttpStatus.NOT_FOUND, 40000, "존재하지 않아요"), 13 | 14 | UNAUTHORIZED(HttpStatus.UNAUTHORIZED, 40100, "권한이 없어요"), 15 | TOKEN_NOT_FOUND(HttpStatus.UNAUTHORIZED, 40101, "토큰이 없어요"), 16 | TOKEN_EXPIRED(HttpStatus.UNAUTHORIZED, 40102, "토큰이 만료되었어요"), 17 | TOKEN_NOT_VALID(HttpStatus.UNAUTHORIZED, 40103, "토큰이 유효하지 않아요"), 18 | UNAUTHENTICATED(HttpStatus.UNAUTHORIZED, 40104, "인증되지 않았어요"), 19 | ; 20 | 21 | fun isCriticalError(): Boolean { 22 | return this.code >= 50000 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/kotlin/com/depromeet/makers/config/MongoConfig.kt: -------------------------------------------------------------------------------- 1 | package com.depromeet.makers.config 2 | 3 | import org.springframework.context.annotation.Bean 4 | import org.springframework.context.annotation.Configuration 5 | import org.springframework.data.mongodb.MongoDatabaseFactory 6 | import org.springframework.data.mongodb.config.EnableMongoAuditing 7 | import org.springframework.data.mongodb.core.convert.DefaultDbRefResolver 8 | import org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper 9 | import org.springframework.data.mongodb.core.convert.MappingMongoConverter 10 | import org.springframework.data.mongodb.core.mapping.MongoMappingContext 11 | 12 | @Configuration 13 | class MongoConfig { 14 | @Bean 15 | fun mappingMongoConverter( 16 | factory: MongoDatabaseFactory, 17 | context: MongoMappingContext, 18 | ) = MappingMongoConverter(DefaultDbRefResolver(factory), context).apply { 19 | setTypeMapper(DefaultMongoTypeMapper(null)) 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/kotlin/com/depromeet/makers/presentation/web/dto/response/KakaoAccountResponse.kt: -------------------------------------------------------------------------------- 1 | package com.depromeet.makers.presentation.web.dto.response 2 | 3 | import com.fasterxml.jackson.annotation.JsonProperty 4 | 5 | data class KakaoAccountResponse( 6 | @JsonProperty("id") 7 | val id: Long, 8 | 9 | @JsonProperty("connected_at") 10 | val connectedAt: String, 11 | 12 | @JsonProperty("kakao_account") 13 | val kakaoAccount: KakaoAccount, 14 | ) 15 | 16 | data class KakaoAccount( 17 | @JsonProperty("profile_nickname_needs_agreement") 18 | val profileNicknameNeedsAgreement: Boolean, 19 | 20 | @JsonProperty("name_needs_agreement") 21 | val nameNeedsAgreement: Boolean, 22 | 23 | @JsonProperty("has_email") 24 | val hasEmail: Boolean, 25 | 26 | @JsonProperty("email") 27 | val email: String?, 28 | 29 | @JsonProperty("email_needs_agreement") 30 | val emailNeedsAgreement: Boolean, 31 | 32 | @JsonProperty("has_phone_number") 33 | val hasPhoneNumber: Boolean, 34 | 35 | @JsonProperty("phone_number_needs_agreement") 36 | val phoneNumberNeedsAgreement: Boolean, 37 | 38 | @JsonProperty("phone_number") 39 | val phoneNumber: String?, 40 | ) 41 | -------------------------------------------------------------------------------- /src/main/kotlin/com/depromeet/makers/config/SwaggerConfig.kt: -------------------------------------------------------------------------------- 1 | package com.depromeet.makers.config 2 | 3 | import io.swagger.v3.oas.models.Components 4 | import io.swagger.v3.oas.models.OpenAPI 5 | import io.swagger.v3.oas.models.info.Info 6 | import io.swagger.v3.oas.models.security.SecurityRequirement 7 | import io.swagger.v3.oas.models.security.SecurityScheme 8 | import io.swagger.v3.oas.models.servers.Server 9 | import org.springframework.context.annotation.Bean 10 | import org.springframework.context.annotation.Configuration 11 | 12 | @Configuration 13 | class SwaggerConfig { 14 | @Bean 15 | fun openAPI(): OpenAPI = OpenAPI() 16 | .servers( 17 | listOf( 18 | Server() 19 | .description("API DEV 서버 URL") 20 | .url("https://dev-makers.ddmz.org"), 21 | Server() 22 | .description("API LOCAL 서버 URL") 23 | .url("http://localhost:8080"), 24 | ), 25 | ) 26 | .info( 27 | Info() 28 | .title("Depromeet Makers BE API") 29 | .version("1.0"), 30 | ) 31 | .addSecurityItem(SecurityRequirement().addList("JWT 토큰")) 32 | .components( 33 | Components().addSecuritySchemes( 34 | "JWT 토큰", 35 | SecurityScheme().type(SecurityScheme.Type.HTTP).scheme("Bearer").bearerFormat("JWT"), 36 | ), 37 | ) 38 | } 39 | 40 | -------------------------------------------------------------------------------- /src/main/kotlin/com/depromeet/makers/config/WebExceptionHandler.kt: -------------------------------------------------------------------------------- 1 | package com.depromeet.makers.config 2 | 3 | import com.depromeet.makers.domain.exception.DomainException 4 | import com.depromeet.makers.domain.exception.ErrorCode 5 | import com.depromeet.makers.presentation.web.dto.response.ErrorResponse 6 | import org.springframework.http.HttpStatus 7 | import org.springframework.http.ResponseEntity 8 | import org.springframework.web.bind.annotation.ControllerAdvice 9 | import org.springframework.web.bind.annotation.ExceptionHandler 10 | import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler 11 | 12 | @ControllerAdvice 13 | class WebExceptionHandler : ResponseEntityExceptionHandler() { 14 | @ExceptionHandler(DomainException::class) 15 | fun handleDomainException(e: DomainException): ResponseEntity { 16 | val errorCode = e.errorCode 17 | if (errorCode.isCriticalError()) { 18 | return handleUnhandledException(e) 19 | } 20 | 21 | return ResponseEntity.status(errorCode.httpStatus) 22 | .body(ErrorResponse(e.errorCode.code, e.errorCode.message)) 23 | } 24 | 25 | @ExceptionHandler 26 | fun handleUnhandledException(e: Exception): ResponseEntity { 27 | e.printStackTrace() 28 | return ResponseEntity 29 | .status(HttpStatus.INTERNAL_SERVER_ERROR) 30 | .body(ErrorResponse(ErrorCode.INTERNAL_ERROR.code, ErrorCode.INTERNAL_ERROR.message)) 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/kotlin/com/depromeet/makers/presentation/web/dto/response/SessionResponse.kt: -------------------------------------------------------------------------------- 1 | package com.depromeet.makers.presentation.web.dto.response 2 | 3 | import com.depromeet.makers.domain.Session 4 | import com.depromeet.makers.domain.enums.SessionType 5 | import com.depromeet.makers.domain.vo.Code 6 | import com.depromeet.makers.domain.vo.SessionPlace 7 | import java.time.LocalDateTime 8 | 9 | data class SessionResponse( 10 | val sessionId: String, 11 | val generation: Int, 12 | val week: Int, 13 | val title: String, 14 | val description: String, 15 | val type: SessionType, 16 | val place: SessionPlace?, 17 | val code: Code, 18 | val startTime: LocalDateTime, 19 | val endTime: LocalDateTime, 20 | ) { 21 | companion object { 22 | fun from(session: Session): SessionResponse { 23 | return SessionResponse( 24 | sessionId = session.id.toHexString(), 25 | generation = session.generation, 26 | week = session.week, 27 | title = session.title, 28 | description = session.description, 29 | type = session.getType(), 30 | place = session.place, 31 | startTime = session.startTime, 32 | code = session.code, 33 | endTime = session.endTime, 34 | ) 35 | } 36 | 37 | fun from(session: Session, mask: Boolean): SessionResponse { 38 | return when (mask) { 39 | false -> from(session) 40 | true -> from(session).copy( 41 | code = session.code.mask() 42 | ) 43 | } 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /.github/workflows/build-and-deploy.yaml: -------------------------------------------------------------------------------- 1 | name: 이미지 빌드 & 푸쉬 2 | on: 3 | push: 4 | branches: [ 'develop' ] 5 | paths: 6 | - '.github/workflows/**' 7 | - 'build.gradle.kts' 8 | - 'settings.gradle.kts' 9 | - 'src/**' 10 | 11 | env: 12 | SPRING_PROFILES_ACTIVE: prod 13 | 14 | jobs: 15 | build: 16 | runs-on: [ ubuntu-latest ] 17 | name: 이미지 빌드하기 18 | 19 | permissions: 20 | id-token: write 21 | contents: read 22 | 23 | steps: 24 | - name: GitHub 에서 레포 받아오기 25 | uses: actions/checkout@v3 26 | 27 | - name: JDK17 준비하기 28 | uses: actions/setup-java@v3 29 | with: 30 | java-version: '17' 31 | distribution: 'temurin' 32 | 33 | - name: 도커허브 로그인 34 | uses: docker/login-action@v3 35 | with: 36 | username: ${{ secrets.DOCKERHUB_USERNAME }} 37 | password: ${{ secrets.DOCKERHUB_TOKEN }} 38 | 39 | - name: Gradle 준비하기 40 | uses: gradle/gradle-build-action@v2 41 | 42 | - name: 이미지 빌드하고 푸쉬하기 43 | id: build-image 44 | run: | 45 | echo "image-tag=$(git rev-parse --short HEAD)" >> $GITHUB_OUTPUT && 46 | chmod +x ./gradlew && 47 | export IMAGE_TAG=$(git rev-parse --short HEAD) && 48 | export IMAGE_NAME=${{ secrets.IMAGE_NAME }} && 49 | ./gradlew jib 50 | 51 | - name: 도커 배포하기 52 | uses: appleboy/ssh-action@v1.0.3 53 | with: 54 | host: ${{ secrets.SSH_HOST }} 55 | username: ${{ secrets.SSH_USERNAME }} 56 | key: ${{ secrets.SSH_KEY }} 57 | script: sudo docker service update makers_web --image ${{ secrets.IMAGE_NAME }}:${{ steps.build-image.outputs.image-tag }} 58 | -------------------------------------------------------------------------------- /src/main/kotlin/com/depromeet/makers/config/WebConfig.kt: -------------------------------------------------------------------------------- 1 | package com.depromeet.makers.config 2 | 3 | import com.depromeet.makers.repository.client.AppleAuthClient 4 | import com.depromeet.makers.repository.client.KakaoAuthClient 5 | import org.springframework.context.annotation.Bean 6 | import org.springframework.context.annotation.Configuration 7 | import org.springframework.web.client.RestClient 8 | import org.springframework.web.client.support.RestClientAdapter 9 | import org.springframework.web.service.invoker.HttpServiceProxyFactory 10 | import org.springframework.web.servlet.config.annotation.CorsRegistry 11 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurer 12 | 13 | @Configuration 14 | class WebConfig : WebMvcConfigurer { 15 | @Bean 16 | fun restClient(): RestClient { 17 | return RestClient.create() 18 | } 19 | 20 | @Bean 21 | fun appleAuthClient(restClient: RestClient): AppleAuthClient { 22 | val restClientAdapter = RestClientAdapter.create(restClient) 23 | return HttpServiceProxyFactory 24 | .builderFor(restClientAdapter) 25 | .build() 26 | .createClient(AppleAuthClient::class.java) 27 | } 28 | 29 | @Bean 30 | fun kakaoAuthClient(restClient: RestClient): KakaoAuthClient { 31 | val restClientAdapter = RestClientAdapter.create(restClient) 32 | return HttpServiceProxyFactory 33 | .builderFor(restClientAdapter) 34 | .build() 35 | .createClient(KakaoAuthClient::class.java) 36 | } 37 | 38 | override fun addCorsMappings(registry: CorsRegistry) { 39 | registry.addMapping("/**") 40 | .allowedMethods("*") 41 | .allowedOrigins("*") 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/kotlin/com/depromeet/makers/presentation/web/SessionController.kt: -------------------------------------------------------------------------------- 1 | package com.depromeet.makers.presentation.web 2 | 3 | import com.depromeet.makers.presentation.web.dto.response.SessionResponse 4 | import com.depromeet.makers.service.SessionService 5 | import io.swagger.v3.oas.annotations.Operation 6 | import io.swagger.v3.oas.annotations.tags.Tag 7 | import org.bson.types.ObjectId 8 | import org.springframework.security.core.Authentication 9 | import org.springframework.web.bind.annotation.GetMapping 10 | import org.springframework.web.bind.annotation.PathVariable 11 | import org.springframework.web.bind.annotation.RequestParam 12 | import org.springframework.web.bind.annotation.RestController 13 | 14 | @Tag(name = "세션 API", description = "세션 관련 API") 15 | @RestController 16 | class SessionController( 17 | private val sessionService: SessionService, 18 | ) { 19 | @Operation(summary = "세션 조회", description = "세션을 조회합니다.") 20 | @GetMapping("/v1/sessions/{sessionId}") 21 | fun getSession( 22 | authentication: Authentication, 23 | @PathVariable sessionId: String, 24 | ): SessionResponse { 25 | val session = sessionService.getSession(sessionId = ObjectId(sessionId)) 26 | return SessionResponse.from(session, mask = true) 27 | } 28 | 29 | @Operation(summary = "전체 세션 조회", description = "기수에 해당하는 세션을 조회합니다.") 30 | @GetMapping("/v1/sessions") 31 | fun getAllSessionByGeneration( 32 | authentication: Authentication, 33 | @RequestParam generation: Int, 34 | ): List { 35 | val sessions = sessionService.getAllSessionByGeneration(generation) 36 | 37 | return sessions.map { session -> SessionResponse.from(session, mask = true) } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/kotlin/com/depromeet/makers/config/filters/JWTAuthenticationFilter.kt: -------------------------------------------------------------------------------- 1 | package com.depromeet.makers.config.filters 2 | 3 | import com.depromeet.makers.components.JWTTokenProvider 4 | import com.depromeet.makers.domain.exception.DomainException 5 | import com.depromeet.makers.domain.exception.ErrorCode 6 | import jakarta.servlet.FilterChain 7 | import jakarta.servlet.http.HttpServletRequest 8 | import jakarta.servlet.http.HttpServletResponse 9 | import org.springframework.security.core.context.SecurityContextHolder 10 | import org.springframework.web.filter.OncePerRequestFilter 11 | import org.springframework.web.servlet.HandlerExceptionResolver 12 | 13 | class JWTAuthenticationFilter( 14 | private val jwtTokenProvider: JWTTokenProvider, 15 | private val handlerExceptionResolver: HandlerExceptionResolver, 16 | ) : OncePerRequestFilter() { 17 | override fun doFilterInternal( 18 | request: HttpServletRequest, 19 | response: HttpServletResponse, 20 | filterChain: FilterChain, 21 | ) { 22 | try { 23 | val authenticationHeader = 24 | request.getHeader("Authorization") ?: throw DomainException(ErrorCode.TOKEN_NOT_FOUND) 25 | val accessToken = if (authenticationHeader.startsWith("Bearer ")) { 26 | authenticationHeader.substring(7) 27 | } else { 28 | throw DomainException(ErrorCode.TOKEN_NOT_VALID) 29 | } 30 | 31 | val authentication = jwtTokenProvider.parseAuthentication(accessToken) 32 | SecurityContextHolder.getContext().authentication = authentication 33 | return filterChain.doFilter(request, response) 34 | } catch (e: Exception) { 35 | // Exception Handler로 넘김 36 | handlerExceptionResolver.resolveException(request, response, null, e) 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /HELP.md: -------------------------------------------------------------------------------- 1 | # Read Me First 2 | The following was discovered as part of building this project: 3 | 4 | * The original package name 'com.depromeet.depromeet-makers-be' is invalid and this project uses 'com.depromeet.makers' instead. 5 | 6 | # Getting Started 7 | 8 | ### Reference Documentation 9 | For further reference, please consider the following sections: 10 | 11 | * [Official Gradle documentation](https://docs.gradle.org) 12 | * [Spring Boot Gradle Plugin Reference Guide](https://docs.spring.io/spring-boot/3.4.3/gradle-plugin) 13 | * [Create an OCI image](https://docs.spring.io/spring-boot/3.4.3/gradle-plugin/packaging-oci-image.html) 14 | * [Spring Data MongoDB](https://docs.spring.io/spring-boot/3.4.3/reference/data/nosql.html#data.nosql.mongodb) 15 | * [Spring Web](https://docs.spring.io/spring-boot/3.4.3/reference/web/servlet.html) 16 | * [Spring Data Redis (Access+Driver)](https://docs.spring.io/spring-boot/3.4.3/reference/data/nosql.html#data.nosql.redis) 17 | * [Spring Security](https://docs.spring.io/spring-boot/3.4.3/reference/web/spring-security.html) 18 | 19 | ### Guides 20 | The following guides illustrate how to use some features concretely: 21 | 22 | * [Accessing Data with MongoDB](https://spring.io/guides/gs/accessing-data-mongodb/) 23 | * [Building a RESTful Web Service](https://spring.io/guides/gs/rest-service/) 24 | * [Serving Web Content with Spring MVC](https://spring.io/guides/gs/serving-web-content/) 25 | * [Building REST services with Spring](https://spring.io/guides/tutorials/rest/) 26 | * [Messaging with Redis](https://spring.io/guides/gs/messaging-redis/) 27 | * [Securing a Web Application](https://spring.io/guides/gs/securing-web/) 28 | * [Spring Boot and OAuth2](https://spring.io/guides/tutorials/spring-boot-oauth2/) 29 | * [Authenticating a User with LDAP](https://spring.io/guides/gs/authenticating-ldap/) 30 | 31 | ### Additional Links 32 | These additional references should also help you: 33 | 34 | * [Gradle Build Scans – insights for your project's build](https://scans.gradle.com#gradle) 35 | 36 | -------------------------------------------------------------------------------- /src/main/kotlin/com/depromeet/makers/domain/Member.kt: -------------------------------------------------------------------------------- 1 | package com.depromeet.makers.domain 2 | 3 | import com.depromeet.makers.domain.enums.MemberPosition 4 | import com.depromeet.makers.domain.enums.MemberRole 5 | import com.depromeet.makers.domain.enums.MemberStatus 6 | import com.depromeet.makers.domain.vo.Image 7 | import com.depromeet.makers.domain.vo.MemberLink 8 | import com.depromeet.makers.domain.vo.TeamHistory 9 | import org.bson.types.ObjectId 10 | import org.springframework.data.annotation.Id 11 | import org.springframework.data.mongodb.core.mapping.Document 12 | 13 | @Document("member") 14 | class Member( 15 | @Id 16 | val id: ObjectId, 17 | var name: String, 18 | var email: String, 19 | var deviceToken: String?, 20 | var description: String?, 21 | var position: MemberPosition, 22 | var role: MemberRole, 23 | var status: MemberStatus, 24 | var profileImage: Image?, 25 | var teamHistory: List, 26 | var company: String?, 27 | var website: Set, 28 | var skills: Set, 29 | ) { 30 | companion object { 31 | fun create( 32 | name: String, 33 | email: String, 34 | deviceToken: String? = null, 35 | role: MemberRole = MemberRole.USER, 36 | position: MemberPosition, 37 | status: MemberStatus, 38 | teamHistory: List, 39 | ): Member { 40 | return Member( 41 | id = ObjectId(), 42 | name = name, 43 | email = email, 44 | deviceToken = deviceToken, 45 | description = null, 46 | position = position, 47 | role = role, 48 | status = status, 49 | profileImage = null, 50 | teamHistory = teamHistory, 51 | company = null, 52 | website = emptySet(), 53 | skills = emptySet(), 54 | ) 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/main/kotlin/com/depromeet/makers/domain/Session.kt: -------------------------------------------------------------------------------- 1 | package com.depromeet.makers.domain 2 | 3 | import com.depromeet.makers.domain.enums.SessionType 4 | import com.depromeet.makers.domain.vo.Code 5 | import com.depromeet.makers.domain.vo.SessionPlace 6 | import org.bson.types.ObjectId 7 | import org.springframework.data.annotation.Id 8 | import org.springframework.data.mongodb.core.index.CompoundIndex 9 | import org.springframework.data.mongodb.core.mapping.Document 10 | import java.time.LocalDateTime 11 | 12 | @Document("session") 13 | @CompoundIndex(def = "{'generation': 1, 'week': 1}", unique = true) 14 | class Session( 15 | @Id 16 | val id: ObjectId, 17 | var generation: Int, 18 | var week: Int, 19 | var title: String, 20 | var description: String, 21 | var place: SessionPlace?, 22 | var code: Code = Code.generate(), 23 | var startTime: LocalDateTime, 24 | var endTime: LocalDateTime, 25 | ) { 26 | fun update( 27 | generation: Int = this.generation, 28 | week: Int = this.week, 29 | title: String = this.title, 30 | description: String = this.description, 31 | place: SessionPlace? = this.place, 32 | startTime: LocalDateTime = this.startTime, 33 | endTime: LocalDateTime = this.endTime, 34 | ) { 35 | this.generation = generation 36 | this.week = week 37 | this.title = title 38 | this.description = description 39 | this.place = place 40 | this.startTime = startTime 41 | this.endTime = endTime 42 | } 43 | 44 | fun getType(): SessionType { 45 | return SessionType.of(this) 46 | } 47 | 48 | companion object { 49 | fun create( 50 | generation: Int, 51 | week: Int, 52 | title: String, 53 | description: String, 54 | place: SessionPlace?, 55 | startTime: LocalDateTime, 56 | endTime: LocalDateTime, 57 | ): Session { 58 | return Session( 59 | id = ObjectId(), 60 | generation = generation, 61 | week = week, 62 | title = title, 63 | description = description, 64 | place = place, 65 | startTime = startTime, 66 | endTime = endTime, 67 | ) 68 | } 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/main/kotlin/com/depromeet/makers/presentation/web/AuthController.kt: -------------------------------------------------------------------------------- 1 | package com.depromeet.makers.presentation.web 2 | 3 | import com.depromeet.makers.presentation.web.dto.request.AppleLoginRequest 4 | import com.depromeet.makers.presentation.web.dto.request.KakaoLoginRequest 5 | import com.depromeet.makers.presentation.web.dto.request.RefreshTokenRequest 6 | import com.depromeet.makers.presentation.web.dto.request.TestLoginRequest 7 | import com.depromeet.makers.presentation.web.dto.response.AuthenticationResponse 8 | import com.depromeet.makers.service.AuthService 9 | import io.swagger.v3.oas.annotations.Operation 10 | import io.swagger.v3.oas.annotations.tags.Tag 11 | import org.springframework.web.bind.annotation.PostMapping 12 | import org.springframework.web.bind.annotation.RequestBody 13 | import org.springframework.web.bind.annotation.RestController 14 | 15 | @Tag(name = "인증 API", description = "로그인 및 토큰 관련 API") 16 | @RestController 17 | class AuthController( 18 | private val authService: AuthService, 19 | ) { 20 | @Operation(summary = "카카오 로그인", description = "카카오 엑세스 토큰으로 로그인을 수행합니다.") 21 | @PostMapping("/v1/auth/kakao") 22 | fun kakaoLogin( 23 | @RequestBody kakaoLoginRequest: KakaoLoginRequest, 24 | ): AuthenticationResponse { 25 | val loginResult = authService.kakaoLogin(kakaoLoginRequest.accessToken) 26 | return AuthenticationResponse.from(loginResult) 27 | } 28 | 29 | @Operation(summary = "애플 로그인", description = "애플 ID 토큰으로 로그인을 수행합니다.") 30 | @PostMapping("/v1/auth/apple") 31 | fun appleLogin( 32 | @RequestBody appleLoginRequest: AppleLoginRequest, 33 | ): AuthenticationResponse { 34 | val loginResult = authService.appleLogin(appleLoginRequest.identityToken) 35 | return AuthenticationResponse.from(loginResult) 36 | } 37 | 38 | @Operation(summary = "테스트 로그인", description = "테스트용 로그인을 수행합니다.") 39 | @PostMapping("/v1/auth/test") 40 | fun testLogin( 41 | @RequestBody testLoginRequest: TestLoginRequest, 42 | ): AuthenticationResponse { 43 | val loginResult = authService.testLogin(testLoginRequest.externalIdentifier) 44 | return AuthenticationResponse.from(loginResult) 45 | } 46 | 47 | @Operation(summary = "토큰 갱신", description = "리프레시 토큰으로 엑세스 토큰을 갱신합니다.") 48 | @PostMapping("/v1/auth/refresh") 49 | fun refresh( 50 | @RequestBody refreshTokenRequest: RefreshTokenRequest, 51 | ): AuthenticationResponse { 52 | val loginResult = authService.refreshWithRefreshToken(refreshTokenRequest.refreshToken) 53 | return AuthenticationResponse.from(loginResult) 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/main/kotlin/com/depromeet/makers/components/SocialLoginProvider.kt: -------------------------------------------------------------------------------- 1 | package com.depromeet.makers.components 2 | 3 | import com.depromeet.makers.domain.exception.DomainException 4 | import com.depromeet.makers.domain.exception.ErrorCode 5 | import com.depromeet.makers.presentation.web.dto.response.AppleKeyResponse 6 | import com.depromeet.makers.presentation.web.dto.response.KakaoAccountResponse 7 | import com.depromeet.makers.repository.client.AppleAuthClient 8 | import com.depromeet.makers.repository.client.KakaoAuthClient 9 | import com.depromeet.makers.util.logger 10 | import com.fasterxml.jackson.databind.ObjectMapper 11 | import com.nimbusds.jose.jwk.JWK 12 | import io.jsonwebtoken.Jwts 13 | import org.springframework.stereotype.Component 14 | import java.util.Base64 15 | 16 | @Component 17 | class SocialLoginProvider( 18 | private val objectMapper: ObjectMapper, 19 | private val appleAuthClient: AppleAuthClient, 20 | private val kakaoAuthClient: KakaoAuthClient, 21 | ) { 22 | private val logger = logger() 23 | 24 | fun authenticateFromKakao(accessToken: String): KakaoAccountResponse = try { 25 | kakaoAuthClient.getKakaoAccount(mapOf("Authorization" to "Bearer $accessToken")) 26 | } catch(e: Exception) { 27 | logger.error("[SocialLoginProvider] failed kakao with error - ${e.message}") 28 | throw DomainException(ErrorCode.INTERNAL_ERROR) 29 | } 30 | 31 | 32 | fun authenticateFromApple(identityToken: String): String { 33 | val pubKeys = try { 34 | appleAuthClient.getApplyKeys() 35 | } catch(e: Exception) { 36 | logger.error("[SocialLoginProvider] failed applekey with error - ${e.message}") 37 | throw DomainException(ErrorCode.INTERNAL_ERROR) 38 | } 39 | return getUserIdFromAppleIdentity(pubKeys.keys.toTypedArray(), identityToken) 40 | } 41 | 42 | 43 | private fun getUserIdFromAppleIdentity(keys: Array, identityToken: String): String { 44 | val tokenParts = identityToken.split("\\.") 45 | val headerPart = String(Base64.getDecoder().decode(tokenParts[0])) 46 | val headerNode = objectMapper.readTree(headerPart) 47 | val kid = headerNode.get("kid").asText() 48 | 49 | val keyStr = keys.firstOrNull { it.kid == kid } 50 | ?: throw RuntimeException("Apple Key not found") 51 | 52 | val pubKey = JWK.parse(objectMapper.writeValueAsString(keyStr)) 53 | .toRSAKey() 54 | .toRSAPublicKey() 55 | 56 | return Jwts.parser() 57 | .verifyWith(pubKey) 58 | .build() 59 | .parseSignedClaims(identityToken) 60 | .payload 61 | .get("sub", String::class.java) 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/main/kotlin/com/depromeet/makers/service/SessionService.kt: -------------------------------------------------------------------------------- 1 | package com.depromeet.makers.service 2 | 3 | import com.depromeet.makers.domain.Session 4 | import com.depromeet.makers.domain.exception.DomainException 5 | import com.depromeet.makers.domain.exception.ErrorCode 6 | import com.depromeet.makers.domain.vo.Code 7 | import com.depromeet.makers.domain.vo.SessionPlace 8 | import com.depromeet.makers.repository.SessionRepository 9 | import org.bson.types.ObjectId 10 | import org.springframework.data.repository.findByIdOrNull 11 | import org.springframework.stereotype.Service 12 | import java.time.LocalDateTime 13 | 14 | @Service 15 | class SessionService( 16 | private val sessionRepository: SessionRepository, 17 | ) { 18 | fun createSession( 19 | generation: Int, 20 | week: Int, 21 | title: String, 22 | description: String, 23 | place: SessionPlace?, 24 | startTime: LocalDateTime, 25 | endTime: LocalDateTime, 26 | ): Session { 27 | return sessionRepository.save( 28 | Session.create( 29 | generation = generation, 30 | week = week, 31 | title = title, 32 | description = description, 33 | place = place, 34 | startTime = startTime, 35 | endTime = endTime, 36 | ) 37 | ) 38 | } 39 | 40 | fun getAllSessionByGeneration( 41 | generation: Int, 42 | ): List { 43 | return sessionRepository.findByGeneration(generation) 44 | } 45 | 46 | fun getSession( 47 | sessionId: ObjectId, 48 | ): Session { 49 | return sessionRepository.findByIdOrNull(sessionId) ?: throw DomainException(ErrorCode.NOT_FOUND) 50 | } 51 | 52 | fun updateSession( 53 | sessionId: ObjectId, 54 | generation: Int, 55 | week: Int, 56 | title: String, 57 | description: String, 58 | place: SessionPlace?, 59 | startTime: LocalDateTime, 60 | endTime: LocalDateTime, 61 | ): Session { 62 | val session = sessionRepository.findByIdOrNull(sessionId) ?: throw DomainException(ErrorCode.NOT_FOUND) 63 | session.update( 64 | generation = generation, 65 | week = week, 66 | title = title, 67 | description = description, 68 | place = place, 69 | startTime = startTime, 70 | endTime = endTime, 71 | ) 72 | return sessionRepository.save(session) 73 | } 74 | 75 | fun updateSessionCode( 76 | sessionId: ObjectId, 77 | ): Session { 78 | val session = sessionRepository.findByIdOrNull(sessionId) ?: throw DomainException(ErrorCode.NOT_FOUND) 79 | session.code = Code.generate() 80 | return sessionRepository.save(session) 81 | } 82 | 83 | fun deleteSession( 84 | sessionId: ObjectId, 85 | ) { 86 | sessionRepository.deleteById(sessionId) 87 | } 88 | 89 | fun deleteAllByGeneration( 90 | generation: Int, 91 | ) { 92 | sessionRepository.deleteAllByGeneration(generation) 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | @rem SPDX-License-Identifier: Apache-2.0 17 | @rem 18 | 19 | @if "%DEBUG%"=="" @echo off 20 | @rem ########################################################################## 21 | @rem 22 | @rem Gradle startup script for Windows 23 | @rem 24 | @rem ########################################################################## 25 | 26 | @rem Set local scope for the variables with windows NT shell 27 | if "%OS%"=="Windows_NT" setlocal 28 | 29 | set DIRNAME=%~dp0 30 | if "%DIRNAME%"=="" set DIRNAME=. 31 | @rem This is normally unused 32 | set APP_BASE_NAME=%~n0 33 | set APP_HOME=%DIRNAME% 34 | 35 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 36 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 37 | 38 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 39 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 40 | 41 | @rem Find java.exe 42 | if defined JAVA_HOME goto findJavaFromJavaHome 43 | 44 | set JAVA_EXE=java.exe 45 | %JAVA_EXE% -version >NUL 2>&1 46 | if %ERRORLEVEL% equ 0 goto execute 47 | 48 | echo. 1>&2 49 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 50 | echo. 1>&2 51 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 52 | echo location of your Java installation. 1>&2 53 | 54 | goto fail 55 | 56 | :findJavaFromJavaHome 57 | set JAVA_HOME=%JAVA_HOME:"=% 58 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 59 | 60 | if exist "%JAVA_EXE%" goto execute 61 | 62 | echo. 1>&2 63 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 64 | echo. 1>&2 65 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 66 | echo location of your Java installation. 1>&2 67 | 68 | goto fail 69 | 70 | :execute 71 | @rem Setup the command line 72 | 73 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 74 | 75 | 76 | @rem Execute Gradle 77 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 78 | 79 | :end 80 | @rem End local scope for the variables with windows NT shell 81 | if %ERRORLEVEL% equ 0 goto mainEnd 82 | 83 | :fail 84 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 85 | rem the _cmd.exe /c_ return code! 86 | set EXIT_CODE=%ERRORLEVEL% 87 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 88 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 89 | exit /b %EXIT_CODE% 90 | 91 | :mainEnd 92 | if "%OS%"=="Windows_NT" endlocal 93 | 94 | :omega 95 | -------------------------------------------------------------------------------- /src/main/kotlin/com/depromeet/makers/service/AuthService.kt: -------------------------------------------------------------------------------- 1 | package com.depromeet.makers.service 2 | 3 | import com.depromeet.makers.components.JWTTokenProvider 4 | import com.depromeet.makers.components.SocialLoginProvider 5 | import com.depromeet.makers.domain.Member 6 | import com.depromeet.makers.domain.SocialCredentials 7 | import com.depromeet.makers.domain.SocialCredentialsKey 8 | import com.depromeet.makers.domain.enums.MemberPosition 9 | import com.depromeet.makers.domain.enums.MemberRole 10 | import com.depromeet.makers.domain.enums.MemberStatus 11 | import com.depromeet.makers.domain.enums.SocialCredentialsProvider 12 | import com.depromeet.makers.domain.exception.DomainException 13 | import com.depromeet.makers.domain.exception.ErrorCode 14 | import com.depromeet.makers.domain.vo.TokenPair 15 | import com.depromeet.makers.repository.MemberRepository 16 | import com.depromeet.makers.repository.SocialCredentialsRepository 17 | import org.springframework.data.repository.findByIdOrNull 18 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken 19 | import org.springframework.security.core.authority.SimpleGrantedAuthority 20 | import org.springframework.stereotype.Service 21 | 22 | @Service 23 | class AuthService( 24 | private val jwtTokenProvider: JWTTokenProvider, 25 | private val socialLoginProvider: SocialLoginProvider, 26 | private val memberRepository: MemberRepository, 27 | private val socialCredentialsRepository: SocialCredentialsRepository, 28 | ) { 29 | fun testLogin(id: String): TokenPair { 30 | val socialCredentialsKey = SocialCredentialsKey( 31 | provider = SocialCredentialsProvider.TEST, 32 | externalIdentifier = id, 33 | ) 34 | return loginWithCredential(socialCredentialsKey) 35 | } 36 | 37 | fun kakaoLogin(accessToken: String): TokenPair { 38 | val kakaoLoginResponse = socialLoginProvider.authenticateFromKakao(accessToken) 39 | val socialCredentialsKey = SocialCredentialsKey( 40 | provider = SocialCredentialsProvider.KAKAO, 41 | externalIdentifier = kakaoLoginResponse.id.toString(), 42 | ) 43 | return loginWithCredential(socialCredentialsKey) 44 | } 45 | 46 | fun appleLogin(identityToken: String): TokenPair { 47 | val appleId = socialLoginProvider.authenticateFromApple(identityToken) 48 | val socialCredentialsKey = SocialCredentialsKey( 49 | provider = SocialCredentialsProvider.APPLE, 50 | externalIdentifier = appleId, 51 | ) 52 | return loginWithCredential(socialCredentialsKey) 53 | } 54 | 55 | fun refreshWithRefreshToken(refreshToken: String): TokenPair { 56 | val memberId = jwtTokenProvider.getMemberIdFromRefreshToken(refreshToken) 57 | val member = memberRepository.findByIdOrNull(memberId) ?: throw DomainException(ErrorCode.NOT_FOUND) 58 | return generateTokenFromMember(member) 59 | } 60 | 61 | private fun loginWithCredential(socialCredentialsKey: SocialCredentialsKey): TokenPair { 62 | val retrievedMember = socialCredentialsRepository.findByIdOrNull(socialCredentialsKey)?.member ?: run { 63 | val newMember = Member.create( 64 | name = "test", 65 | email = "test", 66 | deviceToken = "test", 67 | position = MemberPosition.IOS, 68 | role = MemberRole.ADMIN, 69 | status = MemberStatus.REGISTERED, 70 | teamHistory = emptyList(), 71 | ) 72 | memberRepository.save(newMember).also { 73 | socialCredentialsRepository.save(SocialCredentials(socialCredentialsKey, it)) 74 | } 75 | } 76 | return generateTokenFromMember(retrievedMember) 77 | } 78 | 79 | private fun generateTokenFromMember(member: Member): TokenPair { 80 | val authorities = listOf(SimpleGrantedAuthority(member.role.name)) 81 | val authentication = UsernamePasswordAuthenticationToken(member.id, null, authorities) 82 | return jwtTokenProvider.generateTokenPair(authentication) 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /src/main/kotlin/com/depromeet/makers/presentation/web/AdminSessionController.kt: -------------------------------------------------------------------------------- 1 | package com.depromeet.makers.presentation.web 2 | 3 | import com.depromeet.makers.presentation.web.dto.request.SessionGenerationRequest 4 | import com.depromeet.makers.presentation.web.dto.request.SessionRequest 5 | import com.depromeet.makers.presentation.web.dto.response.SessionResponse 6 | import com.depromeet.makers.service.SessionService 7 | import io.swagger.v3.oas.annotations.Operation 8 | import io.swagger.v3.oas.annotations.tags.Tag 9 | import org.bson.types.ObjectId 10 | import org.springframework.security.core.Authentication 11 | import org.springframework.web.bind.annotation.DeleteMapping 12 | import org.springframework.web.bind.annotation.GetMapping 13 | import org.springframework.web.bind.annotation.PathVariable 14 | import org.springframework.web.bind.annotation.PostMapping 15 | import org.springframework.web.bind.annotation.PutMapping 16 | import org.springframework.web.bind.annotation.RequestBody 17 | import org.springframework.web.bind.annotation.RequestMapping 18 | import org.springframework.web.bind.annotation.RequestParam 19 | import org.springframework.web.bind.annotation.RestController 20 | 21 | @Tag(name = "[어드민] 세션 API", description = "세션 관련 API") 22 | @RestController 23 | @RequestMapping("/admin") 24 | class AdminSessionController( 25 | private val sessionService: SessionService, 26 | ) { 27 | @Operation(summary = "[어드민] 세션 생성", description = "세션을 생성합니다.") 28 | @PostMapping("/v1/sessions") 29 | fun createSession( 30 | @RequestBody request: SessionRequest, 31 | ): SessionResponse { 32 | val session = sessionService.createSession( 33 | generation = request.generation, 34 | week = request.week, 35 | title = request.title, 36 | description = request.description, 37 | place = request.place, 38 | startTime = request.startTime, 39 | endTime = request.endTime, 40 | ) 41 | return SessionResponse.from(session) 42 | } 43 | 44 | @Operation(summary = "[어드민] 세션 조회", description = "세션을 조회합니다.") 45 | @GetMapping("/v1/sessions/{sessionId}") 46 | fun getSession( 47 | authentication: Authentication, 48 | @PathVariable sessionId: String, 49 | ): SessionResponse { 50 | val session = sessionService.getSession(sessionId = ObjectId(sessionId)) 51 | return SessionResponse.from(session) 52 | } 53 | 54 | @Operation(summary = "[어드민] 전체 세션 조회", description = "기수에 해당하는 세션을 조회합니다.") 55 | @GetMapping("/v1/sessions") 56 | fun getAllSessionByGeneration( 57 | authentication: Authentication, 58 | @RequestParam generation: Int, 59 | ): List { 60 | val sessions = sessionService.getAllSessionByGeneration(generation) 61 | 62 | return sessions.map { session -> SessionResponse.from(session) } 63 | } 64 | 65 | @Operation(summary = "[어드민] 세션 수정", description = "특정 세션을 수정합니다.") 66 | @PutMapping("/v1/sessions/{sessionId}") 67 | fun updateSession( 68 | @PathVariable sessionId: String, 69 | @RequestBody request: SessionRequest, 70 | ): SessionResponse { 71 | val session = sessionService.updateSession( 72 | sessionId = ObjectId(sessionId), 73 | generation = request.generation, 74 | week = request.week, 75 | title = request.title, 76 | description = request.description, 77 | place = request.place, 78 | startTime = request.startTime, 79 | endTime = request.endTime, 80 | ) 81 | return SessionResponse.from(session) 82 | } 83 | 84 | @Operation(summary = "[어드민] 세션 코드 갱신", description = "특정 세션의 코드를 갱신합니다.") 85 | @PostMapping("/v1/sessions/{sessionId}/code") 86 | fun updateSessionCode( 87 | authentication: Authentication, 88 | @PathVariable sessionId: String, 89 | ): SessionResponse { 90 | val session = sessionService.updateSessionCode(sessionId = ObjectId(sessionId)) 91 | return SessionResponse.from(session) 92 | } 93 | 94 | @Operation(summary = "[어드민] 세션 삭제", description = "특정 세션을 삭제합니다.") 95 | @DeleteMapping("/v1/sessions/{sessionId}") 96 | fun deleteSession( 97 | @PathVariable sessionId: String, 98 | ) { 99 | sessionService.deleteSession(ObjectId(sessionId)) 100 | } 101 | 102 | @Operation(summary = "[어드민] 기수 별 세션 전체 삭제", description = "기수에 해당하는 모든 세션을 삭제합니다.") 103 | @DeleteMapping("/v1/sessions") 104 | fun deleteAllSessionByGeneration( 105 | @RequestBody request: SessionGenerationRequest, 106 | ) { 107 | sessionService.deleteAllByGeneration(request.generation) 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /src/main/kotlin/com/depromeet/makers/config/WebSecurityConfig.kt: -------------------------------------------------------------------------------- 1 | package com.depromeet.makers.config 2 | 3 | import com.depromeet.makers.components.JWTTokenProvider 4 | import com.depromeet.makers.config.filters.JWTAuthenticationFilter 5 | import com.depromeet.makers.domain.exception.DomainException 6 | import com.depromeet.makers.domain.exception.ErrorCode 7 | import org.springframework.context.annotation.Bean 8 | import org.springframework.context.annotation.Configuration 9 | import org.springframework.core.annotation.Order 10 | import org.springframework.security.config.Customizer 11 | import org.springframework.security.config.annotation.web.builders.HttpSecurity 12 | import org.springframework.security.config.http.SessionCreationPolicy 13 | import org.springframework.security.web.SecurityFilterChain 14 | import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter 15 | import org.springframework.web.servlet.HandlerExceptionResolver 16 | 17 | @Configuration 18 | class WebSecurityConfig { 19 | @Bean 20 | @Order(0) 21 | fun authSecurityFilterChain(httpSecurity: HttpSecurity): SecurityFilterChain = 22 | httpSecurity 23 | .securityMatcher("/v1/auth/**", *swaggerApiPatterns) 24 | .csrf { it.disable() } 25 | .cors(Customizer.withDefaults()) 26 | .sessionManagement { 27 | it.sessionCreationPolicy(SessionCreationPolicy.STATELESS) 28 | } 29 | .authorizeHttpRequests { 30 | it.anyRequest().permitAll() 31 | } 32 | .build() 33 | 34 | @Bean 35 | @Order(1) 36 | fun adminSecurityFilterChain( 37 | httpSecurity: HttpSecurity, 38 | jwtTokenProvider: JWTTokenProvider, 39 | handlerExceptionResolver: HandlerExceptionResolver, 40 | ): SecurityFilterChain = httpSecurity 41 | .securityMatcher("/admin/**") 42 | .csrf { it.disable() } 43 | .cors(Customizer.withDefaults()) 44 | .sessionManagement { 45 | it.sessionCreationPolicy(SessionCreationPolicy.STATELESS) 46 | } 47 | .authorizeHttpRequests { 48 | it.anyRequest().hasRole("hasRole('ADMIN')") 49 | } 50 | .addFilterBefore( 51 | JWTAuthenticationFilter(jwtTokenProvider, handlerExceptionResolver), 52 | UsernamePasswordAuthenticationFilter::class.java, 53 | ) 54 | .exceptionHandling { 55 | it.accessDeniedHandler { request, response, exception -> 56 | handlerExceptionResolver.resolveException( 57 | request, 58 | response, 59 | null, 60 | DomainException(ErrorCode.UNAUTHORIZED), 61 | ) 62 | }.authenticationEntryPoint { request, response, authException -> 63 | handlerExceptionResolver.resolveException( 64 | request, 65 | response, 66 | null, 67 | DomainException(ErrorCode.UNAUTHENTICATED), 68 | ) 69 | } 70 | } 71 | .build() 72 | 73 | @Bean 74 | @Order(2) 75 | fun securityFilterChain( 76 | httpSecurity: HttpSecurity, 77 | jwtTokenProvider: JWTTokenProvider, 78 | handlerExceptionResolver: HandlerExceptionResolver, 79 | ): SecurityFilterChain = httpSecurity 80 | .securityMatcher("/**") 81 | .csrf { it.disable() } 82 | .cors(Customizer.withDefaults()) 83 | .sessionManagement { 84 | it.sessionCreationPolicy(SessionCreationPolicy.STATELESS) 85 | } 86 | .authorizeHttpRequests { 87 | it.anyRequest().authenticated() 88 | } 89 | .addFilterBefore( 90 | JWTAuthenticationFilter(jwtTokenProvider, handlerExceptionResolver), 91 | UsernamePasswordAuthenticationFilter::class.java, 92 | ) 93 | .exceptionHandling { 94 | it.accessDeniedHandler { request, response, exception -> 95 | handlerExceptionResolver.resolveException( 96 | request, 97 | response, 98 | null, 99 | DomainException(ErrorCode.UNAUTHORIZED), 100 | ) 101 | }.authenticationEntryPoint { request, response, authException -> 102 | handlerExceptionResolver.resolveException( 103 | request, 104 | response, 105 | null, 106 | DomainException(ErrorCode.UNAUTHENTICATED), 107 | ) 108 | } 109 | } 110 | .build() 111 | 112 | companion object { 113 | private val swaggerApiPatterns = 114 | arrayOf("/swagger", "/swagger-ui.html", "/swagger-ui/**", "/api-docs", "/api-docs/**", "/v3/api-docs/**") 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /src/main/kotlin/com/depromeet/makers/components/JWTTokenProvider.kt: -------------------------------------------------------------------------------- 1 | package com.depromeet.makers.components 2 | 3 | import com.depromeet.makers.config.properties.AppProperties 4 | import com.depromeet.makers.domain.exception.DomainException 5 | import com.depromeet.makers.domain.exception.ErrorCode 6 | import com.depromeet.makers.domain.vo.TokenPair 7 | import com.depromeet.makers.util.logger 8 | import io.jsonwebtoken.Jwts 9 | import org.bson.types.ObjectId 10 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken 11 | import org.springframework.security.core.Authentication 12 | import org.springframework.security.core.authority.SimpleGrantedAuthority 13 | import org.springframework.stereotype.Component 14 | import java.util.Date 15 | import javax.crypto.SecretKey 16 | import javax.crypto.spec.SecretKeySpec 17 | 18 | @Component 19 | class JWTTokenProvider( 20 | private val appProperties: AppProperties, 21 | ) { 22 | private val logger = logger() 23 | private final val signKey: SecretKey = SecretKeySpec(appProperties.token.secretKey.toByteArray(), "AES") 24 | private val jwtParser = Jwts 25 | .parser() 26 | .decryptWith(signKey) 27 | .build() 28 | 29 | fun generateTokenPair(authentication: Authentication): TokenPair { 30 | val accessToken = generateAccessToken(authentication) 31 | val refreshToken = generateRefreshToken(authentication) 32 | return TokenPair(accessToken, refreshToken) 33 | } 34 | 35 | private fun generateAccessToken(authentication: Authentication): String { 36 | val authorities = authentication.authorities.joinToString(",") { 37 | it.authority 38 | } 39 | return Jwts.builder() 40 | .header() 41 | .add(TOKEN_TYPE_HEADER_KEY, ACCESS_TOKEN_TYPE_VALUE) 42 | .and() 43 | .claims() 44 | .add(USER_ID_CLAIM_KEY, authentication.name) 45 | .add(AUTHORITIES_CLAIM_KEY, authorities) 46 | .and() 47 | .expiration(generateAccessTokenExpiration()) 48 | .encryptWith(signKey, Jwts.ENC.A128CBC_HS256) 49 | .compact() 50 | } 51 | 52 | private fun generateRefreshToken(authentication: Authentication): String = Jwts.builder() 53 | .header() 54 | .add(TOKEN_TYPE_HEADER_KEY, REFRESH_TOKEN_TYPE_VALUE) 55 | .and() 56 | .claims() 57 | .add(USER_ID_CLAIM_KEY, authentication.name) 58 | .and() 59 | .expiration(generateRefreshTokenExpiration()) 60 | .encryptWith(signKey, Jwts.ENC.A128CBC_HS256) 61 | .compact() 62 | 63 | fun parseAuthentication(accessToken: String): Authentication { 64 | val claims = runCatching { 65 | jwtParser.parseEncryptedClaims(accessToken) 66 | }.getOrElse { 67 | throw DomainException(ErrorCode.TOKEN_EXPIRED) 68 | } 69 | val tokenType = claims.header[TOKEN_TYPE_HEADER_KEY] ?: run { 70 | logger.error("Token type not found in header - claims($claims)") 71 | throw RuntimeException("Invalid token type!") 72 | } 73 | if (tokenType != ACCESS_TOKEN_TYPE_VALUE) { 74 | logger.error("Token is not an access token - tokenType($tokenType)") 75 | throw RuntimeException() 76 | } 77 | 78 | val userId = claims.payload[USER_ID_CLAIM_KEY] as? String? ?: run { 79 | logger.error("Cannot parse userId from claims - claims($claims)") 80 | throw RuntimeException() 81 | } 82 | val authoritiesStr = claims.payload[AUTHORITIES_CLAIM_KEY] as? String? 83 | val authorities = if (authoritiesStr.isNullOrEmpty()) { 84 | emptyList() 85 | } else { 86 | claims.payload[AUTHORITIES_CLAIM_KEY]?.toString() 87 | ?.split(",") 88 | ?.map { SimpleGrantedAuthority("ROLE_$it") } 89 | ?: emptyList() 90 | } 91 | 92 | return UsernamePasswordAuthenticationToken( 93 | userId, 94 | accessToken, 95 | authorities, 96 | ) 97 | } 98 | 99 | fun getMemberIdFromRefreshToken(refreshToken: String): ObjectId { 100 | val claims = jwtParser.parseEncryptedClaims(refreshToken) 101 | val tokenType = claims.header[TOKEN_TYPE_HEADER_KEY] ?: run { 102 | logger.error("Token type not found in header - claims($claims)") 103 | throw RuntimeException() 104 | } 105 | if (tokenType != REFRESH_TOKEN_TYPE_VALUE) { 106 | logger.error("Token is not an refresh token - tokenType($tokenType)") 107 | throw RuntimeException() 108 | } 109 | 110 | return ObjectId(claims.payload[USER_ID_CLAIM_KEY] as? String ?: run { 111 | logger.error("Cannot parse userId from claims - claims($claims)") 112 | throw RuntimeException() 113 | }) 114 | } 115 | 116 | private fun generateAccessTokenExpiration() = Date(System.currentTimeMillis() + appProperties.token.expiration.access * 1000) 117 | 118 | private fun generateRefreshTokenExpiration() = Date(System.currentTimeMillis() + appProperties.token.expiration.refresh * 1000) 119 | 120 | companion object { 121 | const val USER_ID_CLAIM_KEY = "user_id" 122 | const val AUTHORITIES_CLAIM_KEY = "authorities" 123 | 124 | const val TOKEN_TYPE_HEADER_KEY = "token_type" 125 | const val ACCESS_TOKEN_TYPE_VALUE = "access_token" 126 | const val REFRESH_TOKEN_TYPE_VALUE = "refresh_token" 127 | } 128 | } 129 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | # SPDX-License-Identifier: Apache-2.0 19 | # 20 | 21 | ############################################################################## 22 | # 23 | # Gradle start up script for POSIX generated by Gradle. 24 | # 25 | # Important for running: 26 | # 27 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 28 | # noncompliant, but you have some other compliant shell such as ksh or 29 | # bash, then to run this script, type that shell name before the whole 30 | # command line, like: 31 | # 32 | # ksh Gradle 33 | # 34 | # Busybox and similar reduced shells will NOT work, because this script 35 | # requires all of these POSIX shell features: 36 | # * functions; 37 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 38 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 39 | # * compound commands having a testable exit status, especially «case»; 40 | # * various built-in commands including «command», «set», and «ulimit». 41 | # 42 | # Important for patching: 43 | # 44 | # (2) This script targets any POSIX shell, so it avoids extensions provided 45 | # by Bash, Ksh, etc; in particular arrays are avoided. 46 | # 47 | # The "traditional" practice of packing multiple parameters into a 48 | # space-separated string is a well documented source of bugs and security 49 | # problems, so this is (mostly) avoided, by progressively accumulating 50 | # options in "$@", and eventually passing that to Java. 51 | # 52 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 53 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 54 | # see the in-line comments for details. 55 | # 56 | # There are tweaks for specific operating systems such as AIX, CygWin, 57 | # Darwin, MinGW, and NonStop. 58 | # 59 | # (3) This script is generated from the Groovy template 60 | # https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 61 | # within the Gradle project. 62 | # 63 | # You can find Gradle at https://github.com/gradle/gradle/. 64 | # 65 | ############################################################################## 66 | 67 | # Attempt to set APP_HOME 68 | 69 | # Resolve links: $0 may be a link 70 | app_path=$0 71 | 72 | # Need this for daisy-chained symlinks. 73 | while 74 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 75 | [ -h "$app_path" ] 76 | do 77 | ls=$( ls -ld "$app_path" ) 78 | link=${ls#*' -> '} 79 | case $link in #( 80 | /*) app_path=$link ;; #( 81 | *) app_path=$APP_HOME$link ;; 82 | esac 83 | done 84 | 85 | # This is normally unused 86 | # shellcheck disable=SC2034 87 | APP_BASE_NAME=${0##*/} 88 | # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) 89 | APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s 90 | ' "$PWD" ) || exit 91 | 92 | # Use the maximum available, or set MAX_FD != -1 to use that value. 93 | MAX_FD=maximum 94 | 95 | warn () { 96 | echo "$*" 97 | } >&2 98 | 99 | die () { 100 | echo 101 | echo "$*" 102 | echo 103 | exit 1 104 | } >&2 105 | 106 | # OS specific support (must be 'true' or 'false'). 107 | cygwin=false 108 | msys=false 109 | darwin=false 110 | nonstop=false 111 | case "$( uname )" in #( 112 | CYGWIN* ) cygwin=true ;; #( 113 | Darwin* ) darwin=true ;; #( 114 | MSYS* | MINGW* ) msys=true ;; #( 115 | NONSTOP* ) nonstop=true ;; 116 | esac 117 | 118 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 119 | 120 | 121 | # Determine the Java command to use to start the JVM. 122 | if [ -n "$JAVA_HOME" ] ; then 123 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 124 | # IBM's JDK on AIX uses strange locations for the executables 125 | JAVACMD=$JAVA_HOME/jre/sh/java 126 | else 127 | JAVACMD=$JAVA_HOME/bin/java 128 | fi 129 | if [ ! -x "$JAVACMD" ] ; then 130 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 131 | 132 | Please set the JAVA_HOME variable in your environment to match the 133 | location of your Java installation." 134 | fi 135 | else 136 | JAVACMD=java 137 | if ! command -v java >/dev/null 2>&1 138 | then 139 | die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 140 | 141 | Please set the JAVA_HOME variable in your environment to match the 142 | location of your Java installation." 143 | fi 144 | fi 145 | 146 | # Increase the maximum file descriptors if we can. 147 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 148 | case $MAX_FD in #( 149 | max*) 150 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. 151 | # shellcheck disable=SC2039,SC3045 152 | MAX_FD=$( ulimit -H -n ) || 153 | warn "Could not query maximum file descriptor limit" 154 | esac 155 | case $MAX_FD in #( 156 | '' | soft) :;; #( 157 | *) 158 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. 159 | # shellcheck disable=SC2039,SC3045 160 | ulimit -n "$MAX_FD" || 161 | warn "Could not set maximum file descriptor limit to $MAX_FD" 162 | esac 163 | fi 164 | 165 | # Collect all arguments for the java command, stacking in reverse order: 166 | # * args from the command line 167 | # * the main class name 168 | # * -classpath 169 | # * -D...appname settings 170 | # * --module-path (only if needed) 171 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 172 | 173 | # For Cygwin or MSYS, switch paths to Windows format before running java 174 | if "$cygwin" || "$msys" ; then 175 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 176 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 177 | 178 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 179 | 180 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 181 | for arg do 182 | if 183 | case $arg in #( 184 | -*) false ;; # don't mess with options #( 185 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 186 | [ -e "$t" ] ;; #( 187 | *) false ;; 188 | esac 189 | then 190 | arg=$( cygpath --path --ignore --mixed "$arg" ) 191 | fi 192 | # Roll the args list around exactly as many times as the number of 193 | # args, so each arg winds up back in the position where it started, but 194 | # possibly modified. 195 | # 196 | # NB: a `for` loop captures its iteration list before it begins, so 197 | # changing the positional parameters here affects neither the number of 198 | # iterations, nor the values presented in `arg`. 199 | shift # remove old arg 200 | set -- "$@" "$arg" # push replacement arg 201 | done 202 | fi 203 | 204 | 205 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 206 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 207 | 208 | # Collect all arguments for the java command: 209 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, 210 | # and any embedded shellness will be escaped. 211 | # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be 212 | # treated as '${Hostname}' itself on the command line. 213 | 214 | set -- \ 215 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 216 | -classpath "$CLASSPATH" \ 217 | org.gradle.wrapper.GradleWrapperMain \ 218 | "$@" 219 | 220 | # Stop when "xargs" is not available. 221 | if ! command -v xargs >/dev/null 2>&1 222 | then 223 | die "xargs is not available" 224 | fi 225 | 226 | # Use "xargs" to parse quoted args. 227 | # 228 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 229 | # 230 | # In Bash we could simply go: 231 | # 232 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 233 | # set -- "${ARGS[@]}" "$@" 234 | # 235 | # but POSIX shell has neither arrays nor command substitution, so instead we 236 | # post-process each arg (as a line of input to sed) to backslash-escape any 237 | # character that might be a shell metacharacter, then use eval to reverse 238 | # that process (while maintaining the separation between arguments), and wrap 239 | # the whole thing up as a single "set" statement. 240 | # 241 | # This will of course break if any of these variables contains a newline or 242 | # an unmatched quote. 243 | # 244 | 245 | eval "set -- $( 246 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 247 | xargs -n1 | 248 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 249 | tr '\n' ' ' 250 | )" '"$@"' 251 | 252 | exec "$JAVACMD" "$@" 253 | --------------------------------------------------------------------------------