refactor: AccountService
This commit is contained in:
+9
-14
@@ -1,21 +1,16 @@
|
|||||||
package club.itstudio.itmanager.controller.v1
|
package club.itstudio.itmanager.controller.v1
|
||||||
|
|
||||||
import club.itstudio.itmanager.entity.ApiResponse
|
import club.itstudio.itmanager.entity.ApiResponse
|
||||||
|
import club.itstudio.itmanager.entity.enums.EmailType
|
||||||
import club.itstudio.itmanager.entity.vo.request.EmailRegisterVO
|
import club.itstudio.itmanager.entity.vo.request.EmailRegisterVO
|
||||||
import club.itstudio.itmanager.entity.vo.request.PasswordResetVO
|
import club.itstudio.itmanager.entity.vo.request.PasswordResetVO
|
||||||
import club.itstudio.itmanager.service.AccountService
|
import club.itstudio.itmanager.service.v1.AuthorizationService
|
||||||
import jakarta.validation.Valid
|
import jakarta.validation.Valid
|
||||||
import jakarta.validation.constraints.Email
|
import jakarta.validation.constraints.Email
|
||||||
import jakarta.validation.constraints.NotBlank
|
import jakarta.validation.constraints.NotBlank
|
||||||
import jakarta.validation.constraints.Pattern
|
|
||||||
import org.slf4j.LoggerFactory
|
import org.slf4j.LoggerFactory
|
||||||
import org.springframework.validation.annotation.Validated
|
import org.springframework.validation.annotation.Validated
|
||||||
import org.springframework.web.bind.annotation.GetMapping
|
import org.springframework.web.bind.annotation.*
|
||||||
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.RequestParam
|
|
||||||
import org.springframework.web.bind.annotation.RestController
|
|
||||||
import org.springframework.web.server.ServerWebExchange
|
import org.springframework.web.server.ServerWebExchange
|
||||||
import reactor.core.publisher.Mono
|
import reactor.core.publisher.Mono
|
||||||
|
|
||||||
@@ -23,34 +18,34 @@ import reactor.core.publisher.Mono
|
|||||||
@RestController
|
@RestController
|
||||||
@RequestMapping("/api/v1/auth")
|
@RequestMapping("/api/v1/auth")
|
||||||
class AuthorizeController(
|
class AuthorizeController(
|
||||||
private val service: AccountService
|
private val service: AuthorizationService
|
||||||
) {
|
) {
|
||||||
private val logger = LoggerFactory.getLogger(this::class.java)
|
private val logger = LoggerFactory.getLogger(this::class.java)
|
||||||
|
|
||||||
@GetMapping("/ask-code")
|
@GetMapping("/ask-code")
|
||||||
fun askVerifyCode(
|
fun askVerifyCode(
|
||||||
@RequestParam @NotBlank @Email email: String,
|
@RequestParam @NotBlank @Email email: String,
|
||||||
@RequestParam @Pattern(regexp = "(register|reset)") type: String,
|
@RequestParam type: EmailType,
|
||||||
exchange: ServerWebExchange
|
exchange: ServerWebExchange
|
||||||
): Mono<ApiResponse<Any?>> {
|
): Mono<ApiResponse<Any?>> {
|
||||||
logger.info("Trying to ask code")
|
logger.info("Trying to ask code")
|
||||||
val ip = exchange.request.remoteAddress?.address?.hostAddress ?: "unknown"
|
val ip = exchange.request.remoteAddress?.address?.hostAddress ?: "unknown"
|
||||||
return service.askEmailVerifyCode(type, email, ip)
|
return service.askEmailVerifyCode(type, email, ip)
|
||||||
.map { messageHandler(it) }
|
.map(::messageHandler)
|
||||||
}
|
}
|
||||||
|
|
||||||
@PostMapping("/register")
|
@PostMapping("/register")
|
||||||
fun emailRegister(@RequestBody @Valid vo: EmailRegisterVO): Mono<ApiResponse<Any?>> {
|
fun emailRegister(@RequestBody @Valid vo: EmailRegisterVO): Mono<ApiResponse<Any?>> {
|
||||||
logger.info("Trying to register")
|
logger.info("Trying to register")
|
||||||
return service.registerEmailAccount(vo)
|
return service.registerEmailAccount(vo)
|
||||||
.map { messageHandler(it) }
|
.map(::messageHandler)
|
||||||
}
|
}
|
||||||
|
|
||||||
@PostMapping("/reset")
|
@PostMapping("/reset")
|
||||||
fun emailResetPassword(@RequestBody @Valid vo: PasswordResetVO): Mono<ApiResponse<Any?>> {
|
fun emailResetPassword(@RequestBody @Valid vo: PasswordResetVO): Mono<ApiResponse<Any?>> {
|
||||||
logger.info("Trying to reset password")
|
logger.info("Trying to reset password")
|
||||||
return service.resetEmailAccountPassword(vo)
|
return service.resetEmailAccountPassword(vo)
|
||||||
.map { messageHandler(it) }
|
.map(::messageHandler)
|
||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping("/logout")
|
@GetMapping("/logout")
|
||||||
@@ -71,7 +66,7 @@ class AuthorizeController(
|
|||||||
return service
|
return service
|
||||||
.jwtTokenRelogin(authorization)
|
.jwtTokenRelogin(authorization)
|
||||||
?.map { ApiResponse.success(it) }
|
?.map { ApiResponse.success(it) }
|
||||||
?: Mono.just(messageHandler("Please login with password."))
|
?: Mono.just(ApiResponse.failure(401, null, "Please login with password."))
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun messageHandler(wrongMessage: String): ApiResponse<Any?> {
|
private fun messageHandler(wrongMessage: String): ApiResponse<Any?> {
|
||||||
|
|||||||
+2
-1
@@ -1,10 +1,11 @@
|
|||||||
package club.itstudio.itmanager.entity.dto
|
package club.itstudio.itmanager.entity.dto
|
||||||
|
|
||||||
|
import club.itstudio.itmanager.entity.enums.EmailType
|
||||||
import kotlinx.serialization.Serializable
|
import kotlinx.serialization.Serializable
|
||||||
|
|
||||||
@Serializable
|
@Serializable
|
||||||
data class EmailVerificationMsg(
|
data class EmailVerificationMsg(
|
||||||
val email: String,
|
val email: String,
|
||||||
val type: String,
|
val type: EmailType,
|
||||||
val code: String
|
val code: String
|
||||||
)
|
)
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
package club.itstudio.itmanager.entity.enums
|
||||||
|
|
||||||
|
import kotlinx.serialization.SerialName
|
||||||
|
import kotlinx.serialization.Serializable
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
enum class AccountRole {
|
||||||
|
@SerialName("user")
|
||||||
|
USER,
|
||||||
|
@SerialName("admin")
|
||||||
|
ADMIN;
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
fun fromIsStaff(isStaff: Boolean): AccountRole = if (isStaff) ADMIN else USER
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
package club.itstudio.itmanager.entity.enums
|
||||||
|
|
||||||
|
import kotlinx.serialization.SerialName
|
||||||
|
import kotlinx.serialization.Serializable
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
enum class EmailType {
|
||||||
|
@SerialName("register")
|
||||||
|
REGISTER,
|
||||||
|
|
||||||
|
@SerialName("reset")
|
||||||
|
RESET,
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
package club.itstudio.itmanager.listener
|
package club.itstudio.itmanager.listener
|
||||||
|
|
||||||
import club.itstudio.itmanager.entity.dto.EmailVerificationMsg
|
import club.itstudio.itmanager.entity.dto.EmailVerificationMsg
|
||||||
|
import club.itstudio.itmanager.entity.enums.EmailType
|
||||||
import kotlinx.serialization.json.Json
|
import kotlinx.serialization.json.Json
|
||||||
import org.slf4j.LoggerFactory
|
import org.slf4j.LoggerFactory
|
||||||
import org.springframework.amqp.rabbit.annotation.RabbitHandler
|
import org.springframework.amqp.rabbit.annotation.RabbitHandler
|
||||||
@@ -28,21 +29,19 @@ class MailQueueListener(
|
|||||||
val (email, type, code) = data
|
val (email, type, code) = data
|
||||||
|
|
||||||
val message = when (type) {
|
val message = when (type) {
|
||||||
"register" -> createMailMessage(
|
EmailType.REGISTER -> createMailMessage(
|
||||||
"Welcome to Our Service",
|
"Welcome to Our Service",
|
||||||
"Thank you for registering! Your verification code is: $code"
|
"Thank you for registering! Your verification code is: $code"
|
||||||
+ "\nThis code is valid for 3 minutes.",
|
+ "\nThis code is valid for 3 minutes.",
|
||||||
email
|
email
|
||||||
)
|
)
|
||||||
|
|
||||||
"reset" -> createMailMessage(
|
EmailType.RESET -> createMailMessage(
|
||||||
"Password Reset Request",
|
"Password Reset Request",
|
||||||
"You requested a password reset. Your verification code is: $code"
|
"You requested a password reset. Your verification code is: $code"
|
||||||
+ "\nThis code is valid for 3 minutes.",
|
+ "\nThis code is valid for 3 minutes.",
|
||||||
email
|
email
|
||||||
)
|
)
|
||||||
|
|
||||||
else -> return
|
|
||||||
}
|
}
|
||||||
sender.send(message)
|
sender.send(message)
|
||||||
logger.info("Email sent to $email.")
|
logger.info("Email sent to $email.")
|
||||||
|
|||||||
+114
-177
@@ -1,207 +1,144 @@
|
|||||||
package club.itstudio.itmanager.service.impl
|
package club.itstudio.itmanager.service.impl
|
||||||
|
|
||||||
import com.baomidou.mybatisplus.core.toolkit.Wrappers
|
|
||||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
|
|
||||||
import club.itstudio.itmanager.entity.dto.Account
|
import club.itstudio.itmanager.entity.dto.Account
|
||||||
import club.itstudio.itmanager.entity.dto.EmailVerificationMsg
|
import club.itstudio.itmanager.entity.enums.AccountRole
|
||||||
import club.itstudio.itmanager.entity.vo.request.EmailRegisterVO
|
|
||||||
import club.itstudio.itmanager.entity.vo.request.PasswordResetVO
|
|
||||||
import club.itstudio.itmanager.entity.vo.response.ReloginVO
|
|
||||||
import club.itstudio.itmanager.mapper.AccountMapper
|
import club.itstudio.itmanager.mapper.AccountMapper
|
||||||
import club.itstudio.itmanager.service.AccountService
|
import club.itstudio.itmanager.service.AccountService
|
||||||
import club.itstudio.itmanager.utils.Const
|
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
|
||||||
|
import org.slf4j.LoggerFactory
|
||||||
import club.itstudio.itmanager.utils.FlowUtils
|
|
||||||
import club.itstudio.itmanager.utils.JwtUtils
|
|
||||||
import org.springframework.amqp.core.AmqpTemplate
|
|
||||||
import org.springframework.data.redis.core.ReactiveStringRedisTemplate
|
|
||||||
import org.springframework.security.core.userdetails.User
|
import org.springframework.security.core.userdetails.User
|
||||||
import org.springframework.security.core.userdetails.UserDetails
|
import org.springframework.security.core.userdetails.UserDetails
|
||||||
import org.springframework.security.core.userdetails.UsernameNotFoundException
|
import org.springframework.security.core.userdetails.UsernameNotFoundException
|
||||||
import org.springframework.security.crypto.password.PasswordEncoder
|
|
||||||
import org.springframework.stereotype.Service
|
import org.springframework.stereotype.Service
|
||||||
import reactor.core.publisher.Mono
|
import reactor.core.publisher.Mono
|
||||||
import reactor.core.scheduler.Schedulers
|
import reactor.core.scheduler.Schedulers
|
||||||
import java.time.Duration
|
import javax.security.auth.login.AccountNotFoundException
|
||||||
|
import kotlin.jvm.java
|
||||||
|
|
||||||
@Service
|
@Service
|
||||||
class AccountServiceImpl(
|
class AccountServiceImpl : ServiceImpl<AccountMapper, Account>(), AccountService {
|
||||||
private val utils: FlowUtils,
|
|
||||||
private val jwtUtils: JwtUtils,
|
|
||||||
private val amqpTemplate: AmqpTemplate,
|
|
||||||
private val stringRedisTemplate: ReactiveStringRedisTemplate,
|
|
||||||
private val encoder: PasswordEncoder
|
|
||||||
) : ServiceImpl<AccountMapper, Account>(), AccountService {
|
|
||||||
|
|
||||||
override fun findByUsername(username: String): Mono<UserDetails> {
|
private val logger = LoggerFactory.getLogger(this::class.java)
|
||||||
return findAccountByNameOrEmail(username)
|
|
||||||
.switchIfEmpty(Mono.error(UsernameNotFoundException("Account with name $username not found")))
|
override fun findByUsername(
|
||||||
.map { account ->
|
username: String
|
||||||
User.withUsername(username)
|
): Mono<UserDetails> {
|
||||||
.password(account.password)
|
|
||||||
.roles(if (account.isStaff) "STAFF" else "USER")
|
return findAccountByName(username)
|
||||||
|
.map {
|
||||||
|
User.withUsername(it.username)
|
||||||
|
.password(it.password)
|
||||||
|
.roles(AccountRole.fromIsStaff(it.isStaff).name)
|
||||||
.build()
|
.build()
|
||||||
}
|
}
|
||||||
|
.onErrorMap(
|
||||||
|
AccountNotFoundException::class.java
|
||||||
|
) {
|
||||||
|
UsernameNotFoundException(
|
||||||
|
"User not found"
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun findAccountByNameOrEmail(text: String): Mono<Account> {
|
override fun findAccountByName(username: String): Mono<Account> =
|
||||||
return Mono.fromCallable {
|
findAccount("username") {
|
||||||
this.query()
|
ktQuery()
|
||||||
.eq("username", text).or()
|
.eq(Account::username, username)
|
||||||
.eq("email", text)
|
|
||||||
.one()
|
.one()
|
||||||
}.flatMap { account ->
|
|
||||||
Mono.just(account)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
override fun findAccountByEmail(email: String): Mono<Account> =
|
||||||
|
findAccount("email") {
|
||||||
|
ktQuery()
|
||||||
|
.eq(Account::email, email)
|
||||||
|
.one()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun <T : Any> blockingCall(
|
||||||
|
block: () -> T?
|
||||||
|
): Mono<T> =
|
||||||
|
Mono.fromCallable(block)
|
||||||
|
.subscribeOn(Schedulers.boundedElastic())
|
||||||
|
|
||||||
|
private fun findAccount(
|
||||||
|
fieldName: String,
|
||||||
|
query: () -> Account?
|
||||||
|
): Mono<Account> {
|
||||||
|
return blockingCall {
|
||||||
|
logger.info(
|
||||||
|
"Searching account by {}",
|
||||||
|
fieldName
|
||||||
|
)
|
||||||
|
query()
|
||||||
|
}.switchIfEmpty(
|
||||||
|
Mono.error(
|
||||||
|
AccountNotFoundException()
|
||||||
|
)
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun askEmailVerifyCode(type: String, email: String, ip: String): Mono<String> {
|
override fun findAccountByNameOrEmail(
|
||||||
return verifyLimit(ip).flatMap { allowed ->
|
text: String
|
||||||
if (allowed) {
|
): Mono<Account> {
|
||||||
val code = (100000..999999).random().toString()
|
return blockingCall {
|
||||||
val data = EmailVerificationMsg(email, type, code)
|
logger.info(
|
||||||
|
"Searching account by identifier"
|
||||||
Mono.fromRunnable<Void> {
|
)
|
||||||
amqpTemplate.convertAndSend("mail", data)
|
ktQuery()
|
||||||
}.then(
|
.and {
|
||||||
stringRedisTemplate.opsForValue()
|
it.eq(Account::email, text)
|
||||||
.set(
|
.or()
|
||||||
Const.VERIFY_EMAIL_DATA + email,
|
.eq(Account::username, text)
|
||||||
code,
|
|
||||||
Duration.ofMinutes(3)
|
|
||||||
)
|
|
||||||
).thenReturn("").subscribeOn(Schedulers.boundedElastic())
|
|
||||||
} else {
|
|
||||||
Mono.just("Request limit exceeded. Please try again later.")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun registerEmailAccount(vo: EmailRegisterVO): Mono<String> {
|
|
||||||
val (email, code, username, password) = vo
|
|
||||||
|
|
||||||
return verifyCode(email, code).flatMap { error ->
|
|
||||||
if (error.isNotBlank()) {
|
|
||||||
return@flatMap Mono.just(error)
|
|
||||||
}
|
|
||||||
|
|
||||||
existAccountByEmail(email).flatMap { emailExists ->
|
|
||||||
if (emailExists) {
|
|
||||||
return@flatMap Mono.just("account with the same email already exists.")
|
|
||||||
}
|
}
|
||||||
|
.one()
|
||||||
|
}.switchIfEmpty(
|
||||||
|
Mono.error(AccountNotFoundException())
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
existAccountByUsername(username).flatMap { usernameExists ->
|
override fun existAccountByName(
|
||||||
if (usernameExists) {
|
username: String
|
||||||
return@flatMap Mono.just("username already exists.")
|
): Mono<Boolean> {
|
||||||
}
|
return blockingCall {
|
||||||
|
ktQuery()
|
||||||
|
.eq(Account::username, username)
|
||||||
|
.exists()
|
||||||
|
|
||||||
val encodedPassword = encoder.encode(password)
|
}
|
||||||
val account = Account(
|
}
|
||||||
username = username,
|
|
||||||
password = encodedPassword!!,
|
override fun existAccountByEmail(
|
||||||
email = email,
|
email: String
|
||||||
isActive = true,
|
): Mono<Boolean> {
|
||||||
isStaff = false
|
return blockingCall {
|
||||||
|
ktQuery()
|
||||||
|
.eq(Account::email, email)
|
||||||
|
.exists()
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun resetPasswordByEmail(
|
||||||
|
email: String,
|
||||||
|
encodedPassword: String
|
||||||
|
): Mono<Void> {
|
||||||
|
return blockingCall {
|
||||||
|
ktUpdate()
|
||||||
|
.eq(Account::email, email)
|
||||||
|
.set(
|
||||||
|
Account::password,
|
||||||
|
encodedPassword
|
||||||
|
)
|
||||||
|
.update()
|
||||||
|
}
|
||||||
|
.flatMap { updated ->
|
||||||
|
if (updated) {
|
||||||
|
Mono.empty()
|
||||||
|
} else {
|
||||||
|
Mono.error(
|
||||||
|
AccountNotFoundException()
|
||||||
)
|
)
|
||||||
|
|
||||||
Mono.fromCallable { this.save(account) }
|
|
||||||
.flatMap { success ->
|
|
||||||
if (success) {
|
|
||||||
stringRedisTemplate.delete(Const.VERIFY_EMAIL_DATA + email)
|
|
||||||
.thenReturn("")
|
|
||||||
} else {
|
|
||||||
Mono.just("something went wrong. Please contact the administrator.")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun resetEmailAccountPassword(vo: PasswordResetVO): Mono<String> {
|
|
||||||
val (email, code, password) = vo
|
|
||||||
|
|
||||||
return verifyCode(email, code).flatMap { error ->
|
|
||||||
if (error.isNotBlank()) {
|
|
||||||
return@flatMap Mono.just(error)
|
|
||||||
}
|
|
||||||
|
|
||||||
existAccountByEmail(email).flatMap { exists ->
|
|
||||||
if (!exists) {
|
|
||||||
return@flatMap Mono.just("account with the email does not exist.")
|
|
||||||
}
|
|
||||||
|
|
||||||
val encodedPassword = encoder.encode(password)
|
|
||||||
|
|
||||||
Mono.fromCallable {
|
|
||||||
this.update()
|
|
||||||
.eq("email", email)
|
|
||||||
.set("password", encodedPassword)
|
|
||||||
.update()
|
|
||||||
}.flatMap { success ->
|
|
||||||
if (success) {
|
|
||||||
stringRedisTemplate.delete(Const.VERIFY_EMAIL_DATA + email)
|
|
||||||
.thenReturn("")
|
|
||||||
} else {
|
|
||||||
Mono.just("something went wrong. Please contact the administrator.")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun jwtTokenRelogin(headerToken: String?): Mono<ReloginVO>? {
|
|
||||||
val user = jwtUtils.resolveJwt(headerToken?.substring("Bearer ".length))
|
|
||||||
?.let { jwtUtils.toUser(it) }
|
|
||||||
?: return null
|
|
||||||
val accountMono = findAccountByNameOrEmail(user.username)
|
|
||||||
val voMono = accountMono.map {
|
|
||||||
ReloginVO(
|
|
||||||
jwtUtils.createJwt(user, it.id!!, it.username),
|
|
||||||
jwtUtils.expiresTime().toInstant().toString()
|
|
||||||
)
|
|
||||||
}
|
|
||||||
return voMono
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun invalidateJwt(headerToken: String?): Boolean {
|
|
||||||
return jwtUtils.invalidateJwt(headerToken)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun existAccountByEmail(email: String): Mono<Boolean> {
|
|
||||||
return Mono.fromCallable {
|
|
||||||
this.baseMapper.exists(
|
|
||||||
Wrappers.query<Account>()
|
|
||||||
.eq("email", email)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun existAccountByUsername(username: String): Mono<Boolean> {
|
|
||||||
return Mono.fromCallable {
|
|
||||||
this.baseMapper.exists(
|
|
||||||
Wrappers.query<Account>()
|
|
||||||
.eq("username", username)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun verifyLimit(ip: String): Mono<Boolean> {
|
|
||||||
val key = Const.VERIFY_EMAIL_LIMIT + ip
|
|
||||||
return utils.limitOnceCheck(key, 60)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun verifyCode(email: String, receivedCode: String?): Mono<String> {
|
|
||||||
return stringRedisTemplate.opsForValue()
|
|
||||||
.get(Const.VERIFY_EMAIL_DATA + email)
|
|
||||||
.flatMap { code ->
|
|
||||||
when {
|
|
||||||
receivedCode == null || code != receivedCode ->
|
|
||||||
Mono.just("verify code is wrong.")
|
|
||||||
|
|
||||||
else -> Mono.just("")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
.switchIfEmpty(Mono.just("verify code has not been sent"))
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+148
@@ -0,0 +1,148 @@
|
|||||||
|
package club.itstudio.itmanager.service.v1
|
||||||
|
|
||||||
|
import club.itstudio.itmanager.entity.dto.Account
|
||||||
|
import club.itstudio.itmanager.entity.dto.EmailVerificationMsg
|
||||||
|
import club.itstudio.itmanager.entity.enums.EmailType
|
||||||
|
import club.itstudio.itmanager.entity.vo.request.EmailRegisterVO
|
||||||
|
import club.itstudio.itmanager.entity.vo.request.PasswordResetVO
|
||||||
|
import club.itstudio.itmanager.entity.vo.response.ReloginVO
|
||||||
|
import club.itstudio.itmanager.service.AccountService
|
||||||
|
import club.itstudio.itmanager.utils.Const
|
||||||
|
import club.itstudio.itmanager.utils.DateUtils.getCurrentDateTime
|
||||||
|
import club.itstudio.itmanager.utils.FlowUtils
|
||||||
|
import club.itstudio.itmanager.utils.JwtUtils
|
||||||
|
import org.springframework.amqp.core.AmqpTemplate
|
||||||
|
import org.springframework.data.redis.core.ReactiveStringRedisTemplate
|
||||||
|
import org.springframework.security.crypto.password.PasswordEncoder
|
||||||
|
import org.springframework.stereotype.Service
|
||||||
|
import reactor.core.publisher.Mono
|
||||||
|
import reactor.core.scheduler.Schedulers
|
||||||
|
import java.time.Duration
|
||||||
|
|
||||||
|
@Service
|
||||||
|
class AuthorizationService(
|
||||||
|
private val accountService: AccountService,
|
||||||
|
private val utils: FlowUtils,
|
||||||
|
private val jwtUtils: JwtUtils,
|
||||||
|
private val amqpTemplate: AmqpTemplate,
|
||||||
|
private val stringRedisTemplate: ReactiveStringRedisTemplate,
|
||||||
|
private val encoder: PasswordEncoder
|
||||||
|
) {
|
||||||
|
fun askEmailVerifyCode(type: EmailType, email: String, ip: String): Mono<String> {
|
||||||
|
return verifyLimit(ip).flatMap { allowed ->
|
||||||
|
if (allowed) {
|
||||||
|
val code = (100000..999999).random().toString()
|
||||||
|
val data = EmailVerificationMsg(email, type, code)
|
||||||
|
|
||||||
|
Mono.fromRunnable<Void> {
|
||||||
|
amqpTemplate.convertAndSend("mail", data)
|
||||||
|
}.then(
|
||||||
|
stringRedisTemplate.opsForValue()
|
||||||
|
.set(
|
||||||
|
Const.VERIFY_EMAIL_DATA + email,
|
||||||
|
code,
|
||||||
|
Duration.ofMinutes(3)
|
||||||
|
)
|
||||||
|
).thenReturn("").subscribeOn(Schedulers.boundedElastic())
|
||||||
|
} else {
|
||||||
|
Mono.just("Request limit exceeded. Please try again later.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun registerEmailAccount(vo: EmailRegisterVO): Mono<String> {
|
||||||
|
val (email, code, username, password) = vo
|
||||||
|
|
||||||
|
return verifyCode(email, code)
|
||||||
|
.flatMap { result ->
|
||||||
|
if (result.isNotBlank()) {
|
||||||
|
return@flatMap Mono.just(result)
|
||||||
|
}
|
||||||
|
accountService.existAccountByEmail(email)
|
||||||
|
.flatMap { emailExists ->
|
||||||
|
if (emailExists) {
|
||||||
|
return@flatMap Mono.just("account with the same email already exists.")
|
||||||
|
}
|
||||||
|
accountService.existAccountByName(username)
|
||||||
|
.flatMap { usernameExists ->
|
||||||
|
if (usernameExists) {
|
||||||
|
return@flatMap Mono.just("username already exists.")
|
||||||
|
}
|
||||||
|
val account = Account(
|
||||||
|
id = null,
|
||||||
|
username = username,
|
||||||
|
password = encoder.encode(password)!!,
|
||||||
|
email = email,
|
||||||
|
isStaff = false,
|
||||||
|
createdAt = getCurrentDateTime()
|
||||||
|
)
|
||||||
|
Mono.fromCallable { accountService.save(account) }
|
||||||
|
.flatMap { success ->
|
||||||
|
if (success) {
|
||||||
|
stringRedisTemplate.delete(Const.VERIFY_EMAIL_DATA + email)
|
||||||
|
.thenReturn("")
|
||||||
|
} else {
|
||||||
|
Const.INTERNAL_ERROR_MONO
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun resetEmailAccountPassword(vo: PasswordResetVO): Mono<String> {
|
||||||
|
val (email, code, password) = vo
|
||||||
|
|
||||||
|
val encodedPassword =
|
||||||
|
encoder.encode(password)
|
||||||
|
?: return Const.INTERNAL_ERROR_MONO
|
||||||
|
|
||||||
|
return verifyCode(email, code)
|
||||||
|
.then(
|
||||||
|
accountService.resetPasswordByEmail(
|
||||||
|
email,
|
||||||
|
encodedPassword
|
||||||
|
)
|
||||||
|
)
|
||||||
|
.then(
|
||||||
|
stringRedisTemplate.delete(
|
||||||
|
Const.VERIFY_EMAIL_DATA + email
|
||||||
|
)
|
||||||
|
)
|
||||||
|
.thenReturn("Password reset successfully")
|
||||||
|
}
|
||||||
|
|
||||||
|
fun jwtTokenRelogin(headerToken: String?): Mono<ReloginVO>? {
|
||||||
|
val user = jwtUtils.resolveJwt(headerToken?.substring("Bearer ".length))
|
||||||
|
?.let { jwtUtils.toUser(it) }
|
||||||
|
?: return null
|
||||||
|
val accountMono = accountService.findAccountByName(user.username)
|
||||||
|
val voMono = accountMono.map {
|
||||||
|
ReloginVO(
|
||||||
|
jwtUtils.createJwt(user, it.id!!, it.username),
|
||||||
|
jwtUtils.expiresTime().toInstant().toString()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return voMono
|
||||||
|
}
|
||||||
|
|
||||||
|
fun invalidateJwt(headerToken: String?): Boolean {
|
||||||
|
return jwtUtils.invalidateJwt(headerToken)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun verifyLimit(ip: String): Mono<Boolean> {
|
||||||
|
val key = Const.VERIFY_EMAIL_LIMIT + ip
|
||||||
|
return utils.limitOnceCheck(key, 60)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun verifyCode(email: String, receivedCode: String?): Mono<String> {
|
||||||
|
return stringRedisTemplate.opsForValue()
|
||||||
|
.get(Const.VERIFY_EMAIL_DATA + email)
|
||||||
|
.flatMap { code ->
|
||||||
|
if (receivedCode == null || code != receivedCode)
|
||||||
|
Mono.just("verify code is wrong.")
|
||||||
|
else Mono.just("")
|
||||||
|
}
|
||||||
|
.switchIfEmpty(Mono.just("verify code has not been sent"))
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user