<commit_before>/**
 * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
 * If a copy of the MPL was not distributed with this file, You can obtain one at
 * http://mozilla.org/MPL/2.0/.
 *
 * This Source Code Form is also subject to the terms of the Health-Related Additional
 * Disclaimer of Warranty and Limitation of Liability available at
 * http://www.carewebframework.org/licensing/disclaimer.
 */
package org.carewebframework.vista.security.base;

import java.util.List;

import ca.uhn.fhir.model.dstu.resource.User;

import org.apache.commons.lang.StringUtils;

import org.carewebframework.api.domain.DomainFactoryRegistry;
import org.carewebframework.api.domain.IUser;
import org.carewebframework.cal.api.domain.UserProxy;
import org.carewebframework.security.spring.AbstractAuthenticationProvider;
import org.carewebframework.security.spring.AuthenticationCancelledException;
import org.carewebframework.vista.api.util.VistAUtil;
import org.carewebframework.vista.mbroker.BrokerSession;
import org.carewebframework.vista.mbroker.Security;
import org.carewebframework.vista.mbroker.Security.AuthResult;

import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;

/**
 * Provides authentication support for the framework. Takes provided authentication credentials and
 * authenticates them against the database.
 */
public class BaseAuthenticationProvider extends AbstractAuthenticationProvider {
    
    private BrokerSession brokerSession;
    
    public BaseAuthenticationProvider() {
        super(false);
    }
    
    protected BaseAuthenticationProvider(boolean debugRole) {
        super(debugRole);
    }
    
    protected BaseAuthenticationProvider(List<String> grantedAuthorities) {
        super(grantedAuthorities);
    }
    
    /**
     * Performs user authentication.
     *
     * @param username Username for the login.
     * @param password Password for the login (ignored if the user is pre-authenticated).
     * @param domain Domain for which the login is requested.
     * @return Authorization result
     */
    @Override
    protected IUser authenticate(String username, String password, String domain) {
        AuthResult authResult = Security.authenticate(brokerSession, username, password, domain);
        IUser user = getAuthenticatedUser();
        checkAuthResult(authResult, user);
        return user;
    }
    
    @Override
    protected List<String> getAuthorities(IUser user) {
        return user == null ? null : VistAUtil.getBrokerSession().callRPCList("RGCWFUSR GETPRIV", null, user.getLogicalId());
    }
    
    private IUser getAuthenticatedUser() {
        try {
            User user = brokerSession.isAuthenticated() ? DomainFactoryRegistry.fetchObject(User.class,
                Integer.toString(brokerSession.getUserId())) : null;
            return user == null ? null : new UserProxy(user);
        } catch (Exception e) {
            return null;
        }
    }
    
    @SuppressWarnings("deprecation")
    private void checkAuthResult(AuthResult result, IUser user) throws AuthenticationException {
        switch (result.status) {
            case SUCCESS:
                return;
                
            case CANCELED:
                throw new AuthenticationCancelledException(StringUtils.defaultIfEmpty(result.reason,<commit_msg>Security refactoring.<commit_after>/**
 * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
 * If a copy of the MPL was not distributed with this file, You can obtain one at
 * http://mozilla.org/MPL/2.0/.
 *
 * This Source Code Form is also subject to the terms of the Health-Related Additional
 * Disclaimer of Warranty and Limitation of Liability available at
 * http://www.carewebframework.org/licensing/disclaimer.
 */
package org.carewebframework.vista.security.base;

import java.util.List;

import ca.uhn.fhir.model.dstu.resource.User;

import org.apache.commons.lang.StringUtils;

import org.carewebframework.api.domain.DomainFactoryRegistry;
import org.carewebframework.api.domain.IUser;
import org.carewebframework.api.security.ISecurityDomain;
import org.carewebframework.cal.api.domain.UserProxy;
import org.carewebframework.security.spring.AbstractAuthenticationProvider;
import org.carewebframework.security.spring.AuthenticationCancelledException;
import org.carewebframework.vista.api.util.VistAUtil;
import org.carewebframework.vista.mbroker.BrokerSession;
import org.carewebframework.vista.mbroker.Security;
import org.carewebframework.vista.mbroker.Security.AuthResult;

import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;

/**
 * Provides authentication support for the framework. Takes provided authentication credentials and
 * authenticates them against the database.
 */
public class BaseAuthenticationProvider extends AbstractAuthenticationProvider {
    
    private BrokerSession brokerSession;
    
    public BaseAuthenticationProvider() {
        super(false);
    }
    
    protected BaseAuthenticationProvider(boolean debugRole) {
        super(debugRole);
    }
    
    protected BaseAuthenticationProvider(List<String> grantedAuthorities) {
        super(grantedAuthorities);
    }
    
    /**
     * Performs user authentication.
     *
     * @param username Username for the login.
     * @param password Password for the login (ignored if the user is pre-authenticated).
     * @param domain Domain for which the login is requested.
     * @return Authorization result
     */
    @Override
    protected IUser authenticate(String username, String password, ISecurityDomain domain) {
        AuthResult authResult = Security.authenticate(brokerSession, username, password, domain.getLogicalId());
        IUser user = getAuthenticatedUser();
        checkAuthResult(authResult, user);
        return user;
    }
    
    @Override
    protected List<String> getAuthorities(IUser user) {
        return user == null ? null : VistAUtil.getBrokerSession().callRPCList("RGCWFUSR GETPRIV", null, user.getLogicalId());
    }
    
    private IUser getAuthenticatedUser() {
        try {
            User user = brokerSession.isAuthenticated() ? DomainFactoryRegistry.fetchObject(User.class,
                Integer.toString(brokerSession.getUserId())) : null;
            return user == null ? null : new UserProxy(user);
        } catch (Exception e) {
            return null;
        }
    }
    
    @SuppressWarnings("deprecation")
    private void checkAuthResult(AuthResult result, IUser user) throws AuthenticationException {
        switch (result.status) {
            case SUCCESS:
                return;
                
            case CANCELED:
                throw new AuthenticationCancelledException(StringUtils.defaultIfEmpty(result.reason,
{'fraction_non_alphanumeric': 0.08051420838971583, 'fraction_numerical': 0.0010825439783491205, 'mean_word_length': 3.6425879396984926, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2504397', 'n_tokens_mistral': 1919, 'n_tokens_neox': 1904, 'n_words': 478}