Skip to content

Commit

Permalink
Merge pull request #1207 from navikt/email_cleanup
Browse files Browse the repository at this point in the history
ORG-1582: Cleanup email sending
  • Loading branch information
eziztm authored Oct 12, 2023
2 parents 5d3c6d8 + 5327622 commit e170d9f
Show file tree
Hide file tree
Showing 5 changed files with 4 additions and 77 deletions.

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,13 @@ public class EmailServiceImpl implements EmailService {
public static final Logger logger = LogManager.getLogger(EmailServiceImpl.class);

private final StorageService storage;
private final EmailProvider emailProvider;
private final SecurityProperties securityProperties;

private final EmailClient emailClient;

public EmailServiceImpl(StorageService storage, EmailProvider emailProvider,
SecurityProperties securityProperties, EmailClient emailClient) {
public EmailServiceImpl(StorageService storage, SecurityProperties securityProperties,
EmailClient emailClient) {
this.storage = storage;
this.emailProvider = emailProvider;
this.securityProperties = securityProperties;
this.emailClient = emailClient;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,13 @@

import com.microsoft.graph.core.ClientException;
import com.microsoft.graph.http.GraphServiceException;
import com.microsoft.graph.models.UserSendMailParameterSet;
import com.microsoft.graph.options.QueryOption;
import com.microsoft.graph.requests.GraphServiceClient;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import no.nav.data.common.exceptions.TechnicalException;
import no.nav.data.common.exceptions.TimeoutException;
import no.nav.data.common.mail.EmailProvider;
import no.nav.data.common.mail.MailTask;
import no.nav.data.common.security.SecurityProperties;
import no.nav.data.common.security.azure.support.GraphLogger;
import no.nav.data.common.storage.StorageService;
import okhttp3.Request;
import org.springframework.stereotype.Service;
import org.springframework.util.StreamUtils;
Expand All @@ -23,42 +18,19 @@
import java.util.List;

import static no.nav.data.common.security.azure.AzureConstants.MICROSOFT_GRAPH_SCOPE_APP;
import static no.nav.data.common.security.azure.support.MailMessage.compose;

@Slf4j
@Service
@RequiredArgsConstructor
public class AzureAdService implements EmailProvider {
public class AzureAdService {

private final AzureTokenProvider azureTokenProvider;
private final SecurityProperties securityProperties;
private final StorageService storage;

public byte[] lookupProfilePictureByNavIdent(String navIdent) {
String userId = lookupUserIdForNavIdent(navIdent);
return lookupUserProfilePicture(userId);
}

@Override
public void sendMail(MailTask mailTask) {
log.info("Sending mail {} to {}", mailTask.getSubject(), mailTask.getTo());
if (securityProperties.isDev()) {
// if (securityProperties.isDev() && !securityProperties.isDevEmailAllowed(mailTask.getTo())) {
// disable mail in dev for now due to trygdeetaten.no
log.info("skipping mail, not allowed in dev");
} else {
getMailGraphClient().me()
.sendMail(UserSendMailParameterSet.newBuilder()
.withMessage(compose(mailTask.getTo(), mailTask.getSubject(), mailTask.getBody()))
.withSaveToSentItems(false)
.build())
.buildRequest()
.post();
}

storage.save(mailTask.toMailLog());
}

private String lookupUserIdForNavIdent(String navIdent) {
var res = getAppGraphClient()
.users().buildRequest(List.of(new QueryOption("$filter", "mailNickname eq '" + navIdent + "'")))
Expand Down Expand Up @@ -91,10 +63,6 @@ private byte[] lookupUserProfilePicture(String id) {
}
}

private GraphServiceClient<Request> getMailGraphClient() {
return azureTokenProvider.getGraphClient(azureTokenProvider.getMailAccessToken());
}

private GraphServiceClient<Request> getAppGraphClient() {
return azureTokenProvider.getGraphClient(azureTokenProvider.getApplicationTokenForResource(MICROSOFT_GRAPH_SCOPE_APP));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

import com.microsoft.aad.msal4j.ClientCredentialFactory;
import com.microsoft.aad.msal4j.ConfidentialClientApplication;
import com.microsoft.aad.msal4j.PublicClientApplication;
import com.nimbusds.jose.jwk.source.RemoteJWKSet;
import com.nimbusds.jose.util.DefaultResourceRetriever;
import com.nimbusds.jose.util.ResourceRetriever;
Expand Down Expand Up @@ -55,15 +54,6 @@ public ConfidentialClientApplication msalClient(AADAuthenticationProperties aadA
.build();
}

@Bean
@SneakyThrows
public PublicClientApplication msalPublicClient(AADAuthenticationProperties aadAuthProps, OIDCProviderMetadata oidcProviderMetadata) {
return PublicClientApplication
.builder(aadAuthProps.getClientId())
.authority(oidcProviderMetadata.getAuthorizationEndpointURI().toString())
.build();
}

@Bean
public ThreadPoolExecutor msalThreadPool() {
return MdcExecutor.newThreadPool(5, "msal");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,8 @@
import com.microsoft.aad.msal4j.ClientCredentialParameters;
import com.microsoft.aad.msal4j.IAuthenticationResult;
import com.microsoft.aad.msal4j.IConfidentialClientApplication;
import com.microsoft.aad.msal4j.PublicClientApplication;
import com.microsoft.aad.msal4j.RefreshTokenParameters;
import com.microsoft.aad.msal4j.ResponseMode;
import com.microsoft.aad.msal4j.UserNamePasswordParameters;
import com.microsoft.graph.requests.GraphServiceClient;
import com.nimbusds.oauth2.sdk.pkce.CodeChallengeMethod;
import io.prometheus.client.Summary;
Expand Down Expand Up @@ -54,7 +52,6 @@ public class AzureTokenProvider implements TokenProvider {
private final Cache<String, IAuthenticationResult> accessTokenCache;

private final IConfidentialClientApplication msalClient;
private final PublicClientApplication msalPublicClient;
private final AuthService authService;

private final AADAuthenticationProperties aadAuthProps;
Expand All @@ -63,11 +60,10 @@ public class AzureTokenProvider implements TokenProvider {
private final Summary tokenMetrics;

public AzureTokenProvider(AADAuthenticationProperties aadAuthProps,
IConfidentialClientApplication msalClient, PublicClientApplication msalPublicClient,
IConfidentialClientApplication msalClient,
AuthService authService, Encryptor encryptor) {
this.aadAuthProps = aadAuthProps;
this.msalClient = msalClient;
this.msalPublicClient = msalPublicClient;
this.authService = authService;
this.encryptor = encryptor;
this.tokenMetrics = MetricUtils.summary()
Expand Down Expand Up @@ -177,12 +173,6 @@ private String getAccessTokenForResource(String refreshToken, String resource) {
return requireNonNull(accessTokenCache.get("refresh" + refreshToken + resource, cacheKey -> acquireTokenByRefreshToken(refreshToken, resource))).accessToken();
}

public String getMailAccessToken() {
log.trace("Getting access token for mail");
return requireNonNull(accessTokenCache.get("mail", cacheKey -> acquireTokenForUser(Set.of("Mail.Send"), aadAuthProps.getMailUser(), aadAuthProps.getMailPassword())))
.accessToken();
}

private IAuthenticationResult acquireTokenByRefreshToken(String refreshToken, String resource) {
try (var ignored = tokenMetrics.labels("accessToken").startTimer()) {
log.debug("Looking up access token for resource {}", resource);
Expand All @@ -192,18 +182,6 @@ private IAuthenticationResult acquireTokenByRefreshToken(String refreshToken, St
}
}

/**
* used for email user
*/
private IAuthenticationResult acquireTokenForUser(Set<String> scopes, String username, String password) {
try {
log.debug("Looking up access token for user {}", username);
return msalPublicClient.acquireToken(UserNamePasswordParameters.builder(scopes, username, password.toCharArray()).build()).get();
} catch (Exception e) {
throw new TechnicalException("Failed to get access token for username " + username, e);
}
}

/**
* access token for app user
*/
Expand Down

0 comments on commit e170d9f

Please sign in to comment.