Search in sources :

Example 6 with Userinfo

use of com.google.api.services.oauth2.model.Userinfo in project workbench by all-of-us.

the class AuthInterceptorTest method preHandleGet_firecloudLookupSucceeds.

@Test
public void preHandleGet_firecloudLookupSucceeds() throws Exception {
    mockGetCallWithBearerToken();
    Userinfo userInfo = new Userinfo();
    userInfo.setEmail("bob@bad-domain.org");
    when(userInfoService.getUserInfo("foo")).thenReturn(userInfo);
    FirecloudUserInfo fcUserInfo = new FirecloudUserInfo();
    fcUserInfo.setUserEmail("bob@fake-domain.org");
    FirecloudMe me = new FirecloudMe();
    me.setUserInfo(fcUserInfo);
    when(fireCloudService.getMe()).thenReturn(me);
    when(userDao.findUserByUsername("bob@fake-domain.org")).thenReturn(user);
    assertThat(interceptor.preHandle(mockRequest, mockResponse, mockHandler)).isTrue();
}
Also used : Userinfo(com.google.api.services.oauth2.model.Userinfo) FirecloudMe(org.pmiops.workbench.firecloud.model.FirecloudMe) FirecloudUserInfo(org.pmiops.workbench.firecloud.model.FirecloudUserInfo) Test(org.junit.jupiter.api.Test)

Example 7 with Userinfo

use of com.google.api.services.oauth2.model.Userinfo in project workbench by all-of-us.

the class AuthInterceptorTest method preHandleGet_firecloudLookupSucceedsNoUserRecordWrongDomain.

@Test
public void preHandleGet_firecloudLookupSucceedsNoUserRecordWrongDomain() throws Exception {
    mockGetCallWithBearerToken();
    Userinfo userInfo = new Userinfo();
    userInfo.setEmail("bob@bad-domain.org");
    when(userInfoService.getUserInfo("foo")).thenReturn(userInfo);
    FirecloudUserInfo fcUserInfo = new FirecloudUserInfo();
    fcUserInfo.setUserEmail("bob@also-bad-domain.org");
    FirecloudMe me = new FirecloudMe();
    me.setUserInfo(fcUserInfo);
    when(fireCloudService.getMe()).thenReturn(me);
    when(userDao.findUserByUsername("bob@also-bad-domain.org")).thenReturn(null);
    assertThat(interceptor.preHandle(mockRequest, mockResponse, mockHandler)).isFalse();
    verify(mockResponse).sendError(HttpServletResponse.SC_UNAUTHORIZED);
}
Also used : Userinfo(com.google.api.services.oauth2.model.Userinfo) FirecloudMe(org.pmiops.workbench.firecloud.model.FirecloudMe) FirecloudUserInfo(org.pmiops.workbench.firecloud.model.FirecloudUserInfo) Test(org.junit.jupiter.api.Test)

Example 8 with Userinfo

use of com.google.api.services.oauth2.model.Userinfo in project workbench by all-of-us.

the class AuthInterceptor method preHandle.

/**
 * Returns true iff the request is auth'd and should proceed. Publishes authenticated user info
 * using Spring's SecurityContext.
 *
 * @param handler The Swagger-generated ApiController. It contains our handler as a private
 *     delegate.
 */
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    // Clear the security context before we start, to make sure we're not using authentication
    // from a previous request.
    SecurityContextHolder.clearContext();
    // OPTIONS methods requests don't need authorization.
    if (request.getMethod().equals(HttpMethods.OPTIONS)) {
        return true;
    }
    HandlerMethod method = (HandlerMethod) handler;
    boolean isAuthRequired = false;
    ApiOperation apiOp = AnnotationUtils.findAnnotation(method.getMethod(), ApiOperation.class);
    if (apiOp != null) {
        for (Authorization auth : apiOp.authorizations()) {
            if (auth.value().equals(authName)) {
                isAuthRequired = true;
                break;
            }
        }
    }
    if (!isAuthRequired) {
        return true;
    }
    String authorizationHeader = request.getHeader(HttpHeaders.AUTHORIZATION);
    if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
        log.warning("No bearer token found in request");
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return false;
    }
    final String token = authorizationHeader.substring("Bearer".length()).trim();
    final Userinfo userInfo = userInfoService.getUserInfo(token);
    // The Workbench considers the user's generated GSuite email to be their userName
    // Don't confuse this with the user's Contact Email, which is unrelated
    String userName = userInfo.getEmail();
    if (workbenchConfigProvider.get().auth.serviceAccountApiUsers.contains(userName)) {
        // Whitelisted service accounts are able to make API calls, too.
        // TODO: stop treating service accounts as normal users, have a separate table for them,
        // administrators.
        DbUser user = userDao.findUserByUsername(userName);
        if (user == null) {
            user = userService.createServiceAccountUser(userName);
        }
        SecurityContextHolder.getContext().setAuthentication(new UserAuthentication(user, userInfo, token, UserType.SERVICE_ACCOUNT));
        log.log(Level.INFO, "{0} service account in use", userName);
        return true;
    }
    String gsuiteDomainSuffix = "@" + workbenchConfigProvider.get().googleDirectoryService.gSuiteDomain;
    if (!userName.endsWith(gsuiteDomainSuffix)) {
        // Temporarily set the authentication with no user, so we can look up what user this
        // corresponds to in FireCloud.
        SecurityContextHolder.getContext().setAuthentication(new UserAuthentication(null, userInfo, token, UserType.SERVICE_ACCOUNT));
        // If the email isn't in our GSuite domain, try FireCloud; we could be dealing with a
        // pet service account. In both AofU and FireCloud, the pet SA is treated as if it were
        // the user it was created for.
        userName = fireCloudService.getMe().getUserInfo().getUserEmail();
        if (!userName.endsWith(gsuiteDomainSuffix)) {
            log.info(String.format("User %s isn't in domain %s, can't access the workbench", userName, gsuiteDomainSuffix));
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
    }
    DbUser user = userDao.findUserByUsername(userName);
    if (user == null) {
        if (workbenchConfigProvider.get().access.unsafeAllowUserCreationFromGSuiteData) {
            user = devUserRegistrationService.createUser(userInfo);
            log.info(String.format("Dev user '%s' has been re-created.", user.getUsername()));
        } else {
            log.severe(String.format("No User row exists for user '%s'", userName));
            return false;
        }
    }
    if (user.getDisabled()) {
        throw new ForbiddenException(WorkbenchException.errorResponse("Rejecting request for disabled user account: " + user.getUsername(), ErrorCode.USER_DISABLED));
    }
    SecurityContextHolder.getContext().setAuthentication(new UserAuthentication(user, userInfo, token, UserType.RESEARCHER));
    // This log line is currently the the only reliable way to associate a particular App Engine
    // request log
    // with the authenticated user identity, which is critical information for debugging.
    // TODO(jaycarlton) replace this log line with a UserInfo entry in a dedicated Stackdriver Auth
    // log.
    log.log(Level.INFO, "{0} logged in", userInfo.getEmail());
    if (!hasRequiredAuthority(method, user)) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return false;
    }
    return true;
}
Also used : Authorization(io.swagger.annotations.Authorization) ForbiddenException(org.pmiops.workbench.exceptions.ForbiddenException) ApiOperation(io.swagger.annotations.ApiOperation) Userinfo(com.google.api.services.oauth2.model.Userinfo) UserAuthentication(org.pmiops.workbench.auth.UserAuthentication) HandlerMethod(org.springframework.web.method.HandlerMethod) DbUser(org.pmiops.workbench.db.model.DbUser)

Example 9 with Userinfo

use of com.google.api.services.oauth2.model.Userinfo in project alfresco-repository by Alfresco.

the class NodeResourceHelper method createNodeResourceBuilder.

public NodeResource.Builder createNodeResourceBuilder(NodeRef nodeRef) {
    final QName type = nodeService.getType(nodeRef);
    final Path path = nodeService.getPath(nodeRef);
    final Map<QName, Serializable> properties = getProperties(nodeRef);
    // minor: save one lookup if creator & modifier are the same
    Map<String, UserInfo> mapUserCache = new HashMap<>(2);
    return NodeResource.builder().setId(nodeRef.getId()).setName((String) properties.get(ContentModel.PROP_NAME)).setNodeType(getQNamePrefixString(type)).setIsFile(isSubClass(type, ContentModel.TYPE_CONTENT)).setIsFolder(isSubClass(type, ContentModel.TYPE_FOLDER)).setCreatedByUser(getUserInfo((String) properties.get(ContentModel.PROP_CREATOR), mapUserCache)).setCreatedAt(getZonedDateTime((Date) properties.get(ContentModel.PROP_CREATED))).setModifiedByUser(getUserInfo((String) properties.get(ContentModel.PROP_MODIFIER), mapUserCache)).setModifiedAt(getZonedDateTime((Date) properties.get(ContentModel.PROP_MODIFIED))).setContent(getContentInfo(properties)).setPrimaryHierarchy(PathUtil.getNodeIdsInReverse(path, false)).setProperties(mapToNodeProperties(properties)).setAspectNames(getMappedAspects(nodeRef));
}
Also used : Path(org.alfresco.service.cmr.repository.Path) Serializable(java.io.Serializable) HashMap(java.util.HashMap) QName(org.alfresco.service.namespace.QName) UserInfo(org.alfresco.repo.event.v1.model.UserInfo) Date(java.util.Date)

Example 10 with Userinfo

use of com.google.api.services.oauth2.model.Userinfo in project ecms by exoplatform.

the class GoogleDriveConnector method authenticate.

/**
 * {@inheritDoc}
 */
@Override
public GoogleUser authenticate(Map<String, String> params) throws CloudDriveException {
    String code = params.get(OAUTH2_CODE);
    if (code != null && code.length() > 0) {
        GoogleDriveAPI driveAPI = new API().auth(code).build();
        Userinfoplus userInfo = driveAPI.userInfo();
        GoogleUser user = new GoogleUser(userInfo.getId(), userInfo.getName(), userInfo.getEmail(), provider, driveAPI);
        return user;
    } else {
        throw new CloudDriveException("Access code should not be null or empty");
    }
}
Also used : Userinfoplus(com.google.api.services.oauth2.model.Userinfoplus) CloudDriveException(org.exoplatform.services.cms.clouddrives.CloudDriveException)

Aggregations

Userinfo (com.google.api.services.oauth2.model.Userinfo)10 Oauth2 (com.google.api.services.oauth2.Oauth2)8 Userinfoplus (com.google.api.services.oauth2.model.Userinfoplus)6 IOException (java.io.IOException)5 NetHttpTransport (com.google.api.client.http.javanet.NetHttpTransport)4 UserInfo (com.developmentontheedge.be5.model.UserInfo)3 Credential (com.google.api.client.auth.oauth2.Credential)3 GoogleCredential (com.google.api.client.googleapis.auth.oauth2.GoogleCredential)3 JacksonFactory (com.google.api.client.json.jackson2.JacksonFactory)3 UserInfo (org.alfresco.repo.event.v1.model.UserInfo)3 JsonObject (com.google.gson.JsonObject)2 CustomWebApplicationException (io.dockstore.webservice.CustomWebApplicationException)2 Test (org.junit.jupiter.api.Test)2 FirecloudMe (org.pmiops.workbench.firecloud.model.FirecloudMe)2 FirecloudUserInfo (org.pmiops.workbench.firecloud.model.FirecloudUserInfo)2 Timed (com.codahale.metrics.annotation.Timed)1 Session (com.developmentontheedge.be5.api.Session)1 JsonView (com.fasterxml.jackson.annotation.JsonView)1 ForIntent (com.google.actions.api.ForIntent)1 TransactionDecision (com.google.actions.api.response.helperintent.transactions.v3.TransactionDecision)1