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

feat: minor changes to email verification #19494

Merged
merged 4 commits into from
Dec 17, 2024
Merged
Show file tree
Hide file tree
Changes from 3 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
@@ -0,0 +1,80 @@
/*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.test.webapi.json.domain;

import java.time.LocalDateTime;
import org.hisp.dhis.jsontree.JsonBoolean;
import org.hisp.dhis.jsontree.JsonDate;
import org.hisp.dhis.jsontree.JsonList;

/**
* Web API equivalent of a {@link org.hisp.dhis.user.User}.
*
* @author Jan Bernitt
netroms marked this conversation as resolved.
Show resolved Hide resolved
*/
public interface JsonMe extends JsonIdentifiableObject {
default String getUsername() {
return getString("username").string();
}

default String getSurname() {
return getString("surname").string();
}

default String getFirstName() {
return getString("firstName").string();
}

default JsonList<JsonUserGroup> getUserGroups() {
return getList("userGroups", JsonUserGroup.class);
}

default boolean getEmailVerified() {
return get("emailVerified", JsonBoolean.class).booleanValue();
}

default JsonList<JsonOrganisationUnit> getOrganisationUnits() {
return getList("organisationUnits", JsonOrganisationUnit.class);
}

default JsonList<JsonOrganisationUnit> getDataViewOrganisationUnits() {
return getList("dataViewOrganisationUnits", JsonOrganisationUnit.class);
}

default JsonList<JsonOrganisationUnit> getTeiSearchOrganisationUnits() {
return getList("teiSearchOrganisationUnits", JsonOrganisationUnit.class);
}

default LocalDateTime getLastLogin() {
return get("lastLogin", JsonDate.class).date();
}

default LocalDateTime getAccountExpiry() {
return get("accountExpiry", JsonDate.class).date();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
import java.net.HttpURLConnection;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.mail.BodyPart;
Expand Down Expand Up @@ -230,6 +231,20 @@ void testReEnrollFails() throws JsonProcessingException {
"User has 2FA enabled already, disable 2FA before you try to enroll again");
}

@Test
void redirectAfterEmailVerificationFailure() {
RestTemplate template = addAdminBasicAuthHeaders(getRestTemplateNoRedirects());
ResponseEntity<String> response =
template.exchange(
dhis2ServerApi + "/account/verifyEmail?token=WRONGTOKEN",
HttpMethod.GET,
new HttpEntity<>(new HashMap(), jsonHeaders()),
String.class);
assertEquals(HttpStatus.FOUND, response.getStatusCode());
List<String> location = response.getHeaders().get("Location");
assertEquals(dhis2Server + "dhis-web-login/#/email-verification-failure", location.get(0));
}

@Test
void testRedirectWithQueryParam() {
assertRedirectToSameUrl("/api/users?fields=id,name,displayName");
Expand Down Expand Up @@ -269,7 +284,7 @@ void testRedirectToCssResourceWorker() {
void testRedirectAccountWhenVerifiedEmailEnforced() {
changeSystemSetting("enforceVerifiedEmail", "true");
try {
assertRedirectUrl("/dhis-web-dashboard/", "/dhis-web-user-profile/#/account");
assertRedirectUrl("/dhis-web-dashboard/", "/dhis-web-user-profile/#/profile");
} finally {
changeSystemSetting("enforceVerifiedEmail", "false");
}
Expand Down Expand Up @@ -472,8 +487,11 @@ private static void sendVerificationEmail(String cookie) {

private static void verifyEmailWithToken(String cookie, String verifyToken) {
ResponseEntity<String> verifyEmailResp =
getWithCookie("/account/verifyEmail?token=" + verifyToken, cookie);
assertEquals(HttpStatus.OK, verifyEmailResp.getStatusCode());
getWithCookie(
getRestTemplateNoRedirects(), "/account/verifyEmail?token=" + verifyToken, cookie);
assertEquals(HttpStatus.FOUND, verifyEmailResp.getStatusCode());
List<String> location = verifyEmailResp.getHeaders().get("Location");
assertEquals(dhis2Server + "dhis-web-login/#/email-verification-success", location.get(0));
}

// --------------------------------------------------------------------------------------------
Expand Down Expand Up @@ -536,17 +554,7 @@ private static void assertRedirectUrl(String url, String redirectUrl) {

private static void testRedirectWhenLoggedIn(String url, String redirectUrl) {
// Disable auto-redirects
ClientHttpRequestFactory requestFactory =
new SimpleClientHttpRequestFactory() {
@Override
protected void prepareConnection(HttpURLConnection connection, String httpMethod)
throws IOException {
super.prepareConnection(connection, httpMethod);
connection.setInstanceFollowRedirects(false);
}
};

RestTemplate restTemplateNoRedirects = new RestTemplate(requestFactory);
RestTemplate restTemplateNoRedirects = getRestTemplateNoRedirects();

// Do an invalid login to capture URL request
ResponseEntity<LoginResponse> firstResponse =
Expand Down Expand Up @@ -623,29 +631,34 @@ private static ResponseEntity<String> postWithCookie(String path, Object body, S
}
}

private static ResponseEntity<String> getWithCookie(String path, String cookie) {
private static ResponseEntity<String> getWithCookie(
RestTemplate template, String path, String cookie) {
HttpHeaders headers = jsonHeaders();
headers.set("Cookie", cookie);
return exchangeWithHeaders(path, HttpMethod.GET, null, headers);
return exchangeWithHeaders(template, path, HttpMethod.GET, null, headers);
}

private static ResponseEntity<String> getWithCookie(String path, String cookie) {
return getWithCookie(restTemplate, path, cookie);
}

private static ResponseEntity<String> getWithAdminBasicAuth(
String path, Map<String, Object> map) {
RestTemplate rt = createRestTemplateWithAdminBasicAuthHeader();
RestTemplate rt = addAdminBasicAuthHeaders(new RestTemplate());
return rt.exchange(
dhis2ServerApi + path, HttpMethod.GET, new HttpEntity<>(map, jsonHeaders()), String.class);
}

private static ResponseEntity<String> postWithAdminBasicAuth(
String path, Map<String, Object> map) {
RestTemplate rt = createRestTemplateWithAdminBasicAuthHeader();
RestTemplate rt = addAdminBasicAuthHeaders(new RestTemplate());
return rt.exchange(
dhis2ServerApi + path, HttpMethod.POST, new HttpEntity<>(map, jsonHeaders()), String.class);
}

private static ResponseEntity<String> deleteWithAdminBasicAuth(
String path, Map<String, Object> map) {
RestTemplate rt = createRestTemplateWithAdminBasicAuthHeader();
RestTemplate rt = addAdminBasicAuthHeaders(new RestTemplate());
return rt.exchange(
dhis2ServerApi + path,
HttpMethod.DELETE,
Expand All @@ -655,16 +668,20 @@ private static ResponseEntity<String> deleteWithAdminBasicAuth(

private static ResponseEntity<String> exchangeWithHeaders(
String path, HttpMethod method, Object body, HttpHeaders headers) {
return exchangeWithHeaders(restTemplate, path, method, body, headers);
}

private static ResponseEntity<String> exchangeWithHeaders(
RestTemplate template, String path, HttpMethod method, Object body, HttpHeaders headers) {
try {
return restTemplate.exchange(
return template.exchange(
dhis2ServerApi + path, method, new HttpEntity<>(body, headers), String.class);
} catch (HttpClientErrorException e) {
return ResponseEntity.status(e.getStatusCode()).body(e.getResponseBodyAsString());
}
}

private static RestTemplate createRestTemplateWithAdminBasicAuthHeader() {
RestTemplate template = new RestTemplate();
private static RestTemplate addAdminBasicAuthHeaders(RestTemplate template) {
String authHeader =
Base64.getUrlEncoder().encodeToString("admin:district".getBytes(StandardCharsets.UTF_8));
template
Expand All @@ -677,6 +694,21 @@ private static RestTemplate createRestTemplateWithAdminBasicAuthHeader() {
return template;
}

@NotNull
private static RestTemplate getRestTemplateNoRedirects() {
// Disable auto-redirects
ClientHttpRequestFactory requestFactory =
new SimpleClientHttpRequestFactory() {
@Override
protected void prepareConnection(HttpURLConnection connection, String httpMethod)
throws IOException {
super.prepareConnection(connection, httpMethod);
connection.setInstanceFollowRedirects(false);
}
};
return new RestTemplate(requestFactory);
}

// --------------------------------------------------------------------------------------------
// Private helper methods for parsing and extracting content from emails
// --------------------------------------------------------------------------------------------
Expand Down Expand Up @@ -812,7 +844,7 @@ private static void setSystemProperty(String property, String value) {
private static void changeSystemSetting(String key, String value) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_PLAIN);
RestTemplate rt = createRestTemplateWithAdminBasicAuthHeader();
RestTemplate rt = addAdminBasicAuthHeaders(new RestTemplate());
ResponseEntity<String> response =
rt.exchange(
dhis2ServerApi + "/systemSettings/" + key,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -246,11 +246,17 @@ void testVerifyEmailWithTokenTwice() {
String token = extractTokenFromEmailText(emailMessage.getText());
assertNotNull(token);

assertStatus(HttpStatus.OK, GET("/account/verifyEmail?token=" + token));
HttpResponse success = GET("/account/verifyEmail?token=" + token);
assertStatus(HttpStatus.FOUND, success);
assertEquals(
"http://localhost/dhis-web-login/#/email-verification-success", success.header("Location"));
user = userService.getUser(user.getId());
assertTrue(userService.isEmailVerified(user));

assertStatus(HttpStatus.CONFLICT, GET("/account/verifyEmail?token=" + token));
HttpResponse failure = GET("/account/verifyEmail?token=" + token);
assertStatus(HttpStatus.FOUND, failure);
assertEquals(
"http://localhost/dhis-web-login/#/email-verification-failure", failure.header("Location"));
}

@Test
Expand Down Expand Up @@ -283,20 +289,21 @@ void testVerifyEmailWithToken() {
String token = extractTokenFromEmailText(emailMessage.getText());
assertValidEmailVerificationToken(token);

assertStatus(HttpStatus.OK, GET("/account/verifyEmail?token=" + token));
HttpResponse success = GET("/account/verifyEmail?token=" + token);
assertStatus(HttpStatus.FOUND, success);
assertEquals(
"http://localhost/dhis-web-login/#/email-verification-success", success.header("Location"));
user = userService.getUser(user.getId());
assertTrue(userService.isEmailVerified(user));
}

@Test
void testVerifyWithBadToken() {
switchToNewUser("zod");
assertWebMessage(
"Conflict",
409,
"ERROR",
"Verification token is invalid",
GET("/account/verifyEmail?token=eviltoken").content(HttpStatus.CONFLICT));
HttpResponse response = GET("/account/verifyEmail?token=WRONGTOKEN");
assertStatus(HttpStatus.FOUND, response);
String location = response.header("Location");
assertEquals("http://localhost/dhis-web-login/#/email-verification-failure", location);
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@
import org.hisp.dhis.security.apikey.ApiKeyTokenGenerator;
import org.hisp.dhis.security.apikey.ApiTokenStore;
import org.hisp.dhis.test.webapi.H2ControllerIntegrationTestBase;
import org.hisp.dhis.test.webapi.json.domain.JsonUser;
import org.hisp.dhis.test.webapi.json.domain.JsonMe;
import org.hisp.dhis.user.CurrentUserUtil;
import org.hisp.dhis.user.User;
import org.junit.jupiter.api.BeforeEach;
Expand Down Expand Up @@ -77,7 +77,7 @@ void setUp() {
@Test
void testGetCurrentUser() {
switchToAdminUser();
assertEquals(getCurrentUser().getUid(), GET("/me").content().as(JsonUser.class).getId());
assertEquals(getCurrentUser().getUid(), GET("/me").content().as(JsonMe.class).getId());
}

@Test
Expand All @@ -97,7 +97,7 @@ void testGetAuthorities() {
@Test
void testUpdateCurrentUser() {
assertSeries(Series.SUCCESSFUL, PUT("/me", "{'surname':'Lars'}"));
assertEquals("Lars", GET("/me").content().as(JsonUser.class).getSurname());
assertEquals("Lars", GET("/me").content().as(JsonMe.class).getSurname());
}

@Test
Expand All @@ -108,6 +108,11 @@ void testHasAuthority() {
assertFalse(GET("/me/authorities/missing").content(HttpStatus.OK).booleanValue());
}

@Test
void testGetEmailVerifiedProperty() {
assertFalse(GET("/me").content().as(JsonMe.class).getEmailVerified());
}

@Test
void testGetSettings() {
JsonObject settings = GET("/me/settings").content(HttpStatus.OK);
Expand Down Expand Up @@ -274,6 +279,6 @@ void testGetCurrentUserAttributeValues() {
userService.updateUser(userByUsername);

assertEquals(
"myvalue", GET("/me").content().as(JsonUser.class).getAttributeValues().get(0).getValue());
"myvalue", GET("/me").content().as(JsonMe.class).getAttributeValues().get(0).getValue());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@
import org.hisp.dhis.user.UserRole;
import org.hisp.dhis.user.UserService;
import org.hisp.dhis.webapi.mvc.annotation.ApiVersion;
import org.hisp.dhis.webapi.utils.ContextUtils;
import org.hisp.dhis.webapi.utils.HttpServletRequestPaths;
import org.hisp.dhis.webapi.webdomain.user.UserLookups;
import org.springframework.http.HttpStatus;
Expand Down Expand Up @@ -564,15 +565,21 @@ public void sendEmailVerification(@CurrentUser User currentUser, HttpServletRequ
currentUser, token, HttpServletRequestPaths.getContextPath(request));

if (!successfullySent) {
throw new ConflictException("Failed to send email verification token");
throw new ConflictException(
"Sorry, we couldn’t send your verification email. Please try again or contact support.");
}
}

@GetMapping("/verifyEmail")
@ResponseStatus(HttpStatus.OK)
public void verifyEmail(@RequestParam String token) throws ConflictException {
if (!userService.verifyEmail(token)) {
throw new ConflictException("Verification token is invalid");
public void verifyEmail(
@RequestParam String token, HttpServletRequest request, HttpServletResponse response)
throws IOException {
if (userService.verifyEmail(token)) {
response.sendRedirect(
ContextUtils.getRootPath(request) + "/dhis-web-login/#/email-verification-success");
} else {
response.sendRedirect(
ContextUtils.getRootPath(request) + "/dhis-web-login/#/email-verification-failure");
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -229,12 +229,12 @@ private String getRedirectUrl(
redirectUrl += "/";
}

// Check enforce verified email, redirect to the account page if email is not verified
// Check enforce verified email, redirect to the profile page if email is not verified
boolean enforceVerifiedEmail = settingsProvider.getCurrentSettings().getEnforceVerifiedEmail();
if (enforceVerifiedEmail) {
UserDetails userDetails = (UserDetails) authentication.getPrincipal();
if (!userDetails.isEmailVerified()) {
return request.getContextPath() + "/dhis-web-user-profile/#/account";
return request.getContextPath() + "/dhis-web-user-profile/#/profile";
}
}

Expand Down
Loading
Loading