Search in sources :

Example 66 with SecurityContext

use of org.springframework.security.core.context.SecurityContext in project midpoint by Evolveum.

the class AbstractModelIntegrationTest method resetAuthentication.

protected void resetAuthentication() {
    SecurityContext securityContext = SecurityContextHolder.getContext();
    securityContext.setAuthentication(null);
}
Also used : SecurityContext(org.springframework.security.core.context.SecurityContext)

Example 67 with SecurityContext

use of org.springframework.security.core.context.SecurityContext in project dhis2-core by dhis2.

the class SpringSecurityActionAccessResolver method hasAccess.

// -------------------------------------------------------------------------
// ActionAccessResolver implementation
// -------------------------------------------------------------------------
@Override
public boolean hasAccess(String module, String name) {
    // ---------------------------------------------------------------------
    // Get ObjectDefinitionSource
    // ---------------------------------------------------------------------
    Configuration config = Dispatcher.getInstance().getConfigurationManager().getConfiguration();
    PackageConfig packageConfig = config.getPackageConfig(module);
    if (packageConfig == null) {
        throw new IllegalArgumentException("Module doesn't exist: '" + module + "'");
    }
    ActionConfig actionConfig = packageConfig.getActionConfigs().get(name);
    if (actionConfig == null) {
        throw new IllegalArgumentException("Module " + module + " doesn't have an action named: '" + name + "'");
    }
    SecurityMetadataSource securityMetadataSource = requiredAuthoritiesProvider.createSecurityMetadataSource(actionConfig);
    // ---------------------------------------------------------------------
    // Test access
    // ---------------------------------------------------------------------
    SecurityContext securityContext = SecurityContextHolder.getContext();
    Authentication authentication = securityContext.getAuthentication();
    try {
        if (securityMetadataSource.getAttributes(actionConfig) != null) {
            if (authentication == null || !authentication.isAuthenticated()) {
                return false;
            }
            accessDecisionManager.decide(authentication, actionConfig, securityMetadataSource.getAttributes(actionConfig));
        }
        log.debug("Access to [" + module + ", " + name + "]: TRUE");
        return true;
    } catch (AccessDeniedException e) {
        log.debug("Access to [" + module + ", " + name + "]: FALSE (access denied)");
        return false;
    } catch (InsufficientAuthenticationException e) {
        log.debug("Access to [" + module + ", " + name + "]: FALSE (insufficient authentication)");
        return false;
    }
}
Also used : ActionConfig(com.opensymphony.xwork2.config.entities.ActionConfig) AccessDeniedException(org.springframework.security.access.AccessDeniedException) Configuration(com.opensymphony.xwork2.config.Configuration) SecurityMetadataSource(org.springframework.security.access.SecurityMetadataSource) Authentication(org.springframework.security.core.Authentication) SecurityContext(org.springframework.security.core.context.SecurityContext) InsufficientAuthenticationException(org.springframework.security.authentication.InsufficientAuthenticationException) PackageConfig(com.opensymphony.xwork2.config.entities.PackageConfig)

Example 68 with SecurityContext

use of org.springframework.security.core.context.SecurityContext in project head by mifos.

the class MultipleLoanAccountsCreationActionStrutsTest method testCreate.

@SuppressWarnings("unchecked")
@Test
public void testCreate() throws Exception {
    SecurityContext securityContext = new SecurityContextImpl();
    MifosUser principal = new MifosUserBuilder().nonLoanOfficer().withAdminRole().build();
    Authentication authentication = new TestingAuthenticationToken(principal, principal);
    securityContext.setAuthentication(authentication);
    SecurityContextHolder.setContext(securityContext);
    EntityMasterData.getInstance().init();
    FieldConfig fieldConfig = FieldConfig.getInstance();
    fieldConfig.init();
    request.setAttribute(Constants.CURRENTFLOWKEY, flowKey);
    createInitialCustomers();
    LoanOfferingBO loanOffering = getLoanOffering("vcxvxc", "a123", ApplicableTo.CLIENTS, WEEKLY, EVERY_WEEK);
    setRequestPathInfo("/multipleloansaction.do");
    addRequestParameter("method", "get");
    addRequestParameter("branchOfficeId", center.getOffice().getOfficeId().toString());
    addRequestParameter("loanOfficerId", center.getPersonnel().getPersonnelId().toString());
    addRequestParameter("prdOfferingId", loanOffering.getPrdOfferingId().toString());
    SessionUtils.setAttribute(LoanConstants.IS_CENTER_HIERARCHY_EXISTS, Constants.YES, request);
    addRequestParameter("centerId", center.getCustomerId().toString());
    addRequestParameter("centerSearchId", center.getSearchId().toString());
    addRequestParameter(Constants.CURRENTFLOWKEY, flowKey);
    actionPerform();
    setRequestPathInfo("/multipleloansaction.do");
    addRequestParameter("clientDetails[0].loanAmount", loanOffering.getEligibleLoanAmountSameForAllLoan().getDefaultLoanAmount().toString());
    addRequestParameter(Constants.CURRENTFLOWKEY, (String) request.getAttribute(Constants.CURRENTFLOWKEY));
    addRequestParameter("stateSelected", "1");
    addRequestParameter("clientDetails[0].selected", "true");
    addRequestParameter(Constants.CURRENTFLOWKEY, (String) request.getAttribute(Constants.CURRENTFLOWKEY));
    addRequestParameter("method", "create");
    addRequestParameter("stateSelected", "1");
    actionPerform();
    verifyActionErrors(new String[] { LoanExceptionConstants.CUSTOMER_PURPOSE_OF_LOAN_FIELD });
    addRequestParameter("clientDetails[0].businessActivity", "0001");
    performNoErrors();
    verifyForward(ActionForwards.create_success.toString());
    List<String> accountNumbers = ((List<String>) request.getAttribute(LoanConstants.ACCOUNTS_LIST));
    Assert.assertEquals(1, accountNumbers.size());
    LoanBO loan = ApplicationContextProvider.getBean(LoanBusinessService.class).findBySystemId(accountNumbers.get(0));
    Assert.assertEquals(loanOffering.getEligibleLoanAmountSameForAllLoan().getDefaultLoanAmount().toString(), loan.getLoanAmount().toString());
    Assert.assertEquals(loanOffering.getDefInterestRate(), loan.getInterestRate());
    Assert.assertEquals(loanOffering.getEligibleInstallmentSameForAllLoan().getDefaultNoOfInstall(), loan.getNoOfInstallments());
    Assert.assertEquals(Short.valueOf("1"), loan.getGracePeriodDuration());
    Assert.assertEquals(Short.valueOf("1"), loan.getAccountState().getId());
    Assert.assertNull(request.getAttribute(Constants.CURRENTFLOWKEY));
    loan = null;
}
Also used : SecurityContextImpl(org.springframework.security.core.context.SecurityContextImpl) LoanBusinessService(org.mifos.accounts.loan.business.service.LoanBusinessService) Authentication(org.springframework.security.core.Authentication) FieldConfig(org.mifos.framework.components.fieldConfiguration.util.helpers.FieldConfig) LoanBO(org.mifos.accounts.loan.business.LoanBO) LoanAmountSameForAllLoanBO(org.mifos.accounts.productdefinition.business.LoanAmountSameForAllLoanBO) SecurityContext(org.springframework.security.core.context.SecurityContext) LoanOfferingBO(org.mifos.accounts.productdefinition.business.LoanOfferingBO) MifosUser(org.mifos.security.MifosUser) MifosUserBuilder(org.mifos.builders.MifosUserBuilder) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) Test(org.junit.Test)

Example 69 with SecurityContext

use of org.springframework.security.core.context.SecurityContext in project head by mifos.

the class LoanAccountActionStrutsTest method setMifosUserFromContext.

private void setMifosUserFromContext() {
    SecurityContext securityContext = new SecurityContextImpl();
    MifosUser principal = new MifosUser(userContext.getId(), userContext.getBranchId(), userContext.getLevelId(), new ArrayList<Short>(userContext.getRoles()), userContext.getName(), "".getBytes(), true, true, true, true, new ArrayList<GrantedAuthority>(), userContext.getLocaleId());
    Authentication authentication = new TestingAuthenticationToken(principal, principal);
    securityContext.setAuthentication(authentication);
    SecurityContextHolder.setContext(securityContext);
}
Also used : SecurityContextImpl(org.springframework.security.core.context.SecurityContextImpl) Authentication(org.springframework.security.core.Authentication) GrantedAuthority(org.springframework.security.core.GrantedAuthority) SecurityContext(org.springframework.security.core.context.SecurityContext) MifosUser(org.mifos.security.MifosUser) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken)

Example 70 with SecurityContext

use of org.springframework.security.core.context.SecurityContext in project head by mifos.

the class LoanBOTestUtils method createLoanAccount.

/**
     * Like
     * <b>createLoanAccountWithDisbursement(String, CustomerBO, AccountState, Date, LoanOfferingBO, int, Short)</b>
     * but differs in various ways.
     * <p/>
     * This test code needs to be refactored! By creating the loan with a
     * set of terms, then directly manipulating instance variables to completely
     * change the repayment schedule, it leaves the loan in an inconsistent
     * state, which leads one to suspect the validity of any of the 67 unit
     * tests that use it.
     *
     * It has been verified that setActionDate method calls in the loop below
     * will set the dates of the installments incorrectly for some if not all
     * cases. For certain classes of tests this doesn't matter, but for others
     * (involving verifying dates) it does. So BEWARE if you call down through
     * this method.
     *
     * @param globalNum
     */
public static LoanBO createLoanAccount(final String globalNum, final CustomerBO customer, final AccountState state, final Date startDate, final LoanOfferingBO loanOffering) {
    Calendar calendar = new GregorianCalendar();
    calendar.setTime(startDate);
    MeetingBO meeting = TestObjectFactory.createLoanMeeting(customer.getCustomerMeeting().getMeeting());
    List<Date> meetingDates = TestObjectFactory.getMeetingDates(customer.getOfficeId(), meeting, 6);
    MifosCurrency currency = loanOffering.getCurrency();
    AmountFeeBO maintanenceFee = (AmountFeeBO) TestObjectFactory.createPeriodicAmountFee("Mainatnence Fee", FeeCategory.LOAN, "100", RecurrenceType.WEEKLY, Short.valueOf("1"));
    IntegrationTestObjectMother.saveFee(maintanenceFee);
    BigDecimal loanAmount = BigDecimal.valueOf(DEFAULT_LOAN_AMOUNT);
    BigDecimal minAllowedLoanAmount = loanAmount;
    BigDecimal maxAllowedLoanAmount = loanAmount;
    Double interestRate = loanOffering.getDefInterestRate();
    LocalDate disbursementDate = new LocalDate(meetingDates.get(0));
    int numberOfInstallments = 6;
    int minAllowedNumberOfInstallments = loanOffering.getEligibleInstallmentSameForAllLoan().getMaxNoOfInstall();
    int maxAllowedNumberOfInstallments = loanOffering.getEligibleInstallmentSameForAllLoan().getMaxNoOfInstall();
    int graceDuration = 0;
    Integer sourceOfFundId = null;
    Integer loanPurposeId = null;
    Integer collateralTypeId = null;
    String collateralNotes = null;
    String externalId = null;
    boolean repaymentScheduleIndependentOfCustomerMeeting = false;
    RecurringSchedule recurringSchedule = null;
    List<CreateAccountFeeDto> accountFees = new ArrayList<CreateAccountFeeDto>();
    accountFees.add(new CreateAccountFeeDto(maintanenceFee.getFeeId().intValue(), maintanenceFee.getFeeAmount().toString()));
    CreateLoanAccount createLoanAccount = new CreateLoanAccount(customer.getCustomerId(), loanOffering.getPrdOfferingId().intValue(), state.getValue().intValue(), loanAmount, minAllowedLoanAmount, maxAllowedLoanAmount, interestRate, disbursementDate, null, numberOfInstallments, minAllowedNumberOfInstallments, maxAllowedNumberOfInstallments, graceDuration, sourceOfFundId, loanPurposeId, collateralTypeId, collateralNotes, externalId, repaymentScheduleIndependentOfCustomerMeeting, recurringSchedule, accountFees, new ArrayList<CreateAccountPenaltyDto>());
    SecurityContext securityContext = new SecurityContextImpl();
    MifosUser principal = new MifosUserBuilder().nonLoanOfficer().withAdminRole().build();
    Authentication authentication = new TestingAuthenticationToken(principal, principal);
    securityContext.setAuthentication(authentication);
    SecurityContextHolder.setContext(securityContext);
    LoanBO loan = IntegrationTestObjectMother.createClientLoan(createLoanAccount);
    loan.updateDetails(TestUtils.makeUser());
    AccountFeesEntity accountPeriodicFee = new AccountFeesEntity(loan, maintanenceFee, (maintanenceFee).getFeeAmount().getAmountDoubleValue());
    AccountTestUtils.addAccountFees(accountPeriodicFee, loan);
    loan.setLoanMeeting(meeting);
    short i = 0;
    for (Date date : meetingDates) {
        LoanScheduleEntity actionDate = (LoanScheduleEntity) loan.getAccountActionDate(++i);
        actionDate.setPrincipal(new Money(currency, "100.0"));
        actionDate.setInterest(new Money(currency, "12.0"));
        // the following line overwrites the correct loan schedule dates
        // with dates that are not correct!
        actionDate.setActionDate(new java.sql.Date(date.getTime()));
        actionDate.setPaymentStatus(PaymentStatus.UNPAID);
        AccountTestUtils.addAccountActionDate(actionDate, loan);
        AccountFeesActionDetailEntity accountFeesaction = new LoanFeeScheduleEntity(actionDate, maintanenceFee, accountPeriodicFee, new Money(currency, "100.0"));
        setFeeAmountPaid(accountFeesaction, new Money(currency, "0.0"));
        actionDate.addAccountFeesAction(accountFeesaction);
    }
    loan.setCreatedBy(Short.valueOf("1"));
    loan.setCreatedDate(new Date(System.currentTimeMillis()));
    setLoanSummary(loan, currency);
    return loan;
}
Also used : SecurityContextImpl(org.springframework.security.core.context.SecurityContextImpl) AccountFeesActionDetailEntity(org.mifos.accounts.business.AccountFeesActionDetailEntity) MeetingBO(org.mifos.application.meeting.business.MeetingBO) ArrayList(java.util.ArrayList) LocalDate(org.joda.time.LocalDate) Money(org.mifos.framework.util.helpers.Money) CreateLoanAccount(org.mifos.clientportfolio.newloan.applicationservice.CreateLoanAccount) CreateAccountPenaltyDto(org.mifos.dto.domain.CreateAccountPenaltyDto) CreateAccountFeeDto(org.mifos.dto.domain.CreateAccountFeeDto) AccountFeesEntity(org.mifos.accounts.business.AccountFeesEntity) MifosCurrency(org.mifos.application.master.business.MifosCurrency) GregorianCalendar(java.util.GregorianCalendar) Calendar(java.util.Calendar) GregorianCalendar(java.util.GregorianCalendar) MifosUser(org.mifos.security.MifosUser) MifosUserBuilder(org.mifos.builders.MifosUserBuilder) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) Date(java.util.Date) LocalDate(org.joda.time.LocalDate) AmountFeeBO(org.mifos.accounts.fees.business.AmountFeeBO) BigDecimal(java.math.BigDecimal) RecurringSchedule(org.mifos.clientportfolio.loan.service.RecurringSchedule) Authentication(org.springframework.security.core.Authentication) SecurityContext(org.springframework.security.core.context.SecurityContext)

Aggregations

SecurityContext (org.springframework.security.core.context.SecurityContext)138 Test (org.junit.Test)60 Authentication (org.springframework.security.core.Authentication)60 TestingAuthenticationToken (org.springframework.security.authentication.TestingAuthenticationToken)46 SecurityContextImpl (org.springframework.security.core.context.SecurityContextImpl)46 MifosUser (org.mifos.security.MifosUser)38 MifosUserBuilder (org.mifos.builders.MifosUserBuilder)29 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)19 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)19 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)16 HttpServletResponse (javax.servlet.http.HttpServletResponse)15 Before (org.junit.Before)15 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)15 GrantedAuthority (org.springframework.security.core.GrantedAuthority)11 ArrayList (java.util.ArrayList)8 HttpServletRequest (javax.servlet.http.HttpServletRequest)8 PrepareOnlyThisForTest (org.powermock.core.classloader.annotations.PrepareOnlyThisForTest)7 SessionDestroyedEvent (org.springframework.security.core.session.SessionDestroyedEvent)7 HttpSession (javax.servlet.http.HttpSession)6 MeetingBO (org.mifos.application.meeting.business.MeetingBO)5