Skip to content

Commit

Permalink
fix: 添加用户密码修改时间用以修复refresh时无任何限制的问题,同时限制密码修改频率。
Browse files Browse the repository at this point in the history
添加逻辑refresh时如果签发时间与当前时间相近则返回旧token
  • Loading branch information
dragove committed Oct 29, 2024
1 parent 58f96e5 commit 4f041b8
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import org.springframework.data.annotation.Transient
import org.springframework.data.mongodb.core.index.Indexed
import org.springframework.data.mongodb.core.mapping.Document
import java.io.Serializable
import java.time.Instant

/**
* @author AnselYuki
Expand All @@ -20,7 +21,7 @@ data class MaaUser(
val email: String,
var password: String,
var status: Int = 0,
var refreshJwtIds: MutableList<String> = ArrayList(),
var pwdUpdateTime: Instant = Instant.MIN,
) : Serializable {

companion object {
Expand Down
19 changes: 17 additions & 2 deletions src/main/kotlin/plus/maa/backend/service/UserService.kt
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ import plus.maa.backend.repository.entity.MaaUser
import plus.maa.backend.service.jwt.JwtExpiredException
import plus.maa.backend.service.jwt.JwtInvalidException
import plus.maa.backend.service.jwt.JwtService
import java.time.Instant
import java.time.temporal.ChronoUnit

/**
* @author AnselYuki
Expand Down Expand Up @@ -76,14 +78,18 @@ class UserService(
check(passwordEncoder.matches(originPassword, maaUser.password)) {
"原密码错误"
}
// 通过原密码修改密码不能过于频繁
check(ChronoUnit.MINUTES.between(maaUser.pwdUpdateTime, Instant.now()) >= 10L) {
"密码修改过于频繁"
}
}
// 修改密码的逻辑,应当使用与 authentication provider 一致的编码器
maaUser.password = passwordEncoder.encode(rawPassword)
// 更新密码时,如果用户未启用则自动启用
if (maaUser.status == 0) {
maaUser.status = 1
}
maaUser.refreshJwtIds = ArrayList()
maaUser.pwdUpdateTime = Instant.now()
userRepository.save(maaUser)
}

Expand Down Expand Up @@ -135,7 +141,16 @@ class UserService(

val userId = old.subject
val user = userRepository.findById(userId).orElseThrow()
val refreshToken = jwtService.issueRefreshToken(userId, null)
if (old.notBefore.isBefore(user.pwdUpdateTime)) {
throw MaaResultException(401, "invalid token")
}

// 刚签发不久的 refreshToken 重新使用
val refreshToken = if (ChronoUnit.MINUTES.between(old.issuedAt, Instant.now()) < 5) {
old
} else {
jwtService.issueRefreshToken(userId, null)
}
val authorities = userDetailService.collectAuthoritiesFor(user)
val authToken = jwtService.issueAuthToken(userId, null, authorities)

Expand Down

0 comments on commit 4f041b8

Please sign in to comment.