This commit is contained in:
lunaticbum
2024-10-07 16:14:03 +09:00
parent 5e80a5ab22
commit 68d4c40f85
13 changed files with 955 additions and 65 deletions
@@ -19,6 +19,8 @@ class GlobalEnvironment : EnvironmentAware {
@Value("\${weather.api.key}")
var weatherApiKey: String? = ""
private val pad = "%7C%2A-%2A%7C"
fun padding(key : String) = pad.plus(key).plus(pad)
override fun setEnvironment(environment: Environment) {
println ("telegramBotKey $telegramBotKey")
@@ -3,11 +3,8 @@ package kr.lunaticbum.back.lun.configs
import com.fasterxml.jackson.databind.ObjectMapper
import jakarta.servlet.http.HttpServletRequest
import jakarta.servlet.http.HttpServletResponse
import kr.lunaticbum.back.lun.model.Role
import kr.lunaticbum.back.lun.utils.LogService
import org.apache.catalina.webresources.TomcatURLStreamHandlerFactory.disable
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.autoconfigure.security.servlet.PathRequest
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.http.HttpMethod
@@ -18,6 +15,7 @@ import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
import org.springframework.security.config.http.SessionCreationPolicy
import org.springframework.security.core.AuthenticationException
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder
import org.springframework.security.web.AuthenticationEntryPoint
import org.springframework.security.web.SecurityFilterChain
import org.springframework.security.web.access.AccessDeniedHandler
@@ -46,6 +44,7 @@ class SecurityConfig {
http.authorizeHttpRequests {
logService.log(it.toString())
it.requestMatchers(HttpMethod.POST,"/user/**").permitAll()
// it.requestMatchers(HttpMethod.POST,"/user/**").permitAll()
// it.requestMatchers("/", "/user/**").permitAll()
// .requestMatchers(".ajax").permitAll()
// it.requestMatchers("/", "/user/joinUser.api").permitAll()
@@ -100,4 +99,9 @@ class SecurityConfig {
writer.write(json)
writer.flush()
}
@Bean
fun bCryptPasswordEncoder(): BCryptPasswordEncoder {
return BCryptPasswordEncoder()
}
}
@@ -3,6 +3,7 @@ package kr.lunaticbum.back.lun.controllers
import com.google.gson.Gson
import jakarta.servlet.http.HttpServletRequest
import kr.lunaticbum.back.lun.configs.GlobalEnvironment
import kr.lunaticbum.back.lun.model.RequestModel
import kr.lunaticbum.back.lun.model.ResponceResult
import kr.lunaticbum.back.lun.model.User
import kr.lunaticbum.back.lun.model.UserManager
@@ -10,6 +11,7 @@ import kr.lunaticbum.back.lun.utils.LogService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity
import org.springframework.security.core.userdetails.UserDetails
import org.springframework.web.bind.annotation.*
import org.springframework.web.reactive.function.client.WebClient
import org.springframework.web.servlet.ModelAndView
@@ -19,7 +21,12 @@ import java.util.*
@RestController
@RequestMapping("user")
class UserController {
val EncTypeKey = "enc"
val EncType00 = "T0"
val EncType11 = "T3"
val EncType10 = "T2"
val EncType01 = "T1"
val ApiKeyWordKey = "keyword"
@Autowired
lateinit var globalEvv : GlobalEnvironment
@@ -33,17 +40,86 @@ class UserController {
fun hello(httpServletRequest: HttpServletRequest): ModelAndView {
logService.log("onJoin")
val vm = ModelAndView("/content/user/join")
when(System.currentTimeMillis() % 5L) {
0L -> vm.modelMap.put("ENC","T4")
1L -> vm.modelMap.put("ENC","T3")
2L -> vm.modelMap.put("ENC","T2")
else -> vm.modelMap.put("ENC","T0")
}
logService.log("${vm.toString()}")
// when(System.currentTimeMillis() % 5L) {
// 0L -> vm.modelMap.put(EncTypeKey,"T4")
// 1L -> vm.modelMap.put(EncTypeKey,"T3")
// 2L -> vm.modelMap.put(EncTypeKey,"T2")
// else -> vm.modelMap.put(EncTypeKey,"T0")
// }
vm.modelMap.put(EncTypeKey,EncType11)
vm.modelMap.put(ApiKeyWordKey,"JOIN")
return vm
}
@GetMapping("/login")
fun userLogin(httpServletRequest: HttpServletRequest): ModelAndView {
logService.log("onJoin")
val vm = ModelAndView("/content/user/login")
// when(System.currentTimeMillis() % 5L) {
// 0L -> vm.modelMap.put(EncTypeKey,"T4")
// 1L -> vm.modelMap.put(EncTypeKey,"T3")
// 2L -> vm.modelMap.put(EncTypeKey,"T2")
// else -> vm.modelMap.put(EncTypeKey,"T0")
// }
vm.modelMap.put(EncTypeKey,EncType11)
vm.modelMap.put(ApiKeyWordKey,"LOGIN")
return vm
}
@ResponseBody
@PostMapping("/login.ajax")
fun login(httpServletRequest: HttpServletRequest, @RequestBody jsonString: String) : ResponseEntity<ResponceResult> {
logService.log("${httpServletRequest.requestURI}")
logService.log(jsonString)
var lResultCode = 0
var lResultMsg = "Suscces"
var u : UserDetails? = null
val decodedBytes: ByteArray = Base64.getDecoder().decode(jsonString)
String(decodedBytes).let {
Gson().fromJson<RequestModel>(it,RequestModel::class.java)?.let { model ->
logService.log(Gson().toJson(model))
model.data?.let { jsonString ->
try {
val reqString = jsonString.split(globalEvv.padding(model.getKeyword()))
val nb = arrayListOf<String>()
val na = arrayListOf<String>()
reqString[0].replace(globalEvv.padding(model.getKeyword()),"").split("").toList().let { na.addAll(it) }
reqString[1].replace(globalEvv.padding(model.getKeyword()),"").split("").toList().let { nb.addAll(it) }
var max = nb.size + na.size
var fullData = arrayListOf<String>()
for (idx in 0..max) { if (idx % 2 == 0) { if (nb.size > 0) { fullData.add(nb.removeLast()) } } else { if (na.size > 0) { fullData.add(na.removeLast()) } } }
logService.log(fullData.joinToString(""))
val target = Gson().fromJson(fullData.joinToString(""), User::class.java) ?: User()
var user = userManager.findById(target.user_id!!)?.block()
if (user == null && ((target.user_id?.length ?: 0) > 3 == true)) {
user = userManager.findByEmail(target.user_id!!)?.block()
}
if (user != null) {
if(userManager.isCorrectUser(user,target.user_pw!!)){
} else {
lResultMsg = "is wrong infomation id or passord"
lResultCode = 7100
}
} else {
lResultMsg = "not founding user[can't find same id,email.. ]"
lResultCode = 7100
}
} catch (e: Exception) {
e.printStackTrace()
lResultMsg = "unknown exception"
lResultCode = 7999
}
}
}
}
val responce = ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(ResponceResult().apply {
this.resultCode = lResultCode
this.resultMsg = lResultMsg
})
return responce
}
@ResponseBody
@@ -51,43 +127,48 @@ class UserController {
fun joinUser(httpServletRequest: HttpServletRequest, @RequestBody jsonString: String) : ResponseEntity<ResponceResult> {
logService.log("${httpServletRequest.requestURI}")
logService.log(jsonString)
var lResultCode = 0
var lResultMsg = "Suscces"
var u : User? = null
val decodedBytes: ByteArray = Base64.getDecoder().decode(jsonString)
String(decodedBytes)?.let { jsonString ->
val reqString = jsonString.split("_||L_")
var nb = arrayListOf<String>()
(reqString[0].replace("_||L_","").split("")).toList().let {
nb.addAll(it)
}
logService.log(nb.toString())
var na = arrayListOf<String>()
reqString[1].replace("_||L_","").split("").toList().let {
na.addAll(it)
}
logService.log(na.toString())
var max = nb.size + na.size
var fullData = arrayListOf<String>()
for (idx in 0..max) {
if (idx % 2 == 0) {
if (nb.size > 0) {
fullData.add(nb.removeLast())
}
} else {
if (na.size > 0) {
fullData.add(na.removeLast())
String(decodedBytes).let {
Gson().fromJson<RequestModel>(it,RequestModel::class.java)?.let { model ->
logService.log(Gson().toJson(model))
model.data?.let { jsonString ->
try {
val reqString = jsonString.split(globalEvv.padding(model.getKeyword()))
val nb = arrayListOf<String>()
val na = arrayListOf<String>()
reqString[0].replace(globalEvv.padding(model.getKeyword()),"").split("").toList().let { na.addAll(it) }
reqString[1].replace(globalEvv.padding(model.getKeyword()),"").split("").toList().let { nb.addAll(it) }
var max = nb.size + na.size
var fullData = arrayListOf<String>()
for (idx in 0..max) { if (idx % 2 == 0) { if (nb.size > 0) { fullData.add(nb.removeLast()) } } else { if (na.size > 0) { fullData.add(na.removeLast()) } } }
logService.log(fullData.joinToString(""))
val user = Gson().fromJson(fullData.joinToString(""), User::class.java) ?: User()
if (user.checkValid() == false) {
lResultCode = 7009
lResultMsg = "user insert Fail Reason : Not Correct Data"
}else if (userManager.findById(user!!.user_id!!)?.block() != null) {
lResultCode = 7001
lResultMsg = "user insert Fail Reason : already has Same Id"
}else if (userManager.findByEmail(user!!.user_email!!)?.block() != null ) {
lResultCode = 7002
lResultMsg = "user insert Fail Reason : already has Same Email"
} else {
u = userManager.save(user).block()
}
} catch (e: Exception) {
e.printStackTrace()
lResultMsg = "unknown exception"
lResultCode = 7999
}
}
}
logService.log(fullData.joinToString(""))
var user = Gson().fromJson(fullData.joinToString(""), User::class.java)
if (user.checkValid()) {
u = userManager.save(user).block()
}
}
val responce = ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(ResponceResult().apply {
resultCode = if (u != null) 0 else 8245
resultMsg = if (u != null) "OK" else "User Insert Fail"
this.resultCode = lResultCode
this.resultMsg = lResultMsg
})
return responce
}
@@ -0,0 +1,12 @@
package kr.lunaticbum.back.lun.model
import lombok.Getter
@Getter
class RequestModel {
var type : String? = null
var key : String? = null
var data : String? = null
fun getKeyword() = key ?: ""
}
@@ -1,8 +1,5 @@
package kr.lunaticbum.back.lun.model
import jdk.jfr.Description
import kotlinx.coroutines.reactive.awaitFirst
import kotlinx.coroutines.reactive.awaitFirstOrElse
import kr.lunaticbum.back.lun.utils.LogService
import lombok.*
import org.springframework.beans.factory.annotation.Autowired
@@ -13,6 +10,7 @@ import org.springframework.data.mongodb.repository.Query
import org.springframework.data.mongodb.repository.ReactiveMongoRepository
import org.springframework.security.core.userdetails.UserDetails
import org.springframework.security.core.userdetails.UserDetailsService
import org.springframework.security.crypto.password.PasswordEncoder
import org.springframework.stereotype.Repository
import org.springframework.stereotype.Service
import reactor.core.publisher.Mono
@@ -47,7 +45,7 @@ class User {
(user_email?.split("@")?.get(0)?.length ?: 0) > 1 &&
(user_email?.split("@")?.get(1)?.length ?: 0) > 1 &&
(user_email?.split(".")?.get(1)?.length ?: 0) > 1
) {
) {
if (user_id.equals("lun_admin") || user_id.equals("lunaticbum")){
isAdmin = "Y"
} else {
@@ -58,6 +56,26 @@ class User {
}
return false
}
/**
* 비밀번호를 암호화
* @param passwordEncoder 암호화 할 인코더 클래스
* @return 변경된 유저 Entity
*/
fun hashPassword(passwordEncoder: PasswordEncoder): User {
this.user_pw = passwordEncoder.encode(this.user_pw)
return this
}
/**
* 비밀번호 확인
* @param plainPassword 암호화 이전의 비밀번호
* @param passwordEncoder 암호화에 사용된 클래스
* @return true | false
*/
fun checkPassword(plainPassword: String?, passwordEncoder: PasswordEncoder): Boolean {
return passwordEncoder.matches(plainPassword, this.user_pw)
}
}
@Getter
@@ -72,14 +90,18 @@ enum class Role(key : String, description: String) {
@Repository
interface UserRepository : ReactiveMongoRepository<User, String> {
@Query("{id :?0}")
override fun findById(id: String): Mono<User>
@Query("{user_id :?0}")
override fun findById(user_id: String): Mono<User>
@Query("{user_email :?0}")
fun findByEmail(user_email: String): Mono<User>
fun save(user: User): Mono<User>
}
interface UserService {
fun findById(id: String): Mono<User>?
fun findByEmail(id: String): Mono<User>?
}
@Service
@@ -90,7 +112,12 @@ class UserManager : UserService , UserDetailsService {
@Autowired
private lateinit var userRepository: UserRepository
@Autowired
private lateinit var bCryptPasswordEncoder: PasswordEncoder
override fun findByEmail(id: String): Mono<User>? {
return userRepository.findByEmail(id)
}
override fun findById(id: String): Mono<User>? {
return userRepository.findById(id)
@@ -100,15 +127,19 @@ class UserManager : UserService , UserDetailsService {
fun save(user: User): Mono<User> {
println("saved user before ${user}")
user.hashPassword(bCryptPasswordEncoder)
return userRepository.save(user)
// .subscribe( { println("saved user after ${it}") },{e -> e.printStackTrace()},{
// println("saved user comp")
// })
}
fun isCorrectUser(user: User, password : String) : Boolean {
return user.checkPassword(password,bCryptPasswordEncoder)
}
override fun loadUserByUsername(username: String?): UserDetails {
var user = findById(username!!)?.blockOptional(Duration.ofMillis(5000L))?.get() ?: User()
logService.log("username ${username}")
user.hashPassword(bCryptPasswordEncoder)
return org.springframework.security.core.userdetails.User.builder().username(user.user_id ?: "").password(user.user_pw).roles(if ("Y".equals(user.isAdmin)) Role.ADMIN.name else {Role.USER.name}).build()
}
}
@@ -0,0 +1,52 @@
//package kr.lunaticbum.back.lun.utils
//
//
//import javax.crypto.Cipher
//import org.apache.commons.codec.DecoderException;
//import org.apache.commons.codec.binary.Base64;
//import org.apache.commons.codec.binary.Hex;
//
//@Throws(Exception::class)
//fun AesECBEncode(plainText: String): String {
// //Cipher 객체 인스턴스화(Java에서는 PKCS#5 = PKCS#7이랑 동일)
//
// val c: Cipher = Cipher.getInstance("AES/ECB/PKCS5Padding")
//
//
// //Cipher 객체 초기화
// c.init(Cipher.ENCRYPT_MODE, secretKey)
//
//
// //Encrpytion/Decryption
// val encrpytionByte: ByteArray = c.doFinal(plainText.toByteArray(charset("UTF-8")))
//
//
// //Hex Encode
// return Hex.encodeHexString(encrpytionByte)
//
//
// //Base64 Encode
//// return Base64.encodeBase64String(encrpytionByte);
//}
//
//
////AES ECB PKCS5Padding 복호화(Hex | Base64)
//@Throws(Exception::class)
//fun AesECBDecode(encodeText: String): String {
// //Cipher 객체 인스턴스화(Java에서는 PKCS#5 = PKCS#7이랑 동일)
//
// val c: Cipher = Cipher.getInstance("AES/ECB/PKCS5Padding")
//
//
// //Cipher 객체 초기화
// c.init(Cipher.DECRYPT_MODE, secretKey)
//
//
// //Decode Hex
// val decodeByte: ByteArray = Hex.decodeHex(encodeText.toCharArray())
//
//
// //Decode Base64
//// byte[] decodeByte = Base64.decodeBase64(encodeText);
// return String(c.doFinal(decodeByte), charset("UTF-8"))
//}