Skip to content

Commit 077da43

Browse files
committed
♻️ refactor: 사용자 인증 정보를 반환하는 util 메서드 추가
1 parent ada5078 commit 077da43

File tree

1 file changed

+23
-6
lines changed

1 file changed

+23
-6
lines changed

backend/src/main/java/io/f1/backend/global/util/SecurityUtils.java

Lines changed: 23 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,21 +2,38 @@
22

33
import io.f1.backend.domain.user.dto.UserPrincipal;
44
import io.f1.backend.domain.user.entity.User;
5-
5+
import java.util.Collections;
66
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
7+
import org.springframework.security.core.Authentication;
78
import org.springframework.security.core.context.SecurityContextHolder;
89

9-
import java.util.Collections;
10-
1110
public class SecurityUtils {
1211

13-
private SecurityUtils() {}
12+
private SecurityUtils() {
13+
}
1414

1515
public static void setAuthentication(User user) {
1616
UserPrincipal userPrincipal = new UserPrincipal(user, Collections.emptyMap());
1717
UsernamePasswordAuthenticationToken authentication =
18-
new UsernamePasswordAuthenticationToken(
19-
userPrincipal, null, userPrincipal.getAuthorities());
18+
new UsernamePasswordAuthenticationToken(
19+
userPrincipal, null, userPrincipal.getAuthorities());
2020
SecurityContextHolder.getContext().setAuthentication(authentication);
2121
}
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+
}
2239
}

0 commit comments

Comments
 (0)