This commit is contained in:
ovo 2024-12-07 18:55:49 +08:00
parent 5b096d27e1
commit def8ac7a6c
1 changed files with 19 additions and 1 deletions

View File

@ -17,6 +17,10 @@ import com.guwan.backend.vo.user.PhoneRegisterRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@ -157,7 +161,21 @@ public class UserServiceImpl implements UserService {
@Override
public Long getCurrentUserId() {
// TODO: 从SecurityContext中获取当前用户ID
// 从SecurityContext中获取认证信息
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
// 如果没有认证信息返回null
if (authentication == null || !authentication.isAuthenticated() ||
authentication instanceof AnonymousAuthenticationToken) {
return null;
}
// 获取UserDetails
Object principal = authentication.getPrincipal();
if (principal instanceof CustomUserDetails) {
return ((CustomUserDetails) principal).getUserId();
}
return null;
}