use of org.hisp.dhis.security.apikey.ApiToken in project dhis2-core by dhis2.
the class ApiTokenController method postJsonObject.
@PostMapping(consumes = "application/json")
@ResponseBody
public WebMessage postJsonObject(HttpServletRequest request) throws Exception {
final ApiToken apiToken = deserializeJsonEntity(request);
User user = currentUserService.getCurrentUser();
if (!aclService.canCreate(user, getEntityClass())) {
throw new CreateAccessDeniedException("You don't have the proper permissions to create this object.");
}
apiToken.getTranslations().clear();
// Validate input values is ok
validateBeforeCreate(apiToken);
// We only make personal access tokens for now
apiToken.setType(ApiTokenType.PERSONAL_ACCESS_TOKEN);
// Generate key and set default values
apiTokenService.initToken(apiToken);
// Save raw key to send in response
final String rawKey = apiToken.getKey();
// Hash the raw token key and overwrite value in the entity to persist
final String hashedKey = apiTokenService.hashKey(apiToken.getKey());
apiToken.setKey(hashedKey);
// Continue POST import as usual
MetadataImportParams params = importService.getParamsFromMap(contextService.getParameterValuesMap()).setImportReportMode(ImportReportMode.FULL).setUser(user).setImportStrategy(ImportStrategy.CREATE).addObject(apiToken);
final ObjectReport objectReport = importService.importMetadata(params).getFirstObjectReport();
final String uid = objectReport.getUid();
WebMessage webMessage = objectReport(objectReport);
if (webMessage.getStatus() == Status.OK) {
webMessage.setHttpStatus(HttpStatus.CREATED);
webMessage.setLocation(getSchema().getRelativeApiEndpoint() + "/" + uid);
// Set our custom web response object that includes the new
// generated key.
webMessage.setResponse(new ApiTokenCreationResponse(objectReport, rawKey));
} else {
webMessage.setStatus(Status.ERROR);
}
return webMessage;
}
Aggregations