use of com.google.api.services.directory.model.User in project workbench by all-of-us.
the class ProfileControllerTest method setUp.
@BeforeEach
@Override
public void setUp() throws IOException {
super.setUp();
config.googleDirectoryService.gSuiteDomain = GSUITE_DOMAIN;
// key UserService logic depends on the existence of the Registered Tier
registeredTier = TestMockFactory.createRegisteredTierForTests(accessTierDao);
rtAddressesConfig = new InstitutionTierConfig().membershipRequirement(InstitutionMembershipRequirement.ADDRESSES).eraRequired(false).accessTierShortName(registeredTier.getShortName());
rtDomainsConfig = new InstitutionTierConfig().membershipRequirement(InstitutionMembershipRequirement.DOMAINS).eraRequired(false).accessTierShortName(registeredTier.getShortName());
Profile profile = new Profile();
profile.setContactEmail(CONTACT_EMAIL);
profile.setFamilyName(FAMILY_NAME);
profile.setGivenName(GIVEN_NAME);
profile.setUsername(USER_PREFIX);
profile.setAreaOfResearch(RESEARCH_PURPOSE);
profile.setAddress(new Address().streetAddress1(STREET_ADDRESS).city(CITY).state(STATE).country(COUNTRY).zipCode(ZIP_CODE));
createAccountRequest = new CreateAccountRequest();
createAccountRequest.setTermsOfServiceVersion(LATEST_AOU_TOS_VERSION);
createAccountRequest.setProfile(profile);
createAccountRequest.setCaptchaVerificationToken(CAPTCHA_TOKEN);
googleUser = new User();
googleUser.setPrimaryEmail(FULL_USER_NAME);
googleUser.setChangePasswordAtNextLogin(true);
googleUser.setPassword("testPassword");
googleUser.setIsEnrolledIn2Sv(true);
config.access.currentDuccVersions = ImmutableList.of(CURRENT_DUCC_VERSION);
when(mockDirectoryService.getUserOrThrow(FULL_USER_NAME)).thenReturn(googleUser);
when(mockDirectoryService.createUser(GIVEN_NAME, FAMILY_NAME, FULL_USER_NAME, CONTACT_EMAIL)).thenReturn(googleUser);
when(mockCloudStorageClient.getCaptchaServerKey()).thenReturn("Server_Key");
try {
when(mockCaptchaVerificationService.verifyCaptcha(CAPTCHA_TOKEN)).thenReturn(true);
when(mockCaptchaVerificationService.verifyCaptcha(WRONG_CAPTCHA_TOKEN)).thenReturn(false);
when(mockFireCloudService.getUserTermsOfServiceStatus()).thenReturn(true);
} catch (ApiException | org.pmiops.workbench.firecloud.ApiException e) {
e.printStackTrace();
}
accessModules = TestMockFactory.createAccessModules(accessModuleDao);
}
use of com.google.api.services.directory.model.User in project workbench by all-of-us.
the class ProfileController method updateContactEmail.
/*
* This un-authed API method is limited such that we only allow contact email updates before the user has signed in
* with the newly created gsuite account. Once the user has logged in, they can change their contact email through
* the normal profile update process.
*/
@Override
public ResponseEntity<Void> updateContactEmail(UpdateContactEmailRequest updateContactEmailRequest) {
String username = updateContactEmailRequest.getUsername().toLowerCase();
User googleUser = directoryService.getUserOrThrow(username);
DbUser user = userService.getByUsernameOrThrow(username);
checkUserCreationNonce(user, updateContactEmailRequest.getCreationNonce());
if (userHasEverLoggedIn(googleUser, user)) {
return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
}
String newEmail = updateContactEmailRequest.getContactEmail();
try {
new InternetAddress(newEmail).validate();
} catch (AddressException e) {
log.log(Level.INFO, "Invalid email entered.");
return ResponseEntity.badRequest().build();
}
user.setContactEmail(newEmail);
return resetPasswordAndSendWelcomeEmail(username, user);
}
use of com.google.api.services.directory.model.User in project workbench by all-of-us.
the class ProfileController method createAccount.
@Override
public ResponseEntity<Profile> createAccount(CreateAccountRequest request) {
if (workbenchConfigProvider.get().captcha.enableCaptcha) {
verifyCaptcha(request.getCaptchaVerificationToken());
}
userService.validateAllOfUsTermsOfService(request.getTermsOfServiceVersion());
profileService.validateAffiliation(request.getProfile());
final Profile profile = request.getProfile();
profileService.cleanProfile(profile);
profileService.validateNewProfile(profile);
String gSuiteUsername = profile.getUsername() + "@" + workbenchConfigProvider.get().googleDirectoryService.gSuiteDomain;
User googleUser = directoryService.createUser(profile.getGivenName(), profile.getFamilyName(), gSuiteUsername, profile.getContactEmail());
DbUser user;
try {
user = userService.createUser(profile.getGivenName(), profile.getFamilyName(), gSuiteUsername, profile.getContactEmail(), profile.getAreaOfResearch(), profile.getProfessionalUrl(), profile.getDegrees(), addressMapper.addressToDbAddress(profile.getAddress()), demographicSurveyMapper.demographicSurveyToDbDemographicSurvey(profile.getDemographicSurvey()), verifiedInstitutionalAffiliationMapper.modelToDbWithoutUser(profile.getVerifiedInstitutionalAffiliation(), institutionService));
} catch (Exception e) {
// If the creation of a User row in the RW database fails, we want to attempt to remove the
// G Suite account to avoid having an orphaned account with no record in our database.
log.severe(String.format("An error occurred when creating DbUser for %s. Attempting to delete " + "orphaned G Suite account", gSuiteUsername));
try {
directoryService.deleteUser(gSuiteUsername);
log.severe("Orphaned G Suite account has been deleted.");
} catch (Exception e2) {
log.severe(String.format("Orphaned G Suite account %s could not be deleted. " + "Manual intervention may be required", gSuiteUsername));
log.log(Level.SEVERE, e2.getMessage(), e2);
// Throw the original error rather than the G Suite error.
throw e;
}
throw e;
}
// we can't call submitTerraTermsOfService() yet because the Terra account doesn't exist yet.
// see maybeInitializeUserWithTerra()
userService.submitAouTermsOfService(user, request.getTermsOfServiceVersion());
String institutionShortName = profile.getVerifiedInstitutionalAffiliation().getInstitutionShortName();
try {
Institution userInstitution = institutionService.getInstitution(institutionShortName).orElseThrow(() -> new BadRequestException("User Institution cannot be found"));
sendWelcomeEmail(user, googleUser, userInstitution);
} catch (BadRequestException ex) {
log.log(Level.SEVERE, "Exception while resending sending welcome email: " + ex.getLocalizedMessage());
throw ex;
}
final MailService mail = mailServiceProvider.get();
institutionService.getInstitutionUserInstructions(institutionShortName).ifPresent(instructions -> {
try {
mail.sendInstitutionUserInstructions(profile.getContactEmail(), instructions, gSuiteUsername);
} catch (MessagingException e) {
throw new WorkbenchException(e);
}
});
// Note: Avoid getProfileResponse() here as this is not an authenticated request.
final Profile createdProfile = profileService.getProfile(user);
profileAuditor.fireCreateAction(createdProfile);
return ResponseEntity.ok(createdProfile);
}
use of com.google.api.services.directory.model.User in project workbench by all-of-us.
the class DirectoryServiceImpl method getAllTwoFactorAuthStatuses.
@Override
public Map<String, Boolean> getAllTwoFactorAuthStatuses() {
final String domain = gSuiteDomain();
Map<String, Boolean> statuses = Maps.newHashMap();
Users response = null;
do {
final String pageToken = Optional.ofNullable(response).map(r -> r.getNextPageToken()).orElse(null);
try {
response = retryHandler.runAndThrowChecked((context) -> getGoogleDirectoryService().users().list().setProjection("basic").setDomain(domain).setPageToken(pageToken).execute());
} catch (IOException e) {
throw ExceptionUtils.convertGoogleIOException(e);
}
for (User u : response.getUsers()) {
statuses.put(u.getPrimaryEmail(), u.getIsEnrolledIn2Sv());
}
} while (!Strings.isNullOrEmpty(response.getNextPageToken()));
return statuses;
}
use of com.google.api.services.directory.model.User in project workbench by all-of-us.
the class DirectoryServiceImpl method resetUserPassword.
@Override
public User resetUserPassword(String username) {
User user = getUserOrThrow(username);
String password = randomString();
user.setPassword(password);
retryHandler.run((context) -> getGoogleDirectoryService().users().update(username, user).execute());
return user;
}
Aggregations