forked from mtusi2026/mtusi2026lab2
Лабораторная 2 на 5 готово
This commit is contained in:
@@ -0,0 +1,147 @@
|
||||
package org.example.service;
|
||||
|
||||
import org.example.config.TokenHasher;
|
||||
import org.example.dto.response.SessionInfoResponse;
|
||||
import org.example.dto.response.SessionResponse;
|
||||
import org.example.dto.response.UserResponse;
|
||||
import org.example.exception.UnauthorizedException;
|
||||
import org.example.model.Session;
|
||||
import org.example.model.User;
|
||||
import org.example.repository.SessionRepository;
|
||||
import org.example.repository.UserRepository;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
@Service
|
||||
public class AuthService {
|
||||
private final UserRepository userRepository;
|
||||
private final SessionRepository sessionRepository;
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
private final UserService userService;
|
||||
private final CacheService cacheService;
|
||||
private final ConcurrentHashMap<String, Object> locks = new ConcurrentHashMap<>();
|
||||
|
||||
@Value("${app.session-ttl-seconds:604800}")
|
||||
private long sessionTtlSeconds;
|
||||
|
||||
public AuthService(
|
||||
UserRepository userRepository,
|
||||
SessionRepository sessionRepository,
|
||||
PasswordEncoder passwordEncoder,
|
||||
UserService userService,
|
||||
CacheService cacheService
|
||||
) {
|
||||
this.userRepository = userRepository;
|
||||
this.sessionRepository = sessionRepository;
|
||||
this.passwordEncoder = passwordEncoder;
|
||||
this.userService = userService;
|
||||
this.cacheService = cacheService;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public SessionResponse login(String username, String rawPassword) {
|
||||
User user = userRepository.findByUsername(username)
|
||||
.orElseThrow(() -> new UnauthorizedException("Unauthorized"));
|
||||
|
||||
if (user.getPassword() == null
|
||||
|| !passwordEncoder.matches(rawPassword, user.getPassword())) {
|
||||
throw new UnauthorizedException("Unauthorized");
|
||||
}
|
||||
|
||||
String rawToken = TokenHasher.newRawToken();
|
||||
Instant expiresAt = Instant.now().plusSeconds(sessionTtlSeconds);
|
||||
|
||||
Session session = Session.builder()
|
||||
.userId(user.getId())
|
||||
.token(TokenHasher.sha256(rawToken))
|
||||
.expiresAt(expiresAt)
|
||||
.createdAt(Instant.now())
|
||||
.build();
|
||||
sessionRepository.save(session);
|
||||
cacheService.put(session.getToken(), user.getId(), expiresAt);
|
||||
|
||||
return SessionResponse.builder()
|
||||
.token(rawToken)
|
||||
.tokenType("Bearer")
|
||||
.expiresAt(expiresAt)
|
||||
.user(UserResponse.builder()
|
||||
.id(user.getId())
|
||||
.username(user.getUsername())
|
||||
.displayName(user.getDisplayName())
|
||||
.createdAt(user.getCreatedAt())
|
||||
.build())
|
||||
.build();
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void logout(String rawToken){
|
||||
if (rawToken == null || rawToken.isBlank()){
|
||||
return;
|
||||
}
|
||||
sessionRepository.findByToken(TokenHasher.sha256(rawToken))
|
||||
.ifPresent(s -> {
|
||||
s.setRevokedAt(Instant.now());
|
||||
sessionRepository.save(s);
|
||||
});
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void logoutCurrent(String rawToken) {
|
||||
String tokenHash = TokenHasher.sha256(rawToken);
|
||||
var session = sessionRepository
|
||||
.findByToken(tokenHash)
|
||||
.filter(s -> s.isActive(Instant.now()))
|
||||
.orElseThrow(() -> new UnauthorizedException("Unauthorized"));
|
||||
|
||||
session.setRevokedAt(Instant.now());
|
||||
sessionRepository.save(session);
|
||||
cacheService.deleteSession(tokenHash);
|
||||
}
|
||||
|
||||
|
||||
public Optional<User> resolveUserByBearer(String rawToken) {
|
||||
String hash = TokenHasher.sha256(rawToken);
|
||||
|
||||
Optional<UUID> cached = cacheService.get(hash);
|
||||
if (cached.isPresent()) {
|
||||
return userRepository.findById(cached.get());
|
||||
}
|
||||
|
||||
Object lock = locks.computeIfAbsent(hash, h -> new Object());
|
||||
try {
|
||||
synchronized (lock) {
|
||||
cached = cacheService.get(hash);
|
||||
if (cached.isPresent()) {
|
||||
return userRepository.findById(cached.get());
|
||||
}
|
||||
return resolveUserByBearer(hash);
|
||||
}
|
||||
} finally {
|
||||
locks.remove(hash, lock);
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<SessionInfoResponse> listSessionsForCurrentUser() {
|
||||
User user = userService.getCurrentUser();
|
||||
Instant now = Instant.now();
|
||||
return sessionRepository.findByUserIdOrderByCreatedAtDesc(user.getId())
|
||||
.stream()
|
||||
.map(s -> SessionInfoResponse.builder()
|
||||
.id(s.getId())
|
||||
.createdAt(s.getCreatedAt())
|
||||
.expiresAt(s.getExpiresAt())
|
||||
.revokedAt(s.getRevokedAt())
|
||||
.active(s.isActive(now))
|
||||
.build())
|
||||
.toList();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package org.example.service;
|
||||
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@Service
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
public class CacheService {
|
||||
|
||||
private static final String PREFIX = "session:";
|
||||
private final StringRedisTemplate redis;
|
||||
|
||||
public void put(String token, UUID userId, Instant expiresAt){
|
||||
long ttlSec = Duration.between(Instant.now(), expiresAt).getSeconds();
|
||||
if (ttlSec <= 0){
|
||||
return;
|
||||
}
|
||||
try {
|
||||
redis.opsForValue().set(
|
||||
PREFIX + token,
|
||||
userId.toString(),
|
||||
ttlSec,
|
||||
TimeUnit.SECONDS
|
||||
);
|
||||
} catch (Exception e){
|
||||
log.warn("Сессия не попала в Redis");
|
||||
}
|
||||
}
|
||||
|
||||
public Optional<UUID> get(String token){
|
||||
try {
|
||||
String v = redis.opsForValue().get(PREFIX + token);
|
||||
if (v == null || v.isBlank()){
|
||||
return Optional.empty();
|
||||
}
|
||||
return Optional.of(UUID.fromString(v));
|
||||
} catch (Exception e){
|
||||
log.warn("Сессии нет в Redis");
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
public void deleteSession(String token){
|
||||
try {
|
||||
redis.delete(PREFIX + token);
|
||||
} catch (Exception e){
|
||||
log.warn("Сессия не удалена в Redis");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
package org.example.service;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.example.dto.ChatPage;
|
||||
import org.example.dto.create.CreateChatDto;
|
||||
import org.example.dto.response.ChatResponse;
|
||||
import org.example.dto.update.UpdateChatDto;
|
||||
import org.example.exception.NotFoundException;
|
||||
import org.example.model.Chat;
|
||||
import org.example.model.ChatMember;
|
||||
import org.example.model.User;
|
||||
import org.example.repository.ChatMemberRepository;
|
||||
import org.example.repository.ChatRepository;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class ChatService {
|
||||
|
||||
private final ChatRepository chatRepository;
|
||||
private final ChatMemberRepository chatMemberRepository;
|
||||
private final UserService userService;
|
||||
|
||||
@Transactional
|
||||
public ChatResponse createChat(CreateChatDto dto) {
|
||||
User currentUser = userService.getCurrentUser();
|
||||
UUID currentId = currentUser.getId();
|
||||
|
||||
List<UUID> memberIds = dto.getMemberIds().stream()
|
||||
.distinct()
|
||||
.toList();
|
||||
|
||||
if (!memberIds.contains(currentId)) {
|
||||
throw new IllegalArgumentException(
|
||||
"Создатель чата должен входить в список участников (member_ids)");
|
||||
}
|
||||
|
||||
for (UUID memberId : memberIds) {
|
||||
if (!userService.exists(memberId)) {
|
||||
throw new NotFoundException("Пользователь с ID " + memberId + " не найден");
|
||||
}
|
||||
}
|
||||
|
||||
Chat chat = chatRepository.save(
|
||||
Chat.builder()
|
||||
.title(dto.getTitle())
|
||||
.build()
|
||||
);
|
||||
|
||||
for (UUID memberId : memberIds) {
|
||||
chatMemberRepository.save(
|
||||
ChatMember.builder()
|
||||
.chatId(chat.getId())
|
||||
.userId(memberId)
|
||||
.build()
|
||||
);
|
||||
}
|
||||
|
||||
return toResponse(chat.getId());
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public ChatResponse getChatById(UUID chatId) {
|
||||
requireMember(chatId);
|
||||
return toResponse(chatId);
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public ChatResponse getChatById(String chatId) {
|
||||
return getChatById(parseUuid(chatId));
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public ChatPage getChatsForCurrentUser(int limit) {
|
||||
UUID userId = userService.getCurrentUser().getId();
|
||||
List<ChatResponse> items = new ArrayList<>();
|
||||
|
||||
for (ChatMember membership : chatMemberRepository.findByUserId(userId)) {
|
||||
if (items.size() >= limit) {
|
||||
break;
|
||||
}
|
||||
chatRepository.findById(membership.getChatId())
|
||||
.ifPresent(chat -> items.add(toResponse(chat.getId())));
|
||||
}
|
||||
return new ChatPage(items, null);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public ChatResponse updateChat(UUID id, UpdateChatDto object) {
|
||||
requireMember(id);
|
||||
Chat chat = chatRepository.findById(id)
|
||||
.orElseThrow(() -> new NotFoundException("Чат не найден"));
|
||||
chat.setTitle(object.getTitle());
|
||||
chatRepository.save(chat);
|
||||
return toResponse(id);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public ChatResponse updateChat(String id, UpdateChatDto object) {
|
||||
return updateChat(parseUuid(id), object);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void deleteChat(UUID id) {
|
||||
requireMember(id);
|
||||
chatRepository.deleteById(id);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void deleteChat(String id) {
|
||||
deleteChat(parseUuid(id));
|
||||
}
|
||||
|
||||
/** Для MessageService: текущий user — участник, иначе 404 */
|
||||
@Transactional(readOnly = true)
|
||||
public void requireMember(UUID chatId) {
|
||||
User currentUser = userService.getCurrentUser();
|
||||
if (!chatRepository.existsById(chatId)
|
||||
|| !chatMemberRepository.existsByChatIdAndUserId(chatId, currentUser.getId())) {
|
||||
throw new NotFoundException("Чат не найден");
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public boolean isMember(UUID chatId, UUID userId) {
|
||||
return chatMemberRepository.existsByChatIdAndUserId(chatId, userId);
|
||||
}
|
||||
|
||||
private ChatResponse toResponse(UUID chatId) {
|
||||
Chat chat = chatRepository.findById(chatId)
|
||||
.orElseThrow(() -> new NotFoundException("Чат не найден"));
|
||||
|
||||
List<UUID> ids = chatMemberRepository.findByChatId(chatId).stream()
|
||||
.map(ChatMember::getUserId)
|
||||
.toList();
|
||||
|
||||
return ChatResponse.builder()
|
||||
.id(chat.getId())
|
||||
.title(chat.getTitle())
|
||||
.memberIds(ids)
|
||||
.createdAt(chat.getCreatedAt())
|
||||
.build();
|
||||
}
|
||||
|
||||
private static UUID parseUuid(String id) {
|
||||
try {
|
||||
return UUID.fromString(id);
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw new NotFoundException("Чат не найден");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
package org.example.service;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.example.dto.MessagePage;
|
||||
import org.example.dto.create.CreateMessageDto;
|
||||
import org.example.dto.update.UpdateMessageDto;
|
||||
import org.example.exception.ForbiddenException;
|
||||
import org.example.exception.NotFoundException;
|
||||
import org.example.model.Message;
|
||||
import org.example.repository.MessageRepository;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class MessageService {
|
||||
|
||||
private final MessageRepository messageRepository;
|
||||
private final ChatService chatService;
|
||||
|
||||
@Transactional
|
||||
public Message sendMessage(UUID chatId, UUID senderId, CreateMessageDto messageObject) {
|
||||
chatService.requireMember(chatId);
|
||||
if (!chatService.isMember(chatId, senderId)){
|
||||
throw new ForbiddenException("Пользователь не является участником чата");
|
||||
}
|
||||
|
||||
Message message = Message.builder()
|
||||
.chatId(chatId)
|
||||
.senderId(senderId)
|
||||
.text(messageObject.getText())
|
||||
.createdAt(Instant.now())
|
||||
.build();
|
||||
|
||||
return messageRepository.save(message);
|
||||
}
|
||||
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public MessagePage getMessage(UUID chatId, UUID userId, String cursor, int limit) {
|
||||
if (limit < 1) {
|
||||
throw new IllegalArgumentException("Лимит должен быть больше 0");
|
||||
}
|
||||
|
||||
chatService.requireMember(chatId);
|
||||
if (!chatService.isMember(chatId, userId)) {
|
||||
throw new NotFoundException("Чат не найден");
|
||||
}
|
||||
|
||||
Pageable pageable = PageRequest.of(0, limit);
|
||||
List<Message> items;
|
||||
|
||||
if (cursor == null || cursor.isBlank()) {
|
||||
items = messageRepository.findByChatIdOrderByCreatedAtDescIdDesc(chatId, pageable);
|
||||
} else {
|
||||
UUID cursorId;
|
||||
try {
|
||||
cursorId = UUID.fromString(cursor.trim());
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw new IllegalArgumentException("Invalid cursor");
|
||||
}
|
||||
|
||||
Message cursorMsg = messageRepository.findByIdAndChatId(cursorId, chatId)
|
||||
.orElse(null);
|
||||
|
||||
if (cursorMsg == null) {
|
||||
throw new IllegalArgumentException("Invalid cursor");
|
||||
}
|
||||
|
||||
items = messageRepository.findNextPage(
|
||||
chatId,
|
||||
cursorMsg.getCreatedAt(),
|
||||
cursorMsg.getId(),
|
||||
pageable
|
||||
);
|
||||
}
|
||||
|
||||
String nextCursor = null;
|
||||
if (items.size() == limit && !items.isEmpty()) {
|
||||
nextCursor = items.get(items.size() - 1).getId().toString();
|
||||
}
|
||||
|
||||
return new MessagePage(items, nextCursor);
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public MessagePage getMessage(String chatId, String userId, String cursor, int limit){
|
||||
return getMessage(parseUuid(chatId, true), parseUuid(userId, false), cursor, limit);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public Message updateMessage(UUID chatId, UUID messageId, UUID userId, UpdateMessageDto object) {
|
||||
chatService.requireMember(chatId);
|
||||
Message message = messageRepository.findByIdAndChatId(messageId, chatId)
|
||||
.orElseThrow(() -> new NotFoundException("Сообщение не найден"));
|
||||
if (!message.getSenderId().equals(userId)){
|
||||
throw new ForbiddenException("Вы не можете редактировать чужие сообщения");
|
||||
}
|
||||
message.setText(object.getText());
|
||||
return messageRepository.save(message);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public Message updateMessage(String chatId, String messageId, String userId, UpdateMessageDto object) {
|
||||
return updateMessage(
|
||||
parseUuid(chatId, true),
|
||||
parseUuid(messageId, true),
|
||||
parseUuid(userId, false),
|
||||
object);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void deleteMessage(UUID chatId, UUID messageId, UUID userId) {
|
||||
chatService.getChatById(chatId);
|
||||
|
||||
Message msg = messageRepository.findByIdAndChatId(messageId, chatId)
|
||||
.orElseThrow(() -> new NotFoundException("Сообщение не найдено"));
|
||||
|
||||
if (!msg.getSenderId().equals(userId)) {
|
||||
throw new ForbiddenException("Вы не можете удалять сообщения других участников");
|
||||
}
|
||||
messageRepository.delete(msg);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void deleteMessage(String chatId, String messageId, String userId) {
|
||||
deleteMessage(
|
||||
parseUuid(chatId, true),
|
||||
parseUuid(messageId, true),
|
||||
parseUuid(userId, false)
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
private static UUID parseUuid(String value, boolean notFoundOnBad) {
|
||||
try {
|
||||
return UUID.fromString(value.trim());
|
||||
} catch (Exception e) {
|
||||
if (notFoundOnBad) {
|
||||
throw new NotFoundException("Не найдено");
|
||||
}
|
||||
throw new IllegalArgumentException("Invalid id");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
package org.example.service;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.example.config.UserContext;
|
||||
import org.example.dto.create.CreateUserDto;
|
||||
import org.example.dto.update.UpdateUserDto;
|
||||
import org.example.exception.NotFoundException;
|
||||
import org.example.exception.UnauthorizedException;
|
||||
import org.example.exception.UserAlreadyExistsException;
|
||||
import org.example.model.User;
|
||||
import org.example.repository.UserRepository;
|
||||
import org.springframework.dao.DataIntegrityViolationException;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class UserService {
|
||||
|
||||
private final UserRepository userRepository;
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
|
||||
@Transactional
|
||||
public User createUser(CreateUserDto userObject) {
|
||||
if (userRepository.existsByUsername(userObject.getUsername())) {
|
||||
throw new UserAlreadyExistsException("Пользователь с таким username уже существует: " + userObject.getUsername());
|
||||
}
|
||||
try {
|
||||
User user = User.builder()
|
||||
.username(userObject.getUsername())
|
||||
.displayName(userObject.getDisplayName())
|
||||
.password(passwordEncoder.encode(userObject.getPassword()))
|
||||
.build();
|
||||
return userRepository.save(user);
|
||||
} catch (DataIntegrityViolationException e){
|
||||
throw new UserAlreadyExistsException(
|
||||
"Пользователь с таким username уже есть: " + userObject.getUsername());
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public User getCurrentUser() {
|
||||
User user = UserContext.getCurrentUser();
|
||||
if (user == null) {
|
||||
throw new UnauthorizedException("Unauthorized");
|
||||
}
|
||||
return user;
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public User getUserById(UUID id) {
|
||||
return userRepository.findById(id)
|
||||
.orElseThrow(() -> new NotFoundException("Пользователь с id: " + id + " не найден."));
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public User updateUser(UUID id, UpdateUserDto updateObject){
|
||||
User existing = getUserById(id);
|
||||
existing.setDisplayName(updateObject.getDisplayName());
|
||||
return userRepository.save(existing);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public User updateUser(String id, UpdateUserDto updateObject) {
|
||||
return updateUser(parseUuid(id), updateObject);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void deleteUser(UUID id) {
|
||||
if (!userRepository.existsById(id)) {
|
||||
throw new NotFoundException("Пользователь с id: " + id + " не найден");
|
||||
}
|
||||
userRepository.deleteById(id);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void deleteUser(String id) {
|
||||
deleteUser(parseUuid(id));
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public boolean exists(UUID id) {
|
||||
return userRepository.existsById(id);
|
||||
}
|
||||
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public boolean exists(String id) {
|
||||
try {
|
||||
return exists(parseUuid(id));
|
||||
}catch (IllegalArgumentException e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static UUID parseUuid(String id) {
|
||||
try {
|
||||
return UUID.fromString(id);
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw new NotFoundException("Пользователь с id: " + id + " не найден");
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user