package io.quarkus.security.runtime.interceptor.check;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;

import io.quarkus.security.ForbiddenException;
import io.quarkus.security.UnauthorizedException;
import io.quarkus.security.identity.SecurityIdentity;

public class RolesAllowedCheck implements SecurityCheck {

    /*
     * The reason we want to cache RolesAllowedCheck is that it is very common
     * to have a lot of methods using the same roles in the security check
     * In such cases there is no need to have multiple instances of the class hanging around
     * for the entire lifecycle of the application
     */
    private static final Map<List<String>, RolesAllowedCheck> CACHE = new ConcurrentHashMap<>();

    private final String[] allowedRoles;

    private RolesAllowedCheck(String[] allowedRoles) {
        this.allowedRoles = allowedRoles;
    }

    public static RolesAllowedCheck of(String[] allowedRoles) {
        return CACHE.computeIfAbsent(Arrays.asList(allowedRoles), new Function<List<String>, RolesAllowedCheck>() {
            @Override
            public RolesAllowedCheck apply(List<String> allowedRolesList) {
                return new RolesAllowedCheck(allowedRolesList.toArray(new String[0]));
            }
        });
    }

    @Override
    public void apply(SecurityIdentity identity) {
        Set<String> roles = identity.getRoles();
        if (roles != null) {
            for (String role : allowedRoles) {
                if (roles.contains(role)) {
                    return;
                }
            }
        }
        if (identity.isAnonymous()) {
            throw new UnauthorizedException();
        } else {
            throw new ForbiddenException();
        }
    }
}

@@ -91,19 +91,81 @@
 va.util.
-Lis
+Collection;%0Aimport java.util.Collections;%0Aimport java.util.HashSe
 t;%0Aimpor
@@ -840,20 +840,26 @@
 nal Map%3C
-List
+Collection
 %3CString%3E
@@ -1166,21 +1166,27 @@
 ent(
-Arrays.asList
+getCollectionForKey
 (all
@@ -1210,20 +1210,26 @@
 unction%3C
-List
+Collection
 %3CString%3E
@@ -1318,20 +1318,26 @@
 k apply(
-List
+Collection
 %3CString%3E
@@ -1473,24 +1473,501 @@
  %7D);%0A    %7D%0A%0A
+    private static Collection%3CString%3E getCollectionForKey(String%5B%5D allowedRoles) %7B%0A        if (allowedRoles.length == 0) %7B // shouldn't happen, but lets be on the safe side%0A            return Collections.emptyList();%0A        %7D else if (allowedRoles.length == 1) %7B%0A            return Collections.singletonList(allowedRoles%5B0%5D);%0A        %7D%0A        // use a set in order to avoid caring about the order of elements%0A        return new HashSet%3C%3E(Arrays.asList(allowedRoles));%0A    %7D%0A%0A
     @Overrid

Make some micro-optimizations to @RolesAllowed CDI handling