This commit is contained in:
lunaticbum 2024-12-05 18:15:20 +09:00
parent cd1072430e
commit a1faf405c8
10 changed files with 132 additions and 60 deletions

View File

@ -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 ======================")

View File

@ -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)

View File

@ -73,6 +73,7 @@ class UserController {
@ResponseBody
@PostMapping("login.ajax")
fun login(httpServletRequest: HttpServletRequest, @RequestBody jsonString: String) : ResponseEntity<LoginResult> {
try {
logService.log(httpServletRequest.requestURI)
logService.log(jsonString)
var lResultCode = 0
@ -84,9 +85,9 @@ class UserController {
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()
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!!)){
@ -107,10 +108,8 @@ class UserController {
}
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=","")
@ -121,6 +120,20 @@ class UserController {
}
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 {
}
}
}

View File

@ -86,7 +86,7 @@ class User {
}
fun getIdentifier(): String? {
return userId
return user_id
}
fun getRole(): UserRole {

View File

@ -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
}
}
}

View File

@ -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<Claims>? {
try {
return Jwts.parserBuilder()
.setSigningKey(secretKey)
.build()
.parseClaimsJws(token)
} catch (e: JwtException) {
throw BusinessException(ErrorCode.INVALID_JWT)
}
}
}
class BusinessException(error : ErrorCode) : Exception(error.name)

View File

@ -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;

View File

@ -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)
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}]`)
}
}
})
}

View File

@ -6,6 +6,12 @@
<tr id="bottom">
<td><h3><a aria-label="licenses" style="color: white" href="../licenses" title="Gmail">licenses</a></h3></td>
<td><h3><a aria-label="sendToMe" style="color: white" href="mailto:lunaticbum@gmail.com" title="Gmail">lunaticbum@gmail.com</a></h3></td>
<th:block th:if="${PERMISSION == 'OK'}">
<td><h3><a aria-label="logout" style="color: white" href="javascript:logout()" title="logout" >logout</a></h3></td>
</th:block>
<th:block th:if="${PERMISSION != 'OK'}">
<td><h3><a aria-label="join" style="color: white" href="javascript:gotoJoin()" title="join" >join</a></h3></td>
</th:block>
</tr>
</table>
</footer>

View File

@ -25,8 +25,9 @@
<div></div>
<div></div>
<div></div>
<div class="user_info" >
<td><h3><a aria-label="logout" style="color: white" href="javascript:logout()" title="logout">logout</a></h3></td>
<div class="hello_to_user" >
<a aria-label="logout" href="javascript:logout()" title="logout" class="hello_to_user_txt" >what's up~!</a><br/>
<a aria-label="logout" href="javascript:logout()" title="logout" class="hello_to_user_txt" >[[${user_id}]]</a>
</div>
</th:block>
</header>