Skip to content

Commit b44c9df

Browse files
committed
FINERACT-2004: Limit login retries
1 parent ef12056 commit b44c9df

File tree

10 files changed

+344
-0
lines changed

10 files changed

+344
-0
lines changed

fineract-core/src/main/java/org/apache/fineract/infrastructure/configuration/api/GlobalConfigurationConstants.java

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,8 @@ public final class GlobalConfigurationConstants {
7979
public static final String ASSET_OWNER_TRANSFER_OUTSTANDING_INTEREST_CALCULATION_STRATEGY = "outstanding-interest-calculation-strategy-for-external-asset-transfer";
8080
public static final String ALLOWED_LOAN_STATUSES_FOR_EXTERNAL_ASSET_TRANSFER = "allowed-loan-statuses-for-external-asset-transfer";
8181
public static final String ALLOWED_LOAN_STATUSES_OF_DELAYED_SETTLEMENT_FOR_EXTERNAL_ASSET_TRANSFER = "allowed-loan-statuses-of-delayed-settlement-for-external-asset-transfer";
82+
public static final String MAX_LOGIN_RETRY_ATTEMPTS = "max-login-retry-attempts";
83+
public static final String ENABLE_ORIGINATOR_CREATION_DURING_LOAN_APPLICATION = "enable-originator-creation-during-loan-application";
8284

8385
private GlobalConfigurationConstants() {}
8486
}

fineract-core/src/main/java/org/apache/fineract/infrastructure/configuration/domain/ConfigurationDomainService.java

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,4 +151,8 @@ public interface ConfigurationDomainService {
151151
boolean isImmediateChargeAccrualPostMaturityEnabled();
152152

153153
String getAssetOwnerTransferOustandingInterestStrategy();
154+
155+
boolean isMaxLoginRetriesEnabled();
156+
157+
Integer retrieveMaxLoginRetries();
154158
}

fineract-core/src/main/java/org/apache/fineract/useradministration/domain/AppUser.java

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,10 @@ public class AppUser extends AbstractPersistableCustom<Long> implements Platform
8686
@Column(name = "nonlocked", nullable = false)
8787
private boolean accountNonLocked;
8888

89+
@Getter
90+
@Column(name = "failed_login_attempts", nullable = false)
91+
private int failedLoginAttempts;
92+
8993
@Column(name = "nonexpired_credentials", nullable = false)
9094
private boolean credentialsNonExpired;
9195

@@ -174,6 +178,7 @@ protected AppUser() {
174178
this.accountNonLocked = false;
175179
this.credentialsNonExpired = false;
176180
this.roles = new HashSet<>();
181+
this.failedLoginAttempts = 0;
177182
}
178183

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

202208
public EnumOptionData organisationalRoleData() {
@@ -429,6 +435,17 @@ public boolean isAccountNonLocked() {
429435
return this.accountNonLocked;
430436
}
431437

438+
public void registerFailedLoginAttempt(int maxRetries) {
439+
this.failedLoginAttempts = this.failedLoginAttempts + 1;
440+
if (maxRetries > 0 && this.failedLoginAttempts >= maxRetries) {
441+
this.accountNonLocked = false;
442+
}
443+
}
444+
445+
public void resetFailedLoginAttempts() {
446+
this.failedLoginAttempts = 0;
447+
}
448+
432449
@Override
433450
public boolean isCredentialsNonExpired() {
434451
return this.credentialsNonExpired;

fineract-provider/src/main/java/org/apache/fineract/infrastructure/configuration/domain/ConfigurationDomainServiceJpa.java

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -548,4 +548,16 @@ public String getAssetOwnerTransferOustandingInterestStrategy() {
548548
return getGlobalConfigurationPropertyData(
549549
GlobalConfigurationConstants.ASSET_OWNER_TRANSFER_OUTSTANDING_INTEREST_CALCULATION_STRATEGY).getStringValue();
550550
}
551+
552+
@Override
553+
public boolean isMaxLoginRetriesEnabled() {
554+
return getGlobalConfigurationPropertyData(GlobalConfigurationConstants.MAX_LOGIN_RETRY_ATTEMPTS).isEnabled();
555+
}
556+
557+
@Override
558+
public Integer retrieveMaxLoginRetries() {
559+
final GlobalConfigurationPropertyData property = getGlobalConfigurationPropertyData(
560+
GlobalConfigurationConstants.MAX_LOGIN_RETRY_ATTEMPTS);
561+
return property.getValue() == null ? null : property.getValue().intValue();
562+
}
551563
}
Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
/**
2+
* Licensed to the Apache Software Foundation (ASF) under one
3+
* or more contributor license agreements. See the NOTICE file
4+
* distributed with this work for additional information
5+
* regarding copyright ownership. The ASF licenses this file
6+
* to you under the Apache License, Version 2.0 (the
7+
* "License"); you may not use this file except in compliance
8+
* with the License. You may obtain a copy of the License at
9+
*
10+
* http://www.apache.org/licenses/LICENSE-2.0
11+
*
12+
* Unless required by applicable law or agreed to in writing,
13+
* software distributed under the License is distributed on an
14+
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15+
* KIND, either express or implied. See the License for the
16+
* specific language governing permissions and limitations
17+
* under the License.
18+
*/
19+
package org.apache.fineract.infrastructure.security.service;
20+
21+
import lombok.RequiredArgsConstructor;
22+
import org.apache.fineract.infrastructure.configuration.domain.ConfigurationDomainService;
23+
import org.apache.fineract.useradministration.domain.AppUser;
24+
import org.apache.fineract.useradministration.domain.AppUserRepository;
25+
import org.springframework.cache.Cache;
26+
import org.springframework.cache.CacheManager;
27+
import org.springframework.context.event.EventListener;
28+
import org.springframework.security.authentication.LockedException;
29+
import org.springframework.security.authentication.event.AbstractAuthenticationFailureEvent;
30+
import org.springframework.security.authentication.event.AuthenticationSuccessEvent;
31+
import org.springframework.security.core.Authentication;
32+
import org.springframework.security.core.AuthenticationException;
33+
import org.springframework.stereotype.Component;
34+
import org.springframework.transaction.annotation.Transactional;
35+
import org.springframework.util.StringUtils;
36+
37+
@Component
38+
@RequiredArgsConstructor
39+
public class LoginAttemptEventListener {
40+
41+
private static final String USERS_CACHE = "users";
42+
private static final String USERS_BY_USERNAME_CACHE = "usersByUsername";
43+
44+
private final ConfigurationDomainService configurationDomainService;
45+
private final AppUserRepository appUserRepository;
46+
private final CacheManager cacheManager;
47+
48+
@Transactional
49+
@EventListener
50+
public void onAuthenticationFailure(final AbstractAuthenticationFailureEvent event) {
51+
if (!configurationDomainService.isMaxLoginRetriesEnabled()) {
52+
return;
53+
}
54+
final Integer maxRetries = configurationDomainService.retrieveMaxLoginRetries();
55+
if (maxRetries == null || maxRetries <= 0) {
56+
return;
57+
}
58+
59+
Authentication authentication = event.getAuthentication();
60+
if (authentication == null || !StringUtils.hasText(authentication.getName())) {
61+
return;
62+
}
63+
64+
AuthenticationException exception = event.getException();
65+
if (exception instanceof LockedException) {
66+
return;
67+
}
68+
69+
AppUser user = appUserRepository.findAppUserByName(authentication.getName());
70+
if (user == null || !user.isAccountNonLocked()) {
71+
return;
72+
}
73+
74+
user.registerFailedLoginAttempt(maxRetries);
75+
appUserRepository.saveAndFlush(user);
76+
evictUserCaches();
77+
}
78+
79+
@Transactional
80+
@EventListener
81+
public void onAuthenticationSuccess(final AuthenticationSuccessEvent event) {
82+
Authentication authentication = event.getAuthentication();
83+
if (authentication == null || !(authentication.getPrincipal() instanceof AppUser user)) {
84+
return;
85+
}
86+
87+
if (user.getFailedLoginAttempts() <= 0) {
88+
return;
89+
}
90+
91+
user.resetFailedLoginAttempts();
92+
appUserRepository.saveAndFlush(user);
93+
evictUserCaches();
94+
}
95+
96+
private void evictUserCaches() {
97+
Cache usersCache = cacheManager.getCache(USERS_CACHE);
98+
if (usersCache != null) {
99+
usersCache.clear();
100+
}
101+
Cache usersByUsernameCache = cacheManager.getCache(USERS_BY_USERNAME_CACHE);
102+
if (usersByUsernameCache != null) {
103+
usersByUsernameCache.clear();
104+
}
105+
}
106+
}

fineract-provider/src/main/resources/db/changelog/tenant/changelog-tenant.xml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -227,4 +227,5 @@
227227
<include file="parts/0206_transaction_summary_with_asset_owner_classification_name_bug_fix.xml" relativeToChangelogFile="true" />
228228
<include file="parts/0207_add_allow_full_term_for_tranche.xml" relativeToChangelogFile="true" />
229229
<include file="parts/0208_trial_balance_summary_with_asset_owner_journal_entry_aggregation_fix.xml" relativeToChangelogFile="true" />
230+
<include file="parts/0209_add_login_retry_configuration.xml" relativeToChangelogFile="true" />
230231
</databaseChangeLog>
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
<!--
2+
3+
Licensed to the Apache Software Foundation (ASF) under one
4+
or more contributor license agreements. See the NOTICE file
5+
distributed with this work for additional information
6+
regarding copyright ownership. The ASF licenses this file
7+
to you under the Apache License, Version 2.0 (the
8+
"License"); you may not use this file except in compliance
9+
with the License. You may obtain a copy of the License at
10+
11+
http://www.apache.org/licenses/LICENSE-2.0
12+
13+
Unless required by applicable law or agreed to in writing,
14+
software distributed under the License is distributed on an
15+
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16+
KIND, either express or implied. See the License for the
17+
specific language governing permissions and limitations
18+
under the License.
19+
20+
-->
21+
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
22+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
23+
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-4.3.xsd">
24+
<changeSet author="fineract" id="1" context="postgresql">
25+
<sql>
26+
SELECT SETVAL('c_configuration_id_seq', COALESCE(MAX(id), 0)+1, false ) FROM c_configuration;
27+
</sql>
28+
</changeSet>
29+
<changeSet author="fineract" id="2">
30+
<addColumn tableName="m_appuser">
31+
<column name="failed_login_attempts" type="INT" defaultValueNumeric="0">
32+
<constraints nullable="false"/>
33+
</column>
34+
</addColumn>
35+
</changeSet>
36+
<changeSet author="fineract" id="3">
37+
<insert tableName="c_configuration">
38+
<column name="name" value="max-login-retry-attempts"/>
39+
<column name="value" valueNumeric="5"/>
40+
<column name="date_value"/>
41+
<column name="string_value"/>
42+
<column name="enabled" valueBoolean="false"/>
43+
<column name="is_trap_door" valueBoolean="false"/>
44+
<column name="description" value="Maximum number of failed login attempts before an account is locked"/>
45+
</insert>
46+
</changeSet>
47+
</databaseChangeLog>

fineract-provider/src/main/resources/static/legacy-docs/apiLive.htm

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18436,6 +18436,7 @@ <h3>Global Configuration</h3>
1843618436
<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>
1843718437
<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>
1843818438
<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>
18439+
<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>
1843918440
</ol>
1844018441
</div>
1844118442
</div>
Lines changed: 139 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,139 @@
1+
/**
2+
* Licensed to the Apache Software Foundation (ASF) under one
3+
* or more contributor license agreements. See the NOTICE file
4+
* distributed with this work for additional information
5+
* regarding copyright ownership. The ASF licenses this file
6+
* to you under the Apache License, Version 2.0 (the
7+
* "License"); you may not use this file except in compliance
8+
* with the License. You may obtain a copy of the License at
9+
*
10+
* http://www.apache.org/licenses/LICENSE-2.0
11+
*
12+
* Unless required by applicable law or agreed to in writing,
13+
* software distributed under the License is distributed on an
14+
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15+
* KIND, either express or implied. See the License for the
16+
* specific language governing permissions and limitations
17+
* under the License.
18+
*/
19+
package org.apache.fineract.infrastructure.security.service;
20+
21+
import static org.junit.jupiter.api.Assertions.assertEquals;
22+
import static org.junit.jupiter.api.Assertions.assertFalse;
23+
import static org.junit.jupiter.api.Assertions.assertTrue;
24+
import static org.mockito.Mockito.mock;
25+
import static org.mockito.Mockito.times;
26+
import static org.mockito.Mockito.verify;
27+
import static org.mockito.Mockito.verifyNoInteractions;
28+
import static org.mockito.Mockito.when;
29+
30+
import java.util.HashSet;
31+
import java.util.List;
32+
import org.apache.fineract.infrastructure.configuration.domain.ConfigurationDomainService;
33+
import org.apache.fineract.infrastructure.core.domain.FineractPlatformTenant;
34+
import org.apache.fineract.infrastructure.core.service.ThreadLocalContextUtil;
35+
import org.apache.fineract.organisation.office.domain.Office;
36+
import org.apache.fineract.useradministration.domain.AppUser;
37+
import org.apache.fineract.useradministration.domain.AppUserRepository;
38+
import org.junit.jupiter.api.AfterEach;
39+
import org.junit.jupiter.api.BeforeEach;
40+
import org.junit.jupiter.api.Test;
41+
import org.junit.jupiter.api.extension.ExtendWith;
42+
import org.mockito.Mock;
43+
import org.mockito.junit.jupiter.MockitoExtension;
44+
import org.springframework.cache.Cache;
45+
import org.springframework.cache.CacheManager;
46+
import org.springframework.security.authentication.BadCredentialsException;
47+
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
48+
import org.springframework.security.authentication.event.AuthenticationFailureBadCredentialsEvent;
49+
import org.springframework.security.authentication.event.AuthenticationSuccessEvent;
50+
import org.springframework.security.core.authority.SimpleGrantedAuthority;
51+
import org.springframework.security.core.userdetails.User;
52+
53+
@ExtendWith(MockitoExtension.class)
54+
class LoginAttemptEventListenerTest {
55+
56+
@Mock
57+
private ConfigurationDomainService configurationDomainService;
58+
@Mock
59+
private AppUserRepository appUserRepository;
60+
@Mock
61+
private CacheManager cacheManager;
62+
@Mock
63+
private Cache usersCache;
64+
@Mock
65+
private Cache usersByUsernameCache;
66+
67+
private LoginAttemptEventListener listener;
68+
69+
@BeforeEach
70+
void setUp() {
71+
ThreadLocalContextUtil
72+
.setTenant(FineractPlatformTenant.builder().id(1L).tenantIdentifier("default").name("default").timezoneId("UTC").build());
73+
listener = new LoginAttemptEventListener(configurationDomainService, appUserRepository, cacheManager);
74+
}
75+
76+
@AfterEach
77+
void tearDown() {
78+
ThreadLocalContextUtil.reset();
79+
}
80+
81+
@Test
82+
void shouldIncrementFailedAttemptsAndLockAccountWhenMaxReached() {
83+
when(configurationDomainService.isMaxLoginRetriesEnabled()).thenReturn(true);
84+
when(configurationDomainService.retrieveMaxLoginRetries()).thenReturn(3);
85+
when(cacheManager.getCache("users")).thenReturn(usersCache);
86+
when(cacheManager.getCache("usersByUsername")).thenReturn(usersByUsernameCache);
87+
88+
AppUser user = buildUser("user");
89+
when(appUserRepository.findAppUserByName("user")).thenReturn(user);
90+
91+
AuthenticationFailureBadCredentialsEvent failureEvent = new AuthenticationFailureBadCredentialsEvent(
92+
new UsernamePasswordAuthenticationToken("user", "bad"), new BadCredentialsException("bad"));
93+
94+
listener.onAuthenticationFailure(failureEvent);
95+
listener.onAuthenticationFailure(failureEvent);
96+
listener.onAuthenticationFailure(failureEvent);
97+
98+
assertEquals(3, user.getFailedLoginAttempts());
99+
assertFalse(user.isAccountNonLocked());
100+
verify(appUserRepository, times(3)).saveAndFlush(user);
101+
}
102+
103+
@Test
104+
void shouldResetFailedAttemptsOnSuccessfulLogin() {
105+
AppUser user = buildUser("user");
106+
user.registerFailedLoginAttempt(10);
107+
user.registerFailedLoginAttempt(10);
108+
when(cacheManager.getCache("users")).thenReturn(usersCache);
109+
when(cacheManager.getCache("usersByUsername")).thenReturn(usersByUsernameCache);
110+
111+
AuthenticationSuccessEvent successEvent = new AuthenticationSuccessEvent(
112+
new UsernamePasswordAuthenticationToken(user, "pass", user.getAuthorities()));
113+
114+
listener.onAuthenticationSuccess(successEvent);
115+
116+
assertEquals(0, user.getFailedLoginAttempts());
117+
assertTrue(user.isAccountNonLocked());
118+
verify(appUserRepository).saveAndFlush(user);
119+
}
120+
121+
@Test
122+
void shouldNotUpdateWhenLimitDisabled() {
123+
when(configurationDomainService.isMaxLoginRetriesEnabled()).thenReturn(false);
124+
125+
AuthenticationFailureBadCredentialsEvent failureEvent = new AuthenticationFailureBadCredentialsEvent(
126+
new UsernamePasswordAuthenticationToken("user", "bad"), new BadCredentialsException("bad"));
127+
128+
listener.onAuthenticationFailure(failureEvent);
129+
130+
verifyNoInteractions(appUserRepository);
131+
verifyNoInteractions(cacheManager);
132+
}
133+
134+
private AppUser buildUser(String username) {
135+
Office office = mock(Office.class);
136+
User springUser = new User(username, "pass", true, true, true, true, List.of(new SimpleGrantedAuthority("ALL_FUNCTIONS")));
137+
return new AppUser(office, springUser, new HashSet<>(), "user@example.com", "First", "Last", null, false, false, null, false);
138+
}
139+
}

0 commit comments

Comments
 (0)