com.google.api.server.spi.response.UnauthorizedException Java Examples

The following examples show how to use com.google.api.server.spi.response.UnauthorizedException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ConferenceApi.java    From ud859 with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Returns a list of Conferences that the user created.
 * In order to receive the websafeConferenceKey via the JSON params, uses a POST method.
 *
 * @param user A user who invokes this method, null when the user is not signed in.
 * @return a list of Conferences that the user created.
 * @throws UnauthorizedException when the user is not signed in.
 */
@ApiMethod(
        name = "getConferencesCreated",
        path = "getConferencesCreated",
        httpMethod = HttpMethod.POST
)
public List<Conference> getConferencesCreated(final User user) throws UnauthorizedException {
    // If not signed in, throw a 401 error.
    if (user == null) {
        throw new UnauthorizedException("Authorization required");
    }
    String userId = user.getUserId();
    Key<Profile> userKey = Key.create(Profile.class, userId);
    return ofy().load().type(Conference.class)
            .ancestor(userKey)
            .order("name").list();
}
 
Example #2
Source File: Echo.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the authenticated user's email. If the user is not authenticated, this will return an HTTP
 * 401.
 *
 * <p>Note that name is not specified. This will default to "{class name}.{method name}". For
 * example, the default is "echo.getUserEmail".
 *
 * <p>Note that httpMethod is not required here. Without httpMethod, this will default to GET due
 * to the API method name. httpMethod is added here for example purposes.
 */
// [START firebase_auth]
@ApiMethod(
    path = "firebase_user",
    httpMethod = ApiMethod.HttpMethod.GET,
    authenticators = {EspAuthenticator.class},
    issuerAudiences = {
        @ApiIssuerAudience(
            name = "firebase",
            audiences = {"YOUR-PROJECT-ID"}
        )
    }
)
public Email getUserEmailFirebase(User user) throws UnauthorizedException {
  if (user == null) {
    throw new UnauthorizedException("Invalid credentials");
  }

  Email response = new Email();
  response.setEmail(user.getEmail());
  return response;
}
 
Example #3
Source File: Echo.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the authenticated user's email. If the user is not authenticated, this will return an HTTP
 * 401.
 *
 * <p>Note that name is not specified. This will default to "{class name}.{method name}". For
 * example, the default is "echo.getUserEmail".
 *
 * <p>Note that httpMethod is not required here. Without httpMethod, this will default to GET due
 * to the API method name. httpMethod is added here for example purposes.
 */
// [START google_id_token_auth]
@ApiMethod(
    httpMethod = ApiMethod.HttpMethod.GET,
    authenticators = {EspAuthenticator.class},
    audiences = {"YOUR_OAUTH_CLIENT_ID"},
    clientIds = {"YOUR_OAUTH_CLIENT_ID"}
)
public Email getUserEmail(User user) throws UnauthorizedException {
  if (user == null) {
    throw new UnauthorizedException("Invalid credentials");
  }

  Email response = new Email();
  response.setEmail(user.getEmail());
  return response;
}
 
Example #4
Source File: CrudOperations.java    From solutions-mobile-backend-starter-java with Apache License 2.0 6 votes vote down vote up
protected EntityListDto deleteAll(EntityListDto cdl, User user) throws UnauthorizedException {

    // check ACL
    Map<String, Entity> entities = getAllEntitiesByKeyList(cdl.readKeyList(user));
    for (Entity e : entities.values()) {
      SecurityChecker.getInstance().checkAclForWrite(e, user);
    }

    // delete from memcache
    memcache.deleteAll(cdl.readIdList());

    // delete all the Entities
    datastore.delete(cdl.readKeyList(user));

    // return a dummy collection
    return new EntityListDto();
  }
 
Example #5
Source File: SecurityChecker.java    From io2014-codelabs with Apache License 2.0 6 votes vote down vote up
/**
 * Checks if the user is allowed to use the backend. The method throws
 * {@link com.google.api.server.spi.response.UnauthorizedException} if the backend is locked down or if the user
 * is null and the authentication through Client IDs is enabled.
 *
 * @param user
 *          {@link com.google.appengine.api.users.User} on behalf of which the call is made from the client.
 * @throws com.google.api.server.spi.response.UnauthorizedException
 *           if the call is not authenticated because of the status of the
 *           authMode or the User.
 */
protected void checkIfUserIsAvailable(User user) throws UnauthorizedException {

  AuthMode authMode = backendConfigManager.getAuthMode();
  switch (authMode) {
  case OPEN: // no check
    return;
  case CLIENT_ID: // error if User is null
    if (user == null) {
      throw new UnauthorizedException("Unauthenticated calls are not allowed");
    } else {
      return;
    }
  case LOCKED: // always error
  default:
    throw new UnauthorizedException("The backend is locked down. The administrator can change "
        + "the authentication/authorization settings on https://" + getHostname() + "/");
  }
}
 
Example #6
Source File: ServletRequestParamReaderTest.java    From endpoints-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testAppEngineUserInjectionThrowsExceptionIfRequired() throws Exception {
  @SuppressWarnings("unused")
  class TestUser {
    @SuppressWarnings("unused")
    public void getUser(com.google.appengine.api.users.User user) { }
  }
  ApiMethodConfig methodConfig = Mockito.mock(ApiMethodConfig.class);
  when(methodConfig.getAuthLevel()).thenReturn(AuthLevel.REQUIRED);
  methodConfig.setAuthLevel(AuthLevel.REQUIRED);
  try {
    Method method = TestUser.class
        .getDeclaredMethod("getUser", com.google.appengine.api.users.User.class);
    readParameters(
        "{}",
        EndpointMethod.create(method.getDeclaringClass(), method),
        methodConfig,
        null,
        null);
    fail("expected unauthorized method exception");
  } catch (UnauthorizedException ex) {
    // expected
  }
}
 
Example #7
Source File: Echo.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the authenticated user's email. If the user is not authenticated, this will return an HTTP
 * 401.
 *
 * Note that name is not specified. This will default to "{class name}.{method name}". For
 * example, the default is "echo.getUserEmail".
 *
 * Note that httpMethod is not required here. Without httpMethod, this will default to GET due
 * to the API method name. httpMethod is added here for example purposes.
 */
@ApiMethod(
    path = "firebase_user",
    httpMethod = ApiMethod.HttpMethod.GET,
    authenticators = {EspAuthenticator.class},
    issuerAudiences = {@ApiIssuerAudience(name = "firebase", audiences = {"YOUR-PROJECT-ID"})}
    )
public Email getUserEmailFirebase(User user) throws UnauthorizedException {
  if (user == null) {
    throw new UnauthorizedException("Invalid credentials");
  }

  Email response = new Email();
  response.setEmail(user.getEmail());
  return response;
}
 
Example #8
Source File: Echo.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the authenticated user's email. If the user is not authenticated, this will return an HTTP
 * 401.
 *
 * Note that name is not specified. This will default to "{class name}.{method name}". For
 * example, the default is "echo.getUserEmail".
 *
 * Note that httpMethod is not required here. Without httpMethod, this will default to GET due
 * to the API method name. httpMethod is added here for example purposes.
 */
@ApiMethod(
    httpMethod = ApiMethod.HttpMethod.GET,
    authenticators = {EspAuthenticator.class},
    audiences = {"YOUR_OAUTH_CLIENT_ID"},
    clientIds = {"YOUR_OAUTH_CLIENT_ID"}
    )
public Email getUserEmail(User user) throws UnauthorizedException {
  if (user == null) {
    throw new UnauthorizedException("Invalid credentials");
  }

  Email response = new Email();
  response.setEmail(user.getEmail());
  return response;
}
 
Example #9
Source File: BlobEndpoint.java    From io2014-codelabs with Apache License 2.0 6 votes vote down vote up
/**
 * Gets a signed URL that can be used to upload a blob.
 *
 * @param bucketName  Google Cloud Storage bucket to use for upload.
 * @param objectPath  path to the object in the bucket.
 * @param accessMode  controls how the uploaded blob can be accessed.
 * @param contentType the MIME type of the object of be uploaded. Can be null.
 * @param user        the user making the request.
 * @throws com.google.api.server.spi.response.UnauthorizedException if the user is not authorized.
 * @throws com.google.api.server.spi.response.BadRequestException   if the bucketName or objectPath are not valid.
 */
@ApiMethod(httpMethod = HttpMethod.GET, path = "blobs/uploads/{bucketName}/{objectPath}")
public BlobAccess getUploadUrl(@Named("bucketName") String bucketName,
                               @Named("objectPath") String objectPath, @Named("accessMode") BlobAccessMode accessMode,
                               @Nullable @Named("contentType") String contentType, User user)
  throws UnauthorizedException, BadRequestException {
  validateUser(user);

  validateBucketAndObjectPath(bucketName, objectPath);

  if (!reserveNameIfAvailable(bucketName, objectPath, accessMode, user)) {
    throw new UnauthorizedException("You don't have permissions to upload this object");
  }

  return getBlobUrlForUpload(
    bucketName, objectPath, accessMode, contentType != null ? contentType : "");
}
 
Example #10
Source File: BlobEndpoint.java    From io2014-codelabs with Apache License 2.0 6 votes vote down vote up
/**
 * Deletes a blob.
 *
 * @param bucketName Google Cloud Storage bucket where the object was uploaded.
 * @param objectPath path to the object in the bucket.
 * @param user       the user making the request.
 * @throws com.google.api.server.spi.response.UnauthorizedException        if the user is not authorized.
 * @throws com.google.api.server.spi.response.BadRequestException          if the bucketName or objectPath are not valid.
 * @throws com.google.api.server.spi.response.InternalServerErrorException when the operation failed.
 */
@ApiMethod(httpMethod = HttpMethod.DELETE, path = "blobs/{bucketName}/{objectPath}")
public void deleteBlob(
  @Named("bucketName") String bucketName, @Named("objectPath") String objectPath, User user)
  throws UnauthorizedException, BadRequestException, InternalServerErrorException {
  validateUser(user);

  validateBucketAndObjectPath(bucketName, objectPath);

  boolean blobExists = checkDeletePermissions(bucketName, objectPath, user);

  if (!blobExists) {
    // DELETE operation is idempotent. The object doesn't exist, so there is no more work to do.
    return;
  }

  if (!deleteAllBlobInformation(bucketName, objectPath)) {
    throw new InternalServerErrorException("Deleting blob failed. You can retry.");
  }
}
 
Example #11
Source File: BlobEndpoint.java    From io2014-codelabs with Apache License 2.0 6 votes vote down vote up
/**
 * Checks user's permissions to read a blob and throws an exception if user doesn't have
 * permissions.
 *
 * @param bucketName Google Cloud Storage bucket where the object was uploaded.
 * @param objectPath path to the object in the bucket.
 * @param user       the user making the request.
 * @throws com.google.api.server.spi.response.UnauthorizedException if the user is not authorized.
 * @throws com.google.api.server.spi.response.NotFoundException     if the object doesn't exist.
 */
private void checkReadObjectPermissions(String bucketName, String objectPath, User user)
  throws UnauthorizedException, NotFoundException {
  BlobMetadata metadata = BlobManager.getBlobMetadata(bucketName, objectPath);
  if (metadata == null) {
    throw new NotFoundException("Blob doesn't exist.");
  }

  if (getUserId(user).equals(metadata.getOwnerId())) {
    // User is the owner so the read operation is allowed regardless of the access mode.
    return;
  }

  if (metadata.getAccessMode() != BlobAccessMode.PUBLIC_READ
    && metadata.getAccessMode() != BlobAccessMode.PUBLIC_READ_FOR_APP_USERS) {
    throw new UnauthorizedException("You don't have permissions to download this object");
  }
}
 
Example #12
Source File: DeviceRegistrationEndpoint.java    From solutions-ios-push-notification-sample-backend-java with Apache License 2.0 6 votes vote down vote up
/**
 * Inserts a new entity into App Engine datastore or updates existing entity.It uses HTTP POST
 * method.
 *
 * @param device the entity to be inserted/updated.
 * @return The inserted/updated entity.
 * @throws ServiceException when the call is unauthenticated and the backend is configured not to
 *         allow them
 */
public DeviceRegistration registerDevice(DeviceRegistration device, User user)
    throws ServiceException {

  if (user == null && !Configuration.ALLOW_UNAUTHENTICATED_CALLS) {
    throw new UnauthorizedException("Only authenticated calls are allowed");
  }

  EntityManager mgr = getEntityManager();
  try {
    device.setTimestamp(new Date());
    mgr.persist(device);
  } finally {
    mgr.close();
  }
  return device;
}
 
Example #13
Source File: CrudOperations.java    From io2014-codelabs with Apache License 2.0 6 votes vote down vote up
protected EntityListDto deleteAll(EntityListDto cdl, User user) throws UnauthorizedException {

    // check ACL
    Map<String, Entity> entities = getAllEntitiesByKeyList(cdl.readKeyList(user));
    for (Entity e : entities.values()) {
      SecurityChecker.getInstance().checkAclForWrite(e, user);
    }

    // delete from memcache
    memcache.deleteAll(cdl.readIdList());

    // delete all the Entities
    datastore.delete(cdl.readKeyList(user));

    // return a dummy collection
    return new EntityListDto();
  }
 
Example #14
Source File: CrudOperations.java    From io2014-codelabs with Apache License 2.0 6 votes vote down vote up
protected EntityDto delete(@Named("kind") String kindName, @Named("id") String id, User user)
    throws UnauthorizedException {

  // check ACL
  Entity e;
  try {
    e = getEntityById(kindName, id, user);
  } catch (NotFoundException e1) {
    return null; // if there's no such entity, just return null
  }
  SecurityChecker.getInstance().checkAclForWrite(e, user);

  // delete from memcache
  memcache.delete(id);

  // delete the CE
  datastore.delete(e.getKey());

  // return a EntityDto
  return EntityDto.createFromEntity(e);
}
 
Example #15
Source File: ConferenceApi.java    From ud859 with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Returns a list of Conferences that the user created.
 * In order to receive the websafeConferenceKey via the JSON params, uses a POST method.
 *
 * @param user A user who invokes this method, null when the user is not signed in.
 * @return a list of Conferences that the user created.
 * @throws UnauthorizedException when the user is not signed in.
 */
@ApiMethod(
        name = "getConferencesCreated",
        path = "getConferencesCreated",
        httpMethod = HttpMethod.POST
)
public List<Conference> getConferencesCreated(final User user) throws UnauthorizedException {
    // If not signed in, throw a 401 error.
    if (user == null) {
        throw new UnauthorizedException("Authorization required");
    }
    String userId = user.getUserId();
    Key<Profile> userKey = Key.create(Profile.class, userId);
    return ofy().load().type(Conference.class)
            .ancestor(userKey)
            .order("name").list();
}
 
Example #16
Source File: BlobEndpoint.java    From solutions-mobile-backend-starter-java with Apache License 2.0 6 votes vote down vote up
/**
 * Checks user's permissions to read a blob and throws an exception if user doesn't have
 * permissions.
 *
 * @param bucketName Google Cloud Storage bucket where the object was uploaded.
 * @param objectPath path to the object in the bucket.
 * @param user the user making the request.
 * @throws UnauthorizedException if the user is not authorized.
 * @throws NotFoundException if the object doesn't exist.
 */
private void checkReadObjectPermissions(String bucketName, String objectPath, User user)
    throws UnauthorizedException, NotFoundException {
  BlobMetadata metadata = BlobManager.getBlobMetadata(bucketName, objectPath);
  if (metadata == null) {
    throw new NotFoundException("Blob doesn't exist.");
  }

  if (getUserId(user).equals(metadata.getOwnerId())) {
    // User is the owner so the read operation is allowed regardless of the access mode.
    return;
  }

  if (metadata.getAccessMode() != BlobAccessMode.PUBLIC_READ
      && metadata.getAccessMode() != BlobAccessMode.PUBLIC_READ_FOR_APP_USERS) {
    throw new UnauthorizedException("You don't have permissions to download this object");
  }
}
 
Example #17
Source File: SecurityChecker.java    From solutions-mobile-backend-starter-java with Apache License 2.0 6 votes vote down vote up
/**
 * Checks ACL of the specified CloudEntity to see if the specified user can
 * write on it.
 *
 * @param e
 *          {@link Entity} of CloudEntity
 * @param user
 *          User object representing the caller.
 * @throws UnauthorizedException
 *           if the user does not have permission to write on the entity
 */
protected void checkAclForWrite(Entity e, User user) throws UnauthorizedException {

  // get ACL
  String userId = getUserId(user);
  String ownerId = (String) e.getProperty(EntityDto.PROP_OWNER);

  // check ACL
  boolean isOwner = userId.equals(ownerId);
  boolean isPublic = e.getKind().startsWith(KIND_PREFIX_PUBLIC);
  boolean isWritable = isOwner || isPublic;
  if (!isWritable) {
    String id = e.getKey().getName();
    throw new UnauthorizedException("Insuffient permission for updating a CloudEntity: " + id
        + " by: " + userId);
  }
}
 
Example #18
Source File: ConferenceApi.java    From ud859 with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Creates or updates a Profile object associated with the given user object.
 *
 * @param user A User object injected by the cloud endpoints.
 * @param profileForm A ProfileForm object sent from the client form.
 * @return Profile object just created.
 * @throws UnauthorizedException when the User object is null.
 */
@ApiMethod(name = "saveProfile", path = "profile", httpMethod = HttpMethod.POST)
public Profile saveProfile(final User user, final ProfileForm profileForm)
        throws UnauthorizedException {
    if (user == null) {
        throw new UnauthorizedException("Authorization required");
    }
    String displayName = profileForm.getDisplayName();
    TeeShirtSize teeShirtSize = profileForm.getTeeShirtSize();

    Profile profile = ofy().load().key(Key.create(Profile.class, getUserId(user))).now();
    if (profile == null) {
        // Populate displayName and teeShirtSize with the default values if null.
        if (displayName == null) {
            displayName = extractDefaultDisplayNameFromEmail(user.getEmail());
        }
        if (teeShirtSize == null) {
            teeShirtSize = TeeShirtSize.NOT_SPECIFIED;
        }
        profile = new Profile(getUserId(user), displayName, user.getEmail(), teeShirtSize);
    } else {
        profile.update(displayName, teeShirtSize);
    }
    ofy().save().entity(profile).now();
    return profile;
}
 
Example #19
Source File: BlobEndpoint.java    From solutions-mobile-backend-starter-java with Apache License 2.0 6 votes vote down vote up
/**
 * Deletes a blob.
 *
 * @param bucketName Google Cloud Storage bucket where the object was uploaded.
 * @param objectPath path to the object in the bucket.
 * @param user the user making the request.
 * @throws UnauthorizedException if the user is not authorized.
 * @throws BadRequestException if the bucketName or objectPath are not valid.
 * @throws InternalServerErrorException when the operation failed.
 */
@ApiMethod(httpMethod = HttpMethod.DELETE, path = "blobs/{bucketName}/{objectPath}")
public void deleteBlob(
    @Named("bucketName") String bucketName, @Named("objectPath") String objectPath, User user)
    throws UnauthorizedException, BadRequestException, InternalServerErrorException {
  validateUser(user);

  validateBucketAndObjectPath(bucketName, objectPath);

  boolean blobExists = checkDeletePermissions(bucketName, objectPath, user);

  if (!blobExists) {
    // DELETE operation is idempotent. The object doesn't exist, so there is no more work to do.
    return;
  }

  if (!deleteAllBlobInformation(bucketName, objectPath)) {
    throw new InternalServerErrorException("Deleting blob failed. You can retry.");
  }
}
 
Example #20
Source File: ConferenceApi.java    From ud859 with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Returns a collection of Conference Object that the user is going to attend.
 *
 * @param user An user who invokes this method, null when the user is not signed in.
 * @return a Collection of Conferences that the user is going to attend.
 * @throws UnauthorizedException when the User object is null.
 */
@ApiMethod(
        name = "getConferencesToAttend",
        path = "getConferencesToAttend",
        httpMethod = HttpMethod.GET
)
public Collection<Conference> getConferencesToAttend(final User user)
        throws UnauthorizedException, NotFoundException {
    // If not signed in, throw a 401 error.
    if (user == null) {
        throw new UnauthorizedException("Authorization required");
    }
    Profile profile = ofy().load().key(Key.create(Profile.class, getUserId(user))).now();
    if (profile == null) {
        throw new NotFoundException("Profile doesn't exist.");
    }
    List<String> keyStringsToAttend = profile.getConferenceKeysToAttend();
    List<Key<Conference>> keysToAttend = new ArrayList<>();
    for (String keyString : keyStringsToAttend) {
        keysToAttend.add(Key.<Conference>create(keyString));
    }
    return ofy().load().keys(keysToAttend).values();
}
 
Example #21
Source File: ConferenceApi.java    From ud859 with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Returns a list of Conferences that the user created.
 * In order to receive the websafeConferenceKey via the JSON params, uses a POST method.
 *
 * @param user An user who invokes this method, null when the user is not signed in.
 * @return a list of Conferences that the user created.
 * @throws UnauthorizedException when the user is not signed in.
 */
@ApiMethod(
        name = "getConferencesCreated",
        path = "getConferencesCreated",
        httpMethod = HttpMethod.POST
)
public List<Conference> getConferencesCreated(final User user) throws UnauthorizedException {
    // If not signed in, throw a 401 error.
    if (user == null) {
        throw new UnauthorizedException("Authorization required");
    }
    String userId = getUserId(user);
    return ofy().load().type(Conference.class)
            .ancestor(Key.create(Profile.class, userId))
            .order("name").list();
}
 
Example #22
Source File: BlobEndpoint.java    From io2014-codelabs with Apache License 2.0 6 votes vote down vote up
@ApiMethod(httpMethod = ApiMethod.HttpMethod.POST,
  path = "images/process/{bucketName}/{objectPath}")
public BlobAccess transformImage(@Named("bucketName") String bucketName,
                                 @Named("objectPath") String objectPath,
                                 @Named("accessMode") BlobAccessMode accessMode,
                                 User user)
  throws BadRequestException, UnauthorizedException, InternalServerErrorException, NotFoundException {
  validateUser(user);
  checkDeletePermissions(bucketName, objectPath, user);
  BlobMetadata metadata = BlobManager.getBlobMetadata(bucketName, objectPath);
  String transformedObjectPath = String.valueOf("transformed-cloudguestbook-picture-" + System.currentTimeMillis());
  BlobAccess blobAccess = getBlobUrlForUpload(bucketName, transformedObjectPath, metadata.getAccessMode(), "");

  if (!reserveNameIfAvailable(bucketName, transformedObjectPath, accessMode, user)) {
    throw new UnauthorizedException("You don't have permissions to upload the transformed image");
  }

  // This method is incomplete.
  // Implement the rest of the method.
  // Complete example is located at MobileBackend/snippets/BlobEndpoints.java
  throw new NotFoundException("This method is not implemented yet.");
}
 
Example #23
Source File: BlobEndpoint.java    From io2014-codelabs with Apache License 2.0 6 votes vote down vote up
/**
 * Deletes a blob.
 *
 * @param bucketName Google Cloud Storage bucket where the object was uploaded.
 * @param objectPath path to the object in the bucket.
 * @param user       the user making the request.
 * @throws com.google.api.server.spi.response.UnauthorizedException        if the user is not authorized.
 * @throws com.google.api.server.spi.response.BadRequestException          if the bucketName or objectPath are not valid.
 * @throws com.google.api.server.spi.response.InternalServerErrorException when the operation failed.
 */
@ApiMethod(httpMethod = HttpMethod.DELETE, path = "blobs/{bucketName}/{objectPath}")
public void deleteBlob(
  @Named("bucketName") String bucketName, @Named("objectPath") String objectPath, User user)
  throws UnauthorizedException, BadRequestException, InternalServerErrorException {
  validateUser(user);

  validateBucketAndObjectPath(bucketName, objectPath);

  boolean blobExists = checkDeletePermissions(bucketName, objectPath, user);

  if (!blobExists) {
    // DELETE operation is idempotent. The object doesn't exist, so there is no more work to do.
    return;
  }

  if (!deleteAllBlobInformation(bucketName, objectPath)) {
    throw new InternalServerErrorException("Deleting blob failed. You can retry.");
  }
}
 
Example #24
Source File: BlobEndpoint.java    From solutions-mobile-backend-starter-java with Apache License 2.0 6 votes vote down vote up
/**
 * Gets a signed URL that can be used to upload a blob.
 *
 * @param bucketName Google Cloud Storage bucket to use for upload.
 * @param objectPath path to the object in the bucket.
 * @param accessMode controls how the uploaded blob can be accessed.
 * @param contentType the MIME type of the object of be uploaded. Can be null.
 * @param user the user making the request.
 * @throws UnauthorizedException if the user is not authorized.
 * @throws BadRequestException if the bucketName or objectPath are not valid.
 */
@ApiMethod(httpMethod = HttpMethod.GET, path = "blobs/uploads/{bucketName}/{objectPath}")
public BlobAccess getUploadUrl(@Named("bucketName") String bucketName,
    @Named("objectPath") String objectPath, @Named("accessMode") BlobAccessMode accessMode,
    @Nullable @Named("contentType") String contentType, User user)
    throws UnauthorizedException, BadRequestException {
  validateUser(user);

  validateBucketAndObjectPath(bucketName, objectPath);

  if (!reserveNameIfAvailable(bucketName, objectPath, accessMode, user)) {
    throw new UnauthorizedException("You don't have permissions to upload this object");
  }

  return getBlobUrlForUpload(
      bucketName, objectPath, accessMode, contentType != null ? contentType : "");
}
 
Example #25
Source File: BlobEndpoint.java    From io2014-codelabs with Apache License 2.0 6 votes vote down vote up
/**
 * Gets a signed URL that can be used to upload a blob.
 *
 * @param bucketName  Google Cloud Storage bucket to use for upload.
 * @param objectPath  path to the object in the bucket.
 * @param accessMode  controls how the uploaded blob can be accessed.
 * @param contentType the MIME type of the object of be uploaded. Can be null.
 * @param user        the user making the request.
 * @throws com.google.api.server.spi.response.UnauthorizedException if the user is not authorized.
 * @throws com.google.api.server.spi.response.BadRequestException   if the bucketName or objectPath are not valid.
 */
@ApiMethod(httpMethod = HttpMethod.GET, path = "blobs/uploads/{bucketName}/{objectPath}")
public BlobAccess getUploadUrl(@Named("bucketName") String bucketName,
                               @Named("objectPath") String objectPath, @Named("accessMode") BlobAccessMode accessMode,
                               @Nullable @Named("contentType") String contentType, User user)
  throws UnauthorizedException, BadRequestException {
  validateUser(user);

  validateBucketAndObjectPath(bucketName, objectPath);

  if (!reserveNameIfAvailable(bucketName, objectPath, accessMode, user)) {
    throw new UnauthorizedException("You don't have permissions to upload this object");
  }

  return getBlobUrlForUpload(
    bucketName, objectPath, accessMode, contentType != null ? contentType : "");
}
 
Example #26
Source File: ConferenceApi.java    From ud859 with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Returns a collection of Conference Object that the user is going to attend.
 *
 * @param user An user who invokes this method, null when the user is not signed in.
 * @return a Collection of Conferences that the user is going to attend.
 * @throws UnauthorizedException when the User object is null.
 */
@ApiMethod(
        name = "getConferencesToAttend",
        path = "getConferencesToAttend",
        httpMethod = HttpMethod.GET
)
public Collection<Conference> getConferencesToAttend(final User user)
        throws UnauthorizedException, NotFoundException {
    // If not signed in, throw a 401 error.
    if (user == null) {
        throw new UnauthorizedException("Authorization required");
    }
    Profile profile = ofy().load().key(Key.create(Profile.class, user.getUserId())).now();
    if (profile == null) {
        throw new NotFoundException("Profile doesn't exist.");
    }
    List<String> keyStringsToAttend = profile.getConferenceKeysToAttend();
    List<Key<Conference>> keysToAttend = new ArrayList<>();
    for (String keyString : keyStringsToAttend) {
        keysToAttend.add(Key.<Conference>create(keyString));
    }
    return ofy().load().keys(keysToAttend).values();
}
 
Example #27
Source File: ServletRequestParamReaderTest.java    From endpoints-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testUserInjectionThrowsExceptionIfRequired() throws Exception {
  @SuppressWarnings("unused")
  class TestUser {
    @SuppressWarnings("unused")
    public void getUser(User user) { }
  }
  ApiMethodConfig methodConfig = Mockito.mock(ApiMethodConfig.class);
  when(methodConfig.getAuthLevel()).thenReturn(AuthLevel.REQUIRED);
  methodConfig.setAuthLevel(AuthLevel.REQUIRED);
  try {
    Method method = TestUser.class.getDeclaredMethod("getUser", User.class);
    readParameters(
        "{}", EndpointMethod.create(method.getDeclaringClass(), method),
        methodConfig,
        null,
        null);
    fail("expected unauthorized method exception");
  } catch (UnauthorizedException ex) {
    // expected
  }
}
 
Example #28
Source File: ConfigurationServlet.java    From solutions-mobile-backend-starter-java with Apache License 2.0 5 votes vote down vote up
/**
 * a request with "op=broadcast" sends a broadcast message to all registered
 * devices. The message will contain all key-value pairs specified as
 * parameter.
 * 
 * example: /admin/cconf?op=broadcast&msg=hello&duration=5
 */
private void sendPushMessage(HttpServletRequest req, JsonObject jsonResp) {

  // decode params and validate
  String topicId = req.getParameter(PARAM_PUSHMSG_TOPIC_ID);
  String props = req.getParameter(PARAM_PUSHMSG_PROPERTIES);
  if (topicId == null || topicId.trim().length() == 0 || props == null
      || props.trim().length() == 0) {
    jsonResp.addProperty(JSON_RESP_PROP_MESSAGE,
        "TopicId or properties are empty.");
    return;
  }

  // decode properties field (comma separated key-value pairs)
  // e.g. foo=bar,hoge=123
  Map<String, Object> params = new HashMap<String, Object>();
  params.put(PARAM_PUSHMSG_TOPIC_ID, topicId);
  for (String prop : props.split(",")) {
    String[] s = prop.split("=");
    params.put(s[0], s[1]);
  }

  // create an entity for _PushMessages from the parameters
  EntityDto cd = new EntityDto();
  cd.setKindName(KIND_NAME_PUSH_MESSAGES);
  cd.setProperties(params);
  EntityListDto cdl = new EntityListDto();
  cdl.add(cd);

  // save the entity to broadcast the toast
  try {
    CrudOperations.getInstance().saveAll(cdl, userService.getCurrentUser());
  } catch (UnauthorizedException e) {
    e.printStackTrace();
  }
  jsonResp.addProperty(JSON_RESP_PROP_MESSAGE, "Broadcast message sent: "
      + params);
}
 
Example #29
Source File: ConferenceApi.java    From ud859 with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns a Profile object associated with the given user object. The cloud
 * endpoints system automatically inject the User object.
 *
 * @param user
 *            A User object injected by the cloud endpoints.
 * @return Profile object.
 * @throws UnauthorizedException
 *             when the User object is null.
 */
@ApiMethod(name = "getProfile", path = "profile", httpMethod = HttpMethod.GET)
public Profile getProfile(final User user) throws UnauthorizedException {
    if (user == null) {
        throw new UnauthorizedException("Authorization required");
    }

    // TODO
    // load the Profile Entity
    String userId = user.getUserId();
    Key key = Key.create(Profile.class, userId);

    Profile profile = (Profile) ofy().load().key(key).now();
    return profile;
}
 
Example #30
Source File: BlobEndpoint.java    From solutions-mobile-backend-starter-java with Apache License 2.0 5 votes vote down vote up
/**
 * Checks user's permissions to delete a blob and throws an exception if user doesn't have
 * permissions.
 *
 * @param bucketName Google Cloud Storage bucket where the object was uploaded.
 * @param objectPath path to the object in the bucket.
 * @param user the user making the request.
 * @return true if the object may exist and delete operation should proceed; false otherwise.
 * @throws UnauthorizedException if the user is not authorized.
 */
private boolean checkDeletePermissions(String bucketName, String objectPath, User user)
    throws UnauthorizedException {
  BlobMetadata metadata = BlobManager.getBlobMetadata(bucketName, objectPath);
  if (metadata == null) {
    return false;
  }

  if (getUserId(user).equals(metadata.getOwnerId())) {
    // User is the owner.
    return true;
  }

  throw new UnauthorizedException("You don't have permissions to delete this object");
}