api key api

Signed-off-by: MiniDigger <admin@minidigger.me>
This commit is contained in:
MiniDigger 2021-05-15 14:09:52 +02:00
parent 56bb8452de
commit ac24435b2e
6 changed files with 45 additions and 203 deletions

View File

@ -1,31 +1,52 @@
package io.papermc.hangar.controller.api.v1;
import io.papermc.hangar.HangarComponent;
import io.papermc.hangar.controller.api.v1.interfaces.IApiKeysController;
import io.papermc.hangar.model.api.ApiKey;
import io.papermc.hangar.model.common.NamedPermission;
import io.papermc.hangar.model.internal.api.requests.CreateAPIKeyForm;
import io.papermc.hangar.security.annotations.permission.PermissionRequired;
import io.papermc.hangar.service.APIKeyService;
import io.papermc.hangar.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import java.util.List;
@Controller
@PermissionRequired(NamedPermission.EDIT_API_KEYS)
public class ApiKeysController implements IApiKeysController {
public class ApiKeysController extends HangarComponent implements IApiKeysController {
private final APIKeyService apiKeyService;
private final PermissionService permissionService;
@Autowired
public ApiKeysController(APIKeyService apiKeyService, PermissionService permissionService) {
this.apiKeyService = apiKeyService;
this.permissionService = permissionService;
}
@Override
@ResponseBody
@ResponseStatus(HttpStatus.CREATED)
public String createKey(CreateAPIKeyForm apiKeyForm) {
// TODO implement
System.out.println(apiKeyForm);
return new String("HELLO THERE");
return apiKeyService.createApiKey(getHangarPrincipal(), apiKeyForm, permissionService.getAllPossiblePermissions(getHangarPrincipal().getUserId()));
}
@Override
@ResponseBody
@ResponseStatus(HttpStatus.OK)
public List<ApiKey> getKeys() {
return apiKeyService.getApiKeys(getHangarPrincipal().getUserId());
}
@Override
@ResponseStatus(HttpStatus.NO_CONTENT)
public void deleteKey(String name) {
// TODO implement
System.out.println(name);
apiKeyService.deleteApiKey(getHangarPrincipal(), name);
}
}

View File

@ -1,5 +1,6 @@
package io.papermc.hangar.controller.api.v1.interfaces;
import io.papermc.hangar.model.api.ApiKey;
import io.papermc.hangar.model.internal.api.requests.CreateAPIKeyForm;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
@ -9,11 +10,13 @@ import io.swagger.annotations.ApiResponses;
import io.swagger.annotations.Authorization;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
import javax.validation.Valid;
@Api(tags = "API Keys")
@ -35,7 +38,20 @@ public interface IApiKeysController {
@PostMapping(path = "/keys", produces = MediaType.TEXT_PLAIN_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
String createKey(@ApiParam(required = true) @Valid @RequestBody CreateAPIKeyForm apiKeyForm);
// TODO get keys method
@ApiOperation(
value = "Fetches a list of API Keys",
nickname = "getKeys",
notes = "Fetches a list of API Keys. Requires the `edit_api_keys` permission.",
response = String.class,
authorizations = @Authorization("Session"),
tags = "API Keys"
)
@ApiResponses({
@ApiResponse(code = 200, message = "Key created", response = ApiKey.class, responseContainer = "List"),
@ApiResponse(code = 401, message = "Api session missing, invalid or expired"),
@ApiResponse(code = 403, message = "Not enough permissions to use this endpoint")})
@GetMapping(path = "/keys", produces = MediaType.APPLICATION_JSON_VALUE)
List<ApiKey> getKeys();
@ApiOperation(
value = "Delete an API key",
@ -49,6 +65,6 @@ public interface IApiKeysController {
@ApiResponse(code = 401, message = "Api session missing, invalid or expired"),
@ApiResponse(code = 403, message = "Not enough permissions to use this endpoint")
})
@DeleteMapping(value = "/keys", consumes = MediaType.APPLICATION_JSON_VALUE)
@DeleteMapping(value = "/keys")
void deleteKey(@ApiParam(value = "The name of the key to delete", required = true) @RequestParam String name);
}

View File

@ -1,77 +0,0 @@
package io.papermc.hangar.controllerold;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.papermc.hangar.db.modelold.ProjectApiKeysTable;
import io.papermc.hangar.db.modelold.ProjectsTable;
import io.papermc.hangar.serviceold.ApiKeyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.server.ResponseStatusException;
import javax.servlet.http.HttpServletRequest;
import java.util.UUID;
import java.util.function.Supplier;
@Controller
@RequestMapping("/api/old")
public class Apiv1Controller extends HangarController {
private final ObjectMapper mapper;
private final ApiKeyService apiKeyService;
private final HttpServletRequest request;
private Supplier<ProjectsTable> projectsTable;
@Autowired
public Apiv1Controller(ObjectMapper mapper, ApiKeyService apiKeyService, HttpServletRequest request) {
this.mapper = mapper;
this.apiKeyService = apiKeyService;
this.request = request;
}
@PreAuthorize("@authenticationService.authV1ApiRequest(T(io.papermc.hangar.model.common.Permission).EditApiKeys, T(io.papermc.hangar.controller.extras.ApiScope).ofProject(#author, #slug))")
// @UserLock
@Secured("ROLE_USER")
@PostMapping("/v1/projects/{author}/{slug}/keys/new") // USED IN project settings (deployment key)
public ResponseEntity<ObjectNode> createKey(@PathVariable String author, @PathVariable String slug) {
ProjectsTable project = projectsTable.get();
ProjectApiKeysTable projectApiKeysTable = apiKeyService.createProjectApiKey(new ProjectApiKeysTable(
project.getId(),
UUID.randomUUID().toString().replace("-", "")
));
// userActionLogService.project(request, LoggedActionType.PROJECT_SETTINGS_CHANGED.with(ProjectContext.of(project.getId())), getCurrentUser().getName() + " created a new ApiKey", "");
ObjectNode apiKeyObj = mapper.createObjectNode();
apiKeyObj
.put("id", projectApiKeysTable.getId())
.put("createdAt", projectApiKeysTable.getCreatedAt().toString())
.put("projectId", projectApiKeysTable.getProjectId())
.put("value", projectApiKeysTable.getValue());
return ResponseEntity.ok(apiKeyObj);
}
@PreAuthorize("@authenticationService.authV1ApiRequest(T(io.papermc.hangar.model.common.Permission).EditApiKeys, T(io.papermc.hangar.controller.extras.ApiScope).ofProject(#author, #slug))")
// @UserLock
@Secured("ROLE_USER")
@PostMapping("/v1/projects/{author}/{slug}/keys/revoke") // USED in project settings (deployment key)
@ResponseStatus(HttpStatus.OK)
public void revokeKey(@PathVariable String author, @PathVariable String slug, @RequestParam long id) {
ProjectApiKeysTable projectApiKey = apiKeyService.getProjectKey(id);
ProjectsTable project = projectsTable.get();
if (projectApiKey == null || project.getId() != projectApiKey.getId()) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST);
}
apiKeyService.deleteProjectApiKey(projectApiKey);
// userActionLogService.project(request, LoggedActionType.PROJECT_SETTINGS_CHANGED.with(ProjectContext.of(project.getId())), getCurrentUser().getName() + " removed an ApiKey", "");
}
}

View File

@ -1,32 +0,0 @@
package io.papermc.hangar.db.daoold;
import io.papermc.hangar.db.modelold.ProjectApiKeysTable;
import org.jdbi.v3.sqlobject.config.RegisterBeanMapper;
import org.jdbi.v3.sqlobject.customizer.BindBean;
import org.jdbi.v3.sqlobject.customizer.Timestamped;
import org.jdbi.v3.sqlobject.statement.GetGeneratedKeys;
import org.jdbi.v3.sqlobject.statement.SqlQuery;
import org.jdbi.v3.sqlobject.statement.SqlUpdate;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
@RegisterBeanMapper(ProjectApiKeysTable.class)
public interface ApiKeyDao {
@Timestamped
@GetGeneratedKeys
@SqlUpdate("INSERT INTO project_api_keys (created_at, project_id, value) VALUES (:now, :projectId, :value)")
ProjectApiKeysTable insert(@BindBean ProjectApiKeysTable projectApiKeysTable);
@SqlUpdate("DELETE FROM project_api_keys WHERE id = :id")
void delete(@BindBean ProjectApiKeysTable projectApiKeysTable);
@SqlQuery("SELECT * FROM project_api_keys WHERE id = :id")
ProjectApiKeysTable getById(long id);
@SqlQuery("SELECT * FROM project_api_keys pak WHERE pak.project_id = :projectId")
List<ProjectApiKeysTable> getByProjectId(long projectId);
}

View File

@ -1,55 +0,0 @@
package io.papermc.hangar.db.modelold;
import java.time.OffsetDateTime;
public class ProjectApiKeysTable {
private long id;
private OffsetDateTime createdAt;
private long projectId;
private String value;
public ProjectApiKeysTable(long projectId, String value) {
this.projectId = projectId;
this.value = value;
}
public ProjectApiKeysTable() { }
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public OffsetDateTime getCreatedAt() {
return createdAt;
}
public void setCreatedAt(OffsetDateTime createdAt) {
this.createdAt = createdAt;
}
public long getProjectId() {
return projectId;
}
public void setProjectId(long projectId) {
this.projectId = projectId;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}

View File

@ -1,31 +0,0 @@
package io.papermc.hangar.serviceold;
import io.papermc.hangar.db.dao.HangarDao;
import io.papermc.hangar.db.daoold.ApiKeyDao;
import io.papermc.hangar.db.modelold.ProjectApiKeysTable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
@Deprecated(forRemoval = true)
public class ApiKeyService {
private final HangarDao<ApiKeyDao> apiKeyDao;
@Autowired
public ApiKeyService(HangarDao<ApiKeyDao> apiKeyDao) {
this.apiKeyDao = apiKeyDao;
}
public ProjectApiKeysTable getProjectKey(long keyId) {
return apiKeyDao.get().getById(keyId);
}
public ProjectApiKeysTable createProjectApiKey(ProjectApiKeysTable projectApiKeysTable) {
return apiKeyDao.get().insert(projectApiKeysTable);
}
public void deleteProjectApiKey(ProjectApiKeysTable projectApiKeysTable) {
apiKeyDao.get().delete(projectApiKeysTable);
}
}