From a1faf405c8581383cd03ba669927aed095a0d0ec Mon Sep 17 00:00:00 2001 From: lunaticbum Date: Thu, 5 Dec 2024 18:15:20 +0900 Subject: [PATCH] ... --- .../back/lun/configs/BumsInterceptor.kt | 3 + .../back/lun/configs/JwtGenerator.kt | 1 + .../back/lun/controllers/UserController.kt | 101 ++++++++++-------- .../kr/lunaticbum/back/lun/model/User.kt | 2 +- .../lunaticbum/back/lun/service/JwtService.kt | 10 ++ .../kr/lunaticbum/back/lun/utils/JwtUtil.kt | 16 ++- src/main/resources/static/css/common.css | 18 ++++ src/main/resources/static/js/common.js | 30 ++++-- .../resources/templates/fragments/footer.html | 6 ++ .../resources/templates/fragments/header.html | 5 +- 10 files changed, 132 insertions(+), 60 deletions(-) diff --git a/src/main/kotlin/kr/lunaticbum/back/lun/configs/BumsInterceptor.kt b/src/main/kotlin/kr/lunaticbum/back/lun/configs/BumsInterceptor.kt index 2eca4d5..63bafb0 100644 --- a/src/main/kotlin/kr/lunaticbum/back/lun/configs/BumsInterceptor.kt +++ b/src/main/kotlin/kr/lunaticbum/back/lun/configs/BumsInterceptor.kt @@ -61,15 +61,18 @@ class BumsInterceptor : HandlerInterceptor { response.addCookie(cookieUpdate(refresh)) response.addCookie(cookieUpdate(access)) modelAndView?.modelMap?.put(WRITE_PERMISSION_KEY,"OK") + modelAndView?.modelMap?.put("user_id", jwtService.getUserIdFromToken(access?.value ?: "")) } else { println("Response correctUserCheck ===> ${correctUserCheck}") response.addCookie(Cookie("access","").apply { maxAge = -1 }) response.addCookie(Cookie("refresh","").apply { maxAge = -1 }) modelAndView?.modelMap?.put(WRITE_PERMISSION_KEY,"NO") + modelAndView?.modelMap?.put("user_id", "") } println("Response modelMap ===> ${Gson().toJson(modelAndView?.modelMap)}") } else if (request.requestURI.contains("logout")) { modelAndView?.modelMap?.put(WRITE_PERMISSION_KEY,"NO") + modelAndView?.modelMap?.put("user_id", "") } println("==================== END ======================") diff --git a/src/main/kotlin/kr/lunaticbum/back/lun/configs/JwtGenerator.kt b/src/main/kotlin/kr/lunaticbum/back/lun/configs/JwtGenerator.kt index 7be2632..3d9bab7 100644 --- a/src/main/kotlin/kr/lunaticbum/back/lun/configs/JwtGenerator.kt +++ b/src/main/kotlin/kr/lunaticbum/back/lun/configs/JwtGenerator.kt @@ -30,6 +30,7 @@ class JwtGenerator { return Jwts.builder() .setHeader(createHeader()) + .setClaims(createClaims(user)) .setSubject(user.getIdentifier()) .setExpiration(Date(now + REFRESH_EXPIRATION)) .signWith(REFRESH_SECRET, SignatureAlgorithm.HS256) diff --git a/src/main/kotlin/kr/lunaticbum/back/lun/controllers/UserController.kt b/src/main/kotlin/kr/lunaticbum/back/lun/controllers/UserController.kt index 211177a..e412795 100644 --- a/src/main/kotlin/kr/lunaticbum/back/lun/controllers/UserController.kt +++ b/src/main/kotlin/kr/lunaticbum/back/lun/controllers/UserController.kt @@ -73,54 +73,67 @@ class UserController { @ResponseBody @PostMapping("login.ajax") fun login(httpServletRequest: HttpServletRequest, @RequestBody jsonString: String) : ResponseEntity { - logService.log(httpServletRequest.requestURI) - logService.log(jsonString) - var lResultCode = 0 - var lResultMsg = "Suscces" - var u : UserDetails? = null - var user : User? = null - var tokenData : TokenData? = null - jsonString.extractModelData { exception, originDataString -> - if (exception == null) { - logService.log(originDataString) - val target = Gson().fromJson(originDataString, User::class.java) ?: User() - 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!!)){ - tokenData = jwtService.generate(user!!) - } else { - lResultMsg = "is wrong infomation id or passord" - lResultCode = 7100 - } - } else { - lResultMsg = "not founding user[can't find same id,email.. ]" - lResultCode = 7100 - } - } else { - exception.printStackTrace() - lResultMsg = exception.message ?: "unknown exception" - lResultCode = 7999 - } - } - val responce = ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).headers { + try { + logService.log(httpServletRequest.requestURI) + logService.log(jsonString) + var lResultCode = 0 + var lResultMsg = "Suscces" + var u : UserDetails? = null + var user : User? = null + var tokenData : TokenData? = null + jsonString.extractModelData { exception, originDataString -> + if (exception == null) { + logService.log(originDataString) + val target = Gson().fromJson(originDataString, User::class.java) ?: User() + user = userManager.findById(target.user_id?.trim() ?: "")?.block() + if (user == null && ((target.user_id?.trim()?.length ?: 0) > 3 == true)) { + user = userManager.findByEmail(target.user_id?.trim() ?: "")?.block() + } + if (user != null) { + if(userManager.isCorrectUser(user!!,target.user_pw!!)){ + tokenData = jwtService.generate(user!!) + } else { + lResultMsg = "is wrong infomation id or passord" + lResultCode = 7100 + } + } else { + lResultMsg = "not founding user[can't find same id,email.. ]" + lResultCode = 7100 + } + } else { + exception.printStackTrace() + lResultMsg = exception.message ?: "unknown exception" + lResultCode = 7999 + } + } + val responce = ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).headers { + + }.body(LoginResult().apply { + this.isOk = lResultCode == 0 + this.resultCode = lResultCode + this.resultMsg = lResultMsg + this.token = setTokenToCookie(JwtRule.ACCESS_PREFIX.value, tokenData?.tokenKey ?: "", globalEvv.ACCESS_EXPIRATION / 1000).toString().replace("access=","") + this.refresh = setTokenToCookie(JwtRule.REFRESH_PREFIX.value, tokenData?.refreshToken ?: "", globalEvv.REFRESH_EXPIRATION / 1000).toString().replace("refresh=","") + }).apply { + } + + return responce + }catch (e: Exception){ + return ResponseEntity.internalServerError().contentType(MediaType.APPLICATION_JSON).headers { + + }.body(LoginResult().apply { + this.isOk = false + this.resultCode = -999 + this.resultMsg = e.message ?: "unknown exception" + this.token = "" + this.refresh = "" + }).apply { - }.body(LoginResult().apply { - this.resultCode = lResultCode - this.resultMsg = lResultMsg - this.token = setTokenToCookie(JwtRule.ACCESS_PREFIX.value, tokenData?.tokenKey ?: "", globalEvv.ACCESS_EXPIRATION / 1000).toString().replace("access=","") - this.refresh = setTokenToCookie(JwtRule.REFRESH_PREFIX.value, tokenData?.refreshToken ?: "", globalEvv.REFRESH_EXPIRATION / 1000).toString().replace("refresh=","") - }).apply { - - - } - - return responce + } + } } diff --git a/src/main/kotlin/kr/lunaticbum/back/lun/model/User.kt b/src/main/kotlin/kr/lunaticbum/back/lun/model/User.kt index 5ee7d97..28579f3 100644 --- a/src/main/kotlin/kr/lunaticbum/back/lun/model/User.kt +++ b/src/main/kotlin/kr/lunaticbum/back/lun/model/User.kt @@ -86,7 +86,7 @@ class User { } fun getIdentifier(): String? { - return userId + return user_id } fun getRole(): UserRole { diff --git a/src/main/kotlin/kr/lunaticbum/back/lun/service/JwtService.kt b/src/main/kotlin/kr/lunaticbum/back/lun/service/JwtService.kt index 09c71d2..bff5706 100644 --- a/src/main/kotlin/kr/lunaticbum/back/lun/service/JwtService.kt +++ b/src/main/kotlin/kr/lunaticbum/back/lun/service/JwtService.kt @@ -1,5 +1,7 @@ package kr.lunaticbum.back.lun.service +import io.jsonwebtoken.Claims +import io.jsonwebtoken.Jws import io.jsonwebtoken.Jwts import jakarta.servlet.http.HttpServletRequest import jakarta.servlet.http.HttpServletResponse @@ -129,4 +131,12 @@ class JwtService { response.addCookie(accessCookie) response.addCookie(refreshCookie) } + fun getUserIdFromToken(token: String?): String? { + try { + return jwtUtil.extractToken(token,jwtUtil.getSigningKey(globalEvv.ACCESS_SECRET_KEY))?.body?.get("Identifier") + .toString() + } catch (e: Exception) { + return null + } + } } \ No newline at end of file diff --git a/src/main/kotlin/kr/lunaticbum/back/lun/utils/JwtUtil.kt b/src/main/kotlin/kr/lunaticbum/back/lun/utils/JwtUtil.kt index b9cd799..85aa305 100644 --- a/src/main/kotlin/kr/lunaticbum/back/lun/utils/JwtUtil.kt +++ b/src/main/kotlin/kr/lunaticbum/back/lun/utils/JwtUtil.kt @@ -1,8 +1,6 @@ package kr.lunaticbum.back.lun.utils -import io.jsonwebtoken.ExpiredJwtException -import io.jsonwebtoken.JwtException -import io.jsonwebtoken.Jwts +import io.jsonwebtoken.* import io.jsonwebtoken.security.Keys import jakarta.servlet.http.Cookie import kr.lunaticbum.back.lun.configs.JwtRule @@ -23,7 +21,6 @@ import java.util.* @RequiredArgsConstructor class JwtUtil { - fun getTokenStatus(token: String?, secretKey: Key?): TokenStatus { try { var cls = Jwts.parserBuilder() @@ -68,6 +65,17 @@ class JwtUtil { cookie.setPath("/") return cookie } + + fun extractToken(token: String?, secretKey: Key?): Jws? { + try { + return Jwts.parserBuilder() + .setSigningKey(secretKey) + .build() + .parseClaimsJws(token) + } catch (e: JwtException) { + throw BusinessException(ErrorCode.INVALID_JWT) + } + } } class BusinessException(error : ErrorCode) : Exception(error.name) diff --git a/src/main/resources/static/css/common.css b/src/main/resources/static/css/common.css index 9e6dbcd..7c833aa 100644 --- a/src/main/resources/static/css/common.css +++ b/src/main/resources/static/css/common.css @@ -74,6 +74,7 @@ header { border-radius: 10px; border-width: 2px; border: #F0F0F514; + padding: 5px; background: #F0F0F524; color: white; text-align: center; @@ -91,6 +92,23 @@ header { color: #ec914b; } +.hello_to_user { + border-radius: 10px; + border-width: 2px; + border: #F0F0F514; + padding: 10px; + background: #F0F0F524; + color: #ec914b; + text-align: center; + margin: 2px; +} + + +.hello_to_user_txt { + color: #ec914b; +} + + #bottom { float: right; display: inline-block; diff --git a/src/main/resources/static/js/common.js b/src/main/resources/static/js/common.js index f3f5cec..a5fef26 100644 --- a/src/main/resources/static/js/common.js +++ b/src/main/resources/static/js/common.js @@ -81,8 +81,8 @@ function postLogin(target,type, data, key,callBackResult) { if (httpRequest.readyState === XMLHttpRequest.DONE) { if (httpRequest.status === 200) { try { - callBackResult(httpRequest.response) - document.location.href = document.location + var data = JSON.parse(httpRequest.response) + callBackResult(data) } catch (e) { } @@ -133,8 +133,8 @@ function logout() { document.cookie = "refresh=; expires=Thu, 01 Jan 1970 00:00:01 GMT;" let logOutUrl = getMainPath() + "/user/logout.ajax"; post(logOutUrl,"","","", function (resultData) { - alert(resultData) - document.location.href = document.location + alert("로그아웃 됨요~! 빠염~!") + document.location.replace(document.location) }) } @@ -144,6 +144,9 @@ function gotoLogin() { location.href = getMainPath()+"/login" } +function gotoJoin() { + document.location.replace(getMainPath() + "/user/join") +} function goToView(path,id) { location.href = path + id; @@ -155,11 +158,20 @@ function onclickLogin(type, keyword) { 'user_id': user_id.value, 'user_pw': user_pw.value, } - postLogin(getMainPath()+"/user/login.ajax",type,JSON.stringify(data),keyword, function (resultData) { - var data = JSON.parse(resultData) - // alert(resultData) - document.cookie = "access=" + data.token.split(";")[0]+";" - document.cookie = "refresh=" + data.refresh.split(";")[0]+";" + postLogin(getMainPath()+"/user/login.ajax",type,JSON.stringify(data),keyword, function (data) { + if (data.isOk) { + document.cookie = "access=" + data.token.split(";")[0]+";" + document.cookie = "refresh=" + data.refresh.split(";")[0]+";" + document.location.replace(document.location) + } else { + if (data.resultCode === 7100) { + if(confirm(`너 누구임 정보 없는데?!\n${data.resultMsg}[${data.resultCode}]\n가입 할래!?`)){ + document.location.replace(getMainPath() + "/user/join") + } + } else { + alert(`너 누구임?!\n${data.resultMsg}[${data.resultCode}]`) + } + } }) } diff --git a/src/main/resources/templates/fragments/footer.html b/src/main/resources/templates/fragments/footer.html index f2e21d4..ef1244e 100644 --- a/src/main/resources/templates/fragments/footer.html +++ b/src/main/resources/templates/fragments/footer.html @@ -6,6 +6,12 @@

licenses

lunaticbum@gmail.com

+ +

logout

+
+ +

join

+
diff --git a/src/main/resources/templates/fragments/header.html b/src/main/resources/templates/fragments/header.html index 5fd3d17..a4cdd4d 100644 --- a/src/main/resources/templates/fragments/header.html +++ b/src/main/resources/templates/fragments/header.html @@ -25,8 +25,9 @@
-