diff --git a/api/src/main/java/com/maptology/api/user/IUserService.java b/api/src/main/java/com/maptology/api/user/IUserService.java index 9688adb..3a629fd 100644 --- a/api/src/main/java/com/maptology/api/user/IUserService.java +++ b/api/src/main/java/com/maptology/api/user/IUserService.java @@ -238,11 +238,12 @@ public interface IUserService { @Path("users/register") @ApiOperation(value = "Registers a new user and sends an email account verification.", tags = { Tags.DEFAULT, Tags.USER }) @ApiResponses({ - @ApiResponse(code=HttpServletResponse.SC_CREATED, message="User registered successfully.", response=User.class), + @ApiResponse(code=HttpServletResponse.SC_OK, message="User registered successfully.", response=User.class), @ApiResponse(code=HttpServletResponse.SC_CONFLICT, message="User login already registered."), @ApiResponse(code=HttpServletResponse.SC_BAD_REQUEST, message="Invalid user registration.") }) @PermitAll + // TODO consider using 201 CREATED response with no body and location header. Response registerUser(@ApiParam(value="The data of the new user.", required=true) @Valid UserRegistration user); /** @@ -260,6 +261,7 @@ public interface IUserService { @ApiResponse(code = HttpServletResponse.SC_BAD_REQUEST, message = "User email has not been verified.") }) @PermitAll + // TODO consider returning error response when sending email has been ignored because minimum time between mails has not passed. + add test Response resetUser(@ApiParam(value="The login of the user to reset.", required=true) @QueryParam("login") @Valid @NotNull String login); @@ -280,6 +282,7 @@ public interface IUserService { @ApiResponse(code=HttpServletResponse.SC_BAD_REQUEST, message="Invalid token or password.") }) @PermitAll + // TODO return better status codes for: code expired, deleted, etc. Forbidden should be for authentication errors only. Response resetUserPassword(@ApiParam(value="The secret token received via email.", required=true) @PathParam("token") @Valid @NotNull String token, @ApiParam(value="The new user password.", required=true) @Valid UserPassword password); diff --git a/api/src/main/java/com/maptology/api/user/User.java b/api/src/main/java/com/maptology/api/user/User.java index 1d151b8..37258d1 100644 --- a/api/src/main/java/com/maptology/api/user/User.java +++ b/api/src/main/java/com/maptology/api/user/User.java @@ -160,6 +160,18 @@ public class User extends Entity { public void setEmails(List emails) { this.emails = emails; } - - + + /** + * Returns the email set for correspondence. + * + * @return The correspondence email. + */ + public Email getCorrespondenceEmail() { + for (Email e : this.emails) { + if (e.isCorrespondence()) { + return e; + } + } + return null; + } } diff --git a/service/ejb/src/main/java/com/maptology/service/session/DebugEmailSessionBean.java b/service/ejb/src/main/java/com/maptology/service/session/DebugEmailSessionBean.java index 2ead0dd..fd8c73f 100644 --- a/service/ejb/src/main/java/com/maptology/service/session/DebugEmailSessionBean.java +++ b/service/ejb/src/main/java/com/maptology/service/session/DebugEmailSessionBean.java @@ -1,5 +1,9 @@ package com.maptology.service.session; +import com.maptology.service.template.EmailAssignment; +import com.maptology.service.template.EmailMessage; +import com.maptology.service.template.EmailTemplate; + import java.util.ArrayList; import java.util.List; import java.util.logging.Level; @@ -16,32 +20,32 @@ import javax.inject.Inject; * An email session bean that simply logs the outgoing emails * to the logger and makes them available as a list of entries * during testing. - * + * * @author Marcus */ @Alternative // alternative implementation, selectable via beans.xml @Singleton public class DebugEmailSessionBean implements IDebugEmailSessionBean { - - + + /** * The log to generate outputs. */ @Inject protected Logger log; - + /** * The email entries that have been sent through the session bean. */ private List entries = new ArrayList<>(); - + @Override @Lock(LockType.WRITE) @PermitAll public void sendEmail(String receiver, String subject, String body) { - sendEmail("noreply@maptology.com", receiver, subject, body); + sendEmail("noreply@maptology.com", receiver, subject, body); } - + @Override @Lock(LockType.WRITE) @PermitAll @@ -50,13 +54,27 @@ public class DebugEmailSessionBean implements IDebugEmailSessionBean { log.log(Level.INFO, entry.toString()); entries.add(entry); } - + + @Override + @Lock(LockType.WRITE) + @PermitAll + public void sendEmailTemplate(String receiver, EmailTemplate template, EmailAssignment assignment) { + EmailMessage message = template.getMessage(assignment); + EmailEntry entry = new EmailEntry( + "noreply@maptology.com", + receiver, + message.getSubject(), + message.getBody(), + assignment.getName(), + assignment.getToken()); + log.log(Level.INFO, entry.toString()); + entries.add(entry); + } + @Override @Lock(LockType.READ) @PermitAll public List getEntries() { return entries; } - - } diff --git a/service/ejb/src/main/java/com/maptology/service/session/EmailSessionBean.java b/service/ejb/src/main/java/com/maptology/service/session/EmailSessionBean.java index 20b7103..a9d62ba 100644 --- a/service/ejb/src/main/java/com/maptology/service/session/EmailSessionBean.java +++ b/service/ejb/src/main/java/com/maptology/service/session/EmailSessionBean.java @@ -1,5 +1,9 @@ package com.maptology.service.session; +import com.maptology.service.template.EmailAssignment; +import com.maptology.service.template.EmailMessage; +import com.maptology.service.template.EmailTemplate; + import java.util.logging.Level; import java.util.logging.Logger; @@ -19,25 +23,32 @@ import javax.mail.internet.MimeMessage; /** * The default email session bean that uses javax.mail to send * emails. - * + * * @author Marcus */ @RequestScoped @Stateful -public class EmailSessionBean implements IEmailSessionBean { - +public class EmailSessionBean implements IEmailSessionBean { + @Inject private Logger log; - + @Inject private Session mailSession; - + @Override @PermitAll public void sendEmail(String receiver, String subject, String body) { - sendEmail("noreply@maptology.com", receiver, subject, body); + sendEmail("noreply@maptology.com", receiver, subject, body); } - + + @Override + @PermitAll + public void sendEmailTemplate(String receiver, EmailTemplate template, EmailAssignment assignment) { + EmailMessage message = template.getMessage(assignment); + sendEmail(receiver, message.getSubject(), message.getBody()); + } + @Override @PermitAll public void sendEmail(String sender, String receiver, String subject, String body) { @@ -48,12 +59,11 @@ public class EmailSessionBean implements IEmailSessionBean { message.setRecipient(RecipientType.TO, new InternetAddress(receiver)); message.setSubject(subject); message.setText(body.toString()); - Transport.send(message); + Transport.send(message); } catch (AddressException e) { - log.log(Level.SEVERE, "Invalid address in message.", e); + log.log(Level.SEVERE, "Invalid address in message.", e); } catch (MessagingException e) { log.log(Level.SEVERE, "Failed to send message.", e); } } - } diff --git a/service/ejb/src/main/java/com/maptology/service/session/IDebugEmailSessionBean.java b/service/ejb/src/main/java/com/maptology/service/session/IDebugEmailSessionBean.java index 9976ebb..5636e47 100644 --- a/service/ejb/src/main/java/com/maptology/service/session/IDebugEmailSessionBean.java +++ b/service/ejb/src/main/java/com/maptology/service/session/IDebugEmailSessionBean.java @@ -7,14 +7,14 @@ import java.util.List; * by allowing the retrieval of messages that have been sent. This * is required since ejbs that implement interfaces will be accessed * through proxies implementing only the views exposed by the interfaces. - * + * * @author Marcus */ public interface IDebugEmailSessionBean extends IEmailSessionBean { /** * An entry in the email list that is kept in memory by this bean. - * + * * @author Marcus */ public static class EmailEntry { @@ -35,18 +35,22 @@ public interface IDebugEmailSessionBean extends IEmailSessionBean { * The body. */ private String body; + /** + * The value of the variable 'token' used in the body. + */ + private String variableToken; + /** + * The value of the variable 'name' used in the body. + */ + private String variableName; /** * Creates a new entry. - * - * @param sender - * The sender. - * @param receiver - * The receiver. - * @param subject - * The subject. - * @param body - * The body. + * + * @param sender The sender. + * @param receiver The receiver. + * @param subject The subject. + * @param body The body. */ public EmailEntry(String sender, String receiver, String subject, String body) { this.sender = sender; @@ -55,9 +59,26 @@ public interface IDebugEmailSessionBean extends IEmailSessionBean { this.subject = subject; } + /** + * Creates a new entry. + * + * @param sender The sender. + * @param receiver The receiver. + * @param subject The subject. + * @param body The body. + */ + public EmailEntry(String sender, String receiver, String subject, String body, String variableName, String variableToken) { + this.sender = sender; + this.receiver = receiver; + this.body = body; + this.subject = subject; + this.variableName = variableName; + this.variableToken = variableToken; + } + /** * Returns the sender address. - * + * * @return The sender address. */ public String getSender() { @@ -66,7 +87,7 @@ public interface IDebugEmailSessionBean extends IEmailSessionBean { /** * Returns the receiver address. - * + * * @return The receiver address. */ public String getReceiver() { @@ -75,7 +96,7 @@ public interface IDebugEmailSessionBean extends IEmailSessionBean { /** * Returns the message body. - * + * * @return The message body. */ public String getBody() { @@ -84,13 +105,31 @@ public interface IDebugEmailSessionBean extends IEmailSessionBean { /** * Returns the subject line. - * + * * @return The subject line. */ public String getSubject() { return subject; } + /** + * Returns the value of the variable 'token' used in the body. + * + * @return The value. + */ + public String getVariableToken() { + return variableToken; + } + + /** + * Returns the value of the variable 'name' used in the body. + * + * @return The value. + */ + public String getVariableName() { + return variableName; + } + @Override public String toString() { StringBuilder b = new StringBuilder(); @@ -104,12 +143,11 @@ public interface IDebugEmailSessionBean extends IEmailSessionBean { b.append(body); return b.toString(); } - } /** * Returns the email entries that the bean has sent out. - * + * * @return The email entries. */ public List getEntries(); diff --git a/service/ejb/src/main/java/com/maptology/service/session/IEmailSessionBean.java b/service/ejb/src/main/java/com/maptology/service/session/IEmailSessionBean.java index 4456e1a..2ee0154 100644 --- a/service/ejb/src/main/java/com/maptology/service/session/IEmailSessionBean.java +++ b/service/ejb/src/main/java/com/maptology/service/session/IEmailSessionBean.java @@ -1,6 +1,7 @@ package com.maptology.service.session; -/** +import com.maptology.service.template.EmailAssignment; +import com.maptology.service.template.EmailTemplate; /** * An interface for the session bean that transmits emails. * * @author Marcus @@ -28,7 +29,16 @@ public interface IEmailSessionBean { * @param body The email body. */ void sendEmail(String sender, String receiver, String subject, String body); - + + /** + * Sends a text email from the sender to the receiver with the + * specified Template and the specified values. + * + * @param address The sender email address. + * @param template The template to use. + * @param assignment The assignment. + */ + void sendEmailTemplate(String address, EmailTemplate template, EmailAssignment assignment); } diff --git a/service/ejb/src/main/java/com/maptology/service/session/UserSessionBean.java b/service/ejb/src/main/java/com/maptology/service/session/UserSessionBean.java index e122e09..0b4114d 100644 --- a/service/ejb/src/main/java/com/maptology/service/session/UserSessionBean.java +++ b/service/ejb/src/main/java/com/maptology/service/session/UserSessionBean.java @@ -235,8 +235,8 @@ public class UserSessionBean extends AbstractPrincipalSessionBean { em.persist(e); CodeEntity c = createCode(CodeType.VERIFY, e, expirationTime); em.persist(c); - EmailMessage msg = EmailTemplate.NEW_USER.getMessage(new EmailAssignment(c.getValue(), u.getName())); - emailSession.sendEmail(e.getAddress(), msg.getSubject(), msg.getBody()); + EmailAssignment assignment = new EmailAssignment(c.getValue(), u.getName()); + emailSession.sendEmailTemplate(e.getAddress(), EmailTemplate.NEW_USER, assignment); em.flush(); return new UserConverter(true).convert(u); } @@ -405,8 +405,8 @@ public class UserSessionBean extends AbstractPrincipalSessionBean { } else { CodeEntity c = createCode(CodeType.VERIFY, e, expirationTime); em.persist(c); - EmailMessage msg = EmailTemplate.NEW_EMAIL.getMessage(new EmailAssignment(c.getValue(), user.getName())); - emailSession.sendEmail(email.getAddress(), msg.getSubject(), msg.getBody()); + EmailAssignment assignment = new EmailAssignment(c.getValue(), user.getName()); + emailSession.sendEmailTemplate(email.getAddress(), EmailTemplate.NEW_EMAIL, assignment); } } else { // update the existing state @@ -414,12 +414,12 @@ public class UserSessionBean extends AbstractPrincipalSessionBean { e.setDeleted(email.isDeleted()); e.setVerified(email.isVerified()); if (!e.isVerified() && !e.isDeleted()) { - // generate verification token and possibly resend email - CodeEntity c = getCode(e, CodeType.VERIFY, currentTime, expirationTime, minimumTime); - if (c != null) { - EmailMessage msg = EmailTemplate.NEW_EMAIL.getMessage(new EmailAssignment(c.getValue(), user.getName())); - emailSession.sendEmail(email.getAddress(), msg.getSubject(), msg.getBody()); - } + // generate verification token and possibly resend email + CodeEntity c = getCode(e, CodeType.VERIFY, currentTime, expirationTime, minimumTime); + if (c != null) { + EmailAssignment assignment = new EmailAssignment(c.getValue(), user.getName()); + emailSession.sendEmailTemplate(email.getAddress(), EmailTemplate.NEW_EMAIL, assignment); + } } } } @@ -507,9 +507,9 @@ public class UserSessionBean extends AbstractPrincipalSessionBean { if (email == null) throw new EntityNotFoundException(UserEntity.class, u.getId(), "User reset for user without correspondence email."); CodeEntity candidate = getCode(email, CodeType.RESET, currentTime, expirationTime, minimumTime); if (candidate != null) { - // send the reset message (if it is not too early) - EmailMessage msg = EmailTemplate.RESET_USER.getMessage(new EmailAssignment(candidate.getValue(), email.getUser().getName())); - emailSession.sendEmail(email.getAddress(), msg.getSubject(), msg.getBody()); + // send the reset message (if it is not too early) + EmailAssignment assignment = new EmailAssignment(candidate.getValue(), email.getUser().getName()); + emailSession.sendEmailTemplate(email.getAddress(), EmailTemplate.RESET_USER, assignment); } } diff --git a/service/war/src/test/java/com/maptology/service/test/rest/UserResourceTest.java b/service/war/src/test/java/com/maptology/service/test/rest/UserResourceTest.java index 1508f20..5d8eb7c 100644 --- a/service/war/src/test/java/com/maptology/service/test/rest/UserResourceTest.java +++ b/service/war/src/test/java/com/maptology/service/test/rest/UserResourceTest.java @@ -1,5 +1,6 @@ package com.maptology.service.test.rest; +import javax.ejb.EJB; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; @@ -8,6 +9,9 @@ import com.maptology.api.device.DeviceInfo; import com.maptology.api.device.IDeviceService; import com.maptology.api.device.OperatingSystem; import com.maptology.api.user.*; +import com.maptology.service.entity.CodeEntity; +import com.maptology.service.entity.CodeType; +import com.maptology.service.session.IDebugEmailSessionBean; import org.jboss.arquillian.junit.Arquillian; import org.junit.Assert; import org.junit.Before; @@ -16,6 +20,8 @@ import org.junit.runner.RunWith; import com.maptology.api.PageConfig; +import java.lang.reflect.Method; +import java.util.Arrays; import java.util.UUID; /** @@ -36,6 +42,9 @@ public class UserResourceTest extends AbstractResourceTest { private User admin; private String adminPassword; + @EJB + private IDebugEmailSessionBean emailSession; + @Before public void setUp() { anonProxy = getTarget().proxy(IUserService.class); @@ -114,6 +123,7 @@ public class UserResourceTest extends AbstractResourceTest { // TODO test changing individual fields (login, roles, name, emails add/remove/verify) // TODO test parallel modification conflict + // TODO test email modification (sending verification mails, setting correspondence correctly (and only once), removing single & multiple mail, dont allow removing correspondence, adding and removing simultaneously (incl. changing correspondence) @Test public void setCurrentUser_AsUser() { // Set same user @@ -187,6 +197,7 @@ public class UserResourceTest extends AbstractResourceTest { // TODO test validation for individual fields // TODO test parallel modification conflict + // TODO test email modification (sending verification email) @Test public void addUser_AsAdmin() { Response r = adminProxy.addUser(createValidUser()); @@ -247,6 +258,7 @@ public class UserResourceTest extends AbstractResourceTest { // TODO test changing individual fields // TODO test parallel modification conflict + // TODO test email modification (see setCurrentUser()) @Test public void setUser_AsAdmin() { Response r = adminProxy.setUser(user.getId(), user); @@ -356,6 +368,8 @@ public class UserResourceTest extends AbstractResourceTest { } // TODO test field validation + // TODO test email set to not verified & correspondence + // TODO test email verification sent @Test public void registerUser_AsAnonymous() { Response r = anonProxy.registerUser(createValidUserRegistration()); @@ -415,16 +429,26 @@ public class UserResourceTest extends AbstractResourceTest { // TODO test valid user with no verified email @Test public void resetUser_AsAnonymous() { + int nextEntryIndex = emailSession.getEntries().size(); + // create test user + UserRegistration user = createValidUserRegistration(); + AssertResponse.isStatus(anonProxy.registerUser(user), Status.OK); + Response r = anonProxy.resetUser(user.getLogin()); AssertResponse.isStatus(r, Status.NO_CONTENT); + IDebugEmailSessionBean.EmailEntry entry = emailSession.getEntries().get(nextEntryIndex); + Assert.assertEquals("Email should be sent to correspondence address.", user.getEmail(), entry.getReceiver()); } @Test public void resetUser_AsAnonymous_WithInvalidUserLogin() { + int previousSize = emailSession.getEntries().size(); + Response r = anonProxy.resetUser("nonexistinglogin"); AssertResponse.isStatus(r, Status.NOT_FOUND); + Assert.assertEquals("Should not have sent an email.", previousSize, emailSession.getEntries().size()); } @Test @@ -448,5 +472,43 @@ public class UserResourceTest extends AbstractResourceTest { AssertResponse.isStatus(r, Status.NO_CONTENT); } - // TODO Email verification workflow (in combination with setCurrentUser) + // TODO with no verified email + @Test + public void resetUserPassword() { + // create verified test user + UserRegistration user = createValidUserRegistration(); + int nextEntryIndex = emailSession.getEntries().size(); + AssertResponse.isStatus(anonProxy.registerUser(user), Status.OK); + String verifyToken = emailSession.getEntries().get(nextEntryIndex).getVariableToken(); + AssertResponse.isStatus(anonProxy.verifyUserEmail(verifyToken), Status.NO_CONTENT); + // send reset mail and get Token + nextEntryIndex = emailSession.getEntries().size(); + AssertResponse.isStatus(anonProxy.resetUser(user.getLogin()), Status.NO_CONTENT); + String token = emailSession.getEntries().get(nextEntryIndex).getVariableToken(); + + Response r = anonProxy.resetUserPassword(token, new UserPassword("newPassword")); + + AssertResponse.isStatus(r, Status.OK); + AssertResponse.hasBodyOfType(r, User.class); + // can authenticate with new password + AssertResponse.isStatus( + getTarget(user.getLogin(), "newPassword") + .proxy(IUserService.class) + .getCurrentUser(), + Status.OK); + } + + @Test + public void verifyUserEmail() { + int nextEntryIndex = emailSession.getEntries().size(); + User newUser = AssertResponse.hasBodyOfType(anonProxy.registerUser(createValidUserRegistration()), User.class); + String token = emailSession.getEntries().get(nextEntryIndex).getVariableToken(); + + Response r = anonProxy.verifyUserEmail(token); + + AssertResponse.isStatus(r, Status.NO_CONTENT); + // check email is verified + User updatedUser = AssertResponse.hasBodyOfType(adminProxy.getUser(newUser.getId()), User.class); + Assert.assertTrue(updatedUser.getCorrespondenceEmail().isVerified()); + } }