forked from Realhedin/topjava02
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLoggedUser.java
More file actions
97 lines (80 loc) · 2.28 KB
/
LoggedUser.java
File metadata and controls
97 lines (80 loc) · 2.28 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package ru.javawebinar.topjava;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import ru.javawebinar.topjava.model.Role;
import ru.javawebinar.topjava.model.User;
import ru.javawebinar.topjava.to.UserTo;
import ru.javawebinar.topjava.util.UserUtil;
import java.io.Serializable;
import java.util.Set;
import static java.util.Objects.requireNonNull;
/**
* GKislin
* 06.03.2015.
* <p>
* Mock implementation
*/
public class LoggedUser implements UserDetails, Serializable {
private UserTo userTo;
private final boolean enabled;
private final Set<Role> roles;
private final String encodedPassword;
public LoggedUser(User user) {
this.userTo = UserUtil.asTo(user);
this.enabled = user.isEnabled();
this.roles = user.getRoles();
this.encodedPassword = user.getPassword();
}
public static LoggedUser safeGet() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth == null) {
return null;
}
Object user = auth.getPrincipal();
return (user instanceof LoggedUser) ? (LoggedUser) user : null;
}
public static LoggedUser get() {
LoggedUser user = safeGet();
requireNonNull(user, "No authorized user found");
return user;
}
public UserTo getUserTo() {
return userTo;
}
public static int id() {
return get().userTo.getId();
}
@Override
public Set<Role> getAuthorities() {
return roles;
}
@Override
public String getPassword() {
return encodedPassword;
}
@Override
public String getUsername() {
return userTo.getEmail();
}
@Override
public boolean isAccountNonExpired() {
return enabled;
}
@Override
public boolean isAccountNonLocked() {
return enabled;
}
@Override
public boolean isCredentialsNonExpired() {
return enabled;
}
@Override
public boolean isEnabled() {
return enabled;
}
public void updateUserTo(UserTo userTo) {
userTo.setId(this.userTo.getId());
this.userTo = UserUtil.asTo(userTo);
}
}