-
Notifications
You must be signed in to change notification settings - Fork 3.7k
[#14396] Add MagicLink logic layer methods #14403
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
Open
TobyCyan
wants to merge
13
commits into
TEAMMATES:master
Choose a base branch
from
TobyCyan:ml-logic
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
16eef35
Create magic link entity
TobyCyan 1a09a72
Change validity period
TobyCyan bd2343a
Remove fields
TobyCyan 93b129b
Merge branch 'master' into magic-link-entity
TobyCyan 137972d
Create migration file
TobyCyan 28ef972
Change expiry time
TobyCyan 1690f13
Add storage layer
TobyCyan 3347d5a
Add db tests
TobyCyan 0ad647f
Use given
TobyCyan e622005
Add logic layer methods
TobyCyan 122a717
Make comments same
TobyCyan 8bd6512
Merge branch 'master' into ml-logic
TobyCyan e88466f
Update method
TobyCyan File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
118 changes: 118 additions & 0 deletions
118
src/main/java/teammates/logic/core/MagicLinksLogic.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,118 @@ | ||
| package teammates.logic.core; | ||
|
|
||
| import java.security.SecureRandom; | ||
| import java.time.Instant; | ||
| import java.util.Base64; | ||
| import java.util.Objects; | ||
|
|
||
| import teammates.common.exception.EntityDoesNotExistException; | ||
| import teammates.common.exception.InvalidParametersException; | ||
| import teammates.common.util.StringHelper; | ||
| import teammates.storage.api.MagicLinksDb; | ||
| import teammates.storage.entity.MagicLink; | ||
|
|
||
| /** | ||
| * Handles operations related to magic links. | ||
| * | ||
| * @see MagicLink | ||
| * @see MagicLinksDb | ||
| */ | ||
| public final class MagicLinksLogic { | ||
|
|
||
| private static final MagicLinksLogic instance = new MagicLinksLogic(); | ||
| private static final SecureRandom SECURE_RANDOM = new SecureRandom(); | ||
| private static final int TOKEN_BYTE_LENGTH = 32; | ||
|
|
||
| private MagicLinksDb magicLinksDb; | ||
|
|
||
| private MagicLinksLogic() { | ||
| // prevent initialization | ||
| } | ||
|
|
||
| public static MagicLinksLogic inst() { | ||
| return instance; | ||
| } | ||
|
|
||
| void initLogicDependencies(MagicLinksDb magicLinksDb) { | ||
| this.magicLinksDb = magicLinksDb; | ||
| } | ||
|
|
||
| /** | ||
| * Creates or replaces a magic link for the given email address. | ||
| * | ||
| * @return the raw one-time token. | ||
| * @throws InvalidParametersException if the magic link is not valid. | ||
| */ | ||
| public String createMagicLink(String email) throws InvalidParametersException { | ||
| // TODO: Add a method to send the magic link to the user via email. | ||
| Objects.requireNonNull(email); | ||
|
|
||
| String token = generateToken(); | ||
| MagicLink magicLink = new MagicLink(email, hashToken(token), Instant.now()); | ||
| validateMagicLink(magicLink); | ||
|
|
||
| magicLinksDb.persistMagicLink(magicLink); | ||
| return token; | ||
| } | ||
|
|
||
| /** | ||
| * Returns a magic link for the given raw token, or null if no matching link exists. | ||
| */ | ||
| public MagicLink getMagicLinkByToken(String token) { | ||
| Objects.requireNonNull(token); | ||
| return magicLinksDb.getMagicLinkByTokenHash(hashToken(token)); | ||
| } | ||
|
|
||
| /** | ||
| * Consumes a usable magic link for the given raw token. | ||
| * | ||
| * <p>Successful consumption deletes the magic link to enforce one-time use. | ||
| * | ||
| * @return the consumed magic link. | ||
| * @throws EntityDoesNotExistException if the token is unknown. | ||
| * @throws InvalidParametersException if the token is not usable. | ||
| */ | ||
| public MagicLink consumeMagicLink(String token) throws InvalidParametersException, EntityDoesNotExistException { | ||
| Objects.requireNonNull(token); | ||
| MagicLink magicLink = getMagicLinkByToken(token); | ||
| if (magicLink == null) { | ||
| throw new EntityDoesNotExistException("Magic link does not exist for the given token."); | ||
| } | ||
|
|
||
| if (!magicLink.isUsable(Instant.now())) { | ||
| throw new InvalidParametersException("Invalid or expired magic link."); | ||
| } | ||
|
|
||
| magicLinksDb.deleteMagicLink(magicLink); | ||
| return magicLink; | ||
| } | ||
|
|
||
| /** | ||
| * Deletes a magic link. | ||
| */ | ||
| public void deleteMagicLink(MagicLink magicLink) { | ||
| Objects.requireNonNull(magicLink); | ||
| magicLinksDb.deleteMagicLink(magicLink); | ||
| } | ||
|
|
||
| /** | ||
| * Hashes a raw magic-link token for storage or lookup. | ||
| */ | ||
| static String hashToken(String token) { | ||
| Objects.requireNonNull(token); | ||
| return StringHelper.generateSha256Hmac("magic-link:" + token); | ||
| } | ||
|
|
||
| private static String generateToken() { | ||
| byte[] tokenBytes = new byte[TOKEN_BYTE_LENGTH]; | ||
| SECURE_RANDOM.nextBytes(tokenBytes); | ||
| return Base64.getUrlEncoder().withoutPadding().encodeToString(tokenBytes); | ||
| } | ||
|
|
||
| private void validateMagicLink(MagicLink magicLink) throws InvalidParametersException { | ||
| if (!magicLink.isValid()) { | ||
| throw new InvalidParametersException(magicLink.getInvalidityInfo()); | ||
| } | ||
| } | ||
|
|
||
| } | ||
106 changes: 106 additions & 0 deletions
106
src/test/java/teammates/logic/core/MagicLinksLogicTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,106 @@ | ||
| package teammates.logic.core; | ||
|
|
||
| import static org.junit.jupiter.api.Assertions.assertEquals; | ||
| import static org.junit.jupiter.api.Assertions.assertThrows; | ||
| import static org.mockito.ArgumentMatchers.any; | ||
| import static org.mockito.Mockito.mock; | ||
| import static org.mockito.Mockito.never; | ||
| import static org.mockito.Mockito.times; | ||
| import static org.mockito.Mockito.verify; | ||
| import static org.mockito.Mockito.when; | ||
|
|
||
| import java.time.Instant; | ||
|
|
||
| import org.mockito.ArgumentCaptor; | ||
| import org.testng.annotations.BeforeMethod; | ||
| import org.testng.annotations.Test; | ||
|
|
||
| import teammates.common.exception.EntityDoesNotExistException; | ||
| import teammates.common.exception.InvalidParametersException; | ||
| import teammates.storage.api.MagicLinksDb; | ||
| import teammates.storage.entity.MagicLink; | ||
| import teammates.test.BaseTestCase; | ||
|
|
||
| /** | ||
| * SUT: {@link MagicLinksLogic}. | ||
| */ | ||
| public class MagicLinksLogicTest extends BaseTestCase { | ||
|
|
||
| private MagicLinksLogic magicLinksLogic = MagicLinksLogic.inst(); | ||
|
|
||
| private MagicLinksDb magicLinksDb; | ||
|
|
||
| @BeforeMethod | ||
| public void setUpMethod() { | ||
| magicLinksDb = mock(MagicLinksDb.class); | ||
| magicLinksLogic.initLogicDependencies(magicLinksDb); | ||
| } | ||
|
|
||
| @Test | ||
| public void createMagicLink_validEmail_generatesTokenAndStoresHash() throws InvalidParametersException { | ||
| when(magicLinksDb.persistMagicLink(any(MagicLink.class))).thenAnswer(inv -> inv.getArgument(0)); | ||
|
|
||
| String token = magicLinksLogic.createMagicLink("user@example.com"); | ||
|
|
||
| ArgumentCaptor<MagicLink> captor = ArgumentCaptor.forClass(MagicLink.class); | ||
| verify(magicLinksDb, times(1)).persistMagicLink(captor.capture()); | ||
| MagicLink persistedMagicLink = captor.getValue(); | ||
|
|
||
| assertEquals("user@example.com", persistedMagicLink.getEmail()); | ||
| assertEquals(MagicLinksLogic.hashToken(token), persistedMagicLink.getTokenHash()); | ||
| } | ||
|
|
||
| @Test | ||
| public void createMagicLink_invalidEmail_throwsInvalidParametersException() { | ||
| assertThrows(InvalidParametersException.class, () -> magicLinksLogic.createMagicLink("invalid-email")); | ||
|
|
||
| verify(magicLinksDb, never()).persistMagicLink(any(MagicLink.class)); | ||
| } | ||
|
|
||
| @Test | ||
| public void getMagicLinkByToken_tokenExists_returnsMagicLink() { | ||
| String token = "raw-token"; | ||
| MagicLink magicLink = new MagicLink("user@example.com", MagicLinksLogic.hashToken(token), Instant.now()); | ||
| when(magicLinksDb.getMagicLinkByTokenHash(MagicLinksLogic.hashToken(token))).thenReturn(magicLink); | ||
|
|
||
| MagicLink actual = magicLinksLogic.getMagicLinkByToken(token); | ||
|
|
||
| assertEquals(magicLink, actual); | ||
| } | ||
|
|
||
| @Test | ||
| public void consumeMagicLink_magicLinkIsUsable_deletesAndReturnsMagicLink() | ||
| throws EntityDoesNotExistException, InvalidParametersException { | ||
| String token = "raw-token"; | ||
| MagicLink magicLink = new MagicLink("user@example.com", MagicLinksLogic.hashToken(token), Instant.now()); | ||
| when(magicLinksDb.getMagicLinkByTokenHash(MagicLinksLogic.hashToken(token))).thenReturn(magicLink); | ||
|
|
||
| MagicLink actual = magicLinksLogic.consumeMagicLink(token); | ||
|
|
||
| assertEquals(magicLink, actual); | ||
| verify(magicLinksDb, times(1)).deleteMagicLink(magicLink); | ||
| } | ||
|
|
||
| @Test | ||
| public void consumeMagicLink_magicLinkIsExpired_throwsInvalidParametersExceptionWithoutDeleting() { | ||
| String token = "raw-token"; | ||
| MagicLink magicLink = new MagicLink("user@example.com", MagicLinksLogic.hashToken(token), Instant.now()); | ||
| magicLink.setExpiresAt(Instant.now().minusSeconds(1)); | ||
| when(magicLinksDb.getMagicLinkByTokenHash(MagicLinksLogic.hashToken(token))).thenReturn(magicLink); | ||
|
|
||
| InvalidParametersException ex = assertThrows( | ||
| InvalidParametersException.class, () -> magicLinksLogic.consumeMagicLink(token)); | ||
|
|
||
| assertEquals("Invalid or expired magic link.", ex.getMessage()); | ||
| verify(magicLinksDb, never()).deleteMagicLink(any(MagicLink.class)); | ||
| } | ||
|
|
||
| @Test | ||
| public void consumeMagicLink_magicLinkDoesNotExist_throwsEntityDoesNotExistException() { | ||
| EntityDoesNotExistException ex = assertThrows( | ||
| EntityDoesNotExistException.class, () -> magicLinksLogic.consumeMagicLink("raw-token")); | ||
|
|
||
| assertEquals("Magic link does not exist for the given token.", ex.getMessage()); | ||
| verify(magicLinksDb, never()).deleteMagicLink(any(MagicLink.class)); | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Why was the 'magic-link:' prefix added here? What purpose does this serve?