Search in sources :

Example 1 with User

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);
}
Also used : InstitutionTierConfig(org.pmiops.workbench.model.InstitutionTierConfig) CreateAccountRequest(org.pmiops.workbench.model.CreateAccountRequest) DbUser(org.pmiops.workbench.db.model.DbUser) User(com.google.api.services.directory.model.User) Address(org.pmiops.workbench.model.Address) Profile(org.pmiops.workbench.model.Profile) ApiException(org.pmiops.workbench.captcha.ApiException) BeforeEach(org.junit.jupiter.api.BeforeEach)

Example 2 with User

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);
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) DbUser(org.pmiops.workbench.db.model.DbUser) User(com.google.api.services.directory.model.User) AddressException(javax.mail.internet.AddressException) DbUser(org.pmiops.workbench.db.model.DbUser)

Example 3 with 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);
}
Also used : DbUser(org.pmiops.workbench.db.model.DbUser) User(com.google.api.services.directory.model.User) MailService(org.pmiops.workbench.mail.MailService) MessagingException(javax.mail.MessagingException) BadRequestException(org.pmiops.workbench.exceptions.BadRequestException) Institution(org.pmiops.workbench.model.Institution) WorkbenchException(org.pmiops.workbench.exceptions.WorkbenchException) Profile(org.pmiops.workbench.model.Profile) UnauthorizedException(org.pmiops.workbench.exceptions.UnauthorizedException) ObjectOptimisticLockingFailureException(org.springframework.orm.ObjectOptimisticLockingFailureException) MessagingException(javax.mail.MessagingException) WorkbenchException(org.pmiops.workbench.exceptions.WorkbenchException) AddressException(javax.mail.internet.AddressException) ConflictException(org.pmiops.workbench.exceptions.ConflictException) BadRequestException(org.pmiops.workbench.exceptions.BadRequestException) ApiException(org.pmiops.workbench.moodle.ApiException) ServerErrorException(org.pmiops.workbench.exceptions.ServerErrorException) ForbiddenException(org.pmiops.workbench.exceptions.ForbiddenException) NotFoundException(org.pmiops.workbench.exceptions.NotFoundException) DbUser(org.pmiops.workbench.db.model.DbUser)

Example 4 with User

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;
}
Also used : IntStream(java.util.stream.IntStream) Directory(com.google.api.services.directory.Directory) DirectoryScopes(com.google.api.services.directory.DirectoryScopes) Arrays(java.util.Arrays) Provider(javax.inject.Provider) IamCredentialsClient(com.google.cloud.iam.credentials.v1.IamCredentialsClient) LoggerFactory(org.slf4j.LoggerFactory) Autowired(org.springframework.beans.factory.annotation.Autowired) HashMap(java.util.HashMap) SecureRandom(java.security.SecureRandom) UserEmail(com.google.api.services.directory.model.UserEmail) Strings(com.google.common.base.Strings) GoogleJsonResponseException(com.google.api.client.googleapis.json.GoogleJsonResponseException) Lists(com.google.common.collect.Lists) OAuth2Credentials(com.google.auth.oauth2.OAuth2Credentials) Service(org.springframework.stereotype.Service) Map(java.util.Map) User(com.google.api.services.directory.model.User) ServiceAccounts(org.pmiops.workbench.auth.ServiceAccounts) ExceptionUtils(org.pmiops.workbench.exceptions.ExceptionUtils) ImmutableSet(com.google.common.collect.ImmutableSet) MeasurementBundle(org.pmiops.workbench.monitoring.MeasurementBundle) Logger(org.slf4j.Logger) GaugeDataCollector(org.pmiops.workbench.monitoring.GaugeDataCollector) Collection(java.util.Collection) HttpTransport(com.google.api.client.http.HttpTransport) MetricLabel(org.pmiops.workbench.monitoring.labels.MetricLabel) IOException(java.io.IOException) GaugeMetric(org.pmiops.workbench.monitoring.views.GaugeMetric) Maps(com.google.common.collect.Maps) Collectors(java.util.stream.Collectors) UserName(com.google.api.services.directory.model.UserName) HttpStatus(org.springframework.http.HttpStatus) List(java.util.List) WorkbenchConfig(org.pmiops.workbench.config.WorkbenchConfig) HttpCredentialsAdapter(com.google.auth.http.HttpCredentialsAdapter) NotFoundException(org.pmiops.workbench.exceptions.NotFoundException) Utils.getDefaultJsonFactory(com.google.api.client.googleapis.util.Utils.getDefaultJsonFactory) Optional(java.util.Optional) Users(com.google.api.services.directory.model.Users) DelegatedUserCredentials(org.pmiops.workbench.auth.DelegatedUserCredentials) Collections(java.util.Collections) User(com.google.api.services.directory.model.User) Users(com.google.api.services.directory.model.Users) IOException(java.io.IOException)

Example 5 with User

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;
}
Also used : User(com.google.api.services.directory.model.User)

Aggregations

User (com.google.api.services.directory.model.User)9 DbUser (org.pmiops.workbench.db.model.DbUser)6 UserName (com.google.api.services.directory.model.UserName)2 AddressException (javax.mail.internet.AddressException)2 BadRequestException (org.pmiops.workbench.exceptions.BadRequestException)2 NotFoundException (org.pmiops.workbench.exceptions.NotFoundException)2 Profile (org.pmiops.workbench.model.Profile)2 GoogleJsonResponseException (com.google.api.client.googleapis.json.GoogleJsonResponseException)1 Utils.getDefaultJsonFactory (com.google.api.client.googleapis.util.Utils.getDefaultJsonFactory)1 HttpTransport (com.google.api.client.http.HttpTransport)1 Directory (com.google.api.services.directory.Directory)1 DirectoryScopes (com.google.api.services.directory.DirectoryScopes)1 UserEmail (com.google.api.services.directory.model.UserEmail)1 Users (com.google.api.services.directory.model.Users)1 HttpCredentialsAdapter (com.google.auth.http.HttpCredentialsAdapter)1 OAuth2Credentials (com.google.auth.oauth2.OAuth2Credentials)1 IamCredentialsClient (com.google.cloud.iam.credentials.v1.IamCredentialsClient)1 Strings (com.google.common.base.Strings)1 ImmutableSet (com.google.common.collect.ImmutableSet)1 Lists (com.google.common.collect.Lists)1