Class UnsubscribeTokenCodec

java.lang.Object
fr.becpg.repo.activity.unsubscribe.UnsubscribeTokenCodec

public class UnsubscribeTokenCodec extends Object
Creates and reads the signed tokens carried by the one-click unsubscribe link of the activity emails.

A token reads base64url(userName).expiry.base64url(signature), where the expiry is in epoch seconds and the signature is the HMAC-SHA256, under the key of the instance, of the instance host, the encoded user name and the expiry. Signing the host keeps a token of one instance from working on a copy of it that shares the same key.

Thread-safe: instances are immutable.

Author:
valentin
  • Field Details

  • Constructor Details

    • UnsubscribeTokenCodec

      public UnsubscribeTokenCodec(byte[] key, String instanceHost, Clock clock)
      Builds a codec bound to one instance.
      Parameters:
      key - the secret key of the instance
      instanceHost - the host name of the instance, part of the signed data
      clock - the clock giving the current time
  • Method Details

    • createToken

      public String createToken(String userName)
      Creates a token designating the given user, valid for VALIDITY.
      Parameters:
      userName - the user to unsubscribe
      Returns:
      the URL-safe token
    • readUserName

      public Optional<String> readUserName(String token)
      Reads the user designated by a token.
      Parameters:
      token - the token received
      Returns:
      the user name, or empty when the token is malformed, altered, expired or signed for another instance
    • readParts

      private Optional<String> readParts(String[] parts)
    • isSignedBy

      private boolean isSignedBy(String[] parts)
    • isExpired

      private boolean isExpired(String expiry)
    • sign

      private byte[] sign(String encodedUserName, String expiry)