Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Some Cleanups in the API-Generation #319

Merged
merged 2 commits into from
Jul 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 26 additions & 32 deletions studymanager/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -235,15 +235,26 @@
<goal>generate</goal>
</goals>
<configuration>
<configOptions>
<useTags>true</useTags>
</configOptions>
<generatorName>spring</generatorName>
<library>spring-boot</library>

<inputSpec>${project.basedir}/src/main/resources/openapi/StudyManagerAPI.yaml</inputSpec>
<output>${project.build.directory}/generated-sources/study-manager</output>

<packageName>io.redlink.more.studymanager.api.v1</packageName>
<generateApis>true</generateApis>
<apiPackage>io.redlink.more.studymanager.api.v1.webservices</apiPackage>
<generateModels>true</generateModels>
<modelPackage>io.redlink.more.studymanager.api.v1.model</modelPackage>
<modelNameSuffix>DTO</modelNameSuffix>

<generateApiTests>false</generateApiTests>
<generateApiDocumentation>true</generateApiDocumentation>
<generateModelTests>false</generateModelTests>
<generateSupportingFiles>false</generateSupportingFiles>

<typeMappings>
<!-- typeMapping>string+date-time=Instant</typeMapping -->
<typeMapping>string+date-time=Instant</typeMapping>
<typeMapping>string+time=LocalTime</typeMapping>
</typeMappings>
<schemaMappings>
Expand All @@ -254,37 +265,20 @@
<importMapping>Instant=java.time.Instant</importMapping>
<importMapping>LocalTime=java.time.LocalTime</importMapping>
</importMappings>

<configOptions>
<useSpringBoot3>true</useSpringBoot3>
<sourceFolder>src</sourceFolder>
<documentationProvider>source</documentationProvider>
<interfaceOnly>true</interfaceOnly>
<useTags>true</useTags>
<openApiNullable>false</openApiNullable>
<skipDefaultInterface>true</skipDefaultInterface>
<requestMappingMode>api_interface</requestMappingMode>
</configOptions>
</configuration>
</execution>
</executions>
<configuration>
<generatorName>spring</generatorName>
<library>spring-boot</library>

<packageName>io.redlink.more.studymanager.api.v1</packageName>

<generateApis>true</generateApis>
<apiPackage>io.redlink.more.studymanager.api.v1.webservices</apiPackage>

<generateModels>true</generateModels>
<modelPackage>io.redlink.more.studymanager.api.v1.model</modelPackage>
<modelNameSuffix>DTO</modelNameSuffix>

<generateApiTests>false</generateApiTests>
<generateApiDocumentation>true</generateApiDocumentation>
<generateModelTests>false</generateModelTests>
<generateSupportingFiles>false</generateSupportingFiles>

<configOptions>
<useSpringBoot3>true</useSpringBoot3>
<sourceFolder>src</sourceFolder>
<documentationProvider>source</documentationProvider>
<interfaceOnly>true</interfaceOnly>
<useTags>false</useTags>
<openApiNullable>false</openApiNullable>
<skipDefaultInterface>true</skipDefaultInterface>
</configOptions>
</configuration>
</plugin>
</plugins>
</build>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,19 +11,24 @@
import io.redlink.more.studymanager.properties.MoreAuthProperties;
import io.redlink.more.studymanager.repository.UserRepository;
import io.redlink.more.studymanager.service.OAuth2AuthenticationService;
import org.springframework.boot.context.properties.EnableConfigurationProperties;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper;
import org.springframework.security.crypto.argon2.Argon2PasswordEncoder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.DelegatingPasswordEncoder;
Expand All @@ -32,9 +37,6 @@
import org.springframework.security.crypto.scrypt.SCryptPasswordEncoder;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper;
import org.springframework.security.oauth2.client.oidc.web.logout.OidcClientInitiatedLogoutSuccessHandler;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.core.oidc.OidcIdToken;
Expand All @@ -50,6 +52,7 @@
import org.springframework.security.web.util.matcher.AndRequestMatcher;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.IpAddressMatcher;
import org.springframework.security.web.util.matcher.NegatedRequestMatcher;

@Configuration
@EnableWebSecurity
Expand All @@ -71,20 +74,24 @@ protected SecurityFilterChain filterChain(HttpSecurity http,
OAuth2AuthorizedClientService oAuth2AuthorizedClientService,
UserRepository userRepository) throws Exception {
// Basics
http.csrf()
http.csrf(csrf -> csrf
.ignoringRequestMatchers("/kibana/**")
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
http.cors().disable();
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
);
http.cors(AbstractHttpConfigurer::disable);

// Restricted Paths
http.authorizeHttpRequests()
.requestMatchers("/api", "/api/v1/me").permitAll()
http.authorizeHttpRequests(auth -> auth
.requestMatchers(HttpMethod.GET, "/api", "/api/v1/me").permitAll()
// Allow unauthenticated access to the ui-/auth-settings
.requestMatchers(HttpMethod.GET, "/api/v1/config/ui").permitAll()
// Allow unauthenticated access to the build-info
.requestMatchers(HttpMethod.GET, "/api/v1/config/buildInfo").permitAll()
//TODO specific handling of temporary sidecar
.requestMatchers("/api/v1/components/observation/lime-survey-observation/end.html").permitAll()
.requestMatchers("/api/v1/studies/*/export/studydata/*").permitAll()
.requestMatchers("/api/v1/studies/*/calendar.ics").permitAll()
// Study-Data-Export is authenticated internally using individual access-tokens
.requestMatchers(HttpMethod.GET, "/api/v1/studies/*/export/studydata/*").permitAll()
.requestMatchers(HttpMethod.GET, "/api/v1/studies/*/calendar.ics").permitAll()
.requestMatchers("/api/v1/**").authenticated()
.requestMatchers("/kibana/**").authenticated()
.requestMatchers("/login/init").authenticated()
Expand All @@ -96,30 +103,44 @@ protected SecurityFilterChain filterChain(HttpSecurity http,
)
).permitAll()
.requestMatchers("/error").authenticated()
.anyRequest().denyAll();
.anyRequest().denyAll()
);

// API-Calls should not be redirected to the login page, but answered with a 401
http.exceptionHandling()
.defaultAuthenticationEntryPointFor(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED), new AntPathRequestMatcher("/api/**"));
http.exceptionHandling(exHandling -> exHandling
.defaultAuthenticationEntryPointFor(
new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED),
new AndRequestMatcher(
new AntPathRequestMatcher("/api/**"),
new NegatedRequestMatcher(
new AntPathRequestMatcher("/api/v1/studies/*/export/studydata/*")
)
)
)
);

// Logout Config
http.logout()
http.logout(logout -> logout
.logoutSuccessHandler(oidcLogoutSuccessHandler())
.logoutSuccessUrl("/");
.logoutSuccessUrl("/")
);

// Enable OAuth2
http.oauth2Login()
http.oauth2Login(oauth -> oauth
// register oauth2-provider under this baseurl to simplify routing
.authorizationEndpoint().baseUri("/login/oauth").and()
.authorizationEndpoint(ep -> ep.baseUri("/login/oauth"))
.authorizedClientService(
new UserSyncingOAuth2AuthorizedClientService(oAuth2AuthorizedClientService, oAuth2AuthenticationService, userRepository)
);
)
);

// Enable OAuth2 client_credentials flow (insomnia)
http.oauth2ResourceServer().jwt();
http.oauth2ResourceServer(oauth -> oauth.jwt(Customizer.withDefaults()));

//TODO maybe disable in production
http.headers().frameOptions().disable();
http.headers(headers -> headers
.frameOptions(HeadersConfigurer.FrameOptionsConfig::disable)
);

return http.build();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@
import io.redlink.more.studymanager.model.transformer.TimelineTransformer;
import io.redlink.more.studymanager.properties.GatewayProperties;
import io.redlink.more.studymanager.service.CalendarService;
import java.time.Instant;
import java.time.LocalDate;
import java.time.OffsetDateTime;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
Expand Down Expand Up @@ -46,7 +46,7 @@ public ResponseEntity<String> getStudyCalendar(Long studyId) {

@Override
@RequiresStudyRole({StudyRole.STUDY_ADMIN, StudyRole.STUDY_OPERATOR})
public ResponseEntity<StudyTimelineDTO> getStudyTimeline(Long studyId, Integer participant, Integer studyGroup, OffsetDateTime referenceDate, LocalDate from, LocalDate to) {
public ResponseEntity<StudyTimelineDTO> getStudyTimeline(Long studyId, Integer participant, Integer studyGroup, Instant referenceDate, LocalDate from, LocalDate to) {
return ResponseEntity.ok(
TimelineTransformer.toStudyTimelineDTO(
service.getTimeline(studyId, participant, studyGroup, referenceDate, from, to)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import io.redlink.more.studymanager.api.v1.model.KeycloakSettingsDTO;
import io.redlink.more.studymanager.api.v1.webservices.ConfigurationApi;
import io.redlink.more.studymanager.properties.FrontendConfigurationProperties;
import java.time.Instant;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
Expand All @@ -32,7 +33,14 @@ public ConfigurationApiV1Controller(FrontendConfigurationProperties uiConfig) {

@Override
public ResponseEntity<BuildInfoDTO> getBuildInfo() {
return null;
return ResponseEntity.ok(
new BuildInfoDTO(
"null",
Instant.MIN
)
.branch("undefined")
.rev("*dirty")
);
}

@Override
Expand All @@ -43,13 +51,13 @@ public ResponseEntity<FrontendConfigurationDTO> getFrontendConfig() {
}

private static FrontendConfigurationDTO transform(FrontendConfigurationProperties uiConfig) {
return new FrontendConfigurationDTO()
return new FrontendConfigurationDTO(
new KeycloakSettingsDTO(
uiConfig.keycloak().server(),
uiConfig.keycloak().realm(),
uiConfig.keycloak().clientId()
))
.title(uiConfig.title())
.auth(new KeycloakSettingsDTO()
.server(uiConfig.keycloak().server())
.realm(uiConfig.keycloak().realm())
.clientId(uiConfig.keycloak().clientId())
)
;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
import io.redlink.more.studymanager.model.StudyRole;
import io.redlink.more.studymanager.model.transformer.StudyDataTransformer;
import io.redlink.more.studymanager.service.DataProcessingService;
import java.time.OffsetDateTime;
import java.time.Instant;
import java.util.Arrays;
import java.util.List;
import org.springframework.http.MediaType;
Expand All @@ -36,7 +36,7 @@ public class DataApiV1Controller implements DataApi {
@Override
@RequiresStudyRole({StudyRole.STUDY_ADMIN, StudyRole.STUDY_VIEWER})
public ResponseEntity<List<DataPointDTO>> getDataPoints(
Long studyId, Integer size, Integer observationId, Integer participantId, OffsetDateTime date
Long studyId, Integer size, Integer observationId, Integer participantId, Instant date
) {
return ResponseEntity.ok().body(
dataProcessingService.getDataPoints(studyId, size, observationId, participantId, date)
Expand All @@ -55,7 +55,7 @@ public ResponseEntity<List<ParticipationDataDTO>> getParticipationData(Long stud

@Override
@RequiresStudyRole({StudyRole.STUDY_ADMIN, StudyRole.STUDY_VIEWER})
public ResponseEntity<ObservationDataViewDataDTO> getObservationViewData(Long studyId, Integer observationId, String viewName, Integer studyGroupId, Integer participantId, OffsetDateTime from, OffsetDateTime to) {
public ResponseEntity<ObservationDataViewDataDTO> getObservationViewData(Long studyId, Integer observationId, String viewName, Integer studyGroupId, Integer participantId, Instant from, Instant to) {
return ResponseEntity.ok().body(
StudyDataTransformer.toObservationDataViewDataDTO(
dataProcessingService.getDataView(studyId, observationId, viewName, studyGroupId, participantId, from, to)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import io.redlink.more.studymanager.core.properties.ActionProperties;
import io.redlink.more.studymanager.model.Action;
import io.redlink.more.studymanager.utils.MapperUtils;
import java.time.Instant;

public final class ActionTransformer {

Expand All @@ -26,12 +27,14 @@ public static Action fromActionDTO_V1(ActionDTO dto) {
}

public static ActionDTO toActionDTO_V1(Action action) {
Instant instant = action.getModified();
Instant instant1 = action.getCreated();
return new ActionDTO()
.actionId(action.getActionId())
.type(action.getType())
.properties(action.getProperties())
.created(Transformers.toOffsetDateTime(action.getCreated()))
.modified(Transformers.toOffsetDateTime(action.getModified()));
.created(instant1)
.modified(instant);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -10,20 +10,21 @@

import io.redlink.more.studymanager.api.v1.model.EndpointTokenDTO;
import io.redlink.more.studymanager.model.EndpointToken;

import java.time.Instant;
import java.util.Collection;
import java.util.List;
import java.util.Objects;

public class EndpointTokenTransformer {
public final class EndpointTokenTransformer {

private EndpointTokenTransformer() {}

public static EndpointToken fromEndpointTokenDTO(EndpointTokenDTO dto) {
Instant offsetDateTime = dto.getCreated();
return new EndpointToken(
dto.getTokenId(),
dto.getTokenLabel(),
Transformers.toInstant(dto.getCreated()),
offsetDateTime,
dto.getToken()
);
}
Expand All @@ -42,7 +43,7 @@ public static EndpointTokenDTO toEndpointTokenDTO(EndpointToken token) {
return new EndpointTokenDTO()
.tokenId(token.tokenId())
.tokenLabel(token.tokenLabel())
.created(Transformers.toOffsetDateTime(token.created()))
.created(token.created())
.token(token.token());
}

Expand Down
Loading
Loading