resolveInternal(RequestContext)   F
last analyzed

Complexity

Conditions 12

Size

Total Lines 58

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 58
c 0
b 0
f 0
cc 12
rs 3.1729

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

Complexity

Complex classes like org.apereo.cas.web.flow.resolver.impl.mfa.GroovyScriptMultifactorAuthenticationPolicyEventResolver.resolveInternal(RequestContext) often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
package org.apereo.cas.web.flow.resolver.impl.mfa;
2
3
import org.apache.commons.lang3.StringUtils;
4
import org.apereo.cas.CentralAuthenticationService;
5
import org.apereo.cas.authentication.Authentication;
6
import org.apereo.cas.authentication.AuthenticationException;
7
import org.apereo.cas.authentication.AuthenticationServiceSelectionPlan;
8
import org.apereo.cas.authentication.AuthenticationSystemSupport;
9
import org.apereo.cas.authentication.MultifactorAuthenticationUtils;
10
import org.apereo.cas.authentication.principal.Service;
11
import org.apereo.cas.configuration.CasConfigurationProperties;
12
import org.apereo.cas.services.MultifactorAuthenticationProvider;
13
import org.apereo.cas.services.MultifactorAuthenticationProviderSelector;
14
import org.apereo.cas.services.RegisteredService;
15
import org.apereo.cas.services.ServicesManager;
16
import org.apereo.cas.ticket.registry.TicketRegistrySupport;
17
import org.apereo.cas.util.CollectionUtils;
18
import org.apereo.cas.util.ResourceUtils;
19
import org.apereo.cas.util.ScriptingUtils;
20
import org.apereo.cas.web.flow.authentication.BaseMultifactorAuthenticationProviderEventResolver;
21
import org.apereo.cas.web.support.WebUtils;
22
import org.slf4j.Logger;
23
import org.slf4j.LoggerFactory;
24
import org.springframework.core.io.Resource;
25
import org.springframework.web.util.CookieGenerator;
26
import org.springframework.webflow.execution.Event;
27
import org.springframework.webflow.execution.RequestContext;
28
29
import java.util.Map;
30
import java.util.Optional;
31
import java.util.Set;
32
33
/**
34
 * This is {@link GroovyScriptMultifactorAuthenticationPolicyEventResolver}
35
 * that conditionally evaluates a groovy script to resolve the mfa provider id
36
 * and event.
37
 *
38
 * @author Misagh Moayyed
39
 * @since 5.1.0
40
 */
41
public class GroovyScriptMultifactorAuthenticationPolicyEventResolver extends BaseMultifactorAuthenticationProviderEventResolver {
42
    private static final Logger LOGGER = LoggerFactory.getLogger(GroovyScriptMultifactorAuthenticationPolicyEventResolver.class);
43
44
    private final Resource groovyScript;
45
46
    public GroovyScriptMultifactorAuthenticationPolicyEventResolver(final AuthenticationSystemSupport authenticationSystemSupport,
47
                                                                    final CentralAuthenticationService centralAuthenticationService,
48
                                                                    final ServicesManager servicesManager,
49
                                                                    final TicketRegistrySupport ticketRegistrySupport,
50
                                                                    final CookieGenerator warnCookieGenerator,
51
                                                                    final AuthenticationServiceSelectionPlan authenticationSelectionStrategies,
52
                                                                    final MultifactorAuthenticationProviderSelector selector,
53
                                                                    final CasConfigurationProperties casProperties) {
54
        super(authenticationSystemSupport, centralAuthenticationService, servicesManager,
55
                ticketRegistrySupport, warnCookieGenerator,
56
                authenticationSelectionStrategies, selector);
57
        groovyScript = casProperties.getAuthn().getMfa().getGroovyScript();
58
    }
59
60
    @Override
61
    public Set<Event> resolveInternal(final RequestContext context) {
62
        final Service service = resolveServiceFromAuthenticationRequest(context);
63
        final RegisteredService registeredService = resolveRegisteredServiceInRequestContext(context);
64
        final Authentication authentication = WebUtils.getAuthentication(context);
65
66
        if (groovyScript == null) {
67
            LOGGER.debug("No groovy script is configured for multifactor authentication");
68
            return null;
69
        }
70
71
        if (!ResourceUtils.doesResourceExist(groovyScript)) {
72
            LOGGER.warn("No groovy script is found at [{}] for multifactor authentication", groovyScript);
73
            return null;
74
        }
75
        
76
        if (authentication == null) {
77
            LOGGER.debug("No authentication is available to determine event for principal");
78
            return null;
79
        }
80
        if (registeredService == null || service == null) {
81
            LOGGER.debug("No registered service is available to determine event for principal [{}]", authentication.getPrincipal());
82
            return null;
83
        }
84
85
        final Map<String, MultifactorAuthenticationProvider> providerMap =
86
                MultifactorAuthenticationUtils.getAvailableMultifactorAuthenticationProviders(this.applicationContext);
87
        if (providerMap == null || providerMap.isEmpty()) {
88
            LOGGER.error("No multifactor authentication providers are available in the application context");
89
            throw new AuthenticationException();
90
        }
91
92
        try {
93
            final Object[] args = {service, registeredService, authentication, LOGGER};
94
            final String provider = ScriptingUtils.executeGroovyScript(groovyScript, args, String.class);
95
            LOGGER.debug("Groovy script run for [{}] returned the provider id [{}]", service, provider);
96
            if (StringUtils.isBlank(provider)) {
97
                return null;
98
            }
99
100
            final Optional<MultifactorAuthenticationProvider> providerFound = resolveProvider(providerMap, provider);
101
            if (providerFound.isPresent()) {
102
                final MultifactorAuthenticationProvider multifactorAuthenticationProvider = providerFound.get();
103
                if (multifactorAuthenticationProvider.isAvailable(registeredService)) {
104
                    final Event event = validateEventIdForMatchingTransitionInContext(multifactorAuthenticationProvider.getId(), context,
105
                            buildEventAttributeMap(authentication.getPrincipal(), registeredService, multifactorAuthenticationProvider));
106
                    return CollectionUtils.wrapSet(event);
107
                }
108
                LOGGER.warn("Located multifactor provider [{}], yet the provider cannot be reached or verified", multifactorAuthenticationProvider);
109
                return null;
110
            }
111
            LOGGER.warn("No multifactor provider could be found for [{}]", provider);
112
            throw new AuthenticationException();
113
114
        } catch (final Exception e) {
115
            LOGGER.error(e.getMessage(), e);
116
        }
117
        return null;
118
    }
119
}
120