|
| 1 | +package it.aboutbits.springboot.toolbox.swagger.customization.authorization_docs; |
| 2 | + |
| 3 | +import io.swagger.v3.oas.models.Operation; |
| 4 | +import it.aboutbits.springboot.toolbox.swagger.annotations.SwaggerScopedAuth; |
| 5 | +import lombok.extern.slf4j.Slf4j; |
| 6 | +import org.springdoc.core.customizers.OperationCustomizer; |
| 7 | +import org.springframework.security.access.prepost.PreAuthorize; |
| 8 | +import org.springframework.web.method.HandlerMethod; |
| 9 | + |
| 10 | +import java.util.ArrayList; |
| 11 | +import java.util.Optional; |
| 12 | + |
| 13 | +@Slf4j |
| 14 | +public class AuthorizationDescriptor implements OperationCustomizer { |
| 15 | + @Override |
| 16 | + public Operation customize(Operation operation, HandlerMethod handlerMethod) { |
| 17 | + try { |
| 18 | + var additionalDescription = new ArrayList<String>(); |
| 19 | + |
| 20 | + var maybeAnnotation = Optional.ofNullable(handlerMethod.getMethodAnnotation(PreAuthorize.class)); |
| 21 | + if (maybeAnnotation.isPresent()) { |
| 22 | + var annotation = maybeAnnotation.get(); |
| 23 | + additionalDescription.add("<b>Authorization:</b> " + annotation.value()); |
| 24 | + } |
| 25 | + |
| 26 | + var maybeAnnotation2 = Optional.ofNullable(handlerMethod.getMethodAnnotation(SwaggerScopedAuth.class)); |
| 27 | + if (maybeAnnotation2.isPresent()) { |
| 28 | + var annotation = maybeAnnotation2.get(); |
| 29 | + additionalDescription.add("<b>Scoped Authorization:</b> " + annotation.value()); |
| 30 | + } |
| 31 | + |
| 32 | + if (!additionalDescription.isEmpty()) { |
| 33 | + |
| 34 | + var currentDescription = Optional.ofNullable(operation.getDescription()); |
| 35 | + |
| 36 | + var description = String.join("<br />", additionalDescription); |
| 37 | + if (currentDescription.isPresent()) { |
| 38 | + description = "<p>" + description + "</p>" + currentDescription.get(); |
| 39 | + } |
| 40 | + |
| 41 | + operation.description( |
| 42 | + description |
| 43 | + ); |
| 44 | + } |
| 45 | + } catch (Exception e) { |
| 46 | + log.error("Error when creating swagger documentation for authorities.", e); |
| 47 | + } |
| 48 | + return operation; |
| 49 | + } |
| 50 | +} |
0 commit comments