@Test
  public void testParseCookieIncorrectVersion() throws Exception {
    String unprotectedvalue = "1.1.1.1:bearer token:testscope:PUBLIC:1111:test-hash";

    when(cryptoSupportMock.unprotect(URL_ENCODING_AGNOSTIC_VALUE)).thenReturn(unprotectedvalue);

    AemCortexContext result = processor.deserializeValue(URL_ENCODING_AGNOSTIC_VALUE);

    assertNull("Context should not have been created", result);
  }
  @Test
  public void testParseCookieMissingData() throws Exception {
    String unprotectedvalue =
        AemCortexCookieTransformerImpl.CURRENT_VERSION + ":bearer token:1111:test-hash";

    when(cryptoSupportMock.unprotect(URL_ENCODING_AGNOSTIC_VALUE)).thenReturn(unprotectedvalue);

    AemCortexContext result = processor.deserializeValue(URL_ENCODING_AGNOSTIC_VALUE);

    assertNull("Context should not have been created", result);
  }
  @Test
  public void testSerializeValue() throws Exception {
    AemCortexContext context =
        new AemCortexContext.ContextBuilder()
            .withAuthenticationToken(TEST_TOKEN)
            .withScope("test-scope")
            .withRole(PUBLIC_ROLE)
            .withExpiryDate(new Date(TEST_EXPIRES_PAST))
            .withIdentifier("test-hash")
            .withVersion(AemCortexCookieTransformerImpl.CURRENT_VERSION)
            .build();

    when(cryptoSupportMock.protect(isA(String.class))).thenReturn(URL_ENCODING_AGNOSTIC_VALUE);

    String result = processor.serializeValue(context);

    assertEquals(result, URL_ENCODING_AGNOSTIC_VALUE);
  }
  @Test
  public void testParseValidCookieValue() throws Exception {
    String unprotectedvalue =
        AemCortexCookieTransformerImpl.CURRENT_VERSION
            + ":bearer token:testscope:PUBLIC:1111:test-hash";

    when(cryptoSupportMock.unprotect(URL_ENCODING_AGNOSTIC_VALUE)).thenReturn(unprotectedvalue);

    AemCortexContext result = processor.deserializeValue(URL_ENCODING_AGNOSTIC_VALUE);

    assertEquals(
        "Cookie version did not match",
        AemCortexCookieTransformerImpl.CURRENT_VERSION,
        result.getVersion());
    assertEquals("Cookie token did not match", TEST_TOKEN, result.getAuthenticationToken());
    assertEquals("Cookie scope did not match", "testscope", result.getScope());
    assertEquals("Cookie role did not match", PUBLIC_ROLE, result.getRole());
    assertEquals(
        "Cookie expires did not match", TEST_EXPIRES_PAST, result.getExpiryDate().getTime());
    assertEquals("Cookie hash did not match", "test-hash", result.getIdentifier());
  }
  @Override
  protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response)
      throws ServletException, IOException {
    HtmlResponse htmlResponse = null;
    ResourceResolver adminResolver = null;
    Session adminSession = null;

    try {
      String email = request.getParameter(REQ_PRM_USERNAME);
      String password = request.getParameter(REQ_PRM_PASSWORD);
      String inviteKey = request.getParameter(REQ_PRM_INVITEKEY);
      String acceptStatus = request.getParameter(REQ_PRM_ACCEPT_STATUS);

      adminResolver = getAdminResolver();
      adminSession = adminResolver.adaptTo(Session.class);

      InvitationToken invToken =
          ccInvitationService.getInvitationTokenByTokenKey(inviteKey, adminResolver);
      if (invToken != null && invToken.isValid() && inviteKey.equals(invToken.getKey())) {

        // Gets user account if user is already configured. Gets null
        // otherwise.
        Resource configResource = CCUtils.getAccountResourceByUserEmail(adminResolver, email);
        if (configResource == null) { // Create configuration if not
          // present. For first time login

          // encrypt the password
          if (!crypto.isProtected(password)) {
            password = crypto.protect(password);
          }
          AccessToken token = null;
          try {
            token = imsService.getAccessToken(email, password);
          } catch (Exception e) {
            log.error(e.getMessage(), e);
            htmlResponse =
                HtmlStatusResponseHelper.createStatusResponse(false, "Invalid Credentials");
          }
          if (token != null) { // succesful login
            String configName = "invited_" + email;
            configName = configName.replace("@", "_at_").replaceAll("\\.", "_");
            PageManager pageManager = pageManagerFactory.getPageManager(adminResolver);
            pageManager.create(CC_CONFIG_ROOT, configName, configName, CC_CONFIG_PAGE_TEMPLATE);

            Node configNode = adminSession.getNode(CC_CONFIG_ROOT + "/" + configName);
            Node contentNode = configNode.getNode("jcr:content");
            contentNode.setProperty(CreativeCloudAccountConfig.PROPERTY_USERNAME, email);
            contentNode.setProperty("sling:resourceType", CreativeCloudAccountConfig.RESOURCE_TYPE);

            contentNode.setProperty(
                CreativeCloudAccountConfig.PROPERTY_ACCESS_TOKEN, token.getAccessToken());
            contentNode.setProperty(
                CreativeCloudAccountConfig.PROPERTY_REFRESH_TOKEN, token.getRefreshToken());
            contentNode.setProperty(
                CreativeCloudAccountConfig.PROPERTY_TOKEN_EXPIRES, token.getExpiresIn());
            contentNode.setProperty(CreativeCloudAccountConfig.PROPERTY_PASSWORD, password);

            Node pollConfigNode = contentNode.addNode(CreativeCloudAccountConfig.NN_POLLCONFIG);
            pollConfigNode.setProperty(
                CreativeCloudAccountConfig.PROPERTY_INTERVAL, importer.getMinimumInterval());
            pollConfigNode.setProperty(CreativeCloudAccountConfig.PROPERTY_ENABLED, true);

            configResource = adminResolver.getResource(contentNode.getPath());
            ccConfigService.initAccount(configResource);
          }
        } else {
          // Sets the jcr content node as the config node
          configResource = configResource.getChild("jcr:content");
        }
        if (acceptStatus != null && acceptStatus.equalsIgnoreCase("false")) {
          htmlResponse = HtmlStatusResponseHelper.createStatusResponse(true, "invitation declined");
        } else {
          String[] paths = invToken.getPaths();
          for (String path : paths) {
            // ccShareService.shareWithCCUser(configResource,
            // adminResolver.getResource(path));
            // Asynchronous sharing
            Object job =
                new CCShareInBackground(factory, configResource.getPath(), path, ccShareService);
            String jobName =
                CCShareInBackground.class.getName()
                    + "_"
                    + UUID.randomUUID().toString().substring(0, 8);
            scheduler.fireJobAt(jobName, job, null, new Date());
          }
          htmlResponse = HtmlStatusResponseHelper.createStatusResponse(true, "invitation accepted");
        }
        ccInvitationService.acceptInvitation(email, inviteKey, adminResolver);
        adminSession.save();

      } else {
        htmlResponse =
            HtmlStatusResponseHelper.createStatusResponse(
                false, "invitation expired or already accepted/declined");
      }
    } catch (Exception e) {
      log.error(e.getMessage(), e);
      htmlResponse = HtmlStatusResponseHelper.createStatusResponse(false, e.getMessage());
      htmlResponse.setError(e);
    } finally {
      if (adminSession != null) {
        adminSession.logout();
      }
      if (adminResolver != null) {
        adminResolver.close();
      }
      assert htmlResponse != null;
      htmlResponse.send(response, true);
    }
  }