Пример #1
0
 private Response generalAuthError(String callback, Exception e) throws Exception {
   logger.error("Generic Auth Error", e);
   OAuthResponse response =
       OAuthResponse.errorResponse(SC_BAD_REQUEST)
           .setError(OAuthError.TokenResponse.INVALID_REQUEST)
           .buildJSONMessage();
   return Response.status(response.getResponseStatus())
       .type(jsonMediaType(callback))
       .entity(wrapJSONPResponse(callback, response.getBody()))
       .build();
 }
Пример #2
0
 private Response findAndCreateFail(String callback) throws Exception {
   logger.error("Unable to find or create user");
   OAuthResponse response =
       OAuthResponse.errorResponse(SC_BAD_REQUEST)
           .setError(OAuthError.TokenResponse.INVALID_REQUEST)
           .setErrorDescription("invalid user")
           .buildJSONMessage();
   return Response.status(response.getResponseStatus())
       .type(jsonMediaType(callback))
       .entity(wrapJSONPResponse(callback, response.getBody()))
       .build();
 }
Пример #3
0
 private Response missingTokenFail(String callback) throws Exception {
   logger.error("Missing Access token");
   OAuthResponse response =
       OAuthResponse.errorResponse(SC_BAD_REQUEST)
           .setError(OAuthError.TokenResponse.INVALID_REQUEST)
           .setErrorDescription("missing access token")
           .buildJSONMessage();
   return Response.status(response.getResponseStatus())
       .type(jsonMediaType(callback))
       .entity(wrapJSONPResponse(callback, response.getBody()))
       .build();
 }
Пример #4
0
  @POST
  @Path("collection/{collection_name}/export")
  @Consumes(APPLICATION_JSON)
  @RequireOrganizationAccess
  public Response exportPostJson(
      @Context UriInfo ui,
      @PathParam("collection_name") String collection_name,
      Map<String, Object> json,
      @QueryParam("callback") @DefaultValue("") String callback)
      throws OAuthSystemException {

    UsergridAwsCredentials uac = new UsergridAwsCredentials();
    UUID jobUUID = null;
    String colExport = collection_name;
    Map<String, String> uuidRet = new HashMap<String, String>();

    Map<String, Object> properties;
    Map<String, Object> storage_info;

    try {
      // checkJsonExportProperties(json);
      if ((properties = (Map<String, Object>) json.get("properties")) == null) {
        throw new NullArgumentException("Could not find 'properties'");
      }
      storage_info = (Map<String, Object>) properties.get("storage_info");
      String storage_provider = (String) properties.get("storage_provider");
      if (storage_provider == null) {
        throw new NullArgumentException("Could not find field 'storage_provider'");
      }
      if (storage_info == null) {
        throw new NullArgumentException("Could not find field 'storage_info'");
      }

      String bucketName = (String) storage_info.get("bucket_location");
      String accessId = (String) storage_info.get("s3_access_id");
      String secretKey = (String) storage_info.get("s3_key");

      if (accessId == null) {
        throw new NullArgumentException("Could not find field 's3_access_id'");
      }
      if (secretKey == null) {
        throw new NullArgumentException("Could not find field 's3_key'");
      }

      if (bucketName == null) {
        throw new NullArgumentException("Could not find field 'bucketName'");
      }

      json.put("organizationId", organization.getUuid());
      json.put("applicationId", applicationId);
      json.put("collectionName", colExport);

      jobUUID = exportService.schedule(json);
      uuidRet.put("Export Entity", jobUUID.toString());
    } catch (NullArgumentException e) {
      return Response.status(SC_BAD_REQUEST)
          .type(JSONPUtils.jsonMediaType(callback))
          .entity(ServiceResource.wrapWithCallback(e.getMessage(), callback))
          .build();
    } catch (Exception e) {

      // TODO: throw descriptive error message and or include on in the response
      // TODO: fix below, it doesn't work if there is an exception.
      // Make it look like the OauthResponse.

      OAuthResponse errorMsg =
          OAuthResponse.errorResponse(SC_INTERNAL_SERVER_ERROR)
              .setErrorDescription(e.getMessage())
              .buildJSONMessage();

      return Response.status(errorMsg.getResponseStatus())
          .type(JSONPUtils.jsonMediaType(callback))
          .entity(ServiceResource.wrapWithCallback(errorMsg.getBody(), callback))
          .build();
    }

    return Response.status(SC_ACCEPTED).entity(uuidRet).build();
  }
  @GET
  @Path("token")
  public Response getAccessToken(
      @Context UriInfo ui,
      @HeaderParam("Authorization") String authorization,
      @QueryParam("grant_type") String grant_type,
      @QueryParam("username") String username,
      @QueryParam("password") String password,
      @QueryParam("pin") String pin,
      @QueryParam("client_id") String client_id,
      @QueryParam("client_secret") String client_secret,
      @QueryParam("code") String code,
      @QueryParam("ttl") long ttl,
      @QueryParam("redirect_uri") String redirect_uri,
      @QueryParam("callback") @DefaultValue("") String callback)
      throws Exception {

    logger.debug("ApplicationResource.getAccessToken");

    User user = null;

    try {

      if (authorization != null) {
        String type = stringOrSubstringBeforeFirst(authorization, ' ').toUpperCase();
        if ("BASIC".equals(type)) {
          String token = stringOrSubstringAfterFirst(authorization, ' ');
          String[] values = Base64.decodeToString(token).split(":");
          if (values.length >= 2) {
            client_id = values[0].toLowerCase();
            client_secret = values[1];
          }
        }
      }

      // do checking for different grant types
      String errorDescription = "invalid username or password";
      if (GrantType.PASSWORD.toString().equals(grant_type)) {
        try {
          user =
              management.verifyAppUserPasswordCredentials(
                  services.getApplicationId(), username, password);
        } catch (UnactivatedAppUserException uaue) {
          errorDescription = "user not activated";
        } catch (DisabledAppUserException daue) {
          errorDescription = "user disabled";
        } catch (Exception e1) {
        }
      } else if ("pin".equals(grant_type)) {
        try {
          user = management.verifyAppUserPinCredentials(services.getApplicationId(), username, pin);
        } catch (Exception e1) {
        }
      } else if ("client_credentials".equals(grant_type)) {
        try {
          AccessInfo access_info = management.authorizeClient(client_id, client_secret, ttl);
          if (access_info != null) {
            return Response.status(SC_OK)
                .type(jsonMediaType(callback))
                .entity(wrapWithCallback(access_info, callback))
                .build();
          }
        } catch (Exception e1) {
        }
      } else if ("authorization_code".equals(grant_type)) {
        AccessInfo access_info = new AccessInfo();
        access_info.setAccessToken(code);
        return Response.status(SC_OK)
            .type(jsonMediaType(callback))
            .entity(wrapWithCallback(access_info, callback))
            .build();
      }

      if (user == null) {
        OAuthResponse response =
            OAuthResponse.errorResponse(SC_BAD_REQUEST)
                .setError(OAuthError.TokenResponse.INVALID_GRANT)
                .setErrorDescription(errorDescription)
                .buildJSONMessage();
        return Response.status(response.getResponseStatus())
            .type(jsonMediaType(callback))
            .entity(wrapWithCallback(response.getBody(), callback))
            .build();
      }

      String token =
          management.getAccessTokenForAppUser(services.getApplicationId(), user.getUuid(), ttl);

      AccessInfo access_info =
          new AccessInfo()
              .withExpiresIn(tokens.getMaxTokenAge(token) / 1000)
              .withAccessToken(token)
              .withProperty("user", user);

      return Response.status(SC_OK)
          .type(jsonMediaType(callback))
          .entity(wrapWithCallback(access_info, callback))
          .build();

    } catch (OAuthProblemException e) {
      logger.error("OAuth Error", e);
      OAuthResponse res = OAuthResponse.errorResponse(SC_BAD_REQUEST).error(e).buildJSONMessage();
      return Response.status(res.getResponseStatus())
          .type(jsonMediaType(callback))
          .entity(wrapWithCallback(res.getBody(), callback))
          .build();
    }
  }
Пример #6
0
  private void doProcess(final HttpServletRequest request, final HttpResponse response)
      throws OAuthSystemException, IOException {
    OAuthResponse oauthResponse;
    String state = request.getParameter(OAuth.OAUTH_STATE);
    String redirectUri = request.getParameter(OAuth.OAUTH_REDIRECT_URI);
    try {
      // Build a request and fail if it is not a valid OAUTH request
      final OAuthAuthzRequest oAuthAuthzRequest = new OAuthAuthzRequest(request);

      // Get oauth parameters
      final String clientId = oAuthAuthzRequest.getClientId();
      final String responseType = oAuthAuthzRequest.getParam(OAuth.OAUTH_RESPONSE_TYPE);
      final Set<String> scopes = oAuthAuthzRequest.getScopes();
      redirectUri = oAuthAuthzRequest.getRedirectURI();
      state = oAuthAuthzRequest.getState();

      int expiresIn = DEFAULT_EXPIRE_TIME;
      if (scopes.contains("permanent_token")) {
        expiresIn = DateUtils.SECOND_PER_DAY * 3650;
      }

      if (redirectUri == null || redirectUri.isEmpty()) {
        redirectUri = "pagenotfound";
      }

      final String login = request.getParameter("login");
      final String password = request.getParameter("password");

      final OAuthASResponse.OAuthAuthorizationResponseBuilder builder =
          OAuthASResponse.authorizationResponse(HttpServletResponse.SC_FOUND);

      // TODO make a more secure Generator ?
      final OAuthIssuer oauthIssuerImpl = new OAuthIssuerImpl(new UUIDValueGenerator());

      if (responseType.equals(ResponseType.CODE.toString())) {
        // Create the token
        final String token = oauthIssuerImpl.authorizationCode();
        // build response
        builder.setCode(token);
        // Add the external service
        authenticator.addExternalService(clientId, login, password, token, scopes);

      } else if (responseType.equals(ResponseType.TOKEN.toString())) {
        // Create tokens
        final String token = oauthIssuerImpl.accessToken();
        final String refresh = oauthIssuerImpl.refreshToken();
        // build response
        builder.setAccessToken(token);
        builder.setParam(OAuth.OAUTH_REFRESH_TOKEN, refresh);
        builder.setExpiresIn(String.valueOf(expiresIn));
        // Add in external services
        authenticator.addExternalService(clientId, login, password, token, scopes);
        authenticator.authorize(token, token, refresh, expiresIn);
      }

      // Finish the construction
      oauthResponse = builder.location(redirectUri).buildQueryMessage();

    } catch (final OAuthProblemException ex) {
      oauthResponse =
          OAuthResponse.errorResponse(HttpServletResponse.SC_FOUND)
              .error(ex)
              .setState(state)
              .location(redirectUri)
              .buildQueryMessage();

    } catch (final AuthorizationException e) {
      oauthResponse =
          OAuthResponse.errorResponse(HttpServletResponse.SC_FOUND)
              .setError("server_error")
              .setErrorDescription("Internal error. Please report.")
              .setState(state)
              .location(redirectUri)
              .buildQueryMessage();

      Log.framework().error("Cannot found a just added service ...", e);
    } catch (final ElementNotFoundException e) {
      response.writeOAuthRedirect(
          302,
          "/"
              + OAuthProcessor.OAUTH_GET_CREDENTIAL_PAGENAME
              + "?fail=true&"
              + request.getQueryString());
      return;
    } catch (final OAuthSystemException e) {
      throw new BadProgrammerException(e);
    }

    // write the response
    response.writeOAuthRedirect(oauthResponse.getResponseStatus(), oauthResponse.getLocationUri());
  }