refactor: add lombok to security module

This commit is contained in:
Hemant Gupta
2022-10-15 08:22:58 +02:00
committed by Arnold Gálovics
parent b45baa12b0
commit 6ea6cb4cb1
16 changed files with 169 additions and 367 deletions
@@ -636,7 +636,8 @@ public final class JsonCommand {
final Long saltValue) { final Long saltValue) {
final String passwordPlainText = stringValueOfParameterNamed(parameterName); final String passwordPlainText = stringValueOfParameterNamed(parameterName);
final PlatformUser dummyPlatformUser = new BasicPasswordEncodablePlatformUser(saltValue, "", passwordPlainText); final PlatformUser dummyPlatformUser = new BasicPasswordEncodablePlatformUser().setId(saltValue).setUsername("")
.setPassword(passwordPlainText);
return platformPasswordEncoder.encode(dummyPlatformUser); return platformPasswordEncoder.encode(dummyPlatformUser);
} }
@@ -270,7 +270,8 @@ public final class JsonQuery {
final Long saltValue) { final Long saltValue) {
final String passwordPlainText = stringValueOfParameterNamed(parameterName); final String passwordPlainText = stringValueOfParameterNamed(parameterName);
final PlatformUser dummyPlatformUser = new BasicPasswordEncodablePlatformUser(saltValue, "", passwordPlainText); final PlatformUser dummyPlatformUser = new BasicPasswordEncodablePlatformUser().setId(saltValue).setUsername("")
.setPassword(passwordPlainText);
return platformPasswordEncoder.encode(dummyPlatformUser); return platformPasswordEncoder.encode(dummyPlatformUser);
} }
} }
@@ -118,7 +118,7 @@ public class AuthenticationApiResource {
final Authentication authenticationCheck = this.customAuthenticationProvider.authenticate(authentication); final Authentication authenticationCheck = this.customAuthenticationProvider.authenticate(authentication);
final Collection<String> permissions = new ArrayList<>(); final Collection<String> permissions = new ArrayList<>();
AuthenticatedUserData authenticatedUserData = new AuthenticatedUserData(request.username, permissions); AuthenticatedUserData authenticatedUserData = new AuthenticatedUserData().setUsername(request.username).setPermissions(permissions);
if (authenticationCheck.isAuthenticated()) { if (authenticationCheck.isAuthenticated()) {
final Collection<GrantedAuthority> authorities = new ArrayList<>(authenticationCheck.getAuthorities()); final Collection<GrantedAuthority> authorities = new ArrayList<>(authenticationCheck.getAuthorities());
@@ -148,14 +148,19 @@ public class AuthenticationApiResource {
&& !principal.hasSpecificPermissionTo(TwoFactorConstants.BYPASS_TWO_FACTOR_PERMISSION); && !principal.hasSpecificPermissionTo(TwoFactorConstants.BYPASS_TWO_FACTOR_PERMISSION);
Long userId = principal.getId(); Long userId = principal.getId();
if (this.springSecurityPlatformSecurityContext.doesPasswordHasToBeRenewed(principal)) { if (this.springSecurityPlatformSecurityContext.doesPasswordHasToBeRenewed(principal)) {
authenticatedUserData = new AuthenticatedUserData(request.username, userId, authenticatedUserData = new AuthenticatedUserData().setUsername(request.username).setUserId(userId)
new String(base64EncodedAuthenticationKey, StandardCharsets.UTF_8), isTwoFactorRequired); .setBase64EncodedAuthenticationKey(new String(base64EncodedAuthenticationKey, StandardCharsets.UTF_8))
.setAuthenticated(true).setShouldRenewPassword(true).setTwoFactorAuthenticationRequired(isTwoFactorRequired);
} else { } else {
authenticatedUserData = new AuthenticatedUserData(request.username, officeId, officeName, staffId, staffDisplayName, authenticatedUserData = new AuthenticatedUserData().setUsername(request.username).setOfficeId(officeId)
organisationalRole, roles, permissions, principal.getId(), .setOfficeName(officeName).setStaffId(staffId).setStaffDisplayName(staffDisplayName)
new String(base64EncodedAuthenticationKey, StandardCharsets.UTF_8), isTwoFactorRequired, .setOrganisationalRole(organisationalRole).setRoles(roles).setPermissions(permissions).setUserId(principal.getId())
returnClientList ? clientReadPlatformService.retrieveUserClients(userId) : null); .setAuthenticated(true)
.setBase64EncodedAuthenticationKey(new String(base64EncodedAuthenticationKey, StandardCharsets.UTF_8))
.setTwoFactorAuthenticationRequired(isTwoFactorRequired)
.setClients(returnClientList ? clientReadPlatformService.retrieveUserClients(userId) : null);
} }
} }
@@ -95,7 +95,8 @@ public class UserDetailsApiResource {
} }
final Collection<String> permissions = new ArrayList<>(); final Collection<String> permissions = new ArrayList<>();
AuthenticatedOauthUserData authenticatedUserData = new AuthenticatedOauthUserData(principal.getUsername(), permissions); AuthenticatedOauthUserData authenticatedUserData = new AuthenticatedOauthUserData().setUsername(principal.getUsername())
.setPermissions(permissions);
final Collection<GrantedAuthority> authorities = new ArrayList<>(authentication.getAuthorities()); final Collection<GrantedAuthority> authorities = new ArrayList<>(authentication.getAuthorities());
for (final GrantedAuthority grantedAuthority : authorities) { for (final GrantedAuthority grantedAuthority : authorities) {
@@ -119,12 +120,15 @@ public class UserDetailsApiResource {
boolean isTwoFactorRequired = this.twoFactorEnabled boolean isTwoFactorRequired = this.twoFactorEnabled
&& !principal.hasSpecificPermissionTo(TwoFactorConstants.BYPASS_TWO_FACTOR_PERMISSION); && !principal.hasSpecificPermissionTo(TwoFactorConstants.BYPASS_TWO_FACTOR_PERMISSION);
if (this.springSecurityPlatformSecurityContext.doesPasswordHasToBeRenewed(principal)) { if (this.springSecurityPlatformSecurityContext.doesPasswordHasToBeRenewed(principal)) {
authenticatedUserData = new AuthenticatedOauthUserData(principal.getUsername(), principal.getId(), authenticatedUserData = new AuthenticatedOauthUserData().setUsername(principal.getUsername()).setUserId(principal.getId())
authentication.getToken().getTokenValue(), isTwoFactorRequired); .setAccessToken(authentication.getToken().getTokenValue()).setAuthenticated(true).setShouldRenewPassword(true)
.setTwoFactorAuthenticationRequired(isTwoFactorRequired);
} else { } else {
authenticatedUserData = new AuthenticatedOauthUserData(principal.getUsername(), officeId, officeName, staffId, staffDisplayName, authenticatedUserData = new AuthenticatedOauthUserData().setUsername(principal.getUsername()).setOfficeId(officeId)
organisationalRole, roles, permissions, principal.getId(), authentication.getToken().getTokenValue(), .setOfficeName(officeName).setStaffId(staffId).setStaffDisplayName(staffDisplayName)
isTwoFactorRequired); .setOrganisationalRole(organisationalRole).setRoles(roles).setPermissions(permissions).setUserId(principal.getId())
.setAccessToken(authentication.getToken().getTokenValue()).setAuthenticated(true)
.setTwoFactorAuthenticationRequired(isTwoFactorRequired);
} }
return this.apiJsonSerializerService.serialize(authenticatedUserData); return this.apiJsonSerializerService.serialize(authenticatedUserData);
@@ -19,29 +19,17 @@
package org.apache.fineract.infrastructure.security.data; package org.apache.fineract.infrastructure.security.data;
import java.time.ZonedDateTime; import java.time.ZonedDateTime;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
@Data
@NoArgsConstructor
@Accessors(chain = true)
public class AccessTokenData { public class AccessTokenData {
private final String token; private String token;
private final ZonedDateTime validFrom; private ZonedDateTime validFrom;
private final ZonedDateTime validTo; private ZonedDateTime validTo;
public AccessTokenData(String token, ZonedDateTime validFrom, ZonedDateTime validTo) {
this.token = token;
this.validFrom = validFrom;
this.validTo = validTo;
}
public String getToken() {
return token;
}
public ZonedDateTime getValidFrom() {
return validFrom;
}
public ZonedDateTime getValidTo() {
return validTo;
}
} }
@@ -19,92 +19,47 @@
package org.apache.fineract.infrastructure.security.data; package org.apache.fineract.infrastructure.security.data;
import java.util.Collection; import java.util.Collection;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import org.apache.fineract.infrastructure.core.data.EnumOptionData; import org.apache.fineract.infrastructure.core.data.EnumOptionData;
import org.apache.fineract.useradministration.data.RoleData; import org.apache.fineract.useradministration.data.RoleData;
/** /**
* Immutable data object for authentication. Used in case of Oauth2. * Immutable data object for authentication. Used in case of Oauth2.
*/ */
@Data
@NoArgsConstructor
@Accessors(chain = true)
public class AuthenticatedOauthUserData { public class AuthenticatedOauthUserData {
@SuppressWarnings("unused") @SuppressWarnings("unused")
private final String username; private String username;
@SuppressWarnings("unused") @SuppressWarnings("unused")
private final Long userId; private Long userId;
@SuppressWarnings("unused") @SuppressWarnings("unused")
private final String accessToken; private String accessToken;
@SuppressWarnings("unused") @SuppressWarnings("unused")
private final boolean authenticated; private boolean authenticated;
@SuppressWarnings("unused") @SuppressWarnings("unused")
private final Long officeId; private Long officeId;
@SuppressWarnings("unused") @SuppressWarnings("unused")
private final String officeName; private String officeName;
@SuppressWarnings("unused") @SuppressWarnings("unused")
private final Long staffId; private Long staffId;
@SuppressWarnings("unused") @SuppressWarnings("unused")
private final String staffDisplayName; private String staffDisplayName;
@SuppressWarnings("unused") @SuppressWarnings("unused")
private final EnumOptionData organisationalRole; private EnumOptionData organisationalRole;
@SuppressWarnings("unused") @SuppressWarnings("unused")
private final Collection<RoleData> roles; private Collection<RoleData> roles;
@SuppressWarnings("unused") @SuppressWarnings("unused")
private final Collection<String> permissions; private Collection<String> permissions;
@SuppressWarnings("unused") @SuppressWarnings("unused")
private final boolean shouldRenewPassword; private boolean shouldRenewPassword;
@SuppressWarnings("unused") @SuppressWarnings("unused")
private final boolean isTwoFactorAuthenticationRequired; private boolean isTwoFactorAuthenticationRequired;
public AuthenticatedOauthUserData(final String username, final Collection<String> permissions) {
this.username = username;
this.userId = null;
this.accessToken = null;
this.authenticated = false;
this.officeId = null;
this.officeName = null;
this.staffId = null;
this.staffDisplayName = null;
this.organisationalRole = null;
this.roles = null;
this.permissions = permissions;
this.shouldRenewPassword = false;
this.isTwoFactorAuthenticationRequired = false;
}
public AuthenticatedOauthUserData(final String username, final Long officeId, final String officeName, final Long staffId,
final String staffDisplayName, final EnumOptionData organisationalRole, final Collection<RoleData> roles,
final Collection<String> permissions, final Long userId, final String accessToken,
final boolean isTwoFactorAuthenticationRequired) {
this.username = username;
this.officeId = officeId;
this.officeName = officeName;
this.staffId = staffId;
this.staffDisplayName = staffDisplayName;
this.organisationalRole = organisationalRole;
this.userId = userId;
this.accessToken = accessToken;
this.authenticated = true;
this.roles = roles;
this.permissions = permissions;
this.shouldRenewPassword = false;
this.isTwoFactorAuthenticationRequired = isTwoFactorAuthenticationRequired;
}
public AuthenticatedOauthUserData(final String username, final Long userId, final String accessToken,
final boolean isTwoFactorAuthenticationRequired) {
this.username = username;
this.officeId = null;
this.officeName = null;
this.staffId = null;
this.staffDisplayName = null;
this.organisationalRole = null;
this.userId = userId;
this.accessToken = accessToken;
this.authenticated = true;
this.roles = null;
this.permissions = null;
this.shouldRenewPassword = true;
this.isTwoFactorAuthenticationRequired = isTwoFactorAuthenticationRequired;
}
} }
@@ -19,97 +19,48 @@
package org.apache.fineract.infrastructure.security.data; package org.apache.fineract.infrastructure.security.data;
import java.util.Collection; import java.util.Collection;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import org.apache.fineract.infrastructure.core.data.EnumOptionData; import org.apache.fineract.infrastructure.core.data.EnumOptionData;
import org.apache.fineract.useradministration.data.RoleData; import org.apache.fineract.useradministration.data.RoleData;
/** /**
* Immutable data object for authentication. * Immutable data object for authentication.
*/ */
@Data
@NoArgsConstructor
@Accessors(chain = true)
public class AuthenticatedUserData { public class AuthenticatedUserData {
@SuppressWarnings("unused") @SuppressWarnings("unused")
private final String username; private String username;
@SuppressWarnings("unused") @SuppressWarnings("unused")
private final Long userId; private Long userId;
@SuppressWarnings("unused") @SuppressWarnings("unused")
private final String base64EncodedAuthenticationKey; private String base64EncodedAuthenticationKey;
@SuppressWarnings("unused") @SuppressWarnings("unused")
private final boolean authenticated; private boolean authenticated;
@SuppressWarnings("unused") @SuppressWarnings("unused")
private final Long officeId; private Long officeId;
@SuppressWarnings("unused") @SuppressWarnings("unused")
private final String officeName; private String officeName;
@SuppressWarnings("unused") @SuppressWarnings("unused")
private final Long staffId; private Long staffId;
@SuppressWarnings("unused") @SuppressWarnings("unused")
private final String staffDisplayName; private String staffDisplayName;
@SuppressWarnings("unused") @SuppressWarnings("unused")
private final EnumOptionData organisationalRole; private EnumOptionData organisationalRole;
@SuppressWarnings("unused") @SuppressWarnings("unused")
private final Collection<RoleData> roles; private Collection<RoleData> roles;
@SuppressWarnings("unused") @SuppressWarnings("unused")
private final Collection<String> permissions; private Collection<String> permissions;
private final Collection<Long> clients; private Collection<Long> clients;
@SuppressWarnings("unused") @SuppressWarnings("unused")
private final boolean shouldRenewPassword; private boolean shouldRenewPassword;
@SuppressWarnings("unused") @SuppressWarnings("unused")
private final boolean isTwoFactorAuthenticationRequired; private boolean isTwoFactorAuthenticationRequired;
public AuthenticatedUserData(final String username, final Collection<String> permissions) {
this.username = username;
this.userId = null;
this.base64EncodedAuthenticationKey = null;
this.authenticated = false;
this.officeId = null;
this.officeName = null;
this.staffId = null;
this.staffDisplayName = null;
this.organisationalRole = null;
this.roles = null;
this.permissions = permissions;
this.shouldRenewPassword = false;
this.isTwoFactorAuthenticationRequired = false;
clients = null;
}
public AuthenticatedUserData(final String username, final Long officeId, final String officeName, final Long staffId,
final String staffDisplayName, final EnumOptionData organisationalRole, final Collection<RoleData> roles,
final Collection<String> permissions, final Long userId, final String base64EncodedAuthenticationKey,
final boolean isTwoFactorAuthenticationRequired, Collection<Long> aListOfClientIDs) {
this.username = username;
this.officeId = officeId;
this.officeName = officeName;
this.staffId = staffId;
this.staffDisplayName = staffDisplayName;
this.organisationalRole = organisationalRole;
this.userId = userId;
this.base64EncodedAuthenticationKey = base64EncodedAuthenticationKey;
this.authenticated = true;
this.roles = roles;
this.permissions = permissions;
this.shouldRenewPassword = false;
this.isTwoFactorAuthenticationRequired = isTwoFactorAuthenticationRequired;
clients = aListOfClientIDs;
}
public AuthenticatedUserData(final String username, final Long userId, final String base64EncodedAuthenticationKey,
final boolean isTwoFactorAuthenticationRequired) {
this.username = username;
this.officeId = null;
this.officeName = null;
this.staffId = null;
this.staffDisplayName = null;
this.organisationalRole = null;
this.userId = userId;
this.base64EncodedAuthenticationKey = base64EncodedAuthenticationKey;
this.authenticated = true;
this.roles = null;
this.permissions = null;
this.shouldRenewPassword = true;
this.isTwoFactorAuthenticationRequired = isTwoFactorAuthenticationRequired;
clients = null;
}
} }
@@ -18,21 +18,15 @@
*/ */
package org.apache.fineract.infrastructure.security.data; package org.apache.fineract.infrastructure.security.data;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
@Data
@NoArgsConstructor
@Accessors(chain = true)
public class OTPDeliveryMethod { public class OTPDeliveryMethod {
private final String name; private String name;
private final String target; private String target;
public OTPDeliveryMethod(String name, String target) {
this.name = name;
this.target = target;
}
public String getName() {
return name;
}
public String getTarget() {
return target;
}
} }
@@ -19,34 +19,17 @@
package org.apache.fineract.infrastructure.security.data; package org.apache.fineract.infrastructure.security.data;
import java.time.ZonedDateTime; import java.time.ZonedDateTime;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
@Data
@NoArgsConstructor
@Accessors(chain = true)
public class OTPMetadata { public class OTPMetadata {
private final ZonedDateTime requestTime; private ZonedDateTime requestTime;
private final int tokenLiveTimeInSec; private int tokenLiveTimeInSec;
private final boolean extendedAccessToken; private boolean extendedAccessToken;
private final OTPDeliveryMethod deliveryMethod; private OTPDeliveryMethod deliveryMethod;
public OTPMetadata(ZonedDateTime requestTime, int tokenLiveTimeInSec, boolean extendedAccessToken, OTPDeliveryMethod deliveryMethod) {
this.requestTime = requestTime;
this.tokenLiveTimeInSec = tokenLiveTimeInSec;
this.extendedAccessToken = extendedAccessToken;
this.deliveryMethod = deliveryMethod;
}
public ZonedDateTime getRequestTime() {
return requestTime;
}
public int getTokenLiveTimeInSec() {
return tokenLiveTimeInSec;
}
public boolean isExtendedAccessToken() {
return extendedAccessToken;
}
public OTPDeliveryMethod getDeliveryMethod() {
return deliveryMethod;
}
} }
@@ -19,30 +19,25 @@
package org.apache.fineract.infrastructure.security.data; package org.apache.fineract.infrastructure.security.data;
import java.time.ZonedDateTime; import java.time.ZonedDateTime;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import org.apache.fineract.infrastructure.core.service.DateUtils; import org.apache.fineract.infrastructure.core.service.DateUtils;
@Data
@NoArgsConstructor
@Accessors(chain = true)
public class OTPRequest { public class OTPRequest {
private final String token; private String token;
private final OTPMetadata metadata; private OTPMetadata metadata;
public OTPRequest(String token, OTPMetadata metadata) {
this.token = token;
this.metadata = metadata;
}
public static OTPRequest create(String token, int tokenLiveTimeInSec, boolean extendedAccessToken, OTPDeliveryMethod deliveryMethod) { public static OTPRequest create(String token, int tokenLiveTimeInSec, boolean extendedAccessToken, OTPDeliveryMethod deliveryMethod) {
final OTPMetadata metadata = new OTPMetadata(DateUtils.getLocalDateTimeOfTenant().atZone(DateUtils.getDateTimeZoneOfTenant()), final OTPMetadata metadata = new OTPMetadata()
tokenLiveTimeInSec, extendedAccessToken, deliveryMethod); .setRequestTime(DateUtils.getLocalDateTimeOfTenant().atZone(DateUtils.getDateTimeZoneOfTenant()))
return new OTPRequest(token, metadata); .setTokenLiveTimeInSec(tokenLiveTimeInSec).setExtendedAccessToken(extendedAccessToken).setDeliveryMethod(deliveryMethod);
}
public String getToken() { return new OTPRequest().setToken(token).setMetadata(metadata);
return token;
}
public OTPMetadata getMetadata() {
return metadata;
} }
public boolean isValid() { public boolean isValid() {
@@ -22,23 +22,29 @@ import java.io.IOException;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import org.apache.commons.lang3.time.StopWatch; import org.apache.commons.lang3.time.StopWatch;
/** /**
* Immutable data object representing platform API request used for logging/debugging. * Immutable data object representing platform API request used for logging/debugging.
*/ */
@Data
@NoArgsConstructor
@Accessors(chain = true)
public final class PlatformRequestLog { public final class PlatformRequestLog {
@SuppressWarnings("unused") @SuppressWarnings("unused")
private final long startTime; private long startTime;
@SuppressWarnings("unused") @SuppressWarnings("unused")
private final long totalTime; private long totalTime;
@SuppressWarnings("unused") @SuppressWarnings("unused")
private final String method; private String method;
@SuppressWarnings("unused") @SuppressWarnings("unused")
private final String url; private String url;
@SuppressWarnings("unused") @SuppressWarnings("unused")
private final Map<String, String[]> parameters; private Map<String, String[]> parameters;
public static PlatformRequestLog from(final StopWatch task, final HttpServletRequest request) throws IOException { public static PlatformRequestLog from(final StopWatch task, final HttpServletRequest request) throws IOException {
final String requestUrl = request.getRequestURL().toString(); final String requestUrl = request.getRequestURL().toString();
@@ -47,15 +53,7 @@ public final class PlatformRequestLog {
parameters.remove("password"); parameters.remove("password");
parameters.remove("_"); parameters.remove("_");
return new PlatformRequestLog(task.getStartTime(), task.getTime(), request.getMethod(), requestUrl, parameters); return new PlatformRequestLog().setStartTime(task.getStartTime()).setTotalTime(task.getTime()).setMethod(request.getMethod())
} .setUrl(requestUrl).setParameters(parameters);
private PlatformRequestLog(final long startTime, final long time, final String method, final String requestUrl,
final Map<String, String[]> parameters) {
this.startTime = startTime;
this.totalTime = time;
this.method = method;
this.url = requestUrl;
this.parameters = parameters;
} }
} }
@@ -19,33 +19,23 @@
package org.apache.fineract.infrastructure.security.domain; package org.apache.fineract.infrastructure.security.domain;
import java.util.Collection; import java.util.Collection;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.experimental.Accessors;
import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.GrantedAuthority;
@Setter
@NoArgsConstructor
@Accessors(chain = true)
public class BasicPasswordEncodablePlatformUser implements PlatformUser { public class BasicPasswordEncodablePlatformUser implements PlatformUser {
private final Long id; @Getter
private final String username; private Long id;
private final String password; @Getter(onMethod = @__(@Override))
private String username;
public BasicPasswordEncodablePlatformUser(final Long id, final String username, final String password) { @Getter(onMethod = @__(@Override))
this.id = id; private String password;
this.username = username;
this.password = password;
}
public Long getId() {
return this.id;
}
@Override
public String getPassword() {
return this.password;
}
@Override
public String getUsername() {
return this.username;
}
@Override @Override
public Collection<GrantedAuthority> getAuthorities() { public Collection<GrantedAuthority> getAuthorities() {
@@ -71,4 +61,5 @@ public class BasicPasswordEncodablePlatformUser implements PlatformUser {
public boolean isEnabled() { public boolean isEnabled() {
return false; return false;
} }
} }
@@ -25,6 +25,10 @@ import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne; import javax.persistence.ManyToOne;
import javax.persistence.Table; import javax.persistence.Table;
import javax.persistence.UniqueConstraint; import javax.persistence.UniqueConstraint;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.experimental.Accessors;
import org.apache.fineract.infrastructure.core.domain.AbstractPersistableCustom; import org.apache.fineract.infrastructure.core.domain.AbstractPersistableCustom;
import org.apache.fineract.infrastructure.core.service.DateUtils; import org.apache.fineract.infrastructure.core.service.DateUtils;
import org.apache.fineract.infrastructure.security.data.AccessTokenData; import org.apache.fineract.infrastructure.security.data.AccessTokenData;
@@ -33,6 +37,10 @@ import org.apache.fineract.useradministration.domain.AppUser;
@Entity @Entity
@Table(name = "twofactor_access_token", uniqueConstraints = { @Table(name = "twofactor_access_token", uniqueConstraints = {
@UniqueConstraint(columnNames = { "token", "appuser_id" }, name = "token_appuser_UNIQUE") }) @UniqueConstraint(columnNames = { "token", "appuser_id" }, name = "token_appuser_UNIQUE") })
@Getter
@Setter
@NoArgsConstructor
@Accessors(chain = true)
public class TFAccessToken extends AbstractPersistableCustom { public class TFAccessToken extends AbstractPersistableCustom {
@Column(name = "token", nullable = false, length = 32) @Column(name = "token", nullable = false, length = 32)
@@ -51,70 +59,20 @@ public class TFAccessToken extends AbstractPersistableCustom {
@Column(name = "enabled", nullable = false) @Column(name = "enabled", nullable = false)
private boolean enabled; private boolean enabled;
public TFAccessToken() {}
public static TFAccessToken create(String token, AppUser user, int tokenLiveTimeInSec) { public static TFAccessToken create(String token, AppUser user, int tokenLiveTimeInSec) {
LocalDateTime validFrom = DateUtils.getLocalDateTimeOfTenant(); LocalDateTime validFrom = DateUtils.getLocalDateTimeOfTenant();
LocalDateTime validTo = validFrom.plusSeconds(tokenLiveTimeInSec); LocalDateTime validTo = validFrom.plusSeconds(tokenLiveTimeInSec);
return new TFAccessToken(token, user, validFrom, validTo, true); return new TFAccessToken().setToken(token).setUser(user).setValidFrom(validFrom).setValidTo(validTo).setEnabled(true);
}
public TFAccessToken(String token, AppUser user, LocalDateTime validFrom, LocalDateTime validTo, boolean enabled) {
this.token = token;
this.user = user;
this.validFrom = validFrom;
this.validTo = validTo;
this.enabled = enabled;
} }
public boolean isValid() { public boolean isValid() {
return this.enabled && isDateInTheFuture(getValidToDate()) && isDateInThePast(getValidFromDate()); return this.enabled && isDateInTheFuture(getValidTo()) && isDateInThePast(getValidFrom());
} }
public AccessTokenData toTokenData() { public AccessTokenData toTokenData() {
return new AccessTokenData(this.token, getValidFromDate().atZone(DateUtils.getDateTimeZoneOfTenant()), return new AccessTokenData().setToken(this.token).setValidFrom(getValidFrom().atZone(DateUtils.getDateTimeZoneOfTenant()))
getValidToDate().atZone(DateUtils.getDateTimeZoneOfTenant())); .setValidTo(getValidTo().atZone(DateUtils.getDateTimeZoneOfTenant()));
}
public String getToken() {
return token;
}
public AppUser getUser() {
return user;
}
public boolean isEnabled() {
return enabled;
}
public LocalDateTime getValidFromDate() {
return validFrom;
}
public LocalDateTime getValidToDate() {
return validTo;
}
public void setToken(String token) {
this.token = token;
}
public void setUser(AppUser user) {
this.user = user;
}
public void setValidFrom(LocalDateTime validFrom) {
this.validFrom = validFrom;
}
public void setValidTo(LocalDateTime validTo) {
this.validTo = validTo;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
} }
private boolean isDateInTheFuture(LocalDateTime dateTime) { private boolean isDateInTheFuture(LocalDateTime dateTime) {
@@ -22,6 +22,10 @@ import javax.persistence.Column;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.Table; import javax.persistence.Table;
import javax.persistence.UniqueConstraint; import javax.persistence.UniqueConstraint;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.experimental.Accessors;
import org.apache.commons.lang3.BooleanUtils; import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.math.NumberUtils; import org.apache.commons.lang3.math.NumberUtils;
import org.apache.fineract.infrastructure.core.domain.AbstractPersistableCustom; import org.apache.fineract.infrastructure.core.domain.AbstractPersistableCustom;
@@ -29,6 +33,10 @@ import org.apache.fineract.infrastructure.security.constants.TwoFactorConfigurat
@Entity @Entity
@Table(name = "twofactor_configuration", uniqueConstraints = { @UniqueConstraint(columnNames = { "name" }, name = "name_UNIQUE") }) @Table(name = "twofactor_configuration", uniqueConstraints = { @UniqueConstraint(columnNames = { "name" }, name = "name_UNIQUE") })
@Getter
@Setter
@NoArgsConstructor
@Accessors(chain = true)
public class TwoFactorConfiguration extends AbstractPersistableCustom { public class TwoFactorConfiguration extends AbstractPersistableCustom {
@Column(name = "name", nullable = false, length = 32) @Column(name = "name", nullable = false, length = 32)
@@ -37,46 +45,14 @@ public class TwoFactorConfiguration extends AbstractPersistableCustom {
@Column(name = "value", nullable = true, length = 1024) @Column(name = "value", nullable = true, length = 1024)
private String value; private String value;
public String getName() {
return name;
}
public String getStringValue() {
return value;
}
public Boolean getBooleanValue() {
return BooleanUtils.toBooleanObject(value);
}
public Integer getIntegerValue() {
try {
return NumberUtils.createInteger(value);
} catch (NumberFormatException e) {
return null;
}
}
public Object getObjectValue() { public Object getObjectValue() {
if (TwoFactorConfigurationConstants.NUMBER_PARAMETERS.contains(name)) { if (TwoFactorConfigurationConstants.NUMBER_PARAMETERS.contains(name)) {
return getIntegerValue(); return NumberUtils.createInteger(value);
} }
if (TwoFactorConfigurationConstants.BOOLEAN_PARAMETERS.contains(name)) { if (TwoFactorConfigurationConstants.BOOLEAN_PARAMETERS.contains(name)) {
return getBooleanValue(); return BooleanUtils.toBooleanObject(value);
} }
return getStringValue(); return getValue();
}
public void setStringValue(String value) {
this.value = value;
}
public void setBooleanValue(boolean value) {
this.value = String.valueOf(value);
}
public void setIntegerValue(long value) {
this.value = String.valueOf(value);
} }
} }
@@ -28,6 +28,8 @@ import java.time.format.DateTimeFormatter;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.fineract.infrastructure.core.api.JsonCommand; import org.apache.fineract.infrastructure.core.api.JsonCommand;
import org.apache.fineract.infrastructure.security.constants.TwoFactorConfigurationConstants; import org.apache.fineract.infrastructure.security.constants.TwoFactorConfigurationConstants;
import org.apache.fineract.infrastructure.security.constants.TwoFactorConstants; import org.apache.fineract.infrastructure.security.constants.TwoFactorConstants;
@@ -78,10 +80,10 @@ public class TwoFactorConfigurationServiceImpl implements TwoFactorConfiguration
continue; continue;
} }
if (command.isChangeInBooleanParameterNamed(parameterName, configuration.getBooleanValue())) { if (command.isChangeInBooleanParameterNamed(parameterName, BooleanUtils.toBooleanObject(configuration.getValue()))) {
final boolean newValue = command.booleanPrimitiveValueOfParameterNamed(parameterName); final boolean newValue = command.booleanPrimitiveValueOfParameterNamed(parameterName);
actualChanges.put(parameterName, newValue); actualChanges.put(parameterName, newValue);
configuration.setBooleanValue(newValue); configuration.setValue(String.valueOf(newValue));
configurationRepository.save(configuration); configurationRepository.save(configuration);
} }
} }
@@ -92,10 +94,10 @@ public class TwoFactorConfigurationServiceImpl implements TwoFactorConfiguration
continue; continue;
} }
if (command.isChangeInStringParameterNamed(parameterName, configuration.getStringValue())) { if (command.isChangeInStringParameterNamed(parameterName, configuration.getValue())) {
final String newValue = command.stringValueOfParameterNamed(parameterName).trim(); final String newValue = command.stringValueOfParameterNamed(parameterName).trim();
actualChanges.put(parameterName, newValue); actualChanges.put(parameterName, newValue);
configuration.setStringValue(newValue); configuration.setValue(newValue);
configurationRepository.save(configuration); configurationRepository.save(configuration);
} }
} }
@@ -106,10 +108,10 @@ public class TwoFactorConfigurationServiceImpl implements TwoFactorConfiguration
continue; continue;
} }
if (command.isChangeInIntegerSansLocaleParameterNamed(parameterName, configuration.getIntegerValue())) { if (command.isChangeInIntegerSansLocaleParameterNamed(parameterName, NumberUtils.createInteger(configuration.getValue()))) {
final Long newValue = command.longValueOfParameterNamed(parameterName); final Long newValue = command.longValueOfParameterNamed(parameterName);
actualChanges.put(parameterName, newValue); actualChanges.put(parameterName, newValue);
configuration.setIntegerValue(newValue); configuration.setValue(String.valueOf(newValue));
configurationRepository.save(configuration); configurationRepository.save(configuration);
} }
} }
@@ -221,7 +223,7 @@ public class TwoFactorConfigurationServiceImpl implements TwoFactorConfiguration
private boolean getBooleanConfig(final String name, final boolean defaultValue) { private boolean getBooleanConfig(final String name, final boolean defaultValue) {
final TwoFactorConfiguration configuration = configurationRepository.findByName(name); final TwoFactorConfiguration configuration = configurationRepository.findByName(name);
Boolean value = configuration.getBooleanValue(); Boolean value = BooleanUtils.toBooleanObject(configuration.getValue());
if (value == null) { if (value == null) {
return defaultValue; return defaultValue;
} }
@@ -230,7 +232,7 @@ public class TwoFactorConfigurationServiceImpl implements TwoFactorConfiguration
private String getStringConfig(final String name, final String defaultValue) { private String getStringConfig(final String name, final String defaultValue) {
final TwoFactorConfiguration configuration = configurationRepository.findByName(name); final TwoFactorConfiguration configuration = configurationRepository.findByName(name);
String value = configuration.getStringValue(); String value = configuration.getValue();
if (value == null) { if (value == null) {
return defaultValue; return defaultValue;
} }
@@ -239,7 +241,7 @@ public class TwoFactorConfigurationServiceImpl implements TwoFactorConfiguration
private Integer getIntegerConfig(final String name, final Integer defaultValue) { private Integer getIntegerConfig(final String name, final Integer defaultValue) {
final TwoFactorConfiguration configuration = configurationRepository.findByName(name); final TwoFactorConfiguration configuration = configurationRepository.findByName(name);
Integer value = configuration.getIntegerValue(); Integer value = NumberUtils.createInteger(configuration.getValue());
if (value == null) { if (value == null) {
return defaultValue; return defaultValue;
} }
@@ -197,7 +197,7 @@ public class TwoFactorServiceImpl implements TwoFactorService {
return null; return null;
} }
return new OTPDeliveryMethod(TwoFactorConstants.SMS_DELIVERY_METHOD_NAME, mobileNo); return new OTPDeliveryMethod().setName(TwoFactorConstants.SMS_DELIVERY_METHOD_NAME).setTarget(mobileNo);
} }
private OTPDeliveryMethod getEmailDeliveryMethodForUser(final AppUser user) { private OTPDeliveryMethod getEmailDeliveryMethodForUser(final AppUser user) {
@@ -205,7 +205,7 @@ public class TwoFactorServiceImpl implements TwoFactorService {
return null; return null;
} }
return new OTPDeliveryMethod(TwoFactorConstants.EMAIL_DELIVERY_METHOD_NAME, user.getEmail()); return new OTPDeliveryMethod().setName(TwoFactorConstants.EMAIL_DELIVERY_METHOD_NAME).setTarget(user.getEmail());
} }
private OTPRequest generateNewToken(final OTPDeliveryMethod deliveryMethod, final boolean extendedAccessToken) { private OTPRequest generateNewToken(final OTPDeliveryMethod deliveryMethod, final boolean extendedAccessToken) {