Compare commits
1 Commits
feature/te
...
feature/lo
| Author | SHA1 | Date | |
|---|---|---|---|
| 1ff6532ada |
24
README.md
24
README.md
@@ -1,25 +1,3 @@
|
|||||||
# Scavenger Hunt API
|
# Scavenger Hunt API
|
||||||
|
|
||||||
REST API to support a community scavenger hunt app.
|
REST API to support a community scavenger hunt app.
|
||||||
|
|
||||||
## Environment variables
|
|
||||||
* `DB_PASSWORD` Password for the database
|
|
||||||
* `DB_URL` JDBC URL for the database
|
|
||||||
* `DB_USER` Username for the database
|
|
||||||
* `JWT_SECRET` Secret pass for the JWT
|
|
||||||
|
|
||||||
## TODO:
|
|
||||||
### User Endpoints
|
|
||||||
* list teams for hunt GET `/hunt/{id}/team`
|
|
||||||
* create new hunt team POST `/hunt/{id}/team`
|
|
||||||
* join hunt team POST `/hunt/{id}/team/{id}`
|
|
||||||
* list items for hunt GET `/hunt/{id}/item`
|
|
||||||
* get hunt item info GET `/hunt/{id}/item/{id}`
|
|
||||||
* get hunt team item info GET `/hunt/{id}/team/{id}/item/{id}`
|
|
||||||
* get photos for hunt item GET `/hunt/{id}/team/{id}/item/{id}/photo`
|
|
||||||
* upload photo for hunt item POST `/hunt/{id}/team/{id}/item/{id}/photo`
|
|
||||||
* delete photo for hunt item DELETE `/hunt/{id}/team/{id}/item/{id}/photo`
|
|
||||||
* list hunt teams with scores for hunt `GET /lead/hunt/{id}/team`
|
|
||||||
* list hunters with scores for hunt GET `/lead/hunt/{id}/hunter`
|
|
||||||
### Admin Endpoints
|
|
||||||
* approve photo for hunt item POST `/admin/hunt/{id}/team/{id}`
|
|
||||||
@@ -29,21 +29,13 @@ repositories {
|
|||||||
dependencies {
|
dependencies {
|
||||||
val mysqlConnectorJ = "9.5.0"
|
val mysqlConnectorJ = "9.5.0"
|
||||||
val commonsValidator = "1.10.1"
|
val commonsValidator = "1.10.1"
|
||||||
val jakartaValidation = "3.1.1"
|
|
||||||
val jsonWebToken = "0.13.0"
|
|
||||||
implementation("org.springframework.boot:spring-boot-starter-actuator")
|
implementation("org.springframework.boot:spring-boot-starter-actuator")
|
||||||
implementation("org.springframework.boot:spring-boot-starter-web")
|
implementation("org.springframework.boot:spring-boot-starter-web")
|
||||||
implementation("org.springframework.boot:spring-boot-starter-data-jpa")
|
implementation("org.springframework.boot:spring-boot-starter-data-jpa")
|
||||||
implementation("org.springframework.boot:spring-boot-starter-validation")
|
|
||||||
implementation("org.springframework.boot:spring-boot-starter-security")
|
|
||||||
implementation("jakarta.validation:jakarta.validation-api:${jakartaValidation}")
|
|
||||||
implementation("com.mysql:mysql-connector-j:${mysqlConnectorJ}")
|
implementation("com.mysql:mysql-connector-j:${mysqlConnectorJ}")
|
||||||
implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
|
implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
|
||||||
implementation("org.jetbrains.kotlin:kotlin-reflect")
|
implementation("org.jetbrains.kotlin:kotlin-reflect")
|
||||||
implementation("commons-validator:commons-validator:${commonsValidator}")
|
implementation("commons-validator:commons-validator:${commonsValidator}")
|
||||||
implementation("io.jsonwebtoken:jjwt-api:${jsonWebToken}")
|
|
||||||
implementation("io.jsonwebtoken:jjwt-impl:${jsonWebToken}")
|
|
||||||
implementation("io.jsonwebtoken:jjwt-jackson:${jsonWebToken}")
|
|
||||||
developmentOnly("org.springframework.boot:spring-boot-devtools")
|
developmentOnly("org.springframework.boot:spring-boot-devtools")
|
||||||
annotationProcessor("org.springframework.boot:spring-boot-configuration-processor")
|
annotationProcessor("org.springframework.boot:spring-boot-configuration-processor")
|
||||||
testImplementation("org.springframework.boot:spring-boot-starter-actuator-test")
|
testImplementation("org.springframework.boot:spring-boot-starter-actuator-test")
|
||||||
|
|||||||
@@ -1,18 +0,0 @@
|
|||||||
package net.halfbinary.scavengerhuntapi.config
|
|
||||||
|
|
||||||
import jakarta.servlet.http.HttpServletRequest
|
|
||||||
import jakarta.servlet.http.HttpServletResponse
|
|
||||||
import org.springframework.security.core.AuthenticationException
|
|
||||||
import org.springframework.security.web.AuthenticationEntryPoint
|
|
||||||
import org.springframework.stereotype.Component
|
|
||||||
|
|
||||||
@Component
|
|
||||||
class AuthEntrypointJwt: AuthenticationEntryPoint {
|
|
||||||
override fun commence(
|
|
||||||
request: HttpServletRequest,
|
|
||||||
response: HttpServletResponse,
|
|
||||||
authException: AuthenticationException
|
|
||||||
) {
|
|
||||||
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException.message)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,49 +0,0 @@
|
|||||||
package net.halfbinary.scavengerhuntapi.config
|
|
||||||
|
|
||||||
import jakarta.servlet.FilterChain
|
|
||||||
import jakarta.servlet.http.HttpServletRequest
|
|
||||||
import jakarta.servlet.http.HttpServletResponse
|
|
||||||
import net.halfbinary.scavengerhuntapi.service.HunterDetailsService
|
|
||||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
|
|
||||||
import org.springframework.security.core.context.SecurityContextHolder
|
|
||||||
import org.springframework.security.core.userdetails.UserDetails
|
|
||||||
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource
|
|
||||||
import org.springframework.stereotype.Component
|
|
||||||
import org.springframework.web.filter.OncePerRequestFilter
|
|
||||||
|
|
||||||
|
|
||||||
@Component
|
|
||||||
class AuthTokenFilter(private val jwtUtils: JwtUtil, private val hunterDetailsService: HunterDetailsService): OncePerRequestFilter() {
|
|
||||||
override fun doFilterInternal(
|
|
||||||
request: HttpServletRequest,
|
|
||||||
response: HttpServletResponse,
|
|
||||||
filterChain: FilterChain
|
|
||||||
) {
|
|
||||||
try {
|
|
||||||
val jwt: String? = parseJwt(request)
|
|
||||||
if (jwt != null && jwtUtils.validateJwtToken(jwt)) {
|
|
||||||
val username = jwtUtils.getUsernameFromToken(jwt)
|
|
||||||
val userDetails: UserDetails = hunterDetailsService.loadUserByUsername(username)
|
|
||||||
val authentication =
|
|
||||||
UsernamePasswordAuthenticationToken(
|
|
||||||
userDetails,
|
|
||||||
null,
|
|
||||||
userDetails.authorities
|
|
||||||
)
|
|
||||||
authentication.details = WebAuthenticationDetailsSource().buildDetails(request)
|
|
||||||
SecurityContextHolder.getContext().authentication = authentication
|
|
||||||
}
|
|
||||||
} catch (e: Exception) {
|
|
||||||
println("Cannot set user authentication: $e")
|
|
||||||
}
|
|
||||||
filterChain.doFilter(request, response)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun parseJwt(request: HttpServletRequest): String? {
|
|
||||||
val headerAuth = request.getHeader("Authorization")
|
|
||||||
if (headerAuth != null && headerAuth.startsWith("Bearer ")) {
|
|
||||||
return headerAuth.substring(7)
|
|
||||||
}
|
|
||||||
return null
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,62 +0,0 @@
|
|||||||
package net.halfbinary.scavengerhuntapi.config
|
|
||||||
|
|
||||||
import io.jsonwebtoken.JwtException
|
|
||||||
import io.jsonwebtoken.Jwts
|
|
||||||
import jakarta.annotation.PostConstruct
|
|
||||||
import org.springframework.beans.factory.annotation.Value
|
|
||||||
import org.springframework.stereotype.Component
|
|
||||||
import java.util.Date
|
|
||||||
import javax.crypto.SecretKey
|
|
||||||
|
|
||||||
@Component
|
|
||||||
class JwtUtil {
|
|
||||||
@Value($$"${jwt.secret}")
|
|
||||||
private val jwtSecret: String? = null
|
|
||||||
|
|
||||||
@Value($$"${jwt.expiration}")
|
|
||||||
private val jwtExpirationMs = 0
|
|
||||||
|
|
||||||
private var key: SecretKey? = null
|
|
||||||
|
|
||||||
// Initializes the key after the class is instantiated and the jwtSecret is injected,
|
|
||||||
// preventing the repeated creation of the key and enhancing performance
|
|
||||||
@PostConstruct
|
|
||||||
fun init() {
|
|
||||||
this.key = Jwts.SIG.HS256.key().build()
|
|
||||||
}
|
|
||||||
|
|
||||||
// Generate JWT token
|
|
||||||
fun generateToken(email: String): String {
|
|
||||||
return Jwts.builder()
|
|
||||||
.subject(email)
|
|
||||||
.issuedAt(Date())
|
|
||||||
.expiration(Date(System.currentTimeMillis() + jwtExpirationMs))
|
|
||||||
.signWith(key)
|
|
||||||
.compact()
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get username from JWT token
|
|
||||||
fun getUsernameFromToken(token: String): String {
|
|
||||||
return Jwts.parser()
|
|
||||||
.verifyWith(key)
|
|
||||||
.build()
|
|
||||||
.parseSignedClaims(token)
|
|
||||||
.payload
|
|
||||||
.subject
|
|
||||||
}
|
|
||||||
|
|
||||||
// Validate JWT token
|
|
||||||
fun validateJwtToken(token: String?): Boolean {
|
|
||||||
try {
|
|
||||||
Jwts.parser().verifyWith(key).build().parseSignedClaims(token)
|
|
||||||
return true
|
|
||||||
} catch (e: SecurityException) {
|
|
||||||
println("Invalid JWT signature: " + e.message)
|
|
||||||
} catch (e: JwtException) {
|
|
||||||
println("Invalid JWT token: " + e.message)
|
|
||||||
} catch (e: IllegalArgumentException) {
|
|
||||||
println("JWT claims string is empty: " + e.message)
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,74 +0,0 @@
|
|||||||
package net.halfbinary.scavengerhuntapi.config
|
|
||||||
|
|
||||||
import org.springframework.context.annotation.Bean
|
|
||||||
import org.springframework.context.annotation.Configuration
|
|
||||||
import org.springframework.security.authentication.AuthenticationManager
|
|
||||||
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration
|
|
||||||
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity
|
|
||||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity
|
|
||||||
import org.springframework.security.config.annotation.web.configurers.CorsConfigurer
|
|
||||||
import org.springframework.security.config.annotation.web.configurers.CsrfConfigurer
|
|
||||||
import org.springframework.security.config.annotation.web.configurers.ExceptionHandlingConfigurer
|
|
||||||
import org.springframework.security.config.annotation.web.configurers.SessionManagementConfigurer
|
|
||||||
import org.springframework.security.config.http.SessionCreationPolicy
|
|
||||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder
|
|
||||||
import org.springframework.security.crypto.password.PasswordEncoder
|
|
||||||
import org.springframework.security.web.SecurityFilterChain
|
|
||||||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter
|
|
||||||
|
|
||||||
|
|
||||||
@Configuration
|
|
||||||
@EnableMethodSecurity
|
|
||||||
class SecurityConfig(private val authEntrypointJwt: AuthEntrypointJwt,
|
|
||||||
private val authTokenFilter: AuthTokenFilter) {
|
|
||||||
|
|
||||||
@Bean
|
|
||||||
fun authenticationJwtTokenFilter(): AuthTokenFilter {
|
|
||||||
return authTokenFilter
|
|
||||||
}
|
|
||||||
|
|
||||||
@Bean
|
|
||||||
@Throws(Exception::class)
|
|
||||||
fun authenticationManager(
|
|
||||||
authenticationConfiguration: AuthenticationConfiguration
|
|
||||||
): AuthenticationManager? {
|
|
||||||
return authenticationConfiguration.getAuthenticationManager()
|
|
||||||
}
|
|
||||||
|
|
||||||
@Bean
|
|
||||||
fun passwordEncoder(): PasswordEncoder {
|
|
||||||
return BCryptPasswordEncoder()
|
|
||||||
}
|
|
||||||
|
|
||||||
@Bean
|
|
||||||
@Throws(Exception::class)
|
|
||||||
fun securityFilterChain(http: HttpSecurity): SecurityFilterChain? {
|
|
||||||
// Updated configuration for Spring Security 6.x
|
|
||||||
http
|
|
||||||
.csrf { csrf: CsrfConfigurer<HttpSecurity> -> csrf.disable() } // Disable CSRF
|
|
||||||
.cors { cors: CorsConfigurer<HttpSecurity> -> cors.disable() } // Disable CORS (or configure if needed)
|
|
||||||
.exceptionHandling { exceptionHandling: ExceptionHandlingConfigurer<HttpSecurity> ->
|
|
||||||
exceptionHandling.authenticationEntryPoint(
|
|
||||||
authEntrypointJwt
|
|
||||||
)
|
|
||||||
}
|
|
||||||
.sessionManagement { sessionManagement: SessionManagementConfigurer<HttpSecurity> ->
|
|
||||||
sessionManagement.sessionCreationPolicy(
|
|
||||||
SessionCreationPolicy.STATELESS
|
|
||||||
)
|
|
||||||
}
|
|
||||||
.authorizeHttpRequests { authorizeRequests ->
|
|
||||||
authorizeRequests
|
|
||||||
.requestMatchers("/auth/**", "/signup")
|
|
||||||
.permitAll()
|
|
||||||
.anyRequest().authenticated()
|
|
||||||
}
|
|
||||||
|
|
||||||
// Add the JWT Token filter before the UsernamePasswordAuthenticationFilter
|
|
||||||
http.addFilterBefore(
|
|
||||||
authenticationJwtTokenFilter(),
|
|
||||||
UsernamePasswordAuthenticationFilter::class.java
|
|
||||||
)
|
|
||||||
return http.build()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,53 +0,0 @@
|
|||||||
package net.halfbinary.scavengerhuntapi.controller
|
|
||||||
|
|
||||||
import jakarta.servlet.http.HttpServletResponse
|
|
||||||
import jakarta.validation.Valid
|
|
||||||
import net.halfbinary.scavengerhuntapi.config.JwtUtil
|
|
||||||
import net.halfbinary.scavengerhuntapi.model.converter.toDomain
|
|
||||||
import net.halfbinary.scavengerhuntapi.model.request.LoginRequest
|
|
||||||
import net.halfbinary.scavengerhuntapi.model.request.LogoutRequest
|
|
||||||
import net.halfbinary.scavengerhuntapi.model.request.RefreshRequest
|
|
||||||
import net.halfbinary.scavengerhuntapi.model.response.LoginResponse
|
|
||||||
import net.halfbinary.scavengerhuntapi.service.LoginService
|
|
||||||
import net.halfbinary.scavengerhuntapi.service.RefreshTokenService
|
|
||||||
import org.springframework.http.ResponseEntity
|
|
||||||
import org.springframework.security.core.authority.SimpleGrantedAuthority
|
|
||||||
import org.springframework.security.core.userdetails.User
|
|
||||||
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 java.util.Collections
|
|
||||||
|
|
||||||
|
|
||||||
@RestController
|
|
||||||
@RequestMapping("/auth")
|
|
||||||
class AuthController(private val loginService: LoginService, private val jwtUtils: JwtUtil, private val refreshTokenService: RefreshTokenService) {
|
|
||||||
@PostMapping("/login")
|
|
||||||
fun login(@Valid @RequestBody body: LoginRequest, response: HttpServletResponse): ResponseEntity<LoginResponse> {
|
|
||||||
val result = loginService.login(body.toDomain())
|
|
||||||
// TODO: Figure out how to use the authorities
|
|
||||||
val hunterAuthorities =
|
|
||||||
if (result.isAdmin) {
|
|
||||||
SimpleGrantedAuthority("ROLE_ADMIN")
|
|
||||||
} else {
|
|
||||||
SimpleGrantedAuthority("ROLE_USER")
|
|
||||||
}
|
|
||||||
val user = User(result.email, result.password, Collections.singleton(hunterAuthorities))
|
|
||||||
val accessToken = jwtUtils.generateToken(result.email)
|
|
||||||
val refreshToken = refreshTokenService.generateRefreshToken(result.email)
|
|
||||||
val loginResponse = LoginResponse(accessToken, refreshToken)
|
|
||||||
return ResponseEntity.ok(loginResponse)
|
|
||||||
}
|
|
||||||
|
|
||||||
@PostMapping("/refresh")
|
|
||||||
fun refresh(@RequestBody body: RefreshRequest): String {
|
|
||||||
return refreshTokenService.getAccessToken(body.refreshToken)
|
|
||||||
}
|
|
||||||
|
|
||||||
@PostMapping("/logout")
|
|
||||||
fun logout(@RequestBody body: LogoutRequest, response: HttpServletResponse): ResponseEntity<String> {
|
|
||||||
refreshTokenService.removeToken(body.refreshToken)
|
|
||||||
return ResponseEntity.ok().build()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,41 +0,0 @@
|
|||||||
package net.halfbinary.scavengerhuntapi.controller
|
|
||||||
|
|
||||||
import jakarta.validation.Valid
|
|
||||||
import net.halfbinary.scavengerhuntapi.model.HuntId
|
|
||||||
import net.halfbinary.scavengerhuntapi.model.HunterId
|
|
||||||
import net.halfbinary.scavengerhuntapi.model.converter.toDomain
|
|
||||||
import net.halfbinary.scavengerhuntapi.model.converter.toResponse
|
|
||||||
import net.halfbinary.scavengerhuntapi.model.request.HuntCreateRequest
|
|
||||||
import net.halfbinary.scavengerhuntapi.model.request.HuntStatus
|
|
||||||
import net.halfbinary.scavengerhuntapi.model.response.HuntResponse
|
|
||||||
import net.halfbinary.scavengerhuntapi.service.HuntService
|
|
||||||
import org.springframework.http.ResponseEntity
|
|
||||||
import org.springframework.security.access.prepost.PreAuthorize
|
|
||||||
import org.springframework.web.bind.annotation.*
|
|
||||||
|
|
||||||
@RestController
|
|
||||||
@RequestMapping("hunt")
|
|
||||||
class HuntController(private val huntService: HuntService) {
|
|
||||||
|
|
||||||
@GetMapping("/{id}")
|
|
||||||
fun getHunt(@PathVariable("id") huntId: HuntId): ResponseEntity<HuntResponse> {
|
|
||||||
return ResponseEntity.ok(huntService.getHunt(huntId).toResponse())
|
|
||||||
}
|
|
||||||
|
|
||||||
@PreAuthorize("hasRole('ADMIN')")
|
|
||||||
@GetMapping()
|
|
||||||
fun getAllHunts(@RequestParam status: HuntStatus?): ResponseEntity<List<HuntResponse>> {
|
|
||||||
return ResponseEntity.ok(huntService.getAllHunts(status).map { it.toResponse() })
|
|
||||||
}
|
|
||||||
|
|
||||||
@PostMapping()
|
|
||||||
fun createHunt(@Valid @RequestBody huntRequest: HuntCreateRequest): ResponseEntity<HuntResponse> {
|
|
||||||
return ResponseEntity.ok(huntService.createHunt(huntRequest.toDomain()).toResponse())
|
|
||||||
}
|
|
||||||
|
|
||||||
@GetMapping("/hunter/{hunterId}")
|
|
||||||
fun getHuntsByHunter(@PathVariable("hunterId") hunterId: HunterId): ResponseEntity<List<HuntResponse>> {
|
|
||||||
return ResponseEntity.ok(huntService.getHuntsByHunter(hunterId).map { it.toResponse() })
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
package net.halfbinary.scavengerhuntapi.controller
|
||||||
|
|
||||||
|
import jakarta.servlet.http.Cookie
|
||||||
|
import jakarta.servlet.http.HttpServletResponse
|
||||||
|
import net.halfbinary.scavengerhuntapi.model.converter.toDomain
|
||||||
|
import net.halfbinary.scavengerhuntapi.model.converter.toLoginResponse
|
||||||
|
import net.halfbinary.scavengerhuntapi.model.request.LoginRequest
|
||||||
|
import net.halfbinary.scavengerhuntapi.model.response.LoginResponse
|
||||||
|
import net.halfbinary.scavengerhuntapi.service.LoginService
|
||||||
|
import org.springframework.http.ResponseEntity
|
||||||
|
import org.springframework.web.bind.annotation.PostMapping
|
||||||
|
import org.springframework.web.bind.annotation.RequestBody
|
||||||
|
import org.springframework.web.bind.annotation.RestController
|
||||||
|
import java.net.URLEncoder
|
||||||
|
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
class LoginController(private val loginService: LoginService) {
|
||||||
|
@PostMapping("/login")
|
||||||
|
fun login(@RequestBody body: LoginRequest, response: HttpServletResponse): ResponseEntity<LoginResponse> {
|
||||||
|
val result = loginService.login(body.toDomain())
|
||||||
|
val creds = "${result.email}|${result.name}"
|
||||||
|
val encodedCreds = URLEncoder.encode(creds, "UTF-8")
|
||||||
|
response.addCookie(Cookie("creds", encodedCreds))
|
||||||
|
return ResponseEntity.ok(result.toLoginResponse())
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/logout")
|
||||||
|
fun logout(response: HttpServletResponse): ResponseEntity<String> {
|
||||||
|
val cookie = Cookie("creds", null)
|
||||||
|
cookie.maxAge = 0
|
||||||
|
response.addCookie(cookie)
|
||||||
|
return ResponseEntity.ok("OK")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,5 @@
|
|||||||
package net.halfbinary.scavengerhuntapi.controller
|
package net.halfbinary.scavengerhuntapi.controller
|
||||||
|
|
||||||
import jakarta.validation.Valid
|
|
||||||
import net.halfbinary.scavengerhuntapi.model.converter.toDomain
|
import net.halfbinary.scavengerhuntapi.model.converter.toDomain
|
||||||
import net.halfbinary.scavengerhuntapi.model.request.HunterSignupRequest
|
import net.halfbinary.scavengerhuntapi.model.request.HunterSignupRequest
|
||||||
import net.halfbinary.scavengerhuntapi.service.SignupService
|
import net.halfbinary.scavengerhuntapi.service.SignupService
|
||||||
@@ -12,7 +11,7 @@ import org.springframework.web.bind.annotation.RestController
|
|||||||
@RestController
|
@RestController
|
||||||
class SignupController(private val signupService: SignupService) {
|
class SignupController(private val signupService: SignupService) {
|
||||||
@PostMapping("/signup")
|
@PostMapping("/signup")
|
||||||
fun hunterSignup(@Valid @RequestBody body: HunterSignupRequest): ResponseEntity<Any> {
|
fun hunterSignup(@RequestBody body: HunterSignupRequest): ResponseEntity<Any> {
|
||||||
signupService.createNewHunter(body.toDomain())
|
signupService.createNewHunter(body.toDomain())
|
||||||
return ResponseEntity.ok().build()
|
return ResponseEntity.ok().build()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,27 +0,0 @@
|
|||||||
package net.halfbinary.scavengerhuntapi.controller
|
|
||||||
|
|
||||||
import jakarta.validation.Valid
|
|
||||||
import net.halfbinary.scavengerhuntapi.model.HuntId
|
|
||||||
import net.halfbinary.scavengerhuntapi.model.request.TeamRequest
|
|
||||||
import net.halfbinary.scavengerhuntapi.model.response.TeamResponse
|
|
||||||
import org.springframework.http.ResponseEntity
|
|
||||||
import org.springframework.web.bind.annotation.GetMapping
|
|
||||||
import org.springframework.web.bind.annotation.PathVariable
|
|
||||||
import org.springframework.web.bind.annotation.PostMapping
|
|
||||||
import org.springframework.web.bind.annotation.RequestBody
|
|
||||||
import org.springframework.web.bind.annotation.RequestMapping
|
|
||||||
import org.springframework.web.bind.annotation.RestController
|
|
||||||
|
|
||||||
@RestController
|
|
||||||
@RequestMapping("hunt/{id}/team")
|
|
||||||
class TeamController {
|
|
||||||
@GetMapping
|
|
||||||
fun listHuntTeams(@PathVariable id: HuntId): ResponseEntity<List<TeamResponse>> {
|
|
||||||
TODO()
|
|
||||||
}
|
|
||||||
|
|
||||||
@PostMapping
|
|
||||||
fun createHuntTeam(@PathVariable id: HuntId, @Valid @RequestBody team: TeamRequest) {
|
|
||||||
TODO()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -2,23 +2,15 @@ package net.halfbinary.scavengerhuntapi.error
|
|||||||
|
|
||||||
import net.halfbinary.scavengerhuntapi.error.exception.InvalidEmailException
|
import net.halfbinary.scavengerhuntapi.error.exception.InvalidEmailException
|
||||||
import net.halfbinary.scavengerhuntapi.error.exception.LoginFailedException
|
import net.halfbinary.scavengerhuntapi.error.exception.LoginFailedException
|
||||||
import net.halfbinary.scavengerhuntapi.error.exception.NotFoundException
|
|
||||||
import net.halfbinary.scavengerhuntapi.error.exception.PreexistingAccountException
|
import net.halfbinary.scavengerhuntapi.error.exception.PreexistingAccountException
|
||||||
import org.slf4j.LoggerFactory
|
|
||||||
import org.springframework.http.HttpStatus
|
import org.springframework.http.HttpStatus
|
||||||
import org.springframework.http.converter.HttpMessageNotReadableException
|
|
||||||
import org.springframework.validation.FieldError
|
|
||||||
import org.springframework.web.bind.MethodArgumentNotValidException
|
|
||||||
import org.springframework.web.bind.annotation.ExceptionHandler
|
import org.springframework.web.bind.annotation.ExceptionHandler
|
||||||
import org.springframework.web.bind.annotation.ResponseStatus
|
import org.springframework.web.bind.annotation.ResponseStatus
|
||||||
import org.springframework.web.bind.annotation.RestControllerAdvice
|
import org.springframework.web.bind.annotation.RestControllerAdvice
|
||||||
|
|
||||||
|
|
||||||
@RestControllerAdvice
|
@RestControllerAdvice
|
||||||
class ExceptionHandler {
|
class ExceptionHandler {
|
||||||
companion object {
|
|
||||||
private val log = LoggerFactory.getLogger(net.halfbinary.scavengerhuntapi.error.ExceptionHandler::class.java)
|
|
||||||
}
|
|
||||||
@ExceptionHandler(PreexistingAccountException::class)
|
@ExceptionHandler(PreexistingAccountException::class)
|
||||||
@ResponseStatus(HttpStatus.CONFLICT)
|
@ResponseStatus(HttpStatus.CONFLICT)
|
||||||
fun preexistingAccountException(e: PreexistingAccountException): String? {
|
fun preexistingAccountException(e: PreexistingAccountException): String? {
|
||||||
@@ -36,39 +28,4 @@ class ExceptionHandler {
|
|||||||
fun invalidEmailException(e: InvalidEmailException): String? {
|
fun invalidEmailException(e: InvalidEmailException): String? {
|
||||||
return e.message
|
return e.message
|
||||||
}
|
}
|
||||||
|
|
||||||
@ExceptionHandler(NotFoundException::class)
|
|
||||||
@ResponseStatus(HttpStatus.NOT_FOUND)
|
|
||||||
fun notFoundException(e: NotFoundException): String? {
|
|
||||||
return e.message
|
|
||||||
}
|
|
||||||
|
|
||||||
@ExceptionHandler(HttpMessageNotReadableException::class)
|
|
||||||
@ResponseStatus(HttpStatus.BAD_REQUEST)
|
|
||||||
fun httpMessageNotReadableException(e: HttpMessageNotReadableException): Map<String, String?> {
|
|
||||||
if (e.message?.contains("body is missing")?:false) {
|
|
||||||
return simpleMap("body","Body is missing")
|
|
||||||
}
|
|
||||||
if (e.message?.contains("parameter")?:false) {
|
|
||||||
val missingParameter = e.message?.split("parameter ")[1]
|
|
||||||
return simpleMap(missingParameter?:"","Missing required parameter $missingParameter")
|
|
||||||
}
|
|
||||||
log.debug("JSON parsing issue", e)
|
|
||||||
return simpleMap("body", "Parsing error")
|
|
||||||
}
|
|
||||||
|
|
||||||
@ExceptionHandler(MethodArgumentNotValidException::class)
|
|
||||||
@ResponseStatus(HttpStatus.BAD_REQUEST)
|
|
||||||
fun handleValidationExceptions(e: MethodArgumentNotValidException): Map<String, String?> {
|
|
||||||
return e.bindingResult.allErrors.associate { error ->
|
|
||||||
Pair(
|
|
||||||
(error as FieldError).field,
|
|
||||||
error.defaultMessage
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun simpleMap(key: String, value: String?): Map<String, String?> {
|
|
||||||
return mapOf(Pair(key, value))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
package net.halfbinary.scavengerhuntapi.error.exception
|
|
||||||
|
|
||||||
import net.halfbinary.scavengerhuntapi.model.RefreshId
|
|
||||||
|
|
||||||
class ExpiredRefreshTokenException(token: RefreshId): RuntimeException("The refresh token $token is expired.")
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
package net.halfbinary.scavengerhuntapi.error.exception
|
|
||||||
|
|
||||||
import net.halfbinary.scavengerhuntapi.model.RefreshId
|
|
||||||
|
|
||||||
class InvalidRefreshTokenException(token: RefreshId): RuntimeException("The refresh token $token is not valid.")
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
package net.halfbinary.scavengerhuntapi.error.exception
|
|
||||||
|
|
||||||
class NotFoundException(override val message: String): RuntimeException(message)
|
|
||||||
@@ -6,5 +6,4 @@ typealias FoundId = UUID
|
|||||||
typealias HuntId = UUID
|
typealias HuntId = UUID
|
||||||
typealias HunterId = UUID
|
typealias HunterId = UUID
|
||||||
typealias ItemId = UUID
|
typealias ItemId = UUID
|
||||||
typealias TeamId = UUID
|
typealias TeamId = UUID
|
||||||
typealias RefreshId = UUID
|
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
package net.halfbinary.scavengerhuntapi.model.converter
|
|
||||||
|
|
||||||
import net.halfbinary.scavengerhuntapi.model.domain.Hunt
|
|
||||||
import net.halfbinary.scavengerhuntapi.model.record.HuntRecord
|
|
||||||
import net.halfbinary.scavengerhuntapi.model.request.HuntCreateRequest
|
|
||||||
import net.halfbinary.scavengerhuntapi.model.response.HuntResponse
|
|
||||||
|
|
||||||
fun HuntRecord.toDomain(): Hunt {
|
|
||||||
return Hunt(id, title, startDateTime, endDateTime, isTerminated)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun Hunt.toResponse(): HuntResponse {
|
|
||||||
return HuntResponse(id, title, startDateTime, endDateTime, isTerminated)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun HuntCreateRequest.toDomain(): Hunt {
|
|
||||||
return Hunt(title = title, startDateTime = startDateTime, endDateTime = endDateTime, isTerminated = false)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun Hunt.toRecord(): HuntRecord {
|
|
||||||
return HuntRecord(id, title, startDateTime, endDateTime, isTerminated)
|
|
||||||
}
|
|
||||||
@@ -3,6 +3,7 @@ package net.halfbinary.scavengerhuntapi.model.converter
|
|||||||
import net.halfbinary.scavengerhuntapi.model.domain.Hunter
|
import net.halfbinary.scavengerhuntapi.model.domain.Hunter
|
||||||
import net.halfbinary.scavengerhuntapi.model.record.HunterRecord
|
import net.halfbinary.scavengerhuntapi.model.record.HunterRecord
|
||||||
import net.halfbinary.scavengerhuntapi.model.request.HunterSignupRequest
|
import net.halfbinary.scavengerhuntapi.model.request.HunterSignupRequest
|
||||||
|
import net.halfbinary.scavengerhuntapi.model.response.LoginResponse
|
||||||
|
|
||||||
fun HunterSignupRequest.toDomain(): Hunter {
|
fun HunterSignupRequest.toDomain(): Hunter {
|
||||||
return Hunter(
|
return Hunter(
|
||||||
@@ -19,4 +20,8 @@ fun Hunter.toRecord(): HunterRecord {
|
|||||||
|
|
||||||
fun HunterRecord.toDomain(): Hunter {
|
fun HunterRecord.toDomain(): Hunter {
|
||||||
return Hunter(id, email, name, password, isAdmin)
|
return Hunter(id, email, name, password, isAdmin)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun Hunter.toLoginResponse(): LoginResponse {
|
||||||
|
return LoginResponse(email, name)
|
||||||
}
|
}
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
package net.halfbinary.scavengerhuntapi.model.converter
|
|
||||||
|
|
||||||
import net.halfbinary.scavengerhuntapi.model.domain.Team
|
|
||||||
import net.halfbinary.scavengerhuntapi.model.record.TeamRecord
|
|
||||||
import net.halfbinary.scavengerhuntapi.model.request.TeamRequest
|
|
||||||
import net.halfbinary.scavengerhuntapi.model.response.TeamResponse
|
|
||||||
|
|
||||||
fun TeamRequest.toDomain(): Team {
|
|
||||||
return Team(name = name)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun Team.toRecord(): TeamRecord {
|
|
||||||
return TeamRecord(id, name)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun TeamRecord.toDomain(): Team {
|
|
||||||
return Team(id, name)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun Team.toResponse(): TeamResponse {
|
|
||||||
return TeamResponse(id, name)
|
|
||||||
}
|
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
package net.halfbinary.scavengerhuntapi.model.domain
|
|
||||||
|
|
||||||
import net.halfbinary.scavengerhuntapi.model.HuntId
|
|
||||||
import java.time.LocalDateTime
|
|
||||||
import java.util.*
|
|
||||||
|
|
||||||
data class Hunt(
|
|
||||||
val id: HuntId = UUID.randomUUID(),
|
|
||||||
val title: String,
|
|
||||||
val startDateTime: LocalDateTime,
|
|
||||||
val endDateTime: LocalDateTime,
|
|
||||||
val isTerminated: Boolean
|
|
||||||
)
|
|
||||||
@@ -1,10 +1,9 @@
|
|||||||
package net.halfbinary.scavengerhuntapi.model.domain
|
package net.halfbinary.scavengerhuntapi.model.domain
|
||||||
|
|
||||||
import net.halfbinary.scavengerhuntapi.model.HunterId
|
import java.util.UUID
|
||||||
import java.util.*
|
|
||||||
|
|
||||||
data class Hunter(
|
data class Hunter(
|
||||||
val id: HunterId = UUID.randomUUID(),
|
val id: UUID = UUID.randomUUID(),
|
||||||
val email: String,
|
val email: String,
|
||||||
val name: String,
|
val name: String,
|
||||||
val password: String,
|
val password: String,
|
||||||
|
|||||||
@@ -1,9 +0,0 @@
|
|||||||
package net.halfbinary.scavengerhuntapi.model.domain
|
|
||||||
|
|
||||||
import net.halfbinary.scavengerhuntapi.model.TeamId
|
|
||||||
import java.util.UUID
|
|
||||||
|
|
||||||
data class Team(
|
|
||||||
val id: TeamId = UUID.randomUUID(),
|
|
||||||
val name: String
|
|
||||||
)
|
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
package net.halfbinary.scavengerhuntapi.model.record
|
|
||||||
|
|
||||||
import jakarta.persistence.Entity
|
|
||||||
import jakarta.persistence.Id
|
|
||||||
import jakarta.persistence.Table
|
|
||||||
import net.halfbinary.scavengerhuntapi.model.RefreshId
|
|
||||||
import java.time.LocalDateTime
|
|
||||||
|
|
||||||
@Entity
|
|
||||||
@Table(name = "refresh_token")
|
|
||||||
data class RefreshTokenRecord(
|
|
||||||
@Id
|
|
||||||
val token: RefreshId,
|
|
||||||
val email: String,
|
|
||||||
val expiryDateTime: LocalDateTime
|
|
||||||
)
|
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
package net.halfbinary.scavengerhuntapi.model.request
|
|
||||||
|
|
||||||
import jakarta.validation.constraints.Future
|
|
||||||
import jakarta.validation.constraints.NotBlank
|
|
||||||
import java.time.LocalDateTime
|
|
||||||
|
|
||||||
data class HuntCreateRequest(
|
|
||||||
@field:NotBlank(message = "Hunt title is required")
|
|
||||||
val title: String,
|
|
||||||
@field:Future
|
|
||||||
val startDateTime: LocalDateTime,
|
|
||||||
@field:Future
|
|
||||||
val endDateTime: LocalDateTime,
|
|
||||||
)
|
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
package net.halfbinary.scavengerhuntapi.model.request
|
|
||||||
|
|
||||||
enum class HuntStatus {
|
|
||||||
UNSTARTED,
|
|
||||||
ONGOING,
|
|
||||||
CLOSED
|
|
||||||
}
|
|
||||||
@@ -1,14 +1,7 @@
|
|||||||
package net.halfbinary.scavengerhuntapi.model.request
|
package net.halfbinary.scavengerhuntapi.model.request
|
||||||
|
|
||||||
import jakarta.validation.constraints.Email
|
|
||||||
import jakarta.validation.constraints.NotBlank
|
|
||||||
|
|
||||||
data class HunterSignupRequest(
|
data class HunterSignupRequest(
|
||||||
@field:Email(message = "Must be a valid email address")
|
|
||||||
@field:NotBlank(message = "Email must not be blank")
|
|
||||||
val email: String,
|
val email: String,
|
||||||
@field:NotBlank(message = "Name cannot be blank")
|
|
||||||
val name: String,
|
val name: String,
|
||||||
@field:NotBlank(message = "Password cannot be blank")
|
|
||||||
val password: String
|
val password: String
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,10 +1,6 @@
|
|||||||
package net.halfbinary.scavengerhuntapi.model.request
|
package net.halfbinary.scavengerhuntapi.model.request
|
||||||
|
|
||||||
import jakarta.validation.constraints.NotBlank
|
|
||||||
|
|
||||||
data class LoginRequest(
|
data class LoginRequest(
|
||||||
@field:NotBlank(message = "Email cannot be blank")
|
|
||||||
val email: String,
|
val email: String,
|
||||||
@field:NotBlank(message = "Password cannot be blank")
|
|
||||||
val password: String
|
val password: String
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,9 +0,0 @@
|
|||||||
package net.halfbinary.scavengerhuntapi.model.request
|
|
||||||
|
|
||||||
import jakarta.validation.constraints.NotBlank
|
|
||||||
import net.halfbinary.scavengerhuntapi.model.RefreshId
|
|
||||||
|
|
||||||
data class LogoutRequest(
|
|
||||||
@field:NotBlank(message = "You must provide a refresh token.")
|
|
||||||
val refreshToken: RefreshId
|
|
||||||
)
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
package net.halfbinary.scavengerhuntapi.model.request
|
|
||||||
|
|
||||||
import jakarta.validation.constraints.NotBlank
|
|
||||||
import net.halfbinary.scavengerhuntapi.model.RefreshId
|
|
||||||
|
|
||||||
data class RefreshRequest(
|
|
||||||
@field:NotBlank(message = "Refresh token cannot be blank")
|
|
||||||
val refreshToken: RefreshId,
|
|
||||||
)
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
package net.halfbinary.scavengerhuntapi.model.request
|
|
||||||
|
|
||||||
data class TeamRequest(
|
|
||||||
val name: String
|
|
||||||
)
|
|
||||||
@@ -1,12 +0,0 @@
|
|||||||
package net.halfbinary.scavengerhuntapi.model.response
|
|
||||||
|
|
||||||
import net.halfbinary.scavengerhuntapi.model.HuntId
|
|
||||||
import java.time.LocalDateTime
|
|
||||||
|
|
||||||
data class HuntResponse(
|
|
||||||
val id: HuntId,
|
|
||||||
val title: String,
|
|
||||||
val startDateTime: LocalDateTime,
|
|
||||||
val endDateTime: LocalDateTime,
|
|
||||||
val isTerminated: Boolean
|
|
||||||
)
|
|
||||||
@@ -1,8 +1,6 @@
|
|||||||
package net.halfbinary.scavengerhuntapi.model.response
|
package net.halfbinary.scavengerhuntapi.model.response
|
||||||
|
|
||||||
import net.halfbinary.scavengerhuntapi.model.RefreshId
|
|
||||||
|
|
||||||
data class LoginResponse(
|
data class LoginResponse(
|
||||||
val accessToken: String,
|
val email: String,
|
||||||
val refreshToken: RefreshId
|
val name: String
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,8 +0,0 @@
|
|||||||
package net.halfbinary.scavengerhuntapi.model.response
|
|
||||||
|
|
||||||
import net.halfbinary.scavengerhuntapi.model.TeamId
|
|
||||||
|
|
||||||
data class TeamResponse(
|
|
||||||
val id: TeamId,
|
|
||||||
val name: String
|
|
||||||
)
|
|
||||||
@@ -1,49 +1,9 @@
|
|||||||
package net.halfbinary.scavengerhuntapi.repository
|
package net.halfbinary.scavengerhuntapi.repository
|
||||||
|
|
||||||
import net.halfbinary.scavengerhuntapi.model.HuntId
|
import net.halfbinary.scavengerhuntapi.model.HuntId
|
||||||
import net.halfbinary.scavengerhuntapi.model.HunterId
|
|
||||||
import net.halfbinary.scavengerhuntapi.model.record.HuntRecord
|
import net.halfbinary.scavengerhuntapi.model.record.HuntRecord
|
||||||
import org.springframework.data.jpa.repository.JpaRepository
|
import org.springframework.data.jpa.repository.JpaRepository
|
||||||
import org.springframework.data.jpa.repository.Query
|
|
||||||
import org.springframework.stereotype.Repository
|
import org.springframework.stereotype.Repository
|
||||||
|
|
||||||
@Repository
|
@Repository
|
||||||
interface HuntRepository : JpaRepository<HuntRecord, HuntId> {
|
interface HuntRepository : JpaRepository<HuntRecord, HuntId>
|
||||||
@Query("""
|
|
||||||
SELECT h.*
|
|
||||||
FROM hunter u
|
|
||||||
INNER JOIN hunter_team ht ON u.id = ht.hunter_id
|
|
||||||
INNER JOIN team t ON ht.team_id = t.id
|
|
||||||
INNER JOIN team_hunt th ON t.id = th.team_id
|
|
||||||
INNER JOIN hunt h ON th.hunt_id = h.id
|
|
||||||
WHERE u.id = :hunterId
|
|
||||||
AND h.is_terminated = FALSE
|
|
||||||
AND h.start_date_time < NOW()
|
|
||||||
AND h.end_date_time > NOW()
|
|
||||||
""", nativeQuery = true)
|
|
||||||
fun findAllOngoingByHunter(hunterId: HunterId): List<HuntRecord>
|
|
||||||
|
|
||||||
@Query("""
|
|
||||||
SELECT h.*
|
|
||||||
FROM hunt h
|
|
||||||
WHERE h.is_terminated = FALSE
|
|
||||||
AND h.start_date_time < NOW()
|
|
||||||
AND h.end_date_time > NOW()
|
|
||||||
""", nativeQuery = true)
|
|
||||||
fun findAllOngoing(): List<HuntRecord>
|
|
||||||
|
|
||||||
@Query("""
|
|
||||||
SELECT h.*
|
|
||||||
FROM hunt h
|
|
||||||
WHERE h.is_terminated = FALSE
|
|
||||||
AND h.start_date_time > NOW()
|
|
||||||
""", nativeQuery = true)
|
|
||||||
fun findAllUnstarted(): List<HuntRecord>
|
|
||||||
|
|
||||||
@Query("""
|
|
||||||
SELECT h.*
|
|
||||||
FROM hunt h
|
|
||||||
WHERE h.is_terminated = TRUE
|
|
||||||
""", nativeQuery = true)
|
|
||||||
fun findAllClosed(): List<HuntRecord>
|
|
||||||
}
|
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
package net.halfbinary.scavengerhuntapi.repository
|
|
||||||
|
|
||||||
import net.halfbinary.scavengerhuntapi.model.RefreshId
|
|
||||||
import net.halfbinary.scavengerhuntapi.model.record.RefreshTokenRecord
|
|
||||||
import org.springframework.data.jpa.repository.JpaRepository
|
|
||||||
|
|
||||||
interface RefreshTokenRepository: JpaRepository<RefreshTokenRecord, RefreshId>
|
|
||||||
@@ -1,36 +0,0 @@
|
|||||||
package net.halfbinary.scavengerhuntapi.service
|
|
||||||
|
|
||||||
import net.halfbinary.scavengerhuntapi.error.exception.NotFoundException
|
|
||||||
import net.halfbinary.scavengerhuntapi.model.HuntId
|
|
||||||
import net.halfbinary.scavengerhuntapi.model.HunterId
|
|
||||||
import net.halfbinary.scavengerhuntapi.model.converter.toDomain
|
|
||||||
import net.halfbinary.scavengerhuntapi.model.converter.toRecord
|
|
||||||
import net.halfbinary.scavengerhuntapi.model.domain.Hunt
|
|
||||||
import net.halfbinary.scavengerhuntapi.model.request.HuntStatus
|
|
||||||
import net.halfbinary.scavengerhuntapi.repository.HuntRepository
|
|
||||||
import org.springframework.data.repository.findByIdOrNull
|
|
||||||
import org.springframework.stereotype.Service
|
|
||||||
|
|
||||||
@Service
|
|
||||||
class HuntService(private val huntRepository: HuntRepository) {
|
|
||||||
fun getHunt(huntId: HuntId): Hunt {
|
|
||||||
return huntRepository.findByIdOrNull(huntId)?.toDomain() ?: throw NotFoundException("No hunt with id ${huntId} found")
|
|
||||||
}
|
|
||||||
|
|
||||||
fun getAllHunts(status: HuntStatus?): List<Hunt> {
|
|
||||||
return when(status) {
|
|
||||||
HuntStatus.UNSTARTED -> huntRepository.findAllUnstarted().map { it.toDomain() }
|
|
||||||
HuntStatus.ONGOING -> huntRepository.findAllOngoing().map { it.toDomain() }
|
|
||||||
HuntStatus.CLOSED -> huntRepository.findAllClosed().map { it.toDomain() }
|
|
||||||
else -> huntRepository.findAll().map { it.toDomain() }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun getHuntsByHunter(hunterId: HunterId): List<Hunt> {
|
|
||||||
return huntRepository.findAllOngoingByHunter(hunterId).map { it.toDomain() }
|
|
||||||
}
|
|
||||||
|
|
||||||
fun createHunt(hunt: Hunt): Hunt {
|
|
||||||
return huntRepository.save(hunt.toRecord()).toDomain()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,32 +0,0 @@
|
|||||||
package net.halfbinary.scavengerhuntapi.service
|
|
||||||
|
|
||||||
import net.halfbinary.scavengerhuntapi.repository.HunterRepository
|
|
||||||
import org.springframework.security.core.authority.SimpleGrantedAuthority
|
|
||||||
import org.springframework.security.core.userdetails.User
|
|
||||||
import org.springframework.security.core.userdetails.UserDetails
|
|
||||||
import org.springframework.security.core.userdetails.UserDetailsService
|
|
||||||
import org.springframework.security.core.userdetails.UsernameNotFoundException
|
|
||||||
import org.springframework.stereotype.Service
|
|
||||||
import java.util.Collections
|
|
||||||
|
|
||||||
|
|
||||||
@Service
|
|
||||||
class HunterDetailsService(private val hunterRepository: HunterRepository): UserDetailsService {
|
|
||||||
override fun loadUserByUsername(username: String): UserDetails {
|
|
||||||
hunterRepository.findByEmail(username)
|
|
||||||
?.let { hunter ->
|
|
||||||
val hunterAuthorities =
|
|
||||||
if (hunter.isAdmin) {
|
|
||||||
SimpleGrantedAuthority("ROLE_ADMIN")
|
|
||||||
} else {
|
|
||||||
SimpleGrantedAuthority("ROLE_USER")
|
|
||||||
}
|
|
||||||
return User(
|
|
||||||
hunter.email,
|
|
||||||
hunter.password,
|
|
||||||
Collections.singleton(hunterAuthorities)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
throw UsernameNotFoundException("User Not Found with username: $username")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,49 +0,0 @@
|
|||||||
package net.halfbinary.scavengerhuntapi.service
|
|
||||||
|
|
||||||
import net.halfbinary.scavengerhuntapi.config.JwtUtil
|
|
||||||
import net.halfbinary.scavengerhuntapi.error.exception.ExpiredRefreshTokenException
|
|
||||||
import net.halfbinary.scavengerhuntapi.error.exception.InvalidRefreshTokenException
|
|
||||||
import net.halfbinary.scavengerhuntapi.model.RefreshId
|
|
||||||
import net.halfbinary.scavengerhuntapi.model.record.RefreshTokenRecord
|
|
||||||
import net.halfbinary.scavengerhuntapi.repository.RefreshTokenRepository
|
|
||||||
import org.slf4j.LoggerFactory
|
|
||||||
import org.springframework.data.repository.findByIdOrNull
|
|
||||||
import org.springframework.stereotype.Service
|
|
||||||
import java.time.LocalDateTime
|
|
||||||
import java.time.temporal.ChronoUnit
|
|
||||||
|
|
||||||
@Service
|
|
||||||
class RefreshTokenService(private val refreshTokenRepository: RefreshTokenRepository, private val jwtUtil: JwtUtil) {
|
|
||||||
|
|
||||||
companion object {
|
|
||||||
private val log = LoggerFactory.getLogger(RefreshTokenService::class.java)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun getAccessToken(tokenId: RefreshId): String {
|
|
||||||
return getToken(tokenId)?.let { refreshToken ->
|
|
||||||
if (isTokenExpired(refreshToken)) {
|
|
||||||
removeToken(tokenId)
|
|
||||||
throw ExpiredRefreshTokenException(tokenId)
|
|
||||||
} else {
|
|
||||||
jwtUtil.generateToken(refreshToken.email)
|
|
||||||
}
|
|
||||||
}?: throw InvalidRefreshTokenException(tokenId)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun generateRefreshToken(email: String): RefreshId {
|
|
||||||
return refreshTokenRepository.save(RefreshTokenRecord(RefreshId.randomUUID(), email, LocalDateTime.now().plus(1, ChronoUnit.MONTHS))).token
|
|
||||||
}
|
|
||||||
|
|
||||||
fun isTokenExpired(token: RefreshTokenRecord): Boolean {
|
|
||||||
return token.expiryDateTime.isBefore(LocalDateTime.now())
|
|
||||||
}
|
|
||||||
|
|
||||||
fun getToken(token: RefreshId): RefreshTokenRecord? {
|
|
||||||
return refreshTokenRepository.findByIdOrNull(token)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun removeToken(token: RefreshId) {
|
|
||||||
log.debug("Removing refresh token: $token")
|
|
||||||
refreshTokenRepository.deleteById(token)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
package net.halfbinary.scavengerhuntapi.service
|
|
||||||
|
|
||||||
import net.halfbinary.scavengerhuntapi.model.HuntId
|
|
||||||
import net.halfbinary.scavengerhuntapi.model.TeamId
|
|
||||||
import net.halfbinary.scavengerhuntapi.model.domain.Team
|
|
||||||
import org.springframework.stereotype.Service
|
|
||||||
|
|
||||||
@Service
|
|
||||||
class TeamService {
|
|
||||||
fun getListOfTeamsForHunt(huntId: HuntId): List<Team> {
|
|
||||||
TODO()
|
|
||||||
}
|
|
||||||
|
|
||||||
fun createTeam(name: String): Team {
|
|
||||||
TODO()
|
|
||||||
}
|
|
||||||
|
|
||||||
fun addTeamToHunt(huntId: HuntId, teamId: TeamId) {
|
|
||||||
TODO()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -7,7 +7,4 @@ spring.jpa.properties.hibernate.type.preferred_uuid_jdbc_type=CHAR
|
|||||||
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
|
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
|
||||||
spring.datasource.url=${DB_URL}
|
spring.datasource.url=${DB_URL}
|
||||||
spring.datasource.username=${DB_USER}
|
spring.datasource.username=${DB_USER}
|
||||||
spring.datasource.password=${DB_PASSWORD}
|
spring.datasource.password=${DB_PASSWORD}
|
||||||
|
|
||||||
jwt.secret=${JWT_SECRET}
|
|
||||||
jwt.expiration=30000
|
|
||||||
Reference in New Issue
Block a user