Commit 6fc24eab by Jan Hrabal

security

parent c0d25a19
......@@ -3,6 +3,8 @@ package com.jh.boot.security;
import java.util.Set;
import java.util.stream.Collectors;
import org.springframework.security.core.Authentication;
import com.jh.boot.security.model.AppRole;
import com.jh.boot.security.model.AppUser;
......@@ -13,7 +15,9 @@ public class SecurityHelper {
private SecurityHelper() {
}
public boolean hasAnyRole(AppUser user, String...roles) {
public boolean hasAnyRole(Authentication auth, String...roles) {
AppUser user = auth instanceof AppUserAuthentication ? ((AppUserAuthentication) auth).getUser() : null;
if (user == null || user.getRoles() == null || roles == null || roles.length == 0) {
return false;
}
......
......@@ -4,8 +4,11 @@
*/
package com.jh.boot.security.model;
import java.util.Collections;
import java.util.Date;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import javax.persistence.Column;
import javax.persistence.Entity;
......@@ -13,8 +16,10 @@ import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import javax.persistence.Transient;
import javax.persistence.Version;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.jh.boot.jpa.AbstractIdEntity;
......@@ -65,6 +70,7 @@ public class AppUser extends AbstractIdEntity {
inverseJoinColumns=
@JoinColumn(name="ROLE_ID", referencedColumnName="ID")
)
@JsonIgnore
private Set<AppRole> roles;
@Column(name = "LOCALE")
......@@ -88,6 +94,18 @@ public class AppUser extends AbstractIdEntity {
@Column(name = "PASSWORD_CHANGED")
private Date passwordChanged;
@Transient
private Map<String, AppRole> rolesMap;
public void initRolesMap() {
if (roles == null) {
rolesMap = Collections.emptyMap();
return;
}
rolesMap = roles.stream().collect(Collectors.toMap(AppRole::getName, r -> r));
}
/**
* Gets the email.
*
......@@ -278,4 +296,12 @@ public class AppUser extends AbstractIdEntity {
this.passwordChanged = passwordChanged;
}
public Map<String, AppRole> getRolesMap() {
return rolesMap;
}
public void setRolesMap(Map<String, AppRole> rolesMap) {
this.rolesMap = rolesMap;
}
}
......@@ -56,6 +56,9 @@ public class AppUserAuthService implements AuthService {
Set<GrantedRole> roles = new HashSet<>();
//initialize roles
user.initRolesMap();
AppUserAuthentication auth = new AppUserAuthentication(user, roles);
return auth;
}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment