View Javadoc
1   /*
2    * Licensed under the GPL License. You may not use this file except in compliance with the License.
3    * You may obtain a copy of the License at
4    *
5    *   https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
6    *
7    * THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
8    * WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
9    * PURPOSE.
10   */
11  package psiprobe.tools;
12  
13  import jakarta.servlet.ServletContext;
14  
15  import java.util.Collection;
16  
17  import org.springframework.security.core.GrantedAuthority;
18  import org.springframework.security.core.context.SecurityContextHolder;
19  
20  /**
21   * The Class SecurityUtils.
22   */
23  public final class SecurityUtils {
24  
25    /**
26     * Prevent Instantiation of security utils.
27     */
28    private SecurityUtils() {
29      // Prevent Instantiation
30    }
31  
32    /**
33     * Checks for attribute value role.
34     *
35     * @param servletContext the servlet context
36     *
37     * @return true, if successful
38     */
39    public static boolean hasAttributeValueRole(ServletContext servletContext) {
40  
41      String[] privilegedRoles = getPrivilegedRoles(servletContext).split(",", -1);
42      for (String privilegedRole : privilegedRoles) {
43        if (userHasRole(privilegedRole)) {
44          return true;
45        }
46      }
47      return false;
48    }
49  
50    /**
51     * User has role.
52     *
53     * @param privilegedRole the privileged role
54     *
55     * @return true, if successful
56     */
57    private static boolean userHasRole(String privilegedRole) {
58      Collection<? extends GrantedAuthority> authorities =
59          SecurityContextHolder.getContext().getAuthentication().getAuthorities();
60  
61      boolean result = false;
62      for (GrantedAuthority authority : authorities) {
63        if (privilegedRole.equals(authority.getAuthority())) {
64          result = true;
65          break;
66        }
67      }
68      return result;
69    }
70  
71    /**
72     * Gets the privileged roles.
73     *
74     * @param servletContext the servlet context
75     *
76     * @return the privileged roles
77     */
78    private static String getPrivilegedRoles(ServletContext servletContext) {
79      return servletContext.getInitParameter("attribute.value.roles");
80    }
81  
82  }