-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathAuthUser.java
More file actions
54 lines (42 loc) · 1.36 KB
/
AuthUser.java
File metadata and controls
54 lines (42 loc) · 1.36 KB
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package ru.javaops.topjava2.web;
import lombok.Getter;
import org.springframework.lang.NonNull;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import ru.javaops.topjava2.model.Role;
import ru.javaops.topjava2.model.User;
import static java.util.Objects.requireNonNull;
@Getter
public class AuthUser extends org.springframework.security.core.userdetails.User {
private final User user;
public AuthUser(@NonNull User user) {
super(user.getEmail(), user.getPassword(), user.getRoles());
this.user = user;
}
public int id() {
return user.id();
}
public static AuthUser safeGet() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth == null) {
return null;
}
return (auth.getPrincipal() instanceof AuthUser au) ? au : null;
}
public static AuthUser get() {
return requireNonNull(safeGet(), "No authorized user found");
}
public static User authUser() {
return get().getUser();
}
public static int authId() {
return get().id();
}
public boolean hasRole(Role role) {
return user.hasRole(role);
}
@Override
public String toString() {
return "AuthUser:" + id() + '[' + user.getEmail() + ']';
}
}