<%#
 Copyright 2013-2024 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;
<%_ if (generateAuthenticationApi && (authenticationTypeOauth2 || authenticationTypeJwt)) { _%>

import <%= packageName %>.config.Constants;
<%_ } _%>

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
<%_ if (reactive) { _%>
import org.springframework.security.core.context.ReactiveSecurityContextHolder;
<%_ } else { _%>
import org.springframework.security.core.context.SecurityContextHolder;
<%_ } _%>
import org.springframework.security.core.userdetails.UserDetails;
<%_ if (authenticationTypeJwt) { _%>
import org.springframework.security.oauth2.jose.jws.MacAlgorithm;
import org.springframework.security.oauth2.jwt.Jwt;
<%_ } _%>
<%_ if (authenticationTypeOauth2) { _%>
  <%_ if (applicationTypeMicroservice && builtInServices?.includes('idm')) { _%>
import <%= packageName %>.repository.UserRepository;
import <%= packageName %>.SpringBootUtil;
  <%_ } else if (applicationTypeGateway) { _%>
import <%= packageName %>.repository.UserRepository;
  <%_ } _%>
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
  <%_ if (reactive) { _%>
import reactor.core.publisher.Mono;
  <%_ } else { _%>
import java.util.stream.Stream;
  <%_ } _%>
<%_ } else { _%>
  <%_ if (reactive) { _%>
import reactor.core.publisher.Mono;
  <%_ } else { _%>
import java.util.stream.Stream;
  <%_ } _%>
<%_ } _%>
import java.util.*;
<%_ if (authenticationTypeOauth2 || authenticationTypeJwt) { _%>
import org.springframework.security.oauth2.core.oidc.StandardClaimNames;
import java.util.stream.Collectors;
<%_ } _%>

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

    public static final MacAlgorithm JWT_ALGORITHM = MacAlgorithm.HS512;

    public static final String AUTHORITIES_KEY = "auth";

    public static final String WX_SESSION_KEY = "session_key"; // add by wangxin WeiXin SESSION_KEY

    public static final String USER_ID = "userId"; // add by wangxin userId
    <%_ if (useMultiTenant) { _%>
    public static final String TENANT_ID = "tenantId"; // add by wangxin tenantId
    <%_ } _%>
<%_ } _%>

    private SecurityUtils() {
    }

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

    private static String extractPrincipal(Authentication authentication) {
        if (authentication == null) {
            return null;
        } else if (authentication.getPrincipal() instanceof UserDetails<% if (javaVersion === '17') { %> springSecurityUser<% } %>) {
            <%_ if (javaVersion !== '17') { _%>
            UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal();
            <%_ } _%>
            return springSecurityUser.getUsername();
<%_ if (authenticationTypeJwt) { _%>
    <%_ if (javaVersion === '8') { _%>
        } else if (authentication.getPrincipal() instanceof Jwt) {
            Jwt jwt = (Jwt) authentication.getPrincipal();
    <%_ } else  {%>
        } else if (authentication.getPrincipal() instanceof Jwt jwt) {
    <%_ } _%>
            return jwt.getSubject();
<%_ } _%>
<%_ 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<% if (javaVersion === '17') { %> s<% } %>) {
            return <% if (javaVersion === '17') { %>s<% } else { %>(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) { %>Mono<% } else { %>Optional<% } %><String> getCurrentUserJWT() {
  <%_ if (reactive) { _%>
        return ReactiveSecurityContextHolder.getContext()
            .map(SecurityContext::getAuthentication)
  <%_ } else { _%>
        SecurityContext securityContext = SecurityContextHolder.getContext();
        return Optional.ofNullable(securityContext.getAuthentication())
  <%_ } _%>
            .filter(authentication -> authentication.getCredentials() instanceof String)
            .map(authentication -> (String) authentication.getCredentials());
    }
<%_ } _%>

    /**
     * Get the id of the current user.
     *
     * @return the id of the current user.
     */
    public static <% if (!reactive) { %>Optional<% } else { %>Mono<% } %><<%= userIdTypeName %>> getCurrentUserId() {
        <%_ if (authenticationTypeOauth2) { _%>
          <%_ if (applicationTypeMicroservice && builtInServices?.includes('idm')) { _%>
        return getCurrentUserLogin()
            .flatMap(userLogin -> SpringBootUtil.getBean(UserRepository.class)
                .findOneByLogin(userLogin)
                .map(user -> Optional.ofNullable(user.getId())))
            .orElse(Optional.empty());
          <%_ } else { _%>
        return <% if (reactive) { %>Mono.empty()<% } else { %>Optional.ofNullable(null)<% } %>; // todo 未实现
          <%_ } _%>
        <%_ } else { _%>
          <%_ if (!reactive) { _%>
        SecurityContext securityContext = SecurityContextHolder.getContext();
        return Optional.ofNullable(securityContext.getAuthentication())
          <%_ } else { _%>
        return ReactiveSecurityContextHolder.getContext()
            .map(SecurityContext::getAuthentication)
          <%_ } _%>
            .map(authentication -> {
                if (authentication.getPrincipal() instanceof UserDetails) {
                    MyUserDetails springSecurityUser = (MyUserDetails) authentication.getPrincipal();
                    return springSecurityUser.getId();
                }
                <%_ if (javaVersion === '8') { _%>
                if (authentication.getPrincipal() instanceof Jwt) {
                    Jwt jwt = (Jwt) authentication.getPrincipal();
                <%_ } else  {%>
                if (authentication.getPrincipal() instanceof Jwt jwt) {
                <%_ } _%>
                    return <% if (userIdTypeName === 'Long') { %>Long.parseLong(jwt.getClaim(USER_ID))<% } else { %>jwt.getClaim(USER_ID)<% } %>;
                }
                return null;
            });
        <%_ } _%>

    }

    /**
     * Check if a user is authenticated.
     *
     * @return true if the user is authenticated, false otherwise.
     */
    public static <% if (reactive) { %>Mono<Boolean><% } else { %>boolean<% } %> isAuthenticated() {
<%_ if (reactive) { _%>
        return ReactiveSecurityContextHolder.getContext()
            .map(SecurityContext::getAuthentication)
            .map(Authentication::getAuthorities)
            .map(authorities -> authorities.stream()
                .map(GrantedAuthority::getAuthority)
                .noneMatch(AuthoritiesConstants.ANONYMOUS::equals)
            );
<%_ } else { _%>
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return authentication != null &&
            getAuthorities(authentication).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) { %>Mono<Boolean><% } else { %>boolean<% } %> hasCurrentUserAnyOfAuthorities(String... authorities) {
<%_ if (reactive) { _%>
        return ReactiveSecurityContextHolder.getContext()
            .map(SecurityContext::getAuthentication)
            .map(Authentication::getAuthorities)
            .map(authorityList -> authorityList.stream()
                .map(GrantedAuthority::getAuthority)
                .anyMatch(authority -> Arrays.asList(authorities).contains(authority))
            );
<%_ } else { _%>
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return (
            authentication != null && getAuthorities(authentication).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) { %>Mono<Boolean><% } else { %>boolean<% } %> hasCurrentUserNoneOfAuthorities(String... authorities) {
<%_ if (reactive) { _%>
        return hasCurrentUserAnyOfAuthorities(authorities).map(result -> !result);
<%_ } else { _%>
        return !hasCurrentUserAnyOfAuthorities(authorities);
<%_ } _%>
    }

    /**
     * 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) { %>Mono<Boolean><% } else { %>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());
    }
<%_ } _%>
<%_ if (useMultiTenant) { _%>

    public static Optional<Long> getTenantId() {
        SecurityContext securityContext = SecurityContextHolder.getContext();
        return Optional.ofNullable(null); // todo
    }
<%_ } _%>
<%_ if (generateAuthenticationApi && ((authenticationTypeOauth2 && !syncUserWithIdp) || (authenticationTypeJwt && skipUserManagement))) { _%>

    public static Map<String, Object> extractDetailsFromTokenAttributes(Map<String, Object> attributes) {
        Map<String, Object> details = new HashMap<>();

        details.put("activated", Optional.ofNullable(attributes.get(StandardClaimNames.EMAIL_VERIFIED)).orElse(true));
        Optional.ofNullable(attributes.get("uid")).ifPresent(id -> details.put("id", id));
        Optional.ofNullable(attributes.get(StandardClaimNames.FAMILY_NAME)).ifPresent(lastName -> details.put("lastName", lastName));
        Optional.ofNullable(attributes.get(StandardClaimNames.PICTURE)).ifPresent(imageUrl -> details.put("imageUrl", imageUrl));

        Optional.ofNullable(attributes.get(StandardClaimNames.GIVEN_NAME)).ifPresentOrElse(
            firstName -> details.put("firstName", firstName),
            () -> Optional.ofNullable(attributes.get(StandardClaimNames.NAME)).ifPresent(firstName -> details.put("firstName", firstName))
        );

        if (attributes.get(StandardClaimNames.EMAIL) != null) {
            details.put("email", attributes.get(StandardClaimNames.EMAIL));
        } else {
            String sub = String.valueOf(attributes.get(StandardClaimNames.SUB));
            String preferredUsername = (String) attributes.get(StandardClaimNames.PREFERRED_USERNAME);
            if (sub.contains("|") && (preferredUsername != null && preferredUsername.contains("@"))) {
                // special handling for Auth0
                details.put("email", preferredUsername);
            } else {
                details.put("email", sub);
            }
        }

        if (attributes.get("langKey") != null) {
            details.put("langKey", attributes.get("langKey"));
        } else if (attributes.get(StandardClaimNames.LOCALE) != null) {
            // trim off country code if it exists
            String locale = (String) attributes.get(StandardClaimNames.LOCALE);
            if (locale.contains("_")) {
                locale = locale.substring(0, locale.indexOf('_'));
            } else if (locale.contains("-")) {
                locale = locale.substring(0, locale.indexOf('-'));
            }
            details.put("langKey", locale.toLowerCase());
        } else {
            // set langKey to default if not specified by IdP
            details.put("langKey", Constants.DEFAULT_LANGUAGE);
        }

        return details;
    }
<%_ } _%>
}
