Skip to content

Commit c9c1243

Browse files
committed
(TP-105) feat: add and impl SecurityService
1 parent 4cb0216 commit c9c1243

2 files changed

Lines changed: 52 additions & 0 deletions

File tree

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
package kattsyn.dev.rentplace.services;
2+
3+
import jakarta.security.auth.message.AuthException;
4+
import kattsyn.dev.rentplace.entities.User;
5+
6+
public interface SecurityService {
7+
8+
String getCurrentUserEmail() throws AuthException;
9+
User getCurrentUser() throws AuthException;
10+
Long getCurrentUserId() throws AuthException;
11+
12+
}
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package kattsyn.dev.rentplace.services.impl;
2+
3+
import jakarta.security.auth.message.AuthException;
4+
import kattsyn.dev.rentplace.entities.User;
5+
import kattsyn.dev.rentplace.exceptions.NotFoundException;
6+
import kattsyn.dev.rentplace.repositories.UserRepository;
7+
import kattsyn.dev.rentplace.services.SecurityService;
8+
import lombok.RequiredArgsConstructor;
9+
import org.springframework.security.core.Authentication;
10+
import org.springframework.security.core.context.SecurityContextHolder;
11+
import org.springframework.stereotype.Service;
12+
13+
@Service
14+
@RequiredArgsConstructor
15+
public class SecurityServiceImpl implements SecurityService {
16+
17+
private final UserRepository userRepository;
18+
19+
@Override
20+
public String getCurrentUserEmail() throws AuthException {
21+
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
22+
if (auth == null || !auth.isAuthenticated() || "anonymousUser".equals(auth.getName())) {
23+
throw new AuthException("Пользователь не авторизован");
24+
}
25+
Object principal = auth.getPrincipal();
26+
return (principal instanceof User) ? ((User) principal).getEmail() : principal.toString();
27+
}
28+
29+
@Override
30+
public User getCurrentUser() throws AuthException {
31+
String email = getCurrentUserEmail();
32+
return userRepository.findByEmail(email)
33+
.orElseThrow(() -> new NotFoundException(String.format("User with email %s not found", email)));
34+
}
35+
36+
@Override
37+
public Long getCurrentUserId() throws AuthException {
38+
return getCurrentUser().getUserId();
39+
}
40+
}

0 commit comments

Comments
 (0)