Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit d0ded6c

Browse files
Getting the current user
1 parent be7bf24 commit d0ded6c

File tree

1 file changed

+22
-0
lines changed
  • src/main/java/com/naturalprogrammer/spring5tutorial/utils

1 file changed

+22
-0
lines changed

‎src/main/java/com/naturalprogrammer/spring5tutorial/utils/MyUtils.java

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,16 @@
11
package com.naturalprogrammer.spring5tutorial.utils;
22

3+
import java.util.Optional;
4+
35
import org.springframework.context.MessageSource;
46
import org.springframework.context.i18n.LocaleContextHolder;
7+
import org.springframework.security.core.Authentication;
8+
import org.springframework.security.core.context.SecurityContextHolder;
59
import org.springframework.stereotype.Component;
610
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
711

12+
import com.naturalprogrammer.spring5tutorial.domain.User;
13+
814
@Component
915
public class MyUtils {
1016

@@ -28,4 +34,20 @@ public static void flash(RedirectAttributes redirectAttributes,
2834

2935
redirectAttributes.addFlashAttribute("flashKind", flashKind);
3036
}
37+
38+
public static Optional<User> currentUser() {
39+
40+
Authentication auth = SecurityContextHolder
41+
.getContext().getAuthentication();
42+
43+
if (auth != null) {
44+
45+
Object principal = auth.getPrincipal();
46+
47+
if (principal instanceof User)
48+
return Optional.of((User) principal);
49+
}
50+
51+
return Optional.empty();
52+
}
3153
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /