Search in sources :

Example 1 with RequestContext

use of org.sagebionetworks.bridge.RequestContext in project BridgeServer2 by Sage-Bionetworks.

the class CRCController method httpBasicAuthentication.

/**
 * This is bound to specific “machine” accounts that are enumerated in the controller. Authentication is
 * session-less. The account itself has no administrative roles, so it can only execute these endpoints that
 * specifically allows it, in the app to which it is bound.
 */
App httpBasicAuthentication() {
    String value = request().getHeader(AUTHORIZATION);
    if (value == null || value.length() < 5) {
        throw new NotAuthenticatedException();
    }
    // Remove "Basic ";
    value = value.substring(5).trim();
    // Decode the credentials from base 64
    value = new String(Base64.getDecoder().decode(value), Charset.defaultCharset());
    // Split to username and password
    String[] credentials = value.split(":");
    if (credentials.length != 2) {
        throw new NotAuthenticatedException();
    }
    String appId = ACCOUNTS.get(credentials[0]);
    if (appId == null) {
        throw new NotAuthenticatedException();
    }
    SignIn.Builder signInBuilder = new SignIn.Builder().withAppId(appId).withPassword(credentials[1]);
    if (credentials[0].contains("@sagebase.org")) {
        signInBuilder.withEmail(credentials[0]);
    } else {
        signInBuilder.withExternalId(credentials[0]);
    }
    App app = appService.getApp(appId);
    // Verify the password
    SignIn signIn = signInBuilder.build();
    Account account = accountService.authenticate(app, signIn);
    // This method of verification sidesteps RequestContext initialization
    // through a session. Set up what is needed in the controller.
    Set<String> studies = BridgeUtils.collectStudyIds(account);
    RequestContext.Builder builder = new RequestContext.Builder().withCallerAppId(appId).withCallerRoles(account.getRoles()).withCallerUserId(account.getId()).withOrgSponsoredStudies(studies).withCallerOrgMembership(account.getOrgMembership());
    RequestContext.set(builder.build());
    return app;
}
Also used : App(org.sagebionetworks.bridge.models.apps.App) Account(org.sagebionetworks.bridge.models.accounts.Account) NotAuthenticatedException(org.sagebionetworks.bridge.exceptions.NotAuthenticatedException) SignIn(org.sagebionetworks.bridge.models.accounts.SignIn) RequestContext(org.sagebionetworks.bridge.RequestContext)

Example 2 with RequestContext

use of org.sagebionetworks.bridge.RequestContext in project BridgeServer2 by Sage-Bionetworks.

the class BaseController method getLanguages.

/**
 * Once we acquire a language for a user, we save it and use that language going forward. Changing their
 * language in the host operating system will not change the language they are using (since changing the
 * language might change their consent state). If they change their language by updating their UserProfile,
 * then they may have to reconsent in the new language they are using for the app. Any warnings to
 * that effect will need to be included in the application.
 */
List<String> getLanguages(UserSession session) {
    StudyParticipant participant = session.getParticipant();
    if (!participant.getLanguages().isEmpty()) {
        return participant.getLanguages();
    }
    RequestContext reqContext = RequestContext.get();
    List<String> languages = reqContext.getCallerLanguages();
    if (!languages.isEmpty()) {
        AccountId accountId = AccountId.forHealthCode(session.getAppId(), session.getHealthCode());
        accountService.editAccount(accountId, account -> account.setLanguages(languages));
        CriteriaContext newContext = new CriteriaContext.Builder().withLanguages(languages).withClientInfo(reqContext.getCallerClientInfo()).withHealthCode(session.getHealthCode()).withUserId(session.getId()).withUserDataGroups(session.getParticipant().getDataGroups()).withUserStudyIds(session.getParticipant().getStudyIds()).withAppId(session.getAppId()).build();
        sessionUpdateService.updateLanguage(session, newContext);
    }
    return languages;
}
Also used : AccountId(org.sagebionetworks.bridge.models.accounts.AccountId) StudyParticipant(org.sagebionetworks.bridge.models.accounts.StudyParticipant) RequestContext(org.sagebionetworks.bridge.RequestContext) CriteriaContext(org.sagebionetworks.bridge.models.CriteriaContext)

Example 3 with RequestContext

use of org.sagebionetworks.bridge.RequestContext in project BridgeServer2 by Sage-Bionetworks.

the class AuthenticationServiceTest method getSessionFromAccount.

// Most of the other behaviors are tested in other methods. This test specifically tests the session created has
// the correct attributes.
@Test
public void getSessionFromAccount() {
    // Create inputs.
    App app = App.create();
    app.setIdentifier(TEST_APP_ID);
    app.setReauthenticationEnabled(true);
    setIpAddress(IP_ADDRESS);
    CriteriaContext context = new CriteriaContext.Builder().withAppId(TEST_APP_ID).build();
    Account account = Account.create();
    account.setId(TEST_USER_ID);
    StudyParticipant participant = new StudyParticipant.Builder().copyOf(PARTICIPANT).withOrgMembership(TEST_ORG_ID).build();
    // Mock pre-reqs.
    when(participantService.getParticipant(any(), any(Account.class), anyBoolean())).thenReturn(participant);
    when(config.getEnvironment()).thenReturn(Environment.LOCAL);
    when(consentService.getConsentStatuses(any(), any())).thenReturn(CONSENTED_STATUS_MAP);
    when(service.generateReauthToken()).thenReturn(REAUTH_TOKEN);
    when(sponsorService.getSponsoredStudyIds(TEST_APP_ID, TEST_ORG_ID)).thenReturn(USER_STUDY_IDS);
    // Execute and validate.
    UserSession session = service.getSessionFromAccount(app, context, account);
    assertSame(session.getParticipant(), participant);
    assertNotNull(session.getSessionToken());
    assertNotNull(session.getInternalSessionToken());
    assertTrue(session.isAuthenticated());
    assertEquals(session.getEnvironment(), Environment.LOCAL);
    assertEquals(session.getIpAddress(), IP_ADDRESS);
    assertEquals(session.getAppId(), TEST_APP_ID);
    assertEquals(session.getReauthToken(), REAUTH_TOKEN);
    assertEquals(session.getConsentStatuses(), CONSENTED_STATUS_MAP);
    verify(accountSecretDao).createSecret(AccountSecretType.REAUTH, TEST_USER_ID, REAUTH_TOKEN);
    RequestContext retValue = RequestContext.updateFromSession(session, sponsorService);
    assertEquals(retValue.getCallerAppId(), TEST_APP_ID);
    assertEquals(retValue.getOrgSponsoredStudies(), USER_STUDY_IDS);
    assertEquals(retValue.getCallerUserId(), TEST_USER_ID);
    assertEquals(retValue.getCallerOrgMembership(), TEST_ORG_ID);
}
Also used : App(org.sagebionetworks.bridge.models.apps.App) Account(org.sagebionetworks.bridge.models.accounts.Account) UserSession(org.sagebionetworks.bridge.models.accounts.UserSession) StudyParticipant(org.sagebionetworks.bridge.models.accounts.StudyParticipant) RequestContext(org.sagebionetworks.bridge.RequestContext) CriteriaContext(org.sagebionetworks.bridge.models.CriteriaContext) Test(org.testng.annotations.Test)

Example 4 with RequestContext

use of org.sagebionetworks.bridge.RequestContext in project BridgeServer2 by Sage-Bionetworks.

the class EnrollmentService method getEnrollmentsForUser.

public List<EnrollmentDetail> getEnrollmentsForUser(String appId, @Nullable String studyId, String userIdToken) {
    checkNotNull(appId);
    checkNotNull(userIdToken);
    // verify the study exists if it is passed in
    if (studyId != null) {
        studyService.getStudy(appId, studyId, true);
    }
    // Developers accessing production accounts will be prevented by getAccount()
    AccountId accountId = BridgeUtils.parseAccountId(appId, userIdToken);
    Account account = accountService.getAccount(accountId).orElseThrow(() -> new EntityNotFoundException(Account.class));
    // Study-scoped users must have access to the study, roles like developer/researcher/admin are also OK
    CAN_EDIT_ENROLLMENTS.checkAndThrow(STUDY_ID, studyId, USER_ID, account.getId());
    // Global roles can see all enrollments, but study-scoped roles only see studies they are associated to
    RequestContext context = RequestContext.get();
    Set<String> studyIds = context.isInRole(ImmutableSet.of(DEVELOPER, RESEARCHER, ADMIN)) ? ImmutableSet.of() : context.getOrgSponsoredStudies();
    return enrollmentDao.getEnrollmentsForUser(appId, studyIds, account.getId());
}
Also used : Account(org.sagebionetworks.bridge.models.accounts.Account) AccountId(org.sagebionetworks.bridge.models.accounts.AccountId) EntityNotFoundException(org.sagebionetworks.bridge.exceptions.EntityNotFoundException) RequestContext(org.sagebionetworks.bridge.RequestContext)

Example 5 with RequestContext

use of org.sagebionetworks.bridge.RequestContext in project BridgeServer2 by Sage-Bionetworks.

the class StudyService method deleteStudyPermanently.

public void deleteStudyPermanently(String appId, String studyId) {
    checkNotNull(appId);
    checkNotNull(studyId);
    Study existing = getStudy(appId, studyId, true);
    RequestContext context = RequestContext.get();
    if (!CAN_DELETE_STUDY.contains(existing.getPhase()) && !context.isInRole(ADMIN)) {
        throw new BadRequestException("Study cannot be deleted during phase " + existing.getPhase().label());
    }
    String scheduleGuid = existing.getScheduleGuid();
    studyDao.deleteStudyPermanently(appId, studyId);
    if (scheduleGuid != null) {
        scheduleService.deleteSchedulePermanently(appId, scheduleGuid);
    }
    CacheKey cacheKey = CacheKey.publicStudy(appId, studyId);
    cacheProvider.removeObject(cacheKey);
}
Also used : Study(org.sagebionetworks.bridge.models.studies.Study) BadRequestException(org.sagebionetworks.bridge.exceptions.BadRequestException) RequestContext(org.sagebionetworks.bridge.RequestContext) CacheKey(org.sagebionetworks.bridge.cache.CacheKey)

Aggregations

RequestContext (org.sagebionetworks.bridge.RequestContext)25 CriteriaContext (org.sagebionetworks.bridge.models.CriteriaContext)7 AccountId (org.sagebionetworks.bridge.models.accounts.AccountId)7 App (org.sagebionetworks.bridge.models.apps.App)7 StudyParticipant (org.sagebionetworks.bridge.models.accounts.StudyParticipant)6 Test (org.testng.annotations.Test)6 CacheKey (org.sagebionetworks.bridge.cache.CacheKey)4 BadRequestException (org.sagebionetworks.bridge.exceptions.BadRequestException)4 UserSession (org.sagebionetworks.bridge.models.accounts.UserSession)4 EntityNotFoundException (org.sagebionetworks.bridge.exceptions.EntityNotFoundException)3 Account (org.sagebionetworks.bridge.models.accounts.Account)3 Enrollment (org.sagebionetworks.bridge.models.studies.Enrollment)3 Study (org.sagebionetworks.bridge.models.studies.Study)3 PostMapping (org.springframework.web.bind.annotation.PostMapping)3 JsonNode (com.fasterxml.jackson.databind.JsonNode)2 Vector (java.util.Vector)2 HttpServletRequest (javax.servlet.http.HttpServletRequest)2 DateTimeZone (org.joda.time.DateTimeZone)2 UnauthorizedException (org.sagebionetworks.bridge.exceptions.UnauthorizedException)2 RequestInfo (org.sagebionetworks.bridge.models.RequestInfo)2