|
2 | 2 |
|
3 | 3 | import io.f1.backend.domain.user.dto.UserPrincipal; |
4 | 4 | import io.f1.backend.domain.user.entity.User; |
5 | | - |
| 5 | +import java.util.Collections; |
6 | 6 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; |
| 7 | +import org.springframework.security.core.Authentication; |
7 | 8 | import org.springframework.security.core.context.SecurityContextHolder; |
8 | 9 |
|
9 | | -import java.util.Collections; |
10 | | - |
11 | 10 | public class SecurityUtils { |
12 | 11 |
|
13 | | - private SecurityUtils() {} |
| 12 | + private SecurityUtils() { |
| 13 | + } |
14 | 14 |
|
15 | 15 | public static void setAuthentication(User user) { |
16 | 16 | UserPrincipal userPrincipal = new UserPrincipal(user, Collections.emptyMap()); |
17 | 17 | UsernamePasswordAuthenticationToken authentication = |
18 | | - new UsernamePasswordAuthenticationToken( |
19 | | - userPrincipal, null, userPrincipal.getAuthorities()); |
| 18 | + new UsernamePasswordAuthenticationToken( |
| 19 | + userPrincipal, null, userPrincipal.getAuthorities()); |
20 | 20 | SecurityContextHolder.getContext().setAuthentication(authentication); |
21 | 21 | } |
| 22 | + |
| 23 | + public static UserPrincipal getCurrentUserPrincipal() { |
| 24 | + Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); |
| 25 | + if (authentication != null |
| 26 | + && authentication.getPrincipal() instanceof UserPrincipal userPrincipal) { |
| 27 | + return userPrincipal; |
| 28 | + } |
| 29 | + throw new RuntimeException("E401001: 로그인이 필요합니다."); |
| 30 | + } |
| 31 | + |
| 32 | + public static Long getCurrentUserId() { |
| 33 | + return getCurrentUserPrincipal().getUserId(); |
| 34 | + } |
| 35 | + |
| 36 | + public static String getCurrentUserNickname() { |
| 37 | + return getCurrentUserPrincipal().getUserNickname(); |
| 38 | + } |
22 | 39 | } |
0 commit comments