forked from knastnt/JavaRush-Training-Topjava
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSecurityUtil.java
More file actions
34 lines (26 loc) · 977 Bytes
/
SecurityUtil.java
File metadata and controls
34 lines (26 loc) · 977 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package ru.javawebinar.topjava.web;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import ru.javawebinar.topjava.AuthorizedUser;
import static java.util.Objects.requireNonNull;
public class SecurityUtil {
private SecurityUtil() {
}
public static AuthorizedUser safeGet() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth == null) {
return null;
}
Object principal = auth.getPrincipal();
return (principal instanceof AuthorizedUser) ? (AuthorizedUser) principal : null;
}
public static AuthorizedUser get() {
return requireNonNull(safeGet(), "No authorized user found");
}
public static int authUserId() {
return get().getUserTo().id();
}
public static int authUserCaloriesPerDay() {
return get().getUserTo().getCaloriesPerDay();
}
}