Setting user permissions for GET /activities

There are many ways to update the ExampleActivitiesApiHandler.getActivities handler method to check user permissions for certain actions. This example presents a simple solution to the problem:
  • Unrestricted user su can view activities for all users
  • Individual users can view their own activities only
To provide permission checking on the GET /activities/{activityId} operation, you need to update the following methods in the ExampleActivitiesApiHandler API handler class:
  • getActivities
  • loadActivityById

Adding the assignedUser parameter to the Swagger schema

First, you need to add a parameter for assignedUser to the GET /activities definition in file activityAPI.swagger.yaml so that the parameter is available to the handler class.
/activities:
  get:
    ...
    parameters:
      - name: assignedUser
      in: query
      type: string
    ...

Adding functionality to handler method getActivities

Class ExampleActivitiesApiHandler exists in the following directory in the Studio Project window:
  • configuration > gsrc > mc > activityapi

The following code fragment illustrates how to add logic to that permits unrestricted user su to view all activities and the calling user to view only activities associated with that user.

function getActivities(assignedUser : String) : List<TransformResult> {
  var query = Query.make(Activity)
  if (assignedUser != null) {
    var credential = Query.make(Credential).compare(Credential#UserName, Relop.Equals, assignedUser).select().AtMostOneRow
    if (credential == null) {
      throw new BadInputException("No user was found with username " + assignedUser)
    }
    var user = Query.make(User).compare(User#Credential, Relop.Equals, credential).select().AtMostOneRow
    query.compare(Activity#AssignedUser, Relop.Equals, user)
  }

  var resultSet = query.select()
  var mapper = JsonConfigAccess.getMapper("mc.activityapi.activityAPI-1.0", "ActivitySummary")

  return mapper.transformObjects(resultSet)
}

Adding functionality to private handler method loadActivityById

In modifying the ExampleActivitiesApiHandler class, it makes sense to put the view permission check in the loadActivityById method. In doing so, it provides a means to make the following two conditions return the same error message:
  • Bad activity ID
  • No permission to view
Thus, a user without the permission to view an activity cannot tell if the URL is valid or not.
private function loadActivityById(activityId : String) : Activity {
  var activity = Query.make(Activity).compare(Activity#PublicID, Relop.Equals, activityId).select().AtMostOneRow
  if (activity == null || !perm.Activity.view(activity)) {
    throw new NotFoundException("No activity was found with id " + activityId)
  }
  return activity
}