@Override
 public Notification createNotification(String orcid, Notification notification) {
   if (notification.getPutCode() != null) {
     throw new IllegalArgumentException("Put code must be null when creating a new notification");
   }
   NotificationEntity notificationEntity = notificationAdapter.toNotificationEntity(notification);
   ProfileEntity profile = profileEntityCacheManager.retrieve(orcid);
   if (profile == null) {
     throw OrcidNotFoundException.newInstance(orcid);
   }
   notificationEntity.setProfile(profile);
   notificationEntity.setSource(sourceManager.retrieveSourceEntity());
   notificationDao.persist(notificationEntity);
   return notificationAdapter.toNotification(notificationEntity);
 }
  @Override
  public void sendWelcomeEmail(OrcidProfile orcidProfile, String email) {
    Map<String, Object> templateParams = new HashMap<String, Object>();
    String subject = getSubject("email.subject.register.thanks", orcidProfile);
    String emailName = deriveEmailFriendlyName(orcidProfile);
    String verificationUrl = createVerificationUrl(email, orcidUrlManager.getBaseUrl());
    String orcidId = orcidProfile.getOrcidIdentifier().getPath();
    String baseUri = orcidUrlManager.getBaseUrl();
    String baseUriHttp = orcidUrlManager.getBaseUriHttp();

    templateParams.put("subject", subject);
    templateParams.put("emailName", emailName);
    templateParams.put("verificationUrl", verificationUrl);
    templateParams.put("orcidId", orcidId);
    templateParams.put("baseUri", baseUri);
    templateParams.put("baseUriHttp", baseUriHttp);

    SourceEntity source = sourceManager.retrieveSourceEntity();
    if (source != null) {
      String sourceId = source.getSourceId();
      String sourceName = source.getSourceName();
      // If the source is not the user itself
      if (sourceId != null && !sourceId.equals(orcidId)) {
        if (!PojoUtil.isEmpty(sourceName)) {
          String paramValue =
              " " + localeManager.resolveMessage("common.through") + " " + sourceName + ".";
          templateParams.put("source_name_if_exists", paramValue);
        } else {
          templateParams.put("source_name_if_exists", ".");
        }
      } else {
        templateParams.put("source_name_if_exists", ".");
      }
    } else {
      templateParams.put("source_name_if_exists", ".");
    }

    addMessageParams(templateParams, orcidProfile);

    // Generate body from template
    String body = templateManager.processTemplate("welcome_email.ftl", templateParams);
    // Generate html from template
    String html = templateManager.processTemplate("welcome_email_html.ftl", templateParams);

    mailGunManager.sendEmail(SUPPORT_VERIFY_ORCID_ORG, email, subject, body, html);
  }
 @Override
 protected Authentication attemptSwitchUser(HttpServletRequest request)
     throws AuthenticationException {
   String targetUserOrcid = request.getParameter(SPRING_SECURITY_SWITCH_USERNAME_KEY);
   ProfileEntity profileEntity = sourceManager.retrieveSourceProfileEntity();
   if (OrcidType.ADMIN.equals(profileEntity.getOrcidType())) {
     return super.attemptSwitchUser(request);
   }
   // If we are switching back to me it is OK
   if (isSwitchingBack(request)) {
     return super.attemptSwitchUser(request);
   }
   for (GivenPermissionByEntity gpbe : profileEntity.getGivenPermissionBy()) {
     if (gpbe.getGiver().getId().equals(targetUserOrcid)) {
       return super.attemptSwitchUser(request);
     }
   }
   Object params[] = {};
   throw new SwitchUserAuthenticationException(
       localeManager.resolveMessage("web.orcid.switchuser.exception", params));
 }
 @Override
 @Transactional
 public Notification flagAsArchived(String orcid, Long id)
     throws OrcidNotificationAlreadyReadException {
   NotificationEntity notificationEntity = notificationDao.findByOricdAndId(orcid, id);
   if (notificationEntity == null) {
     return null;
   }
   String sourceId = sourceManager.retrieveSourceOrcid();
   if (sourceId != null && !sourceId.equals(notificationEntity.getSource().getSourceId())) {
     Map<String, String> params = new HashMap<String, String>();
     params.put("activity", "notification");
     throw new WrongSourceException(params);
   }
   if (notificationEntity.getReadDate() != null) {
     throw new OrcidNotificationAlreadyReadException();
   }
   if (notificationEntity.getArchivedDate() == null) {
     notificationEntity.setArchivedDate(new Date());
     notificationDao.merge(notificationEntity);
   }
   return notificationAdapter.toNotification(notificationEntity);
 }
  @Override
  public void sendAmendEmail(
      OrcidProfile amendedProfile, AmendedSection amendedSection, Collection<Item> items) {
    String amenderOrcid = sourceManager.retrieveSourceOrcid();
    if (amenderOrcid == null) {
      LOGGER.debug("Not sending amend email, because amender is null: {}", amendedProfile);
      return;
    }
    if (amenderOrcid.equals(amendedProfile.getOrcidIdentifier().getPath())) {
      LOGGER.debug("Not sending amend email, because self edited: {}", amendedProfile);
      return;
    }
    SendChangeNotifications sendChangeNotifications =
        amendedProfile.getOrcidInternal().getPreferences().getSendChangeNotifications();
    if (sendChangeNotifications == null || !sendChangeNotifications.isValue()) {
      LOGGER.debug(
          "Not sending amend email, because option to send change notifications not set to true: {}",
          amendedProfile);
      return;
    }
    if (OrcidType.ADMIN.equals(profileDao.retrieveOrcidType(amenderOrcid))) {
      LOGGER.debug(
          "Not sending amend email, because modified by admin ({}): {}",
          amenderOrcid,
          amendedProfile);
      return;
    }

    String subject = getSubject("email.subject.amend", amendedProfile);

    // Create map of template params
    Map<String, Object> templateParams = new HashMap<String, Object>();
    templateParams.put("emailName", deriveEmailFriendlyName(amendedProfile));
    templateParams.put("orcid", amendedProfile.getOrcidIdentifier().getPath());
    templateParams.put("amenderName", extractAmenderName(amendedProfile, amenderOrcid));
    templateParams.put("baseUri", orcidUrlManager.getBaseUrl());
    templateParams.put("baseUriHttp", orcidUrlManager.getBaseUriHttp());
    templateParams.put("subject", subject);

    addMessageParams(templateParams, amendedProfile);

    // Generate body from template
    String body = templateManager.processTemplate("amend_email.ftl", templateParams);
    // Generate html from template
    String html = templateManager.processTemplate("amend_email_html.ftl", templateParams);

    boolean notificationsEnabled =
        profileDao.find(amendedProfile.getOrcidIdentifier().getPath()).getEnableNotifications();
    if (notificationsEnabled) {
      NotificationAmended notification = new NotificationAmended();
      notification.setNotificationType(NotificationType.AMENDED);
      notification.setAmendedSection(amendedSection);
      if (items != null) {
        notification.setItems(new Items(new ArrayList<>(items)));
      }
      createNotification(amendedProfile.getOrcidIdentifier().getPath(), notification);
    } else {
      String email =
          amendedProfile.getOrcidBio().getContactDetails().retrievePrimaryEmail().getValue();
      mailGunManager.sendEmail(AMEND_NOTIFY_ORCID_ORG, email, subject, body, html);
    }
  }
 private boolean isSwitchingBack(HttpServletRequest request) {
   String targetUserOrcid = request.getParameter(SPRING_SECURITY_SWITCH_USERNAME_KEY);
   String realUser = sourceManager.retrieveRealUserOrcid();
   return targetUserOrcid.equals(realUser);
 }