Guest User

Untitled

a guest
Feb 19th, 2018
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 12.06 KB | None | 0 0
  1. Privilege.java
  2. ```java
  3. // Privilege.java
  4. import javax.persistence.*;
  5. import java.io.Serializable;
  6. import java.util.Set;
  7.  
  8.  
  9. @Setter
  10. @Getter
  11. @EqualsAndHashCode(exclude = {"roles"})
  12. @ToString(exclude = {"roles"})
  13. @NoArgsConstructor
  14. @Builder
  15. @AllArgsConstructor
  16. //
  17. @Entity
  18. @Table(name = "cms_privilege")
  19. public class Privilege implements Serializable {
  20. static final long serialVersionUID = -12393123123L;
  21. @Id
  22. @GeneratedValue(strategy = GenerationType.AUTO)
  23. @Column(name = "id")
  24. private Long id;
  25. private String name;
  26.  
  27. @ManyToMany(mappedBy = "privileges", cascade = {CascadeType.MERGE, CascadeType.PERSIST, CascadeType.DETACH, CascadeType.REMOVE})
  28. private Set<Role> roles;
  29. }
  30. ```
  31.  
  32. Role.java
  33. ```java
  34. // Role.java
  35. import lombok.*;
  36. import org.hibernate.annotations.Fetch;
  37. import org.hibernate.annotations.FetchMode;
  38.  
  39. import javax.persistence.*;
  40. import javax.validation.constraints.NotNull;
  41. import java.io.Serializable;
  42. import java.util.Set;
  43.  
  44. @Setter
  45. @Getter
  46. @EqualsAndHashCode(exclude = {"privileges", "users"})
  47. @ToString(exclude = {"privileges", "users"})
  48. @NoArgsConstructor
  49. @Builder
  50. @AllArgsConstructor
  51. //
  52. @Entity
  53. @Table(name = "cms_role")
  54. public class Role implements Serializable {
  55. static final long serialVersionUID = 1283712837L;
  56. @Id
  57. @GeneratedValue(strategy = GenerationType.AUTO)
  58. @Column(name = "id")
  59. private Long id;
  60.  
  61. @Column(name = "name")
  62. @NotNull
  63. private String name;
  64.  
  65. @Column(name = "home_page")
  66. private String homePage;
  67.  
  68. @ManyToMany(mappedBy = "roles")
  69. private Set<User> users;
  70. @ManyToMany(fetch = FetchType.EAGER)
  71. @JoinTable(name = "cms_roles_privileges",
  72. joinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id"),
  73. inverseJoinColumns = @JoinColumn(name = "privilege_id", referencedColumnName = "id")
  74. )
  75. @Fetch(FetchMode.JOIN)
  76. private Set<Privilege> privileges;
  77. }
  78. ```
  79.  
  80.  
  81. User.java
  82. ```java
  83. import com.google.common.collect.Sets;
  84. import lombok.*;
  85.  
  86. import javax.persistence.*;
  87. import javax.validation.constraints.NotNull;
  88. import java.io.Serializable;
  89. import java.util.Arrays;
  90. import java.util.List;
  91. import java.util.Set;
  92. import java.util.stream.Collectors;
  93.  
  94. @Setter
  95. @Getter
  96. @EqualsAndHashCode(exclude = {"roles"})
  97. @ToString(exclude = {"roles"})
  98. @NoArgsConstructor
  99. @Builder
  100. @AllArgsConstructor
  101. //
  102. @Entity
  103. @Table(name = "cms_user", uniqueConstraints = {
  104. @UniqueConstraint(columnNames = "username", name = "unq_cms_user_username")
  105. })
  106. public class User implements Serializable {
  107. static final long serialVersionUID = -234789L;
  108. @Id
  109. @Column(name = "id")
  110. @GeneratedValue(strategy = GenerationType.AUTO)
  111. private Long id;
  112.  
  113. @Column(name = "username", unique = true, nullable = false)
  114. @NotNull
  115. private String username;
  116.  
  117. @Column(name = "password", nullable = false)
  118. @NotNull
  119. private String password;
  120.  
  121. @Column(name = "status", nullable = false)
  122. private Integer status;
  123. @Column(name = "first_name")
  124. private String firstName;
  125. @Column(name = "last_name")
  126. private String lastName;
  127.  
  128. @Column(name = "description")
  129. private String description;
  130.  
  131. @Column(name = "user_type")
  132. private Integer userType;
  133.  
  134. @ManyToMany(fetch = FetchType.EAGER, cascade = {CascadeType.MERGE, CascadeType.PERSIST})
  135. @JoinTable(name = "cms_users_roles",
  136. joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"),
  137. inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id")
  138. )
  139. private Set<Role> roles;
  140.  
  141. @Column(name = "phone_number")
  142. private String phone;
  143.  
  144. @Transient
  145. public String displayName() {
  146. return this.getFirstName() + " " + this.getLastName();
  147. }
  148.  
  149.  
  150. @Transient
  151. public boolean hasAnyRoles(String... roles) {
  152. return hasAnyRoles(Arrays.asList(roles));
  153. }
  154.  
  155. @Transient
  156. public boolean hasAnyRoles(List<String> roles) {
  157. Set<String> _roles = this.getRoles()
  158. .stream()
  159. .map(Role::getName)
  160. .collect(Collectors.toSet());
  161. Sets.SetView<String> intersection = Sets.intersection(Sets.newHashSet(roles), _roles);
  162. return !intersection.isEmpty();
  163. }
  164.  
  165. @Transient
  166. public boolean hasRoles(String... roles) {
  167. return hasRoles(Arrays.asList(roles));
  168. }
  169.  
  170. @Transient
  171. public boolean hasRoles(List<String> roles) {
  172. Set<String> _roles = this.getRoles()
  173. .stream()
  174. .map(Role::getName)
  175. .collect(Collectors.toSet());
  176. return _roles.containsAll(roles);
  177. }
  178.  
  179. @Transient
  180. public boolean hasAnyPrivileges(String... privileges) {
  181. return hasAnyPrivileges(Arrays.asList(privileges));
  182. }
  183.  
  184. @Transient
  185. public boolean hasAnyPrivileges(List<String> privileges) {
  186. Set<String> _privileges = this.getRoles()
  187. .stream()
  188. .flatMap(s -> s.getPrivileges().stream())
  189. .map(Privilege::getName)
  190. .collect(Collectors.toSet());
  191. Sets.SetView<String> intersection = Sets.intersection(_privileges, Sets.newHashSet(privileges));
  192. return !intersection.isEmpty();
  193. }
  194.  
  195. @Transient
  196. public boolean hasPrivileges(String... privileges) {
  197. return hasPrivileges(Arrays.asList(privileges));
  198. }
  199.  
  200. @Transient
  201. public boolean hasPrivileges(List<String> privileges) {
  202. Set<String> _privileges = this.getRoles()
  203. .stream()
  204. .flatMap(s -> s.getPrivileges().stream())
  205. .map(Privilege::getName)
  206. .collect(Collectors.toSet());
  207. return _privileges.containsAll(privileges);
  208. }
  209. }
  210. ```
  211.  
  212. This one will work in any case (not only Spring)
  213. If your using some sort of AOP (Spring-aop for example)
  214. You can do something like this:
  215.  
  216. Aspect.java
  217.  
  218. ```java
  219. @org.aspectj.lang.annotation.Aspect
  220. @Component
  221. @Slf4j
  222. public class Aspect {
  223.  
  224.  
  225. @Autowired
  226. UserActionRepository userActionRepository;
  227.  
  228. @Around("@annotation(RequiredPrivilege)")
  229. public Object preCheckPrivilege(ProceedingJoinPoint joinPoint) throws Throwable {
  230. MethodSignature signature = (MethodSignature) joinPoint.getSignature();
  231. Method method = signature.getMethod();
  232. RequiredPrivilege requiredPrivilege = method.getAnnotation(RequiredPrivilege.class);
  233. String[] privileges = requiredPrivilege.privileges().length == 0 ?
  234. requiredPrivilege.value() : requiredPrivilege.privileges();
  235. if (privileges.length == 0) {
  236. return joinPoint.proceed();
  237. } else if (requiredPrivilege.anyMatch()) {
  238. LoggedInUsers.checkAnyPrivileges(privileges);
  239. } else {
  240. LoggedInUsers.checkPrivileges(privileges);
  241. }
  242. for (Object obj : joinPoint.getArgs()) {
  243. if (obj instanceof Model) {
  244. ((Model) (obj)).addAttribute("_user", LoggedInUsers.currentUser());
  245. }
  246. }
  247. return joinPoint.proceed();
  248. }
  249.  
  250. @Around("@annotation(RequiredRole)")
  251. public Object preCheckRole(ProceedingJoinPoint joinPoint) throws Throwable {
  252. MethodSignature signature = (MethodSignature) joinPoint.getSignature();
  253. Method method = signature.getMethod();
  254. RequiredRole requiredRoles = method.getAnnotation(RequiredRole.class);
  255. String[] roles = requiredRoles.roles().length == 0 ?
  256. requiredRoles.value() : requiredRoles.roles();
  257. if (roles.length == 0) {
  258. return joinPoint.proceed();
  259. } else if (requiredRoles.anyMatch()) {
  260. LoggedInUsers.checkAnyRoles(roles);
  261. } else {
  262. LoggedInUsers.checkRoles(roles);
  263. }
  264. return joinPoint.proceed();
  265. }
  266.  
  267. @Around("@annotation(TrackingAction)")
  268. public Object trackUserAction(ProceedingJoinPoint joinPoint) throws Throwable {
  269. MethodSignature signature = (MethodSignature) joinPoint.getSignature();
  270. Method method = signature.getMethod();
  271. TrackingAction trackingAction = method.getAnnotation(TrackingAction.class);
  272. String clazzName = method.getDeclaringClass().getSimpleName();
  273. String actionName = trackingAction.actionName();
  274. String methodName = method.getName();
  275. String desc;
  276. if (!Strings.isNullOrEmpty(trackingAction.descriptionFormat())) {
  277. Map<String, Object> map = new HashMap<>();
  278. map.put("username", LoggedInUsers.currentUser().getUsername());
  279. for (int i = 0; i < joinPoint.getArgs().length; i++) {
  280. map.put("" + i, joinPoint.getArgs()[i]);
  281. }
  282. String descriptionFormat = trackingAction.descriptionFormat();
  283. StrSubstitutor substitutor = new StrSubstitutor(map);
  284. desc = substitutor.replace(descriptionFormat);
  285. } else {
  286. String parameters = Arrays.toString(joinPoint.getArgs());
  287. desc = clazzName + "::" + methodName + "(" + parameters + ")";
  288. }
  289. if (Strings.isNullOrEmpty(actionName)) {
  290. actionName = clazzName + "#" + methodName;
  291. }
  292.  
  293. UserAction userAction = UserAction.builder()
  294. .timestamp(new Timestamp(System.currentTimeMillis()))
  295. .user(LoggedInUsers.currentUser())
  296. .type(trackingAction.actionType().name())
  297. .actionName(actionName)
  298. .description(desc)
  299. .build();
  300. try {
  301. userActionRepository.save(userAction);
  302. } catch (Exception ex) {
  303. log.error("Cannot insert userAction: {}", userAction, ex);
  304. } finally {
  305. return joinPoint.proceed();
  306. }
  307. }
  308.  
  309.  
  310. }
  311. ```
  312. RequiredPrivilege.java
  313. ```java
  314. import java.lang.annotation.ElementType;
  315. import java.lang.annotation.Retention;
  316. import java.lang.annotation.RetentionPolicy;
  317. import java.lang.annotation.Target;
  318.  
  319. @Target(ElementType.METHOD)
  320. @Retention(RetentionPolicy.RUNTIME)
  321. public @interface RequiredPrivilege {
  322. String[] value();
  323.  
  324. // alternative for value
  325. String[] privileges() default {};
  326.  
  327. boolean anyMatch() default true;
  328. }
  329. ```
  330. RequiredRole.java
  331.  
  332. ```java
  333. import java.lang.annotation.ElementType;
  334. import java.lang.annotation.Retention;
  335. import java.lang.annotation.RetentionPolicy;
  336. import java.lang.annotation.Target;
  337.  
  338. @Target(ElementType.METHOD)
  339. @Retention(RetentionPolicy.RUNTIME)
  340. public @interface RequiredRole {
  341. String[] value();
  342.  
  343. // alternative for value
  344. String[] roles() default {};
  345.  
  346. boolean anyMatch() default true;
  347. }
  348. ```
  349.  
  350. TrackingAction.java
  351.  
  352. ```java
  353. import org.aspectj.lang.ProceedingJoinPoint;
  354.  
  355. import java.lang.annotation.ElementType;
  356. import java.lang.annotation.Retention;
  357. import java.lang.annotation.RetentionPolicy;
  358. import java.lang.annotation.Target;
  359.  
  360. /**
  361. * @see vn.vng.wpl.livestream.admin.cms.aop.Aspect#trackUserAction(ProceedingJoinPoint)
  362. */
  363. @Target(ElementType.METHOD)
  364. @Retention(RetentionPolicy.RUNTIME)
  365. public @interface TrackingAction {
  366. UserActionType actionType();
  367.  
  368. String actionName() default "";
  369.  
  370. /**
  371. * Use with {@link org.apache.commons.lang3.text.StrSubstitutor}
  372. *
  373. * @return
  374. */
  375. String descriptionFormat() default "";
  376. }
  377. ```
Add Comment
Please, Sign In to add comment