use of com.google.api.services.oauth2.model.Userinfoplus 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 {
// 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;
}
String token = authorizationHeader.substring("Bearer".length()).trim();
Userinfoplus userInfo;
try {
userInfo = userInfoService.getUserInfo(token);
} catch (HttpResponseException e) {
log.log(Level.WARNING, "{0} response getting user info for bearer token {1}: {2}", new Object[] { e.getStatusCode(), token, e.getStatusMessage() });
response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
return false;
}
// TODO: check Google group membership to ensure user is in registered user group
String userEmail = userInfo.getEmail();
WorkbenchConfig workbenchConfig = workbenchConfigProvider.get();
if (workbenchConfig.auth.serviceAccountApiUsers.contains(userEmail)) {
// 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.
User user = userDao.findUserByEmail(userEmail);
if (user == null) {
user = userService.createServiceAccountUser(userEmail);
}
SecurityContextHolder.getContext().setAuthentication(new UserAuthentication(user, userInfo, token, UserType.SERVICE_ACCOUNT));
log.log(Level.INFO, "{0} service account in use", userInfo.getEmail());
return true;
}
String gsuiteDomainSuffix = "@" + workbenchConfig.googleDirectoryService.gSuiteDomain;
if (!userEmail.endsWith(gsuiteDomainSuffix)) {
try {
// 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.
userEmail = fireCloudService.getMe().getUserInfo().getUserEmail();
} catch (ApiException e) {
log.log(Level.INFO, "FireCloud lookup for {0} failed, can't access the workbench: {1}", new Object[] { userInfo.getEmail(), e.getMessage() });
response.sendError(e.getCode());
return false;
}
if (!userEmail.endsWith(gsuiteDomainSuffix)) {
log.log(Level.INFO, "User {0} isn't in domain {1}, can't access the workbench", new Object[] { userEmail, gsuiteDomainSuffix });
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return false;
}
}
User user = userDao.findUserByEmail(userEmail);
if (user == null) {
// TODO(danrodney): start populating contact email in Google account, use it here.
user = userService.createUser(userInfo.getGivenName(), userInfo.getFamilyName(), userInfo.getEmail(), null);
} else {
if (user.getDisabled()) {
throw new ForbiddenException(ExceptionUtils.errorResponse(ErrorCode.USER_DISABLED, "This user account has been disabled."));
}
}
SecurityContextHolder.getContext().setAuthentication(new UserAuthentication(user, userInfo, token, UserType.RESEARCHER));
// TODO: setup this in the context, get rid of log statement
log.log(Level.INFO, "{0} logged in", userInfo.getEmail());
if (!hasRequiredAuthority(method, user)) {
response.sendError(HttpServletResponse.SC_FORBIDDEN);
return false;
}
return true;
}
use of com.google.api.services.oauth2.model.Userinfoplus in project workbench by all-of-us.
the class AuthInterceptorTest method preHandleGet_firecloudLookupSucceedsNoUserRecordWrongDomain.
@Test
public void preHandleGet_firecloudLookupSucceedsNoUserRecordWrongDomain() throws Exception {
when(handler.getMethod()).thenReturn(getProfileApiMethod("getBillingProjects"));
when(request.getMethod()).thenReturn(HttpMethods.GET);
when(request.getHeader(HttpHeaders.AUTHORIZATION)).thenReturn("Bearer foo");
Userinfoplus userInfo = new Userinfoplus();
userInfo.setEmail("bob@bad-domain.org");
when(userInfoService.getUserInfo("foo")).thenReturn(userInfo);
UserInfo fcUserInfo = new UserInfo();
fcUserInfo.setUserEmail("bob@also-bad-domain.org");
Me me = new Me();
me.setUserInfo(fcUserInfo);
when(fireCloudService.getMe()).thenReturn(me);
when(userDao.findUserByEmail("bob@also-bad-domain.org")).thenReturn(null);
assertThat(interceptor.preHandle(request, response, handler)).isFalse();
verify(response).sendError(HttpServletResponse.SC_NOT_FOUND);
}
use of com.google.api.services.oauth2.model.Userinfoplus in project workbench by all-of-us.
the class AuthInterceptorTest method preHandleGet_firecloudLookupSucceeds.
@Test
public void preHandleGet_firecloudLookupSucceeds() throws Exception {
when(handler.getMethod()).thenReturn(getProfileApiMethod("getBillingProjects"));
when(request.getMethod()).thenReturn(HttpMethods.GET);
when(request.getHeader(HttpHeaders.AUTHORIZATION)).thenReturn("Bearer foo");
Userinfoplus userInfo = new Userinfoplus();
userInfo.setEmail("bob@bad-domain.org");
when(userInfoService.getUserInfo("foo")).thenReturn(userInfo);
UserInfo fcUserInfo = new UserInfo();
fcUserInfo.setUserEmail("bob@fake-domain.org");
Me me = new Me();
me.setUserInfo(fcUserInfo);
when(fireCloudService.getMe()).thenReturn(me);
when(userDao.findUserByEmail("bob@fake-domain.org")).thenReturn(user);
assertThat(interceptor.preHandle(request, response, handler)).isTrue();
}
use of com.google.api.services.oauth2.model.Userinfoplus in project workbench by all-of-us.
the class AuthInterceptorTest method preHandleGet_userInfoSuccess.
@Test
public void preHandleGet_userInfoSuccess() throws Exception {
when(handler.getMethod()).thenReturn(getProfileApiMethod("getBillingProjects"));
when(request.getMethod()).thenReturn(HttpMethods.GET);
when(request.getHeader(HttpHeaders.AUTHORIZATION)).thenReturn("Bearer foo");
Userinfoplus userInfo = new Userinfoplus();
userInfo.setEmail("bob@fake-domain.org");
when(userInfoService.getUserInfo("foo")).thenReturn(userInfo);
when(userDao.findUserByEmail("bob@fake-domain.org")).thenReturn(user);
assertThat(interceptor.preHandle(request, response, handler)).isTrue();
}
use of com.google.api.services.oauth2.model.Userinfoplus in project google-cloud-intellij by GoogleCloudPlatform.
the class GoogleLoginUtils method getUserInfo.
/**
* Sets the user info on the callback.
*/
@SuppressWarnings("FutureReturnValueIgnored")
public static void getUserInfo(@NotNull final Credential credential, final IUserPropertyCallback<Userinfoplus> callback) {
final Oauth2 userInfoService = new Oauth2.Builder(new NetHttpTransport(), new JacksonFactory(), credential).setApplicationName(ServiceManager.getService(PluginInfoService.class).getUserAgent()).build();
ApplicationManager.getApplication().executeOnPooledThread(() -> {
Userinfoplus userInfo = null;
try {
userInfo = userInfoService.userinfo().get().execute();
} catch (IOException ex) {
// The core IDE functionality still works, so this does
// not affect anything right now. The user will receive
// error messages when they attempt to do something that
// requires a logged in state.
LOG.warn("Error retrieving user information.", ex);
}
if (userInfo != null && userInfo.getId() != null) {
callback.setProperty(userInfo);
} else {
callback.setProperty(null);
}
});
}
Aggregations