io.dropwizard.auth.Auth Java Examples

The following examples show how to use io.dropwizard.auth.Auth. 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: SecretsResource.java    From keywhiz with Apache License 2.0 6 votes vote down vote up
/**
 * Rollback to a previous secret version
 *
 * @param user       the admin user performing this operation
 * @param secretName the name of the secret to rollback
 * @param versionId  the ID of the version to return to
 * @return 200 if the rollback was successful, 404 for missing secret or bad input
 * <p>
 * description Returns the previous versions of the secret if found Used by Keywhiz CLI.
 * <p>
 * responseMessage 200 Found and reset the secret to this version
 * <p>
 * responseMessage 404 Secret with given name not found or invalid version provided
 */
@Path("rollback/{secretName}/{versionId}")
@Timed @ExceptionMetered
@POST
public Response resetSecretVersion(@Auth User user, @PathParam("secretName") String secretName,
    @PathParam("versionId") LongParam versionId) {

  logger.info("User '{}' rolling back secret '{}' to version with ID '{}'.", user, secretName,
      versionId);

  secretDAOReadWrite.setCurrentSecretVersionByName(secretName, versionId.get(), user.getName());

  // If the secret wasn't found or the request was misformed, setCurrentSecretVersionByName
  // already threw an exception
  Map<String, String> extraInfo = new HashMap<>();
  extraInfo.put("new version", versionId.toString());
  auditLog.recordEvent(
      new Event(Instant.now(), EventTag.SECRET_CHANGEVERSION, user.getName(), secretName,
          extraInfo));

  // Send the new secret in response
  URI uri = UriBuilder.fromResource(SecretsResource.class)
      .path("rollback/{secretName}/{versionID}")
      .build(secretName, versionId);
  return Response.created(uri).entity(secretDetailResponseFromName(secretName)).build();
}
 
Example #2
Source File: GroupResource.java    From keywhiz with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieve information on a group
 *
 * @param name Group name
 *
 * responseMessage 200 Group information retrieved
 * responseMessage 404 Group not found
 */
@Timed @ExceptionMetered
@GET
@Path("{name}")
@Produces(APPLICATION_JSON)
public GroupDetailResponseV2 groupInfo(@Auth AutomationClient automationClient,
    @PathParam("name") String name) {
  Group group = groupDAOReadOnly.getGroup(name)
      .orElseThrow(NotFoundException::new);

  Set<String> secrets = aclDAOReadOnly.getSanitizedSecretsFor(group).stream()
      .map(SanitizedSecret::name)
      .collect(toSet());

  Set<String> clients = aclDAOReadOnly.getClientsFor(group).stream()
      .map(Client::getName)
      .collect(toSet());

  return GroupDetailResponseV2.builder()
      .group(group)
      .secrets(secrets)
      .clients(clients)
      .build();
}
 
Example #3
Source File: SecretResource.java    From keywhiz with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieve listing of secret names.  If "idx" and "num" are both provided, retrieve "num"
 * names starting at "idx" from a list of secret names ordered by creation date, with
 * order depending on "newestFirst" (which defaults to "true")
 *
 * @param idx the index from which to start retrieval in the list of secret names
 * @param num the number of names to retrieve
 * @param newestFirst whether to list the most-recently-created names first
 * responseMessage 200 List of secret names
 * responseMessage 400 Invalid (negative) idx or num
 */
@Timed @ExceptionMetered
@GET
@Produces(APPLICATION_JSON)
public Iterable<String> secretListing(@Auth AutomationClient automationClient,
    @QueryParam("idx") Integer idx, @QueryParam("num") Integer num,
    @DefaultValue("true") @QueryParam("newestFirst") boolean newestFirst) {
  if (idx != null && num != null) {
    if (idx < 0 || num < 0) {
      throw new BadRequestException(
          "Index and num must both be positive when retrieving batched secrets!");
    }
    return secretControllerReadOnly.getSecretsBatched(idx, num, newestFirst).stream()
        .map(SanitizedSecret::name)
        .collect(toList());
  }
  return secretControllerReadOnly.getSanitizedSecrets(null, null).stream()
      .map(SanitizedSecret::name)
      .collect(toSet());
}
 
Example #4
Source File: ArticleResource.java    From rufus with MIT License 6 votes vote down vote up
@Path("/tagStubs")
@GET
public Response tagStubs(@Auth Optional<User> user) {
    List<Source> sources;
    if (user.isPresent()) {
        User present = user.get();
        if (!articleDao.hasSubscriptions(present.getId())) {
            return Response.status(Response.Status.OK)
                .type(MediaType.APPLICATION_JSON_TYPE)
                .entity(Collections.EMPTY_LIST)
                .build();
        } else {
            sources = articleDao.getSources(userDao.findByEmail(present.getEmail()).getId());
        }
    } else {
        sources = articleDao.getPublicSources();
    }

    Set<String> tags = sources.stream()
            .map(Source::getTags)
            .filter(Objects::nonNull)
            .flatMap(List::stream)
            .collect(Collectors.toSet());

    return Response.ok(tags).build();
}
 
Example #5
Source File: AutomationGroupResource.java    From keywhiz with Apache License 2.0 6 votes vote down vote up
/**
 * Deletes a group
 *
 * @param automationClient the client with automation access performing this operation
 * @param groupId the ID of the group to delete
 * @return 200 if the group was removed successfully, 404 if the group was not found
 *
 * description Deletes a single group by id
 * responseMessage 200 Deleted group
 * responseMessage 404 Group not found by id
 */
@Timed @ExceptionMetered
@DELETE
@Path("{groupId}")
public Response deleteGroup(
    @Auth AutomationClient automationClient,
    @PathParam("groupId") LongParam groupId) {
  Group group = groupDAO.getGroupById(groupId.get()).orElseThrow(NotFoundException::new);
  groupDAO.deleteGroup(group);
  Map<String, String> extraInfo = new HashMap<>();
  extraInfo.put("deprecated", "true");
  auditLog.recordEvent(
      new Event(Instant.now(), EventTag.GROUP_DELETE, automationClient.getName(), group.getName(),
          extraInfo));
  return Response.ok().build();
}
 
Example #6
Source File: ClientResource.java    From keywhiz with Apache License 2.0 6 votes vote down vote up
/**
 * Modify a client
 *
 * @param currentName Client name
 * @param request     JSON request to modify the client
 * @return the updated client
 * <p>
 * responseMessage 201 Client updated
 * <p>
 * responseMessage 404 Client not found
 */
@Timed @ExceptionMetered
@POST
@Path("{name}")
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON)
public ClientDetailResponseV2 modifyClient(@Auth AutomationClient automationClient,
    @PathParam("name") String currentName, @Valid ModifyClientRequestV2 request) {
  Client client = clientDAOReadWrite.getClientByName(currentName)
      .orElseThrow(NotFoundException::new);
  String newName = request.name();

  // TODO: implement change client (name, updatedAt, updatedBy)
  throw new NotImplementedException(format(
      "Need to implement mutation methods in DAO to rename %s to %s", client.getName(), newName));
}
 
Example #7
Source File: MonitorResource.java    From SAPNetworkMonitor with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Agent和Server之间的心跳,可以1分钟或更长时间一次,传回Monitor的信息,返回MonitorJob信息
 *
 * @param monitorId
 * @param monitor
 * @return
 */
@POST
@Path("/monitor/{monitorId}/heartbeat")
public RestfulReturnResult heartbeat(@Auth OAuthUser user, @PathParam("monitorId") String monitorId, @NotNull @Valid Monitor monitor) {
    if (!monitorId.equals(monitor.getMonitorId())) {
        log.error("monitor id in path {} and json {} and parameter not match error.", monitorId, monitor.getMonitorId());
        return new RestfulReturnResult(new NiPingException(MonitoridNotMatchError), null);
    }

    monitor.setMonitorId(monitorId);
    monitor.setAccountId(user.getAccountId());

    log.info("user {} monitorId {} send heartbeat {}", user, monitorId, monitor);
    monitorService.heartbeat(monitor);
    Optional<MonitorJob> job = Optional.empty();
    try {
        monitorService.saveMonitor(monitor);
        job = taskService.getNextJob(monitorId, monitor.getRunningTaskIds());
        if (log.isInfoEnabled() && job.isPresent()) {
            log.info("user {} monitorId {} get next job {}", user, monitorId, job.get());
        }
    } catch (NiPingException e) {
        return new RestfulReturnResult(e, job.orElse(null));
    }
    return new RestfulReturnResult(SUCCESS, job.orElse(null));
}
 
Example #8
Source File: BasicAuthRequestFilter.java    From eagle with Apache License 2.0 6 votes vote down vote up
public BasicAuthRequestFilter(Authenticator<BasicCredentials, User> authenticator, AbstractMethod method) {
    this.authenticator = authenticator;
    this.method = method;
    this.hasPermitAllAnnotation = method.isAnnotationPresent(PermitAll.class);
    this.hasDenyAllAnnotation = method.isAnnotationPresent(DenyAll.class);
    this.hasRolesAllowedAnnotation = method.isAnnotationPresent(RolesAllowed.class);
    this.isSecurityDefined = this.hasPermitAllAnnotation || this.hasDenyAllAnnotation || this.hasRolesAllowedAnnotation;
    for (Parameter parameter : method.getMethod().getParameters()) {
        if (isAuthRequired && isAuthDefined) {
            break;
        }
        Auth[] authAnnotations = parameter.getAnnotationsByType(Auth.class);
        this.isAuthDefined = authAnnotations.length > 0 || this.isAuthDefined;
        for (Auth auth : authAnnotations) {
            this.isAuthRequired = auth.required() || this.isAuthRequired;
        }
    }
    this.isSecurityDefined = this.isAuthDefined || this.isSecurityDefined;
    Preconditions.checkArgument(!(this.hasDenyAllAnnotation && this.hasPermitAllAnnotation), "Conflict @DenyAll and @PermitAll on method " + this.method.toString());
}
 
Example #9
Source File: DatabusResource.java    From SAPNetworkMonitor with GNU General Public License v3.0 6 votes vote down vote up
@POST
@Path("/monitor/{monitorId}/result")
public RestfulReturnResult result(@Auth OAuthUser user, @PathParam("monitorId") String monitorId, @NotNull @Valid MonitorNiPingResult
        monitorNiPingResult) {
    if (!monitorId.equals(monitorNiPingResult.getMonitorId())) {
        log.error("monitor id in path {} and json {} and parameter not match error.", monitorId, monitorNiPingResult.getMonitorId());
        return new RestfulReturnResult(new NiPingException(MonitoridNotMatchError), null);
    }

    monitorNiPingResult.setAccountId(user.getAccountId());
    monitorNiPingResult.setMonitorId(monitorId);
    try {
        log.info("user {} save monitor NiPing result {}", user, monitorNiPingResult);
        taskService.saveMonitorNiPingResult(monitorNiPingResult);
    } catch (NiPingException e) {
        return new RestfulReturnResult(e, null);
    }
    return new RestfulReturnResult(SUCCESS, null);
}
 
Example #10
Source File: LobbyWatcherController.java    From triplea with GNU General Public License v3.0 6 votes vote down vote up
@POST
@Path(LobbyWatcherClient.PLAYER_LEFT_PATH)
@RateLimited(
    reportOnly = true,
    keys = {KeyPart.IP},
    rates = {@Rate(limit = 20, duration = 1, timeUnit = TimeUnit.MINUTES)})
@RolesAllowed(UserRole.HOST)
public Response playerLeftGame(
    @Auth final AuthenticatedUser authenticatedUser,
    final PlayerLeftNotification playerLeftNotification) {

  gameListing.removePlayerFromGame(
      UserName.of(playerLeftNotification.getPlayerName()),
      authenticatedUser.getApiKey(),
      playerLeftNotification.getGameId());

  return Response.ok().build();
}
 
Example #11
Source File: AutomationGroupResource.java    From keywhiz with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieve Group by a specified name, or all Groups if no name given
 *
 * @param automationClient the client with automation access performing this operation
 * @param name the name of the Group to retrieve, if provided
 * @return details on the specified group, or an all groups if no name specified
 *
 * optionalParams name
 * description Returns a single Group or a set of all Groups
 * responseMessage 200 Found and retrieved Group(s)
 * responseMessage 404 Group with given name not found (if name provided)
 */
@Timed @ExceptionMetered
@GET
public Response getGroupByName(
    @Auth AutomationClient automationClient,
    @QueryParam("name") Optional<String> name) {
  if (name.isPresent()) {
    Group group = groupDAO.getGroup(name.get()).orElseThrow(NotFoundException::new);

    ImmutableList<Client> clients = ImmutableList.copyOf(aclDAO.getClientsFor(group));
    ImmutableList<SanitizedSecret> sanitizedSecrets =
        ImmutableList.copyOf(aclDAO.getSanitizedSecretsFor(group));
    return Response.ok()
        .entity(GroupDetailResponse.fromGroup(group, sanitizedSecrets, clients))
        .build();
  }

  ImmutableList<SanitizedSecret> emptySecrets = ImmutableList.of();
  ImmutableList<Client> emptyClients = ImmutableList.of();
  List<GroupDetailResponse> groups = groupDAO.getGroups().stream()
      .map((g) -> GroupDetailResponse.fromGroup(g, emptySecrets, emptyClients))
      .collect(toList());
  return Response.ok()
      .entity(groups)
      .build();
}
 
Example #12
Source File: AutomationSecretAccessResource.java    From keywhiz with Apache License 2.0 6 votes vote down vote up
/**
 * Assign Secret to Group
 *
 * @param automationClient the client with automation access performing this operation
 * @param secretId the ID of the Secret to assign
 * @param groupId the ID of the Group to be assigned to
 * @return 200 on success, 404 if the secret or group is absent
 *
 * description Assigns the Secret specified by the secretID to the Group specified by the groupID
 * responseMessage 200 Successfully enrolled Secret in Group
 * responseMessage 404 Could not find Secret or Group
 */
@Timed @ExceptionMetered
@PUT
public Response allowAccess(
    @Auth AutomationClient automationClient,
    @PathParam("secretId") LongParam secretId,
    @PathParam("groupId") LongParam groupId) {
  logger.info("Client '{}' allowing groupId={} access to secretId={}",
      automationClient, secretId, groupId);

  try {
    Map<String, String> extraInfo = new HashMap<>();
    extraInfo.put("deprecated", "true");
    aclDAO.findAndAllowAccess(secretId.get(), groupId.get(), auditLog, automationClient.getName(), extraInfo);
  } catch (IllegalStateException e) {
    throw new NotFoundException();
  }

  return Response.ok().build();
}
 
Example #13
Source File: AutomationSecretResource.java    From keywhiz with Apache License 2.0 6 votes vote down vote up
/**
 * Deletes all versions of a secret series
 *
 * @param automationClient the client with automation access performing this operation
 * @param secretName the name of the secret series to delete
 * @return 200 if the deletion is successful, or 404 if the given secret was not found
 *
 * description Deletes all versions of a secret series.  This will delete a single secret ID.
 * responseMessage 200 Deleted secret series
 * responseMessage 404 Secret series not Found
 */
@Path("{secretName}")
@Timed @ExceptionMetered
@DELETE
public Response deleteSecretSeries(
    @Auth AutomationClient automationClient,
    @PathParam("secretName") String secretName) {

  Secret secret = secretController.getSecretByName(secretName).orElseThrow(() -> new NotFoundException("Secret series not found."));
  Set<String> groups = aclDAO.getGroupsFor(secret).stream().map(Group::getName).collect(toSet());
  secretDAO.deleteSecretsByName(secretName);

  // Record all groups to which this secret belongs, so they can be restored manually if necessary
  Map<String, String> extraInfo = new HashMap<>();
  extraInfo.put("deprecated", "true");
  extraInfo.put("groups", groups.toString());
  extraInfo.put("current version", secret.getVersion().toString());
  auditLog.recordEvent(new Event(Instant.now(), EventTag.SECRET_DELETE, automationClient.getName(), secretName, extraInfo));

  return Response.ok().build();
}
 
Example #14
Source File: AutomationSecretResource.java    From keywhiz with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieve secret by ID
 *
 * @param automationClient the client with automation access performing this operation
 * @param secretId the ID of the secret to retrieve
 * @return details on the specified secret
 *
 * description Returns a single secret if found
 * responseMessage 200 Found and retrieved secret with given ID
 * responseMessage 404 Secret with given ID not found
 */
@Path("{secretId}")
@Timed @ExceptionMetered
@GET
public AutomationSecretResponse readSecretById(
    @Auth AutomationClient automationClient,
    @PathParam("secretId") LongParam secretId) {

  Optional<Secret> secret = secretController.getSecretById(secretId.get());
  if (!secret.isPresent()) {
    throw new NotFoundException("Secret not found.");
  }

  ImmutableList<Group> groups = ImmutableList.copyOf(aclDAO.getGroupsFor(secret.get()));

  return AutomationSecretResponse.fromSecret(secret.get(), groups);
}
 
Example #15
Source File: AutomationEnrollClientGroupResource.java    From keywhiz with Apache License 2.0 6 votes vote down vote up
/**
 * Remove Client from Group
 *
 * @param automationClient the client with automation access performing this operation
 * @param clientId the ID of the Client to unassign
 * @param groupId the ID of the Group to be removed from
 * @return 200 on succes, 404 if client or group not present
 *
 * description Unassigns the Client specified by the clientID from the Group specified by the
 * groupID
 * responseMessage 200 Successfully removed Client from Group
 * responseMessage 404 Could not find Client or Group
 */
@Timed @ExceptionMetered
@DELETE
public Response evictClientFromGroup(
    @Auth AutomationClient automationClient,
    @PathParam("clientId") long clientId,
    @PathParam("groupId") long groupId) {

  try {
    Map<String, String> extraInfo = new HashMap<>();
    extraInfo.put("deprecated", "true");
    aclDAO.findAndEvictClient(clientId, groupId, auditLog, automationClient.getName(), extraInfo);
  } catch (IllegalStateException e) {
    throw new NotFoundException();
  }

  return Response.ok().build();
}
 
Example #16
Source File: AutomationEnrollClientGroupResource.java    From keywhiz with Apache License 2.0 6 votes vote down vote up
/**
 * Enroll Client in Group
 *
 * @param automationClient the client with automation access performing this operation
 * @param clientId the ID of the Client to assign
 * @param groupId the ID of the Group to be assigned to
 * @return 200 on success, 404 if client or group is missing
 *
 * description Assigns the Client specified by the clientID to the Group specified by the
 * groupID
 * responseMessage 200 Successfully enrolled Client in Group
 * responseMessage 404 Could not find Client or Group
 */
@Timed @ExceptionMetered
@PUT
public Response enrollClientInGroup(
    @Auth AutomationClient automationClient,
    @PathParam("clientId") LongParam clientId,
    @PathParam("groupId") LongParam groupId) {

  try {
    Map<String, String> extraInfo = new HashMap<>();
    extraInfo.put("deprecated", "true");
    aclDAO.findAndEnrollClient(clientId.get(), groupId.get(), auditLog,
        automationClient.getName(), extraInfo);
  } catch (IllegalStateException e) {
    throw new NotFoundException();
  }

  return Response.ok().build();
}
 
Example #17
Source File: GroupsResource.java    From keywhiz with Apache License 2.0 6 votes vote down vote up
/**
 * Delete Group by ID
 *
 * @param user the admin user performing this operation
 * @param groupId the ID of the Group to be deleted
 * @return 200 if the deletion succeeded, 404 if the group was not found
 *
 * description Deletes a single Group if found.
 * Used by Keywhiz CLI and the web ui.
 * responseMessage 200 Found and deleted Group with given ID
 * responseMessage 404 Group with given ID not Found
 */
@Path("{groupId}")
@Timed @ExceptionMetered
@DELETE
public Response deleteGroup(@Auth User user, @PathParam("groupId") LongParam groupId) {
  logger.info("User '{}' deleting group id={}.", user, groupId);

  Optional<Group> group = groupDAO.getGroupById(groupId.get());
  if (!group.isPresent()) {
    throw new NotFoundException("Group not found.");
  }

  groupDAO.deleteGroup(group.get());
  auditLog.recordEvent(new Event(Instant.now(), EventTag.GROUP_DELETE, user.getName(), group.get().getName()));
  return Response.noContent().build();
}
 
Example #18
Source File: SecretsResource.java    From keywhiz with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieve Secret by a specified name and version, or all Secrets if name is not given
 *
 * @param user        the admin user performing this operation
 * @param name        the name of the Secret to retrieve, if provided
 * @param nameOnly    if set, the result only contains the id and name for the secrets.
 * @param idx         if set, the desired starting index in a list of secrets to be retrieved
 * @param num         if set, the number of secrets to retrieve
 * @param newestFirst whether to order the secrets by creation date with newest first; defaults to
 *                    true
 * @return a single Secret or a set of all Secrets for this user.
 * <p>
 * Used by Keywhiz CLI and the web ui.
 * <p>
 * responseMessage 200 Found and retrieved Secret(s)
 * <p>
 * responseMessage 404 Secret with given name not found (if name provided)
 */
@Timed @ExceptionMetered
@GET
public Response findSecrets(@Auth User user, @DefaultValue("") @QueryParam("name") String name,
    @DefaultValue("") @QueryParam("nameOnly") String nameOnly, @QueryParam("idx") Integer idx,
    @QueryParam("num") Integer num,
    @DefaultValue("true") @QueryParam("newestFirst") Boolean newestFirst) {
  if (!name.isEmpty() && idx != null && num != null) {
    throw new BadRequestException("Name and idx/num cannot both be specified");
  }

  validateArguments(name, nameOnly, idx, num);

  if (name.isEmpty()) {
    if (nameOnly.isEmpty()) {
      if (idx == null || num == null) {
        return Response.ok().entity(listSecrets(user)).build();
      } else {
        return Response.ok().entity(listSecretsBatched(user, idx, num, newestFirst)).build();
      }
    } else {
      return Response.ok().entity(listSecretsNameOnly(user)).build();
    }
  }
  return Response.ok().entity(retrieveSecret(user, name)).build();
}
 
Example #19
Source File: SecretResource.java    From keywhiz with Apache License 2.0 6 votes vote down vote up
/**
 * Reset the current version of the given secret to the given version index.
 *
 * @param request A request to update a given secret
 *
 * responseMessage 201 Secret series current version updated successfully
 * responseMessage 400 Invalid secret version specified
 * responseMessage 404 Secret series not found
 */
@Timed @ExceptionMetered
@Path("{name}/setversion")
@POST
public Response resetSecretVersion(@Auth AutomationClient automationClient,
    @Valid SetSecretVersionRequestV2 request) {
  secretDAO.setCurrentSecretVersionByName(request.name(), request.version(),
      automationClient.getName());

  // If the secret wasn't found or the request was misformed, setCurrentSecretVersionByName
  // already threw an exception
  Map<String, String> extraInfo = new HashMap<>();
  extraInfo.put("new version", Long.toString(request.version()));
  auditLog.recordEvent(new Event(Instant.now(), EventTag.SECRET_CHANGEVERSION,
      automationClient.getName(), request.name(), extraInfo));

  return Response.status(Response.Status.CREATED).build();
}
 
Example #20
Source File: MembershipResource.java    From keywhiz with Apache License 2.0 6 votes vote down vote up
/**
 * Remove a Client from a Group
 *
 * @param user the admin user performing this operation
 * @param clientId ID value of a Client
 * @param groupId ID value of a Group
 * @return 200 on success, 404 if client or group not found
 *
 * description Unassigns the Client specified by the clientID from the Group specified by the groupID
 * responseMessage 200 Successfully removed Client from Group
 * responseMessage 404 Could not find Client or Group
 */
@Path("/clients/{clientId}/groups/{groupId}")
@Timed @ExceptionMetered
@DELETE
public Response evictClient(
    @Auth User user,
    @PathParam("clientId") LongParam clientId,
    @PathParam("groupId") LongParam groupId) {
  logger.info("User {} evicting clientId {} from groupId {}.", user.getName(), clientId, groupId);

  try {
    aclDAO.findAndEvictClient(clientId.get(), groupId.get(), auditLog, user.getName(), new HashMap<>());
  } catch (IllegalStateException e) {
    throw new NotFoundException();
  }

  return Response.ok().build();
}
 
Example #21
Source File: MembershipResource.java    From keywhiz with Apache License 2.0 6 votes vote down vote up
/**
 * Enroll a Client into a Group
 *
 * @param user the admin user performing this operation
 * @param clientId ID value of a Client
 * @param groupId ID value of a Group
 * @return 200 on success, 404 if client or group not found
 *
 * description Assigns the Client specified by the clientID to the Group specified by the groupID
 * responseMessage 200 Successfully enrolled Client in Group
 * responseMessage 404 Could not find Client or Group
 */
@Path("/clients/{clientId}/groups/{groupId}")
@Timed @ExceptionMetered
@PUT
public Response enrollClient(
  @Auth User user,
  @PathParam("clientId") LongParam clientId,
  @PathParam("groupId") LongParam groupId) {

  logger.info("User {} enrolling clientId {} in groupId {}.", user.getName(), clientId, groupId);

  try {
    aclDAO.findAndEnrollClient(clientId.get(), groupId.get(), auditLog, user.getName(), new HashMap<>());
  } catch (IllegalStateException e) {
    throw new NotFoundException();
  }

  return Response.ok().build();
}
 
Example #22
Source File: SecretsResource.java    From keywhiz with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieve the given range of versions of this secret, sorted from newest to oldest update time.
 * If versionIdx is nonzero, then numVersions versions, starting from versionIdx in the list and
 * increasing in index, will be returned (set numVersions to a very large number to retrieve all
 * versions). For instance, versionIdx = 5 and numVersions = 10 will retrieve entries at indices 5
 * through 14.
 *
 * @param user        the admin user performing this operation
 * @param name        Secret series name
 * @param versionIdx  The index in the list of versions of the first version to retrieve
 * @param numVersions The number of versions to retrieve
 * @return a list of a secret's versions, if found
 * <p>
 * responseMessage 200 Secret series information retrieved
 * <p>
 * responseMessage 404 Secret series not found
 */
@Timed @ExceptionMetered
@GET
@Path("versions/{name}")
@Produces(APPLICATION_JSON)
public List<SanitizedSecret> secretVersions(@Auth User user,
    @PathParam("name") String name, @QueryParam("versionIdx") int versionIdx,
    @QueryParam("numVersions") int numVersions) {

  logger.info("User '{}' listing {} versions starting at index {} for secret '{}'.", user,
      numVersions, versionIdx, name);

  ImmutableList<SanitizedSecret> versions =
      secretDAOReadOnly.getSecretVersionsByName(name, versionIdx, numVersions)
          .orElseThrow(NotFoundException::new);

  return versions;
}
 
Example #23
Source File: SecretResource.java    From keywhiz with Apache License 2.0 5 votes vote down vote up
/**
 * Creates or updates (if it exists) a secret.
 *
 * @param request JSON request to create a secret
 *
 * responseMessage 201 Created secret and assigned to given groups
 */
@Timed @ExceptionMetered
@Path("{name}")
@POST
@Consumes(APPLICATION_JSON)
public Response createOrUpdateSecret(@Auth AutomationClient automationClient,
    @PathParam("name") String name,
    @Valid CreateOrUpdateSecretRequestV2 request) {
  SecretBuilder builder = secretController
      .builder(name, request.content(), automationClient.getName(), request.expiry())
      .withDescription(request.description())
      .withMetadata(request.metadata())
      .withType(request.type());

  builder.createOrUpdate();

  Map<String, String> extraInfo = new HashMap<>();
  if (request.description() != null) {
    extraInfo.put("description", request.description());
  }
  if (request.metadata() != null) {
    extraInfo.put("metadata", request.metadata().toString());
  }
  extraInfo.put("expiry", Long.toString(request.expiry()));
  auditLog.recordEvent(new Event(Instant.now(), EventTag.SECRET_CREATEORUPDATE, automationClient.getName(), name, extraInfo));

  UriBuilder uriBuilder = UriBuilder.fromResource(SecretResource.class).path(name);

  return Response.created(uriBuilder.build()).build();
}
 
Example #24
Source File: LobbyWatcherController.java    From triplea with GNU General Public License v3.0 5 votes vote down vote up
/** Replaces an existing game with new game data details. */
@RateLimited(
    reportOnly = true,
    keys = {KeyPart.IP},
    rates = {@Rate(limit = 10, duration = 1, timeUnit = TimeUnit.SECONDS)})
@POST
@Path(LobbyWatcherClient.UPDATE_GAME_PATH)
public Response updateGame(
    @Auth final AuthenticatedUser authenticatedUser, final UpdateGameRequest updateGameRequest) {
  gameListing.updateGame(
      authenticatedUser.getApiKey(),
      updateGameRequest.getGameId(),
      updateGameRequest.getGameData());
  return Response.ok().build();
}
 
Example #25
Source File: UpdateAccountController.java    From triplea with GNU General Public License v3.0 5 votes vote down vote up
@POST
@Path(UserAccountClient.CHANGE_EMAIL_PATH)
@RolesAllowed(UserRole.PLAYER)
public Response changeEmail(
    @Auth final AuthenticatedUser authenticatedUser, final String newEmail) {
  ArgChecker.checkNotEmpty(newEmail);
  Preconditions.checkArgument(authenticatedUser.getUserIdOrThrow() > 0);

  userAccountService.changeEmail(authenticatedUser.getUserIdOrThrow(), newEmail);
  return Response.ok().build();
}
 
Example #26
Source File: SecretResource.java    From keywhiz with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieve listing of secrets expiring soon in a group
 *
 * @param time timestamp for farthest expiry to include
 * @param name Group name
 * responseMessage 200 List of secrets expiring soon in group
 */
@Timed @ExceptionMetered
@Path("expiring/{time}/{name}")
@GET
@Produces(APPLICATION_JSON)
public Iterable<String> secretListingExpiringForGroup(@Auth AutomationClient automationClient,
    @PathParam("time") Long time, @PathParam("name") String name) {
  Group group = groupDAO.getGroup(name).orElseThrow(NotFoundException::new);

  List<SanitizedSecret> secrets = secretControllerReadOnly.getSanitizedSecrets(time, group);
  return secrets.stream()
      .map(SanitizedSecret::name)
      .collect(toSet());
}
 
Example #27
Source File: UserBanController.java    From triplea with GNU General Public License v3.0 5 votes vote down vote up
@POST
@Path(ModeratorChatClient.BAN_PLAYER_PATH)
@RateLimited(
    keys = {KeyPart.IP},
    rates = {@Rate(limit = 5, duration = 1, timeUnit = TimeUnit.MINUTES)})
public Response banPlayer(
    @Auth final AuthenticatedUser authenticatedUser, final BanPlayerRequest banPlayerRequest) {
  Preconditions.checkNotNull(banPlayerRequest);
  Preconditions.checkNotNull(banPlayerRequest.getPlayerChatId());
  Preconditions.checkArgument(banPlayerRequest.getBanMinutes() > 0);

  bannedUsersService.banUser(authenticatedUser.getUserIdOrThrow(), banPlayerRequest);
  return Response.ok().build();
}
 
Example #28
Source File: SecretResource.java    From keywhiz with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieve information on a secret series
 *
 * @param name Secret series name
 *
 * responseMessage 200 Secret series information retrieved
 * responseMessage 404 Secret series not found
 */
@Timed @ExceptionMetered
@GET
@Path("{name}/sanitized")
@Produces(APPLICATION_JSON)
public SanitizedSecret getSanitizedSecret(@Auth AutomationClient automationClient,
    @PathParam("name") String name) {
  return SanitizedSecret.fromSecretSeriesAndContent(
      secretDAO.getSecretByName(name).orElseThrow(NotFoundException::new));
}
 
Example #29
Source File: DashboardResource.java    From eagle with Apache License 2.0 5 votes vote down vote up
@DELETE
@Path("/{uuid}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@RolesAllowed({User.Role.USER, User.Role.ADMINISTRATOR})
public RESTResponse<DashboardEntity> deleteDashboard(String uuid, @Auth User user) {
    return RESTResponse.async(() -> dashboardEntityService.deleteByUUID(uuid, user)).get();
}
 
Example #30
Source File: LobbyWatcherController.java    From triplea with GNU General Public License v3.0 5 votes vote down vote up
/** Explicit remove of a game from the lobby. */
@RateLimited(
    reportOnly = true,
    keys = {KeyPart.IP},
    rates = {@Rate(limit = 5, duration = 1, timeUnit = TimeUnit.SECONDS)})
@POST
@Path(LobbyWatcherClient.REMOVE_GAME_PATH)
public Response removeGame(@Auth final AuthenticatedUser authenticatedUser, final String gameId) {
  gameListing.removeGame(authenticatedUser.getApiKey(), gameId);
  return Response.ok().build();
}