Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ public final class GlobalConfigurationConstants {
public static final String ASSET_OWNER_TRANSFER_OUTSTANDING_INTEREST_CALCULATION_STRATEGY = "outstanding-interest-calculation-strategy-for-external-asset-transfer";
public static final String ALLOWED_LOAN_STATUSES_FOR_EXTERNAL_ASSET_TRANSFER = "allowed-loan-statuses-for-external-asset-transfer";
public static final String ALLOWED_LOAN_STATUSES_OF_DELAYED_SETTLEMENT_FOR_EXTERNAL_ASSET_TRANSFER = "allowed-loan-statuses-of-delayed-settlement-for-external-asset-transfer";
public static final String MAX_LOGIN_RETRY_ATTEMPTS = "max-login-retry-attempts";
public static final String ENABLE_ORIGINATOR_CREATION_DURING_LOAN_APPLICATION = "enable-originator-creation-during-loan-application";

private GlobalConfigurationConstants() {}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -151,4 +151,8 @@ public interface ConfigurationDomainService {
boolean isImmediateChargeAccrualPostMaturityEnabled();

String getAssetOwnerTransferOustandingInterestStrategy();

boolean isMaxLoginRetriesEnabled();

Integer retrieveMaxLoginRetries();
}
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,10 @@ public class AppUser extends AbstractPersistableCustom<Long> implements Platform
@Column(name = "nonlocked", nullable = false)
private boolean accountNonLocked;

@Getter
@Column(name = "failed_login_attempts", nullable = false)
private int failedLoginAttempts;

@Column(name = "nonexpired_credentials", nullable = false)
private boolean credentialsNonExpired;

Expand Down Expand Up @@ -174,6 +178,7 @@ protected AppUser() {
this.accountNonLocked = false;
this.credentialsNonExpired = false;
this.roles = new HashSet<>();
this.failedLoginAttempts = 0;
}

public AppUser(final Office office, final User user, final Set<Role> roles, final String email, final String firstname,
Expand All @@ -197,6 +202,7 @@ public AppUser(final Office office, final User user, final Set<Role> roles, fina
this.isSelfServiceUser = isSelfServiceUser;
this.appUserClientMappings = createAppUserClientMappings(clients);
this.cannotChangePassword = cannotChangePassword;
this.failedLoginAttempts = 0;
}

public EnumOptionData organisationalRoleData() {
Expand Down Expand Up @@ -429,6 +435,17 @@ public boolean isAccountNonLocked() {
return this.accountNonLocked;
}

public void registerFailedLoginAttempt(int maxRetries) {
this.failedLoginAttempts = this.failedLoginAttempts + 1;
if (maxRetries > 0 && this.failedLoginAttempts >= maxRetries) {
this.accountNonLocked = false;
}
}

public void resetFailedLoginAttempts() {
this.failedLoginAttempts = 0;
}

@Override
public boolean isCredentialsNonExpired() {
return this.credentialsNonExpired;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -548,4 +548,16 @@ public String getAssetOwnerTransferOustandingInterestStrategy() {
return getGlobalConfigurationPropertyData(
GlobalConfigurationConstants.ASSET_OWNER_TRANSFER_OUTSTANDING_INTEREST_CALCULATION_STRATEGY).getStringValue();
}

@Override
public boolean isMaxLoginRetriesEnabled() {
return getGlobalConfigurationPropertyData(GlobalConfigurationConstants.MAX_LOGIN_RETRY_ATTEMPTS).isEnabled();
}

@Override
public Integer retrieveMaxLoginRetries() {
final GlobalConfigurationPropertyData property = getGlobalConfigurationPropertyData(
GlobalConfigurationConstants.MAX_LOGIN_RETRY_ATTEMPTS);
return property.getValue() == null ? null : property.getValue().intValue();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.infrastructure.security.service;

import lombok.RequiredArgsConstructor;
import org.apache.fineract.infrastructure.configuration.domain.ConfigurationDomainService;
import org.apache.fineract.useradministration.domain.AppUser;
import org.apache.fineract.useradministration.domain.AppUserRepository;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.context.event.EventListener;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.authentication.event.AbstractAuthenticationFailureEvent;
import org.springframework.security.authentication.event.AuthenticationSuccessEvent;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

@Component
@RequiredArgsConstructor
public class LoginAttemptEventListener {

private static final String USERS_CACHE = "users";
private static final String USERS_BY_USERNAME_CACHE = "usersByUsername";

private final ConfigurationDomainService configurationDomainService;
private final AppUserRepository appUserRepository;
private final CacheManager cacheManager;

@Transactional
@EventListener
public void onAuthenticationFailure(final AbstractAuthenticationFailureEvent event) {
if (!configurationDomainService.isMaxLoginRetriesEnabled()) {
return;
}
final Integer maxRetries = configurationDomainService.retrieveMaxLoginRetries();
if (maxRetries == null || maxRetries <= 0) {
return;
}

Authentication authentication = event.getAuthentication();
if (authentication == null || !StringUtils.hasText(authentication.getName())) {
return;
}

AuthenticationException exception = event.getException();
if (exception instanceof LockedException) {
return;
}

AppUser user = appUserRepository.findAppUserByName(authentication.getName());
if (user == null || !user.isAccountNonLocked()) {
return;
}

user.registerFailedLoginAttempt(maxRetries);
appUserRepository.saveAndFlush(user);
evictUserCaches();
}

@Transactional
@EventListener
public void onAuthenticationSuccess(final AuthenticationSuccessEvent event) {
Authentication authentication = event.getAuthentication();
if (authentication == null || !(authentication.getPrincipal() instanceof AppUser user)) {
return;
}

if (user.getFailedLoginAttempts() <= 0) {
return;
}

user.resetFailedLoginAttempts();
appUserRepository.saveAndFlush(user);
evictUserCaches();
}

private void evictUserCaches() {
Cache usersCache = cacheManager.getCache(USERS_CACHE);
if (usersCache != null) {
usersCache.clear();
}
Cache usersByUsernameCache = cacheManager.getCache(USERS_BY_USERNAME_CACHE);
if (usersByUsernameCache != null) {
usersByUsernameCache.clear();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -227,4 +227,5 @@
<include file="parts/0206_transaction_summary_with_asset_owner_classification_name_bug_fix.xml" relativeToChangelogFile="true" />
<include file="parts/0207_add_allow_full_term_for_tranche.xml" relativeToChangelogFile="true" />
<include file="parts/0208_trial_balance_summary_with_asset_owner_journal_entry_aggregation_fix.xml" relativeToChangelogFile="true" />
<include file="parts/0209_add_login_retry_configuration.xml" relativeToChangelogFile="true" />
</databaseChangeLog>
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
<!--

Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.

-->
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-4.3.xsd">
<changeSet author="fineract" id="1" context="postgresql">
<sql>
SELECT SETVAL('c_configuration_id_seq', COALESCE(MAX(id), 0)+1, false ) FROM c_configuration;
</sql>
</changeSet>
<changeSet author="fineract" id="2">
<addColumn tableName="m_appuser">
<column name="failed_login_attempts" type="INT" defaultValueNumeric="0">
<constraints nullable="false"/>
</column>
</addColumn>
</changeSet>
<changeSet author="fineract" id="3">
<insert tableName="c_configuration">
<column name="name" value="max-login-retry-attempts"/>
<column name="value" valueNumeric="5"/>
<column name="date_value"/>
<column name="string_value"/>
<column name="enabled" valueBoolean="false"/>
<column name="is_trap_door" valueBoolean="false"/>
<column name="description" value="Maximum number of failed login attempts before an account is locked"/>
</insert>
</changeSet>
</databaseChangeLog>
Original file line number Diff line number Diff line change
Expand Up @@ -18436,6 +18436,7 @@ <h3>Global Configuration</h3>
<li><b>savings-interest-posting-current-period-end</b> - Set it at the database level before any savings interest is posted. When set as false(default), interest will be posted on the first date of next period. If set as true, interest will be posted on last date of current period. There is no difference in the interest amount posted.</li>
<li><b>financial-year-beginning-month</b> - Set it at the database level before any savings interest is posted. Allowed values 1 - 12 (January - December). Interest posting periods are evaluated based on this configuration.</li>
<li><b>meetings-mandatory-for-jlg-loans</b> - if set to true, enforces all JLG loans to follow a meeting schedule belonging to either the parent group or Center.</li>
<li><b>max-login-retry-attempts</b> - defaults to 5 - when enabled, limits failed login attempts and locks the user after N failed attempts.</li>
</ol>
</div>
</div>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.infrastructure.security.service;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;

import java.util.HashSet;
import java.util.List;
import org.apache.fineract.infrastructure.configuration.domain.ConfigurationDomainService;
import org.apache.fineract.infrastructure.core.domain.FineractPlatformTenant;
import org.apache.fineract.infrastructure.core.service.ThreadLocalContextUtil;
import org.apache.fineract.organisation.office.domain.Office;
import org.apache.fineract.useradministration.domain.AppUser;
import org.apache.fineract.useradministration.domain.AppUserRepository;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.event.AuthenticationFailureBadCredentialsEvent;
import org.springframework.security.authentication.event.AuthenticationSuccessEvent;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;

@ExtendWith(MockitoExtension.class)
class LoginAttemptEventListenerTest {

@Mock
private ConfigurationDomainService configurationDomainService;
@Mock
private AppUserRepository appUserRepository;
@Mock
private CacheManager cacheManager;
@Mock
private Cache usersCache;
@Mock
private Cache usersByUsernameCache;

private LoginAttemptEventListener listener;

@BeforeEach
void setUp() {
ThreadLocalContextUtil
.setTenant(FineractPlatformTenant.builder().id(1L).tenantIdentifier("default").name("default").timezoneId("UTC").build());
listener = new LoginAttemptEventListener(configurationDomainService, appUserRepository, cacheManager);
}

@AfterEach
void tearDown() {
ThreadLocalContextUtil.reset();
}

@Test
void shouldIncrementFailedAttemptsAndLockAccountWhenMaxReached() {
when(configurationDomainService.isMaxLoginRetriesEnabled()).thenReturn(true);
when(configurationDomainService.retrieveMaxLoginRetries()).thenReturn(3);
when(cacheManager.getCache("users")).thenReturn(usersCache);
when(cacheManager.getCache("usersByUsername")).thenReturn(usersByUsernameCache);

AppUser user = buildUser("user");
when(appUserRepository.findAppUserByName("user")).thenReturn(user);

AuthenticationFailureBadCredentialsEvent failureEvent = new AuthenticationFailureBadCredentialsEvent(
new UsernamePasswordAuthenticationToken("user", "bad"), new BadCredentialsException("bad"));

listener.onAuthenticationFailure(failureEvent);
listener.onAuthenticationFailure(failureEvent);
listener.onAuthenticationFailure(failureEvent);

assertEquals(3, user.getFailedLoginAttempts());
assertFalse(user.isAccountNonLocked());
verify(appUserRepository, times(3)).saveAndFlush(user);
}

@Test
void shouldResetFailedAttemptsOnSuccessfulLogin() {
AppUser user = buildUser("user");
user.registerFailedLoginAttempt(10);
user.registerFailedLoginAttempt(10);
when(cacheManager.getCache("users")).thenReturn(usersCache);
when(cacheManager.getCache("usersByUsername")).thenReturn(usersByUsernameCache);

AuthenticationSuccessEvent successEvent = new AuthenticationSuccessEvent(
new UsernamePasswordAuthenticationToken(user, "pass", user.getAuthorities()));

listener.onAuthenticationSuccess(successEvent);

assertEquals(0, user.getFailedLoginAttempts());
assertTrue(user.isAccountNonLocked());
verify(appUserRepository).saveAndFlush(user);
}

@Test
void shouldNotUpdateWhenLimitDisabled() {
when(configurationDomainService.isMaxLoginRetriesEnabled()).thenReturn(false);

AuthenticationFailureBadCredentialsEvent failureEvent = new AuthenticationFailureBadCredentialsEvent(
new UsernamePasswordAuthenticationToken("user", "bad"), new BadCredentialsException("bad"));

listener.onAuthenticationFailure(failureEvent);

verifyNoInteractions(appUserRepository);
verifyNoInteractions(cacheManager);
}

private AppUser buildUser(String username) {
Office office = mock(Office.class);
User springUser = new User(username, "pass", true, true, true, true, List.of(new SimpleGrantedAuthority("ALL_FUNCTIONS")));
return new AppUser(office, springUser, new HashSet<>(), "user@example.com", "First", "Last", null, false, false, null, false);
}
}
Loading
Loading