package com.digirati.elucidate.infrastructure.security.impl;

import com.digirati.elucidate.infrastructure.security.UserSecurityDetails;
import com.digirati.elucidate.infrastructure.security.UserSecurityDetailsLoader;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.provider.token.DefaultUserAuthenticationConverter;

import java.util.Collections;
import java.util.List;
import java.util.Map;

public final class JwtUserAuthenticationConverter extends DefaultUserAuthenticationConverter {

    private List<String> uidProperties;
    private UserSecurityDetailsLoader securityDetailsLoader;

    public JwtUserAuthenticationConverter(List<String> uidProperties, UserSecurityDetailsLoader securityDetailsLoader) {
        this.uidProperties = uidProperties;
        this.securityDetailsLoader = securityDetailsLoader;
    }

    @Override
    public Authentication extractAuthentication(Map<String, ?> details) {
        return uidProperties.stream()
            .filter(details::containsKey)
            .map(prop -> (String) details.get(prop))
            .findFirst()
            .map(uid -> {
                UserSecurityDetails securityDetails = securityDetailsLoader.findOrCreateUserDetails(uid);
                Authentication auth = new UsernamePasswordAuthenticationToken(
                    securityDetails,
                    "N/A",
                    Collections.emptySet()
                );

                return auth;
            })
            .orElse(null);
    }
}

@@ -211,16 +211,120 @@
 Loader;%0A
+import java.util.Collection;%0Aimport java.util.Collections;%0Aimport java.util.List;%0Aimport java.util.Map;%0A
 import o
@@ -500,140 +500,190 @@
 ity.
-oauth2.provider.token.DefaultUserAuthenticationConverter;%0A%0Aimport java.util.Collections;%0Aimport java.util.List;%0Aimport java.util.Map
+core.GrantedAuthority;%0Aimport org.springframework.security.core.authority.AuthorityUtils;%0Aimport org.springframework.security.oauth2.provider.token.DefaultUserAuthenticationConverter
 ;%0A%0Ap
@@ -1489,16 +1489,335 @@
 s(uid);%0A
+                Collection%3CString%3E roles = (Collection%3CString%3E) details.get(AUTHORITIES);%0A%0A                if (roles == null) %7B%0A                    roles = Collections.emptyList();%0A                %7D%0A%0A                List%3CGrantedAuthority%3E authorities = AuthorityUtils.createAuthorityList(roles.toArray(new String%5B0%5D));%0A
         
@@ -1975,30 +1975,19 @@
     
-Collections.emptySet()
+authorities
 %0A   

Fix decoding of admin authorities from access tokens