Commit 92c7b2f6 authored by Enriko Käsper's avatar Enriko Käsper
Browse files

Merge branch 'develop' into 'master'

Release: merge 'develop' into 'master' created by Enriko Käsper

See merge request teis/common-api-gateway!140
parents 32d97980 e3386096
Pipeline #1090 failed
......@@ -7,6 +7,7 @@ import ee.sm.ti.teis.servicerequest.RequestMetaDTO;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import static java.util.UUID.randomUUID;
import static org.junit.jupiter.api.Assertions.assertThrows;
class ViolationControllerTest extends CommonApiGatewayTestBase {
......@@ -17,13 +18,13 @@ class ViolationControllerTest extends CommonApiGatewayTestBase {
@Test
void getViolations_badRequest() {
assertThrows(NoResponseFromRabbitException.class, () ->
controller.getViolations("", "", new RequestMetaDTO()));
controller.getViolations(randomUUID(), randomUUID(), new RequestMetaDTO()));
}
@Test
void getViolation_badRequest() {
assertThrows(NoResponseFromRabbitException.class, () ->
controller.getViolation("", new RequestMetaDTO()));
controller.getViolation(randomUUID(), new RequestMetaDTO()));
}
}
......@@ -7,6 +7,7 @@ import ee.sm.ti.teis.servicecommon.config.PropertyLogger;
import org.camunda.bpm.spring.boot.starter.annotation.EnableProcessApplication;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Import;
@SpringBootApplication
......@@ -15,6 +16,7 @@ import org.springframework.context.annotation.Import;
ExchangeConfig.class,
QueueConfigurator.class,
DataSourceConfig.class})
@EnableConfigurationProperties
public class CommonApiGateway {
public static void main(String[] args) {
SpringApplication.run(CommonApiGateway.class, args);
......
......@@ -44,7 +44,7 @@ public class FileContentService {
private final FileMetaProcessingService fileMetaProcessingService;
private final FileProcessingService fileProcessingService;
@Value("${teis.file.file-reference.update-timeout}")
private final int fileReferenceUpdateTimeout = 5000;
private int fileReferenceUpdateTimeout;
@Value("${minio.bucket}")
private String bucketName;
@Value("${minio.bucket-thumbnail}")
......
......@@ -28,7 +28,7 @@ public class MessageController extends TeisBaseController {
@ApiResponses(value = {
@ApiResponse(code = 400, message = "Sisendi parameetrid ei vasta nõuetele")})
@GetMapping(value = "{dataObjectId}")
public List<MessageDto> getMessages(@PathVariable String dataObjectId, @ApiIgnore RequestMetaDTO requestMetaDTO) {
public List<MessageDto> getMessages(@PathVariable UUID dataObjectId, @ApiIgnore RequestMetaDTO requestMetaDTO) {
MessagesRequest request = new MessagesRequest();
request.setPayload(dataObjectId, requestMetaDTO);
......@@ -68,7 +68,7 @@ public class MessageController extends TeisBaseController {
@ApiResponse(code = 403, message = "Kasutajal ei ole õigust andmeobjekti pärida"),
@ApiResponse(code = 404, message = "Sisendis esitatud andmetega objekti ei eksisteeri")})
@DeleteMapping(value = "{id}")
public void delete(@PathVariable String id, @ApiIgnore RequestMetaDTO requestMetaDTO) {
public void delete(@PathVariable UUID id, @ApiIgnore RequestMetaDTO requestMetaDTO) {
DeleteMessageRequest request = new DeleteMessageRequest();
request.setPayload(id, requestMetaDTO);
......
......@@ -32,7 +32,7 @@ public class ProceedingInspectionDocumentController extends TeisBaseController {
@ApiResponse(code = 404, message = "Sisendis esitatud andmetega andmeobjekti ei eksisteeri")})
@ApiImplicitParams(@ApiImplicitParam(name = "id", value = "${teis.api.messages.proceeding.get-proceeding-inspection-item-id}"))
@GetMapping(value = "proceedings/{id}/inspection-documents", produces = APPLICATION_JSON_VALUE)
public List<ProceedingInspectionDocumentPublicDto> getDocuments(@PathVariable String id, @ApiIgnore RequestMetaDTO requestMetaDTO) {
public List<ProceedingInspectionDocumentPublicDto> getDocuments(@PathVariable UUID id, @ApiIgnore RequestMetaDTO requestMetaDTO) {
ProceedingInspectionDocumentsPublicRequest request = new ProceedingInspectionDocumentsPublicRequest();
request.setPayload(id, requestMetaDTO);
......@@ -45,7 +45,7 @@ public class ProceedingInspectionDocumentController extends TeisBaseController {
@ApiResponse(code = 400, message = "Sisendi parameetrid ei vasta nõuetele"),
@ApiResponse(code = 404, message = "Sisendis esitatud andmetega andmeobjekti ei eksisteeri")})
@PostMapping(value = "proceedings/{id}/inspection-documents", produces = APPLICATION_JSON_VALUE)
public ProceedingInspectionDocumentPublicDto createDocument(@PathVariable String id, @RequestBody ClassifierItemLightDto document, @ApiIgnore RequestMetaDTO requestMetaDTO) {
public ProceedingInspectionDocumentPublicDto createDocument(@PathVariable UUID id, @RequestBody ClassifierItemLightDto document, @ApiIgnore RequestMetaDTO requestMetaDTO) {
CreateProceedingInspectionDocumentPublicRequest request = new CreateProceedingInspectionDocumentPublicRequest();
CreateProceedingInspectionDocumentPublicRequest.Parameters payload = new CreateProceedingInspectionDocumentPublicRequest.Parameters();
payload.setDocumentId(document.getCode());
......@@ -62,7 +62,7 @@ public class ProceedingInspectionDocumentController extends TeisBaseController {
@ApiResponse(code = 404, message = "Sisendis esitatud andmetega andmeobjekti ei eksisteeri")})
@ApiImplicitParams(@ApiImplicitParam(name = "id", value = "${teis.api.messages.proceeding.inspection-document-id}"))
@PostMapping(value = "proceeding-inspection-documents/{id}/weblink", produces = APPLICATION_JSON_VALUE)
public List<WebLinkDto> createWebLinks(@PathVariable String id, @RequestBody List<String> url, @ApiIgnore RequestMetaDTO requestMetaDTO) {
public List<WebLinkDto> createWebLinks(@PathVariable UUID id, @RequestBody List<String> url, @ApiIgnore RequestMetaDTO requestMetaDTO) {
CreateWebLinkRequest request = new CreateWebLinkRequest();
request.setPayload(new CreateWebLinkRequest.Parameters(url, id), requestMetaDTO);
......@@ -74,9 +74,9 @@ public class ProceedingInspectionDocumentController extends TeisBaseController {
@ApiResponse(code = 400, message = "Sisendi parameetrid ei vasta nõuetele"),
@ApiResponse(code = 404, message = "Sisendis esitatud andmetega andmeobjekti ei eksisteeri")})
@DeleteMapping(value = "proceeding-inspection-documents/{documentId}/weblink/{webLinkId}", produces = APPLICATION_JSON_VALUE)
public void deleteWebLink(@PathVariable String documentId, @PathVariable String webLinkId, @ApiIgnore RequestMetaDTO requestMetaDTO) {
public void deleteWebLink(@PathVariable UUID documentId, @PathVariable UUID webLinkId, @ApiIgnore RequestMetaDTO requestMetaDTO) {
DeleteWebLinkRequest request = new DeleteWebLinkRequest();
request.setPayload(new DeleteWebLinkRequest.Parameters(UUID.fromString(documentId), UUID.fromString(webLinkId)), requestMetaDTO);
request.setPayload(new DeleteWebLinkRequest.Parameters(documentId, webLinkId), requestMetaDTO);
processingService.deleteWebLink(request);
}
......
......@@ -16,6 +16,7 @@ import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;
import java.util.List;
import java.util.UUID;
@Profile({"dev", "test", "local", "integtest"})
@RestController
......@@ -31,7 +32,7 @@ public class ProceedingInspectionDocumentTestController extends TeisBaseControll
@ApiResponse(code = 400, message = "Sisendi parameetrid ei vasta nõuetele"),
@ApiResponse(code = 404, message = "Sisendis esitatud andmetega andmeobjekti ei eksisteeri")})
@GetMapping
public List<WebLinkDto> getWebLinks(@PathVariable String documentId, @ApiIgnore RequestMetaDTO requestMetaDTO) {
public List<WebLinkDto> getWebLinks(@PathVariable UUID documentId, @ApiIgnore RequestMetaDTO requestMetaDTO) {
WebLinksTestRequest request = new WebLinksTestRequest();
request.setPayload(documentId, requestMetaDTO);
......
......@@ -11,6 +11,7 @@ import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;
import java.util.List;
import java.util.UUID;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
......@@ -27,8 +28,8 @@ public class ViolationController extends TeisBaseController {
@ApiResponse(code = 403, message = "Kasutajal ei ole õigust andmeobjekti pärida"),
@ApiResponse(code = 404, message = "Sisendis esitatud andmetega objekti ei eksisteeri")})
@GetMapping(produces = APPLICATION_JSON_VALUE)
public List<ViolationPublicDto> getViolations(@RequestParam(value = "proceduralActId", required = false) String proceduralActId,
@RequestParam(value = "proceedingId", required = false) String proceedingId,
public List<ViolationPublicDto> getViolations(@RequestParam(value = "proceduralActId", required = false) UUID proceduralActId,
@RequestParam(value = "proceedingId", required = false) UUID proceedingId,
@ApiIgnore RequestMetaDTO requestMetaDTO) {
ViolationsPublicRequest request = new ViolationsPublicRequest();
request.setPayload(new ViolationsPublicRequest.Parameters(proceduralActId, proceedingId), requestMetaDTO);
......@@ -41,10 +42,10 @@ public class ViolationController extends TeisBaseController {
@ApiResponse(code = 400, message = "Sisendi parameetrid ei vasta nõuetele"),
@ApiResponse(code = 403, message = "Kasutajal ei ole õigust andmeobjekti pärida"),
@ApiResponse(code = 404, message = "Sisendis esitatud andmetega objekti ei eksisteeri")})
@GetMapping(value ="/{id}", produces = APPLICATION_JSON_VALUE)
public ViolationPublicDto getViolation(@PathVariable(value = "id") String violationId, @ApiIgnore RequestMetaDTO requestMetaDTO) {
@GetMapping(value = "/{id}", produces = APPLICATION_JSON_VALUE)
public ViolationPublicDto getViolation(@PathVariable UUID id, @ApiIgnore RequestMetaDTO requestMetaDTO) {
ViolationPublicRequest request = new ViolationPublicRequest();
request.setPayload(new ViolationPublicRequest.Parameters(violationId), requestMetaDTO);
request.setPayload(id, requestMetaDTO);
return service.getViolation(request);
}
......
......@@ -23,7 +23,6 @@ public class AuthPublicController extends TeisBaseController {
return keycloakTokenService.getAuthConfig();
}
@ApiOperation(value = "${teis.api.messages.auth-token}", response = String.class)
@ApiResponses(value = {@ApiResponse(code = 200, message = "Tagastatakse nii access_token, kui refreshToken ja nende eluajad."),
@ApiResponse(code = 400, message = "Sisendparameetrid on vigased.")})
......@@ -31,7 +30,8 @@ public class AuthPublicController extends TeisBaseController {
consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public OAuthToken getAccessToken(
@ApiParam(name = "tokenRequest", value = "Kui grantType='authorization_code', siis peab olema täidetud 'code';<br> Kui grantType='refreshToken', siis peab olema täidetud 'refreshToken';", required = true)
@ApiParam(name = "tokenRequest", value = "Kui grantType='authorization_code', siis peab olema täidetud " +
"'code';<br> Kui grantType='refreshToken', siis peab olema täidetud 'refreshToken';", required = true)
@RequestBody TokenRequest tokenRequest, @ApiIgnore RequestMetaDTO requestMetaDTO) {
return keycloakTokenService.exchangeAccessTokenRequest(tokenRequest, requestMetaDTO);
}
......
package ee.sm.ti.teis.commongateway.security.auth;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "teis.auth-user-info-api")
@Getter
@Setter
public class AuthUserInfoProperties {
private String url;
private String secret;
private String userInfoPath;
private String mockUserInfoPath;
private String officeUserInfoPath;
private String mockOfficeUserInfoPath;
}
......@@ -23,9 +23,12 @@ import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import static ee.sm.ti.teis.commongateway.security.auth.GrantType.AUTHORIZATION_CODE;
import static ee.sm.ti.teis.commongateway.security.auth.GrantType.REFRESH_TOKEN;
import static ee.sm.ti.teis.servicerequest.UserType.SYSTEM;
import static org.apache.commons.lang.StringUtils.defaultString;
import static org.apache.commons.lang.StringUtils.isEmpty;
import static org.springframework.http.MediaType.APPLICATION_FORM_URLENCODED;
@Service
@Slf4j
......@@ -33,10 +36,12 @@ public class KeycloakTokenService {
private static final String OFFICE_ROLES_SCOPE = "TeIS_Office_Roles";
private static final String PORTAL_ROLES_SCOPE = "TeIS_Roles";
private final JwtDecoder jwtDecoder;
private final PersonProcessingService personProcessingService;
private final AuthProperties authProperties;
private final AuthConfig authConfig;
@Value("${teis.system.name}")
private String systemName;
......@@ -61,7 +66,7 @@ public class KeycloakTokenService {
public OAuthToken exchangeAccessTokenRequest(TokenRequest tokenRequest, RequestMetaDTO requestMetaDTO) {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = getHttpHeaders(MediaType.APPLICATION_FORM_URLENCODED);
HttpHeaders headers = getHttpHeaders(APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> keycloakTokenRequest = getAccessTokenRequestParams(tokenRequest);
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(keycloakTokenRequest, headers);
log.debug("Get access token with parameters: " + keycloakTokenRequest.toString());
......@@ -69,12 +74,15 @@ public class KeycloakTokenService {
ResponseEntity<OAuthToken> response = restTemplate.exchange(getAuthConfig().getTokenEndpoint(),
HttpMethod.POST, request, OAuthToken.class);
OAuthToken keycloakToken = response.getBody();
if (tokenRequest.getGrantType() == GrantType.AUTHORIZATION_CODE
if (keycloakToken == null) {
throw new IllegalArgumentException("Key cloak token missing from request");
}
if (tokenRequest.getGrantType() == AUTHORIZATION_CODE
&& isPortalRequest(tokenRequest.getClientId())) {
boolean personNameUpdated = updatePersonNameIfChanged(keycloakToken, requestMetaDTO);
if (personNameUpdated) {
tokenRequest.setRefreshToken(keycloakToken.getRefreshToken());
tokenRequest.setGrantType(GrantType.REFRESH_TOKEN);
tokenRequest.setGrantType(REFRESH_TOKEN);
keycloakTokenRequest = getAccessTokenRequestParams(tokenRequest);
request = new HttpEntity<>(keycloakTokenRequest, headers);
log.info("Get new access token with updated Person name using refresh token with parameters: "
......@@ -93,7 +101,7 @@ public class KeycloakTokenService {
public void logout(LogoutRequest logoutRequest, RequestMetaDTO requestMetaDTO) {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = getHttpHeaders(MediaType.APPLICATION_FORM_URLENCODED);
HttpHeaders headers = getHttpHeaders(APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> keycloakLogoutRequest = getLogoutRequestParams(logoutRequest);
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(keycloakLogoutRequest, headers);
log.debug("Logout user with parameters: " + keycloakLogoutRequest.toString());
......@@ -153,10 +161,10 @@ public class KeycloakTokenService {
MultiValueMap<String, String> requestParams = new LinkedMultiValueMap<>();
addClientIdParam(tokenRequest.getClientId(), requestParams);
requestParams.add("grant_type", tokenRequest.getGrantType().getValue());
if (tokenRequest.getGrantType() == GrantType.AUTHORIZATION_CODE) {
if (tokenRequest.getGrantType() == AUTHORIZATION_CODE) {
requestParams.add("redirect_uri", tokenRequest.getRedirectUri());
requestParams.add("code", tokenRequest.getCode());
} else if (tokenRequest.getGrantType() == GrantType.REFRESH_TOKEN) {
} else if (tokenRequest.getGrantType() == REFRESH_TOKEN) {
requestParams.add("refresh_token", tokenRequest.getRefreshToken());
}
String scopesStr = defaultString(tokenRequest.getScope());
......
......@@ -5,10 +5,12 @@ import ee.sm.ti.teis.commongateway.auth.UserCompanySelectionDto;
import ee.sm.ti.teis.commongateway.security.auth.AuthProcessingService;
import ee.sm.ti.teis.gatewaycommon.controller.TeisBaseController;
import ee.sm.ti.teis.servicerequest.RequestMetaDTO;
import io.swagger.annotations.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Profile;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
......@@ -31,18 +33,6 @@ public class AuthMockController extends TeisBaseController {
@ApiOperation(value = "${teis.api.messages.post-mock-auth}", response = String.class)
@ApiResponses(value = {@ApiResponse(code = 200, message = "Mock autentimine õnnestus."),
@ApiResponse(code = 404, message = "Sisendis esitatud andmetega isikut või riiki ei eksisteeri.")})
// TODO: Need further investigation. Request body example doesn't work, although
// it's done by the book: http://springfox.github.io/springfox/docs/snapshot/#q27
@ApiImplicitParams({
@ApiImplicitParam(
name = "mockUser",
dataType = "MockUserLoginRequest",
examples = @Example(
value = {
@ExampleProperty(value = "{'countryCode's: 'EE', 'idCode': '48806060014'}",
mediaType = MediaType.APPLICATION_XML_VALUE)
}))
})
@PostMapping(value = "/public/mock/auth")
public MockAuthResponse authenticate(@Valid @RequestBody MockUserLoginRequest mockUser,
@ApiIgnore RequestMetaDTO requestMetaDTO) {
......@@ -53,9 +43,8 @@ public class AuthMockController extends TeisBaseController {
@ApiResponses(value = {@ApiResponse(code = 200, message = "Mock autentimine õnnestus."),
@ApiResponse(code = 404, message = "Sisendis esitatud andmetega isikut või riiki ei eksisteeri.")})
@PostMapping(value = "/public/mock/office/auth")
public MockAuthResponse authenticateOfficeUser(@Valid @RequestBody MockUserLoginRequest mockUser,
@ApiIgnore RequestMetaDTO requestMetaDTO) {
return mockAuthService.createOfficeMockAuthResponse(mockUser, requestMetaDTO);
public MockAuthResponse authenticateOfficeUser(@Valid @RequestBody MockUserLoginRequest mockUser) {
return mockAuthService.createOfficeMockAuthResponse(mockUser);
}
@ApiOperation(value = "${teis.api.messages.post-mock-auth-select-company}", response = String.class)
......
package ee.sm.ti.teis.commongateway.security.mock;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "teis.mockauth")
@Getter
@Setter
public class MockAuthProperties {
private String tokenSecret;
private Long expire;
}
......@@ -4,15 +4,16 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import ee.sm.ti.teis.ErrorDTO;
import ee.sm.ti.teis.commongateway.auth.AuthServiceUserInfo;
import ee.sm.ti.teis.commongateway.person.PersonProcessingService;
import ee.sm.ti.teis.commongateway.security.auth.AuthUserInfoProperties;
import ee.sm.ti.teis.exceptions.TeisRestException;
import ee.sm.ti.teis.security.JwtUserInfo;
import ee.sm.ti.teis.servicerequest.RequestMetaDTO;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Profile;
import org.springframework.http.HttpEntity;
......@@ -23,63 +24,25 @@ import org.springframework.web.client.HttpStatusCodeException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
import java.security.Key;
import java.util.Date;
import java.util.Map;
import static io.jsonwebtoken.io.Decoders.BASE64;
import static org.apache.commons.lang3.StringUtils.isEmpty;
@Component
@Profile({"mockauth", "local", "integtest"})
@Slf4j
@SuppressWarnings("unchecked")
@RequiredArgsConstructor
public class MockAuthService {
private final PersonProcessingService personProcessingService;
private final Long expirationTime;
private final String tokenSecret;
private final String authApiUrl;
private final String authApiSecret;
private final String teisClaimName;
private final String authApiUserInfoPath;
private final String authApiMockUserInfoPath;
private final String authApiOfficeUserInfoPath;
private final String authApiMockOfficeUserInfoPath;
private RestTemplate restTemplate;
@Autowired
public MockAuthService(
RestTemplate restTemplate,
PersonProcessingService personProcessingService,
@Value("${teis.mockauth.token-secret}")
String tokenSecret,
@Value("${teis.mockauth.expire:86400}")
Long expirationTime,
@Value("${teis.auth-user-info-api.url}")
String authApiUrl,
@Value("${teis.auth-user-info-api.secret}")
String authApiSecret,
@Value("${teis.auth-user-info-api.user-info-path}")
String authApiUserInfoPath,
@Value("${teis.auth-user-info-api.mock-user-info-path}")
String authApiMockUserInfoPath,
@Value("${teis.auth-user-info-api.office-user-info-path}")
String authApiOfficeUserInfoPath,
@Value("${teis.auth-user-info-api.mock-office-user-info-path}")
String authApiMockOfficeUserInfoPath,
@Value("${teis.oauth2.user-info-claim-name}")
String userInfoClaimName) {
this.restTemplate = restTemplate;
this.personProcessingService = personProcessingService;
this.tokenSecret = tokenSecret;
this.expirationTime = expirationTime;
this.authApiUrl = authApiUrl;
this.authApiSecret = authApiSecret;
this.authApiUserInfoPath = authApiUserInfoPath;
this.authApiMockUserInfoPath = authApiMockUserInfoPath;
this.teisClaimName = userInfoClaimName;
this.authApiOfficeUserInfoPath = authApiOfficeUserInfoPath;
this.authApiMockOfficeUserInfoPath = authApiMockOfficeUserInfoPath;
}
private final RestTemplate restTemplate;
private final MockAuthProperties mockAuthProperties;
private final AuthUserInfoProperties authUserInfoProperties;
@Value("${teis.oauth2.user-info-claim-name}")
private String teisClaimName;
MockAuthResponse createMockAuthResponse(MockUserLoginRequest mockUser, RequestMetaDTO requestMetaDTO) {
// Get user info from Auth service
......@@ -100,7 +63,7 @@ public class MockAuthService {
.build();
}
MockAuthResponse createOfficeMockAuthResponse(MockUserLoginRequest mockUser, RequestMetaDTO requestMetaDTO) {
MockAuthResponse createOfficeMockAuthResponse(MockUserLoginRequest mockUser) {
// Get user info from Auth service
AuthServiceUserInfo authServiceUserInfo = getMockUserInfoFromAuthService(mockUser, true);
// Create mocked JWT token
......@@ -113,7 +76,7 @@ public class MockAuthService {
}
String refreshToken(String accessToken, RequestMetaDTO requestMetaDTO) {
Claims tokenBody = Jwts.parser().setSigningKey(tokenSecret).parseClaimsJws(accessToken).getBody();
Claims tokenBody = Jwts.parser().setSigningKey(mockAuthProperties.getTokenSecret()).parseClaimsJws(accessToken).getBody();
String preferredUserName = (String) tokenBody.get("preferred_username");
if (isEmpty(preferredUserName)) {
throw new IllegalArgumentException("preferred_username field is empty in access token.");
......@@ -127,7 +90,7 @@ public class MockAuthService {
}
JwtUserInfo parseToken(String token) {
Claims body = Jwts.parser().setSigningKey(tokenSecret).parseClaimsJws(token).getBody();
Claims body = Jwts.parser().setSigningKey(mockAuthProperties.getTokenSecret()).parseClaimsJws(token).getBody();
Map<String, Object> userInfo = (Map<String, Object>) body.get(teisClaimName);
ObjectMapper mapper = new ObjectMapper();
return mapper.convertValue(userInfo, JwtUserInfo.class);
......@@ -136,8 +99,8 @@ public class MockAuthService {
private AuthServiceUserInfo getMockUserInfoFromAuthService(MockUserLoginRequest mockUser, boolean isOfficeUser) {
HttpHeaders headers = new HttpHeaders();
String personalCode = mockUser.getCountryCode().toLowerCase() + mockUser.getIdCode();
if (!isEmpty(authApiSecret)) {
headers.add("Authorization", authApiSecret);
if (!isEmpty(authUserInfoProperties.getSecret())) {
headers.add("Authorization", authUserInfoProperties.getSecret());
}
UriComponentsBuilder uriBuilder;
boolean hasMockRoles = mockUser.getRoles() != null && !mockUser.getRoles().isEmpty();
......@@ -145,12 +108,16 @@ public class MockAuthService {
uriBuilder = composeUserInfoUri(mockUser, isOfficeUser, hasMockRoles, hasMockPrivileges);
uriBuilder.queryParam("personalCode", personalCode)
.queryParam("includeRoles", true);
HttpEntity request = new HttpEntity<>(headers);
HttpEntity<HttpHeaders> request = new HttpEntity<>(headers);
log.debug("Get User Info from auth service token with parameters: " + uriBuilder.toUriString());
try {
HttpEntity<AuthServiceUserInfo> userInfoResponse = restTemplate.exchange(uriBuilder.toUriString(),
HttpMethod.GET, request, AuthServiceUserInfo.class);
return userInfoResponse.getBody();
AuthServiceUserInfo userInfo = userInfoResponse.getBody();
if (userInfo == null) {
throw new IllegalArgumentException("User info missing from auth service");
}
return userInfo;
} catch (HttpStatusCodeException e) {
ErrorDTO errorDto = ErrorDTO.builder()
.httpResponse(e.getStatusCode())
......@@ -161,19 +128,21 @@ public class MockAuthService {
}
}
private UriComponentsBuilder composeUserInfoUri(MockUserLoginRequest mockUser, boolean isOfficeUser, boolean hasMockRoles, boolean hasMockPrivileges) {
private UriComponentsBuilder composeUserInfoUri(MockUserLoginRequest mockUser, boolean isOfficeUser,
boolean hasMockRoles, boolean hasMockPrivileges) {
UriComponentsBuilder uriBuilder;
if (isOfficeUser) {
if (hasMockRoles || hasMockPrivileges) {
uriBuilder = composeMockUri(mockUser, authApiMockOfficeUserInfoPath);
uriBuilder = composeMockUri(mockUser, authUserInfoProperties.getMockOfficeUserInfoPath());
} else {
uriBuilder = UriComponentsBuilder.fromHttpUrl(authApiUrl + authApiOfficeUserInfoPath);
uriBuilder = UriComponentsBuilder.fromHttpUrl(authUserInfoProperties.getUrl() +
authUserInfoProperties.getOfficeUserInfoPath());
}
} else {
if (mockUser.getSelectedCompanyRegCode() != null) {
uriBuilder = composeMockUri(mockUser, authApiMockUserInfoPath);
uriBuilder = composeMockUri(mockUser, authUserInfoProperties.getMockUserInfoPath());
} else {
uriBuilder = UriComponentsBuilder.fromHttpUrl(authApiUrl + authApiUserInfoPath);
uriBuilder = UriComponentsBuilder.fromHttpUrl(authUserInfoProperties.getUrl() + authUserInfoProperties.getUserInfoPath());
}
}
return uriBuilder;
......@@ -181,7 +150,7 @@ public class MockAuthService {
private UriComponentsBuilder composeMockUri(MockUserLoginRequest mockUser, String mockUserInfoPath) {
UriComponentsBuilder uriBuilder;
uriBuilder = UriComponentsBuilder.fromHttpUrl(authApiUrl + mockUserInfoPath);
uriBuilder = UriComponentsBuilder.fromHttpUrl(authUserInfoProperties.getUrl() + mockUserInfoPath);
if (mockUser.getRoles() != null && !mockUser.getRoles().isEmpty()) {
uriBuilder.queryParam("roles", String.join(",", mockUser.getRoles()));
}
......@@ -194,7 +163,6 @@ public class MockAuthService {
}
public String generateToken(MockUserLoginRequest mockUser, AuthServiceUserInfo authServiceUserInfo) {
JwtUserInfo userInfo = JwtUserInfo.builder()
.userId(authServiceUserInfo.getPersonId())
.idCode(authServiceUserInfo.getPersonalCode())
......@@ -221,15 +189,20 @@ public class MockAuthService {
.setClaims(claims)
.setIssuedAt(createdDate)
.setExpiration(expirationDate)
.signWith(SignatureAlgorithm.HS512, tokenSecret)
.signWith(getSigningKey())
.compact();
}
private Key getSigningKey() {
byte[] keyBytes = BASE64.decode(mockAuthProperties.getTokenSecret());
return Keys.hmacShaKeyFor(keyBytes);
}
private Date calculateExpirationDate(Date createdDate) {
return new Date(createdDate.getTime() + (expirationTime * 1000));
return new Date(createdDate.getTime() + (mockAuthProperties.getExpire() * 1000));
}
public JwtParser getMockJwtParser() {
return Jwts.parser().setSigningKey(tokenSecret);
return Jwts.parser().setSigningKey(mockAuthProperties.getTokenSecret());
}
}