Context: In my organization, we are using google's services for email. In the UI, we let user change their email alias, and delete their email alias. They can only have one email alias.
I am using Directory API or ADMIN SDK in Spring boot to insert/delete alias.
The Problem:
I am inserting an alias using, directoryService.users().aliases().insert(primaryEmailId, alias).execute();
It takes 1 minutes for a new alias to reflect.
Now if a user wants to delete/change the email alias within one minute of adding up a new alias, the request for deletion will fail at the backend since the newly inserted alias has not been reflected yet. As a result, a newest alias will be created but the old one will not get deleted.
How to tackle this? One way to fix this is to disable edit button for 1 minute in the UI, but this is not a good user experience.
So are there any other ways?
Insert Alias METHOD:
Alias alias = new Alias();
alias.setAlias(newEmailAlias);
try {
directoryService.users().aliases().insert(primaryEmailId, alias).execute();
} catch (IOException e) {
e.printStackTrace();
}
GET ALIAS METHOD:
public List<String> getAliases(String primaryEmailId) {
User user = null;
try {
user = directoryService.users().get(primaryEmailId).execute();
} catch (IOException e) {
e.printStackTrace();
}
return user.getAliases();
}
Delete alias:
try {
directoryService.users().aliases().delete(primaryEmailId, emailAlias).execute();
} catch (IOException e) {
e.printStackTrace();
}
Adding some more details on how i am generating directory object. I am using a service account to get the service object:
private static final String APPLICATION_NAME = "Google Aliases List";
private static final List<String> SCOPES = Collections.singletonList(DirectoryScopes.ADMIN_DIRECTORY_USER);
private static final String CREDENTIALS_FILE_PATH = "/gmail-api-randonnum-randomletter.json";
@Bean
public Directory directoryService() {
HttpTransport httpTransport = null;
Directory service = null;
try {
httpTransport = GoogleNetHttpTransport.newTrustedTransport();
JsonFactory jsonFactory = GsonFactory.getDefaultInstance();
HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(getCredentials());
service = new Directory.Builder(httpTransport, jsonFactory, requestInitializer)
.setApplicationName(APPLICATION_NAME)
.build();
} catch (GeneralSecurityException | IOException e) {
System.out.println(e);
}
return service;
}
private GoogleCredentials getCredentials() throws IOException {
// Load client secrets.
InputStream in = GoogleDirectoryAPIConfig.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
if (in == null) {
throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);
}
return GoogleCredentials.fromStream(in).createScoped(SCOPES).createDelegated("admin@email.com");
}