Search in sources :

Example 21 with Userinfo

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;
}
Also used : Oauth2(com.google.api.services.oauth2.Oauth2) OAuthException(org.gatein.security.oauth.exception.OAuthException) Userinfo(com.google.api.services.oauth2.model.Userinfo) HttpResponseException(com.google.api.client.http.HttpResponseException) IOException(java.io.IOException)

Example 22 with Userinfo

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();
}
Also used : Serializable(java.io.Serializable) ContentInfo(org.alfresco.repo.event.v1.model.ContentInfo) ZonedDateTime(java.time.ZonedDateTime) QName(org.alfresco.service.namespace.QName) Builder(org.alfresco.repo.event.v1.model.NodeResource.Builder) UserInfo(org.alfresco.repo.event.v1.model.UserInfo)

Example 23 with Userinfo

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;
}
Also used : UserInfo(org.alfresco.repo.event.v1.model.UserInfo)

Example 24 with 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!");
    }
}
Also used : Credential(com.google.api.client.auth.oauth2.Credential) AuthenticatorSecurityException(uk.ac.cam.cl.dtg.segue.auth.exceptions.AuthenticatorSecurityException) NetHttpTransport(com.google.api.client.http.javanet.NetHttpTransport) UserFromAuthProvider(uk.ac.cam.cl.dtg.isaac.dos.users.UserFromAuthProvider) Oauth2(com.google.api.services.oauth2.Oauth2) CacheBuilder(com.google.common.cache.CacheBuilder) NoUserException(uk.ac.cam.cl.dtg.segue.auth.exceptions.NoUserException) Userinfo(com.google.api.services.oauth2.model.Userinfo) IOException(java.io.IOException) EmailVerificationStatus(uk.ac.cam.cl.dtg.isaac.dos.users.EmailVerificationStatus) JacksonFactory(com.google.api.client.json.jackson2.JacksonFactory)

Example 25 with Userinfo

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;
}
Also used : Userinfoplus(com.google.api.services.oauth2.model.Userinfoplus) User(io.dockstore.webservice.core.User) Gson(com.google.gson.Gson) JsonObject(com.google.gson.JsonObject) Token(io.dockstore.webservice.core.Token) BearerToken(com.google.api.client.auth.oauth2.BearerToken) CustomWebApplicationException(io.dockstore.webservice.CustomWebApplicationException) TokenResponse(com.google.api.client.auth.oauth2.TokenResponse) JsonElement(com.google.gson.JsonElement) Path(javax.ws.rs.Path) UnitOfWork(io.dropwizard.hibernate.UnitOfWork) POST(javax.ws.rs.POST) Timed(com.codahale.metrics.annotation.Timed) ApiOperation(io.swagger.annotations.ApiOperation) JsonView(com.fasterxml.jackson.annotation.JsonView) ApiOperation(io.swagger.annotations.ApiOperation) Operation(io.swagger.v3.oas.annotations.Operation)

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