<%#
 Copyright 2013-2021 the original author or authors from the JHipster project.

 This file is part of the JHipster project, see https://www.jhipster.tech/
 for more information.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      https://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-%>
package <%= packageName %>.security;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
<%_ if (authenticationTypeOauth2) { _%>
import org.springframework.security.core.authority.SimpleGrantedAuthority;
<%_ } _%>
<%_ if (reactive) { _%>
import org.springframework.security.core.context.ReactiveSecurityContextHolder;
<%_ } _%>
import org.springframework.security.core.context.SecurityContext;
<%_ if (!reactive) { _%>
import org.springframework.security.core.context.SecurityContextHolder;
<%_ } _%>
import org.springframework.security.core.userdetails.UserDetails;
<%_ if (authenticationTypeOauth2) { _%>
import org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
<%_ } _%>
<%_ if (authenticationTypeOauth2) { _%>
import java.util.*;
import java.util.stream.Collectors;
  <%_ if (reactive) { _%>
import reactor.core.publisher.Mono;
  <%_ } else { _%>
import java.util.stream.Stream;
  <%_ } _%>
<%_ } else { _%>
  <%_ if (reactive) { _%>
import reactor.core.publisher.Mono;
import java.util.Arrays;
  <%_ } else { _%>
import java.util.Arrays;
import java.util.Optional;
import java.util.stream.Stream;
  <%_ } _%>
<%_ } _%>

/**
 * Utility class for Spring Security.
 */
public final class SecurityUtils {
<%_ if (authenticationTypeOauth2) { _%>
    public static final String CLAIMS_NAMESPACE = "https://www.jhipster.tech/";
<%_ } _%>

    private SecurityUtils() {
    }

    /**
     * Get the login of the current user.
     *
     * @return the login of the current user.
     */
    public static <% if (!reactive) { %>Optional<% } else { %>Mono<% } %><String> getCurrentUserLogin() {
<%_ if (!reactive) { _%>
        SecurityContext securityContext = SecurityContextHolder.getContext();
        return Optional.ofNullable(extractPrincipal(securityContext.getAuthentication()));
<%_ } else { _%>
        return ReactiveSecurityContextHolder.getContext()
            .map(SecurityContext::getAuthentication)
            .flatMap(authentication -> Mono.justOrEmpty(extractPrincipal(authentication)));
<%_ } _%>
    }

    private static String extractPrincipal(Authentication authentication) {
        if (authentication == null) {
            return null;
        } else if (authentication.getPrincipal() instanceof UserDetails) {
            UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal();
            return springSecurityUser.getUsername();
<%_ if (authenticationTypeOauth2) { _%>
        } else if (authentication instanceof JwtAuthenticationToken) {
            return (String) ((JwtAuthenticationToken)authentication).getToken().getClaims().get("preferred_username");
        } else if (authentication.getPrincipal() instanceof DefaultOidcUser) {
            Map<String, Object> attributes = ((DefaultOidcUser) authentication.getPrincipal()).getAttributes();
            if (attributes.containsKey("preferred_username")) {
                return (String) attributes.get("preferred_username");
            }
<%_ } _%>
        } else if (authentication.getPrincipal() instanceof String) {
            return (String) authentication.getPrincipal();
        }
        return null;
    }

<%_ if (authenticationTypeJwt) { _%>

    /**
     * Get the JWT of the current user.
     *
     * @return the JWT of the current user.
     */
    public static <% if (!reactive) { %>Optional<% } else { %>Mono<% } %><String> getCurrentUserJWT() {
  <%_ if (!reactive) { _%>
        SecurityContext securityContext = SecurityContextHolder.getContext();
        return Optional.ofNullable(securityContext.getAuthentication())
  <%_ } else { _%>
        return ReactiveSecurityContextHolder.getContext()
            .map(SecurityContext::getAuthentication)
  <%_ } _%>
            .filter(authentication -> authentication.getCredentials() instanceof String)
            .map(authentication -> (String) authentication.getCredentials());
    }
<%_ } _%>

    /**
     * Check if a user is authenticated.
     *
     * @return true if the user is authenticated, false otherwise.
     */
    public static <% if (!reactive) { %>boolean<% } else { %>Mono<Boolean><% } %> isAuthenticated() {
<%_ if (!reactive) { _%>
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return authentication != null &&
            getAuthorities(authentication).noneMatch(AuthoritiesConstants.ANONYMOUS::equals);
<%_ } else { _%>
        return ReactiveSecurityContextHolder.getContext()
            .map(SecurityContext::getAuthentication)
            .map(Authentication::getAuthorities)
            .map(authorities -> authorities.stream()
                .map(GrantedAuthority::getAuthority)
                .noneMatch(AuthoritiesConstants.ANONYMOUS::equals)
            );
<%_ } _%>
    }

    /**
     * Checks if the current user has any of the authorities.
     *
     * @param authorities the authorities to check.
     * @return true if the current user has any of the authorities, false otherwise.
     */
    public static <% if (!reactive) { %>boolean<% } else { %>Mono<Boolean><% } %> hasCurrentUserAnyOfAuthorities(String... authorities) {
<%_ if (!reactive) { _%>
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return (
            authentication != null && getAuthorities(authentication).anyMatch(authority -> Arrays.asList(authorities).contains(authority))
        );
<%_ } else { _%>
        return ReactiveSecurityContextHolder.getContext()
            .map(SecurityContext::getAuthentication)
            .map(Authentication::getAuthorities)
            .map(authorityList -> authorityList.stream()
                .map(GrantedAuthority::getAuthority)
                .anyMatch(authority -> Arrays.asList(authorities).contains(authority))
            );
<%_ } _%>
    }

    /**
     * Checks if the current user has none of the authorities.
     *
     * @param authorities the authorities to check.
     * @return true if the current user has none of the authorities, false otherwise.
     */
    public static <% if (!reactive) { %>boolean<% } else { %>Mono<Boolean><% } %> hasCurrentUserNoneOfAuthorities(String... authorities) {
<%_ if (!reactive) { _%>
        return !hasCurrentUserAnyOfAuthorities(authorities);
<%_ } else { _%>
        return hasCurrentUserAnyOfAuthorities(authorities).map(result -> !result);
<%_ } _%>
    }

    /**
     * Checks if the current user has a specific authority.
     *
     * @param authority the authority to check.
     * @return true if the current user has the authority, false otherwise.
     */
    public static <% if (!reactive) { %>boolean<% } else { %>Mono<Boolean><% } %> hasCurrentUserThisAuthority(String authority) {
        return hasCurrentUserAnyOfAuthorities(authority);
    }

<%_ if (!reactive) { _%>
    private static Stream<String> getAuthorities(Authentication authentication) {
  <%_ if (authenticationTypeOauth2) { _%>
        Collection<? extends GrantedAuthority> authorities = authentication instanceof JwtAuthenticationToken ?
            extractAuthorityFromClaims(((JwtAuthenticationToken) authentication).getToken().getClaims())
            : authentication.getAuthorities();
        return authorities.stream()
  <%_ } else { _%>
        return authentication.getAuthorities().stream()
  <%_ } _%>
            .map(GrantedAuthority::getAuthority);
    }

<%_ } _%>
<%_ if (authenticationTypeOauth2) { _%>
    public static List<GrantedAuthority> extractAuthorityFromClaims(Map<String, Object> claims) {
        return mapRolesToGrantedAuthorities(getRolesFromClaims(claims));
    }

    @SuppressWarnings("unchecked")
    private static Collection<String> getRolesFromClaims(Map<String, Object> claims) {
        return (Collection<String>) claims.getOrDefault("groups",
            claims.getOrDefault("roles",
            claims.getOrDefault(CLAIMS_NAMESPACE + "roles", new ArrayList<>())));
    }

    private static List<GrantedAuthority> mapRolesToGrantedAuthorities(Collection<String> roles) {
        return roles.stream()
            .filter(role -> role.startsWith("ROLE_"))
            .map(SimpleGrantedAuthority::new)
            .collect(Collectors.toList());
    }
<%_ } _%>
}
