Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

O3-2761: Add ability to save user email #188

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
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 @@ -11,6 +11,7 @@

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.validator.EmailValidator;
import org.openmrs.Person;
import org.openmrs.PersonName;
import org.openmrs.Provider;
Expand Down Expand Up @@ -43,6 +44,8 @@

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.lang.reflect.Field;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
Expand Down Expand Up @@ -112,6 +115,17 @@ public List<Role> getRoles(WebRequest request) {
public String showForm(@RequestParam(required = false, value = "userId") Integer userId,
@RequestParam(required = false, value = "createNewPerson") String createNewPerson,
@ModelAttribute("user") User user, ModelMap model) {

try {
boolean isPlatform22OrNewer = isPlatform22OrNewer();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we need the above variable? Why not just directly call the method in the if statement?

if (isPlatform22OrNewer) {
Field emailField = getEmailField();
model.addAttribute("hasEmailField", isPlatform22OrNewer);
model.addAttribute("email", emailField.get(user));
}
} catch (IllegalArgumentException | IllegalAccessException | NullPointerException e) {
log.warn("Email field not available for setting", e);
}

// the formBackingObject method above sets up user, depending on userId and personId parameters

Expand Down Expand Up @@ -157,6 +171,7 @@ public String handleSubmission(WebRequest request, HttpSession httpSession, Mode
@RequestParam(required = false, value = "roleStrings") String[] roles,
@RequestParam(required = false, value = "createNewPerson") String createNewPerson,
@RequestParam(required = false, value = "providerCheckBox") String addToProviderTableOption,
@RequestParam(required = false, value = "email") String email,
@ModelAttribute("user") User user, BindingResult errors, HttpServletResponse response) {

UserService us = Context.getUserService();
Expand Down Expand Up @@ -227,6 +242,18 @@ public String handleSubmission(WebRequest request, HttpSession httpSession, Mode
}
}

if (isPlatform22OrNewer() && isEmailValid(email)) {
Field emailField;
try {
emailField = getEmailField();
emailField.set(user, email);
} catch (IllegalArgumentException | IllegalAccessException | NullPointerException e) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Aren't these exceptions thrown and caught within getEmailField?

log.error("Error while setting the email field", e);
}
} else {
log.warn("Invalid or unspecified email: " + (email != null ? "'" + email + "'" : "not provided"));
}

Set<Role> newRoles = new HashSet<Role>();
if (roles != null) {
for (String r : roles) {
Expand Down Expand Up @@ -321,4 +348,43 @@ private Boolean isNewUser(User user) {
return user == null ? true : user.getUserId() == null;
}

/**
* @return true if email is valid or false otherwise
* @param email
*/
private boolean isEmailValid(String email) {
return StringUtils.hasLength(email) && EmailValidator.getInstance().isValid(email);
}

/**
* @return an email field
* @param user
*/
private Field getEmailField() {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't this method return the email field value instead of the field object?

Copy link
Contributor Author

@jnsereko jnsereko Jan 31, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i would find it hard to reuse this method in handleSubmission if it was returning the value

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh i see!

try {
Field emailField = User.class.getDeclaredField("email");
emailField.setAccessible(true);
return emailField;
} catch (NoSuchFieldException | SecurityException e) {
log.warn("Email field not available for setting", e);
return null;
}
}

/**
* @return true if the platform version is 2.2 or higher
*/
private boolean isPlatform22OrNewer() {
String platformVersion = OpenmrsConstants.OPENMRS_VERSION_SHORT.substring(0, 3);
try {
float versionFloat = Float.parseFloat(platformVersion);
if (versionFloat >= 2.2) {
return true;
}
}
catch (NumberFormatException e) {
log.error("Unable to parse platform value text to float", e);
}
return false;
}
}
6 changes: 6 additions & 0 deletions omod/src/main/webapp/admin/users/userForm.jsp
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,12 @@
<spring:nestedPath path="user.person.names[0]">
<openmrs:portlet url="nameLayout" id="namePortlet" size="full" parameters="layoutMode=edit|layoutShowTable=false|layoutShowExtended=false" />
</spring:nestedPath>
<c:if test="${hasEmailField}">
<tr>
<td><openmrs:message code="Email" /></td>
<td><input type="email" size="30" name="email" value="${email}"/></td>
</tr>
</c:if>
<tr>
<td><openmrs:message code="Person.gender"/><span class="required">*</span></td>
<td><spring:bind path="user.person.gender">
Expand Down
2 changes: 1 addition & 1 deletion omod/src/main/webapp/resources/css/openmrs.css
Original file line number Diff line number Diff line change
Expand Up @@ -671,7 +671,7 @@ tr.searchHighlight {
overflow-y: auto;
}

input[type="text"], input[type="password"] {
input[type="text"], input[type="email"], input[type="password"] {
padding: 1px;
border: 1px solid cadetblue;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ public void handleSubmission_shouldWorkForAnExample() throws Exception {
user.addName(new PersonName("This", "is", "Test"));
user.getPerson().setGender("F");
controller.handleSubmission(request, new MockHttpSession(), new ModelMap(), "", "Save User", "pass123", "pass123",
null, null, null, new String[0], "true", null, user, new BindException(user, "user"),
null, null, null, new String[0], "true", null, "[email protected]", user, new BindException(user, "user"),
new MockHttpServletResponse());
}

Expand All @@ -71,7 +71,7 @@ public void handleSubmission_createUserProviderAccountWhenProviderAccountCheckbo
controller.showForm(2, "true", user, model);
controller.handleSubmission(request, new MockHttpSession(), new ModelMap(), "", null, "Test1234",
"valid secret question", "valid secret answer", "Test1234", false, new String[] { "Provider" }, "true",
"addToProviderTable", user, new BindException(user, "user"), response);
"addToProviderTable", "[email protected]", user, new BindException(user, "user"), response);
Assert.assertFalse(Context.getProviderService().getProvidersByPerson(user.getPerson()).isEmpty());
Assert.assertEquals(200, response.getStatus());
}
Expand All @@ -85,7 +85,7 @@ public void shouldSetResponseStatusToBadRequestOnError() throws Exception {
MockHttpServletResponse response = new MockHttpServletResponse();
controller.handleSubmission(request, new MockHttpSession(), new ModelMap(), "", null, "Test123",
"valid secret question", "valid secret answer", "Test1234", false, new String[] { "Provider" }, "true",
"addToProviderTable", user, new BindException(user, "user"), response);
"addToProviderTable", "[email protected]", user, new BindException(user, "user"), response);
Assert.assertEquals(400, response.getStatus());
}

Expand Down
Loading