Search in sources :

Example 6 with UserInfo

use of com.google.api.services.actions_fulfillment.v2.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 7 with UserInfo

use of com.google.api.services.actions_fulfillment.v2.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 8 with UserInfo

use of com.google.api.services.actions_fulfillment.v2.model.UserInfo in project hale by halestudio.

the class HaleConnectServiceImpl method getUserInfo.

/**
 * @see eu.esdihumboldt.hale.io.haleconnect.HaleConnectService#getUserInfo(java.lang.String)
 */
@Override
public HaleConnectUserInfo getUserInfo(String userId) throws HaleConnectException {
    if (!this.isLoggedIn()) {
        return null;
    }
    if (!userInfoCache.containsKey(userId)) {
        UsersApi api = UserServiceHelper.getUsersApi(this, this.getSession().getToken());
        try {
            UserInfo info = api.getProfile(userId);
            userInfoCache.put(info.getId(), new HaleConnectUserInfo(info.getId(), info.getScreenName(), info.getFullName()));
        } catch (ApiException e) {
            throw new HaleConnectException(e.getMessage(), e);
        }
    }
    return userInfoCache.get(userId);
}
Also used : UsersApi(com.haleconnect.api.user.v1.api.UsersApi) HaleConnectUserInfo(eu.esdihumboldt.hale.io.haleconnect.HaleConnectUserInfo) UserInfo(com.haleconnect.api.user.v1.model.UserInfo) HaleConnectUserInfo(eu.esdihumboldt.hale.io.haleconnect.HaleConnectUserInfo) HaleConnectException(eu.esdihumboldt.hale.io.haleconnect.HaleConnectException) ApiException(com.haleconnect.api.user.v1.ApiException)

Example 9 with UserInfo

use of com.google.api.services.actions_fulfillment.v2.model.UserInfo in project be5 by DevelopmentOnTheEdge.

the class LoginServiceImpl method saveUser.

@Override
public void saveUser(String username, Request req) {
    List<String> availableRoles = selectAvailableRoles(username);
    if (ModuleLoader2.getDevRoles().size() > 0) {
        availableRoles.addAll(ModuleLoader2.getDevRoles());
    }
    String savedRoles = coreUtils.getUserSetting(username, DatabaseConstants.CURRENT_ROLE_LIST);
    List<String> currentRoles;
    if (savedRoles != null) {
        currentRoles = parseRoles(savedRoles);
    } else {
        currentRoles = availableRoles;
    }
    UserInfo ui = userHelper.saveUser(username, availableRoles, currentRoles, req.getLocale(), req.getRemoteAddr(), req.getSession());
    Session session = req.getSession();
    session.set("remoteAddr", req.getRemoteAddr());
    session.set(SessionConstants.USER_INFO, ui);
    session.set(SessionConstants.CURRENT_USER, ui.getUserName());
    log.fine("Login user: " + username);
}
Also used : UserInfo(com.developmentontheedge.be5.model.UserInfo) Session(com.developmentontheedge.be5.api.Session)

Example 10 with UserInfo

use of com.google.api.services.actions_fulfillment.v2.model.UserInfo in project be5 by DevelopmentOnTheEdge.

the class UserHelper method saveUser.

public UserInfo saveUser(String userName, List<String> availableRoles, List<String> currentRoles, Locale locale, String remoteAddr, Session session) {
    UserInfo ui = new UserInfo(userName, availableRoles, currentRoles, session);
    ui.setRemoteAddr(remoteAddr);
    ui.setLocale(meta.getLocale(locale));
    UserInfoHolder.setUserInfo(ui);
    return ui;
}
Also used : UserInfo(com.developmentontheedge.be5.model.UserInfo)

Aggregations

Userinfo (com.google.api.services.oauth2.model.Userinfo)10 UserInfo (com.developmentontheedge.be5.model.UserInfo)3 Oauth2 (com.google.api.services.oauth2.Oauth2)3 UserInfo (org.alfresco.repo.event.v1.model.UserInfo)3 ApiException (com.haleconnect.api.user.v1.ApiException)2 IOException (java.io.IOException)2 Test (org.junit.jupiter.api.Test)2 FirecloudMe (org.pmiops.workbench.firecloud.model.FirecloudMe)2 FirecloudUserInfo (org.pmiops.workbench.firecloud.model.FirecloudUserInfo)2 Session (com.developmentontheedge.be5.api.Session)1 ForIntent (com.google.actions.api.ForIntent)1 TransactionDecision (com.google.actions.api.response.helperintent.transactions.v3.TransactionDecision)1 Credential (com.google.api.client.auth.oauth2.Credential)1 HttpResponseException (com.google.api.client.http.HttpResponseException)1 NetHttpTransport (com.google.api.client.http.javanet.NetHttpTransport)1 JacksonFactory (com.google.api.client.json.jackson2.JacksonFactory)1 Action (com.google.api.services.actions_fulfillment.v2.model.Action)1 GooglePaymentOption (com.google.api.services.actions_fulfillment.v2.model.GooglePaymentOption)1 LineItemV3 (com.google.api.services.actions_fulfillment.v2.model.LineItemV3)1 Location (com.google.api.services.actions_fulfillment.v2.model.Location)1