use of com.google.api.services.oauth2.model.Userinfo in project gatein-portal by Meeds-io.
the class GoogleProcessorImpl method obtainUserInfo.
@Override
public Userinfo obtainUserInfo(GoogleAccessTokenContext accessTokenContext) {
final Oauth2 oauth2 = getOAuth2Instance(accessTokenContext);
GoogleRequest<Userinfo> googleRequest = new GoogleRequest<Userinfo>() {
@Override
protected Userinfo invokeRequest(GoogleAccessTokenContext accessTokenContext) throws IOException {
return oauth2.userinfo().v2().me().get().execute();
}
@Override
protected OAuthException createException(IOException cause) {
if (cause instanceof HttpResponseException) {
return new OAuthException(OAuthExceptionCode.ACCESS_TOKEN_ERROR, "Error when obtaining userInfo: " + cause.getMessage(), cause);
} else {
return new OAuthException(OAuthExceptionCode.IO_ERROR, "IO Error when obtaining userInfo: " + cause.getMessage(), cause);
}
}
};
Userinfo uinfo = googleRequest.executeRequest(accessTokenContext, this);
if (log.isTraceEnabled()) {
log.trace("Successfully obtained userInfo from google: " + uinfo);
}
return uinfo;
}
use of com.google.api.services.oauth2.model.Userinfo in project alfresco-repository by Alfresco.
the class EventConsolidator method buildNodeResourceBeforeDelta.
protected NodeResource buildNodeResourceBeforeDelta(NodeResource after) {
if (after == null) {
return null;
}
Builder builder = NodeResource.builder();
Map<QName, Serializable> changedPropsBefore = getBeforeMapChanges(propertiesBefore, propertiesAfter);
if (!changedPropsBefore.isEmpty()) {
// Set only the changed properties
Map<String, Serializable> mappedProps = helper.mapToNodeProperties(changedPropsBefore);
if (!mappedProps.isEmpty()) {
builder.setProperties(mappedProps);
resourceBeforeAllFieldsNull = false;
}
String name = (String) changedPropsBefore.get(ContentModel.PROP_NAME);
if (name != null) {
builder.setName(name);
resourceBeforeAllFieldsNull = false;
}
ContentInfo contentInfo = helper.getContentInfo(changedPropsBefore);
if (contentInfo != null) {
builder.setContent(contentInfo);
resourceBeforeAllFieldsNull = false;
}
UserInfo modifier = helper.getUserInfo((String) changedPropsBefore.get(ContentModel.PROP_MODIFIER));
if (modifier != null) {
builder.setModifiedByUser(modifier);
resourceBeforeAllFieldsNull = false;
}
ZonedDateTime modifiedAt = helper.getZonedDateTime((Date) changedPropsBefore.get(ContentModel.PROP_MODIFIED));
if (modifiedAt != null) {
builder.setModifiedAt(modifiedAt);
resourceBeforeAllFieldsNull = false;
}
}
Set<String> aspectsBefore = getMappedAspectsBefore(after.getAspectNames());
if (!aspectsBefore.isEmpty()) {
builder.setAspectNames(aspectsBefore);
resourceBeforeAllFieldsNull = false;
}
if (primaryHierarchyBefore != null && !primaryHierarchyBefore.isEmpty()) {
builder.setPrimaryHierarchy(primaryHierarchyBefore);
resourceBeforeAllFieldsNull = false;
}
if (nodeTypeBefore != null) {
builder.setNodeType(helper.getQNamePrefixString(nodeTypeBefore));
resourceBeforeAllFieldsNull = false;
}
return builder.build();
}
use of com.google.api.services.oauth2.model.Userinfo in project alfresco-repository by Alfresco.
the class NodeResourceHelper method getUserInfo.
private UserInfo getUserInfo(String userName, Map<String, UserInfo> mapUserCache) {
UserInfo userInfo = mapUserCache.get(userName);
if (userInfo == null) {
userInfo = getUserInfo(userName);
mapUserCache.put(userName, userInfo);
}
return userInfo;
}
use of com.google.api.services.oauth2.model.Userinfo in project isaac-api by isaacphysics.
the class GoogleAuthenticator method getUserInfo.
@Override
public synchronized UserFromAuthProvider getUserInfo(final String internalProviderReference) throws NoUserException, AuthenticatorSecurityException {
Credential credentials = credentialStore.getIfPresent(internalProviderReference);
if (verifyAccessTokenIsValid(credentials)) {
log.debug("Successful Verification of access token with provider.");
} else {
log.error("Unable to verify access token - it could be an indication of fraud.");
throw new AuthenticatorSecurityException("Access token is invalid - the client id returned by the identity provider does not match ours.");
}
Oauth2 userInfoService = new Oauth2.Builder(new NetHttpTransport(), new JacksonFactory(), credentials).setApplicationName(Constants.APPLICATION_NAME).build();
Userinfo userInfo = null;
try {
userInfo = userInfoService.userinfo().get().execute();
log.debug("Retrieved User info from google: " + userInfo.toPrettyString());
} catch (IOException e) {
log.error("An IO error occurred while trying to retrieve user information: " + e);
}
if (userInfo != null && userInfo.getId() != null) {
EmailVerificationStatus emailStatus = userInfo.isVerifiedEmail() ? EmailVerificationStatus.VERIFIED : EmailVerificationStatus.NOT_VERIFIED;
String email = userInfo.getEmail();
if (null == email) {
email = userInfo.getId() + "-google";
emailStatus = EmailVerificationStatus.DELIVERY_FAILED;
log.warn("No email address provided by Google! Using (" + email + ") instead");
}
return new UserFromAuthProvider(userInfo.getId(), userInfo.getGivenName(), userInfo.getFamilyName(), email, emailStatus, null, null, null);
} else {
throw new NoUserException("No user could be created from provider details!");
}
}
use of com.google.api.services.oauth2.model.Userinfo in project dockstore by dockstore.
the class TokenResource method addGoogleToken.
/**
* Adds a Google token to the existing user if user is authenticated already.
* Otherwise, below table indicates what happens when the "Login with Google" button in the UI2 is clicked
* <table border="1">
* <tr>
* <td></td> <td><b> Have GitHub account no Google Token (no GitHub account)</b></td> <td><b>Have GitHub account with Google token</b></td>
* </tr>
* <tr>
* <td> <b>Have Google Account no Google token</b></td> <td>Login with Google account (1)</td> <td>Login with GitHub account(2)</td>
* </tr>
* <tr>
* <td> <b>Have Google Account with Google token</b></td> <td>Login with Google account (3)</td> <td> Login with Google account (4)</td>
* </tr>
* <tr>
* <td> <b>No Google Account</b></td> <td> Create Google account (5)</td> <td>Login with GitHub account (6)</td>
* </tr>
* </table>
*
* @param authUser The optional Dockstore-authenticated user
* @param satellizerJson Satellizer object returned by satellizer
* @return The user's Dockstore token
*/
@POST
@Timed
@UnitOfWork
@Path("/google")
@JsonView(TokenViews.Auth.class)
@Operation(operationId = "addGoogleToken", description = "Allow satellizer to post a new Google token to Dockstore.", security = @SecurityRequirement(name = OPENAPI_JWT_SECURITY_DEFINITION_NAME))
@ApiOperation(value = "Allow satellizer to post a new Google token to Dockstore.", authorizations = { @Authorization(value = JWT_SECURITY_DEFINITION_NAME) }, notes = "A post method is required by satellizer to send the Google token", response = Token.class)
public Token addGoogleToken(@ApiParam(hidden = true) @Parameter(hidden = true, name = "user") @Auth Optional<User> authUser, @ApiParam("code") String satellizerJson) {
Gson gson = new Gson();
JsonElement element = gson.fromJson(satellizerJson, JsonElement.class);
JsonObject satellizerObject = element.getAsJsonObject();
final String code = getCodeFromSatellizerObject(satellizerObject);
final String redirectUri = getRedirectURIFromSatellizerObject(satellizerObject);
final boolean registerUser = getRegisterFromSatellizerObject(satellizerObject);
TokenResponse tokenResponse = GoogleHelper.getTokenResponse(googleClientID, googleClientSecret, code, redirectUri);
String accessToken = tokenResponse.getAccessToken();
String refreshToken = tokenResponse.getRefreshToken();
LOG.info("Token expires in " + tokenResponse.getExpiresInSeconds().toString() + " seconds.");
Userinfoplus userinfo = getUserInfo(accessToken);
long userID;
Token dockstoreToken = null;
Token googleToken = null;
String googleLoginName = userinfo.getEmail();
String googleOnlineProfileId = userinfo.getId();
// We will not be able to get everyone's Google profile ID so check if we can match a user by id first, and then by username if that fails.
User user = userDAO.findByGoogleOnlineProfileId(googleOnlineProfileId);
if (user == null) {
user = userDAO.findByGoogleEmail(googleLoginName);
}
if (registerUser && authUser.isEmpty()) {
if (user == null) {
String googleLogin = userinfo.getEmail();
String username = googleLogin;
int count = 1;
while (userDAO.findByUsername(username) != null || DeletedUserHelper.nonReusableUsernameFound(username, deletedUsernameDAO)) {
username = googleLogin + count++;
}
user = new User();
user.setUsername(username);
userID = userDAO.create(user);
} else {
throw new CustomWebApplicationException("User already exists, cannot register new user", HttpStatus.SC_FORBIDDEN);
}
} else {
if (authUser.isPresent()) {
userID = authUser.get().getId();
} else if (user != null) {
if (user.isCurator() || user.getIsAdmin()) {
throw new CustomWebApplicationException(ADMINS_AND_CURATORS_MAY_NOT_LOGIN_WITH_GOOGLE, HttpStatus.SC_UNAUTHORIZED);
}
userID = user.getId();
} else {
throw new CustomWebApplicationException("Login failed, you may need to register an account", HttpStatus.SC_UNAUTHORIZED);
}
List<Token> tokens = tokenDAO.findDockstoreByUserId(userID);
if (!tokens.isEmpty()) {
dockstoreToken = tokens.get(0);
}
tokens = tokenDAO.findGoogleByUserId(userID);
if (!tokens.isEmpty()) {
googleToken = tokens.get(0);
}
}
user = userDAO.findById(userID);
acceptTOSAndPrivacyPolicy(user);
if (dockstoreToken == null) {
LOG.info("Could not find user's dockstore token. Making new one...");
dockstoreToken = createDockstoreToken(userID, user.getUsername());
}
if (googleToken == null) {
LOG.info("Could not find user's Google token. Making new one...");
// CREATE GOOGLE TOKEN
googleToken = new Token(accessToken, refreshToken, userID, googleLoginName, TokenType.GOOGLE_COM, googleOnlineProfileId);
checkIfAccountHasBeenLinked(googleToken, TokenType.GOOGLE_COM);
tokenDAO.create(googleToken);
// Update user profile too
user = userDAO.findById(userID);
GoogleHelper.updateUserFromGoogleUserinfoplus(userinfo, user);
LOG.info("Google token created for {}", googleLoginName);
} else {
// Update tokens if exists
googleToken.setContent(accessToken);
googleToken.setRefreshToken(refreshToken);
googleToken.setUsername(googleLoginName);
googleToken.setOnlineProfileId(googleOnlineProfileId);
tokenDAO.update(googleToken);
}
return dockstoreToken;
}
Aggregations