diff --git a/smp-angular/src/app/common/panels/user-settings-panel/user-profile-panel.component.html b/smp-angular/src/app/common/panels/user-settings-panel/user-profile-panel.component.html index e5406f5fdaa88a71a168e941b340fdbae02fd305..f9fae6db7244ea63a955a51dc0235d38db8e1abc 100644 --- a/smp-angular/src/app/common/panels/user-settings-panel/user-profile-panel.component.html +++ b/smp-angular/src/app/common/panels/user-settings-panel/user-profile-panel.component.html @@ -129,20 +129,28 @@ [showTitle]="showDataPanelTitles" text="Reset username password for the UI login"> <div style="display: flex;flex-flow: row wrap;"> - <mat-form-field style="flex-grow: 1"> + <mat-form-field style="flex-grow:2 " floatLabel="always"> <mat-label>Last set</mat-label> - <input id="passwordUpdatedOn_id" matInput placeholder="Last set" - value="{{!userCredentialForm.get('passwordUpdatedOn').value?nullValue:userCredentialForm.get('passwordUpdatedOn').value | date:dateTimeFormat}}" - maxlength="255" disabled> + <input id="passwordUpdatedOn_id" matInput [ngxMatDatetimePicker]="passwordUpdatedOnPicker" + formControlName="passwordUpdatedOn" + placeholder="---" + readonly> + <mat-datepicker-toggle matSuffix [for]="passwordUpdatedOnPicker" style="visibility: hidden"></mat-datepicker-toggle> + <ngx-mat-datetime-picker #passwordUpdatedOnPicker [showSpinners]="true" [showSeconds]="false" + [hideTime]="false"></ngx-mat-datetime-picker> </mat-form-field> <mat-form-field style="flex-grow: 1"> <mat-label>Password expire on</mat-label> <input id="passwordExpireOn_id" - *ngIf="!!userCredentialForm.get('passwordExpireOn').value; else noPasswordExpirySet " matInput - placeholder="Valid until" - value="{{userCredentialForm.get('passwordExpireOn').value | date:dateTimeFormat}}" - maxlength="255" disabled> + *ngIf="!!userCredentialForm.get('passwordExpireOn').value; else noPasswordExpirySet " + matInput [ngxMatDatetimePicker]="passwordExpireOnPicker" + formControlName="passwordExpireOn" + placeholder="---" + readonly> + <mat-datepicker-toggle matSuffix [for]="passwordExpireOnPicker" style="visibility: hidden"></mat-datepicker-toggle> + <ngx-mat-datetime-picker #passwordExpireOnPicker [showSpinners]="true" [showSeconds]="false" + [hideTime]="false"></ngx-mat-datetime-picker> <ng-template #noPasswordExpirySet> <input id="passwordExpireOnMessage_id" matInput placeholder="Valid until" style="color: red" matTooltip="Default password set by system admin! User must change password immediately!" @@ -151,29 +159,36 @@ </ng-template> </mat-form-field> </div> - <div style="display: flex;flex-flow: row wrap;"> - <mat-form-field style="flex-grow: 2"> + <div style="display: flex;flex-flow: row;"> + <mat-form-field style="flex-grow: 2" floatLabel="always"> <mat-label>Seq. failed attempts</mat-label> <input id="sequentialLoginFailureCount_id" matInput placeholder="Seq. failed attempts" [value]="userCredentialForm.controls['sequentialLoginFailureCount'].value" + placeholder="0" maxlength="255" disabled readonly> </mat-form-field> - <mat-form-field style="flex-grow: 1"> + <mat-form-field style="flex-grow:2 " floatLabel="always"> <mat-label>Last failed attempt</mat-label> - <input id="lastFailedLoginAttempt_id" matInput placeholder="Last failed attempt" - value="{{!userCredentialForm.get('lastFailedLoginAttempt').value?nullValue:userCredentialForm.get('lastFailedLoginAttempt').value | date:dateTimeFormat}}" - maxlength="255" disabled> + <input id="LastFailedAttempt_id" matInput [ngxMatDatetimePicker]="LastFailedAttemptPicker" + formControlName="lastFailedLoginAttempt" + placeholder="---" + readonly> + <mat-datepicker-toggle matSuffix [for]="LastFailedAttemptPicker" style="visibility: hidden"></mat-datepicker-toggle> + <ngx-mat-datetime-picker #LastFailedAttemptPicker [showSpinners]="true" [showSeconds]="false" + [hideTime]="false"></ngx-mat-datetime-picker> </mat-form-field> - </div> - <div style="display: flex;flex-flow: row wrap;"> - <mat-form-field style="flex-grow: 1"> + + <mat-form-field style="flex-grow:2 " floatLabel="always"> <mat-label>Suspended until</mat-label> - <input id="suspendedUtil_id" matInput placeholder="Suspended until" - value="{{!userCredentialForm.get('suspendedUtil').value?nullValue:userCredentialForm.get('suspendedUtil').value | date:dateTimeFormat}}" - maxlength="255" disabled> + <input id="suspendedUtil_id" matInput [ngxMatDatetimePicker]="suspendedUtilPicker" + formControlName="suspendedUtil" + placeholder="---" + readonly> + <mat-datepicker-toggle matSuffix [for]="suspendedUtilPicker" style="visibility: hidden"></mat-datepicker-toggle> + <ngx-mat-datetime-picker #suspendedUtilPicker [showSpinners]="true" [showSeconds]="false" + [hideTime]="false"></ngx-mat-datetime-picker> </mat-form-field> </div> - <mat-toolbar class ="mat-elevation-z2"> <mat-toolbar-row class="smp-toolbar-row"> <button mat-flat-button color="primary" id="changePassword_id" diff --git a/smp-angular/src/app/common/panels/user-settings-panel/user-profile-panel.component.ts b/smp-angular/src/app/common/panels/user-settings-panel/user-profile-panel.component.ts index 45cc862d38724ab7c5c2f1f2116ffdecddb506fc..b6056865aa52b529124ce03cfffd4f612a74564e 100644 --- a/smp-angular/src/app/common/panels/user-settings-panel/user-profile-panel.component.ts +++ b/smp-angular/src/app/common/panels/user-settings-panel/user-profile-panel.component.ts @@ -43,8 +43,6 @@ export class UserProfilePanelComponent { _managedUserData: UserRo; currentDate: Date = new Date(); - - currentPwdCredential: CredentialRo; userController: UserController; @Input() showDataPanelTitles: boolean = true @@ -105,6 +103,8 @@ export class UserProfilePanelComponent { @Input() set managedUserData(value: UserRo) { this._managedUserData = value; + this.updatePwdCredential(value); + if (!!this._managedUserData) { this.userForm.controls['username'].setValue(this._managedUserData.username); this.userForm.controls['active'].setValue(this._managedUserData.active); @@ -140,15 +140,22 @@ export class UserProfilePanelComponent { - private updatePwdCredential(currentPwdCredential: CredentialRo) { - this.currentPwdCredential = { - ...currentPwdCredential + private updatePwdCredential(value: UserRo) { + // form is always disabled + this.userCredentialForm.disable() + if (!value) { + this.userCredentialForm.controls['passwordUpdatedOn'].setValue(null); + this.userCredentialForm.controls['passwordExpireOn'].setValue(null); + this.userCredentialForm.controls['sequentialLoginFailureCount'].setValue(null); + this.userCredentialForm.controls['lastFailedLoginAttempt'].setValue(null); + this.userCredentialForm.controls['suspendedUtil'].setValue(null); + } else { + this.userCredentialForm.controls['passwordUpdatedOn'].setValue(value.passwordUpdatedOn); + this.userCredentialForm.controls['passwordExpireOn'].setValue(value.passwordExpireOn); + this.userCredentialForm.controls['sequentialLoginFailureCount'].setValue(value.sequentialLoginFailureCount); + this.userCredentialForm.controls['lastFailedLoginAttempt'].setValue(value.lastFailedLoginAttempt); + this.userCredentialForm.controls['suspendedUtil'].setValue(value.suspendedUtil); } - this.userCredentialForm.controls['passwordUpdatedOn'].setValue(this.currentPwdCredential.updatedOn); - this.userCredentialForm.controls['passwordExpireOn'].setValue(this.currentPwdCredential.expireOn); - this.userCredentialForm.controls['sequentialLoginFailureCount'].setValue(this.currentPwdCredential.sequentialLoginFailureCount); - this.userCredentialForm.controls['lastFailedLoginAttempt'].setValue(this.currentPwdCredential.lastFailedLoginAttempt); - this.userCredentialForm.controls['suspendedUtil'].setValue(this.currentPwdCredential.suspendedUtil); // mark form as pristine this.userCredentialForm.markAsPristine(); } diff --git a/smp-angular/src/app/system-settings/user/user-ro.model.ts b/smp-angular/src/app/system-settings/user/user-ro.model.ts index 81dbbce93bf8bea0f05d26e0fdb8d080fde116d8..a09c44d486283c89eadb8290d28b2946fd7fae70 100644 --- a/smp-angular/src/app/system-settings/user/user-ro.model.ts +++ b/smp-angular/src/app/system-settings/user/user-ro.model.ts @@ -12,18 +12,20 @@ export interface UserRo extends SearchTableEntity { role: ApplicationRoleEnum; active: boolean; - - - accessTokenId?: string; passwordExpireOn?: Date; - accessTokenExpireOn?: Date; + passwordUpdatedOn?: Date; suspended?: boolean; - certificate?: CertificateRo; casUserDataUrl?: string; sequentialLoginFailureCount?:number; lastFailedLoginAttempt?:Date; suspendedUtil?:Date; + + + // deprecated + accessTokenId?: string; + accessTokenExpireOn?: Date; + certificate?: CertificateRo; sequentialTokenLoginFailureCount?:number; lastTokenFailedLoginAttempt?:Date; tokenSuspendedUtil?:Date; diff --git a/smp-angular/src/app/user-settings/user-access-tokens/access-token-panel/access-token-panel.component.html b/smp-angular/src/app/user-settings/user-access-tokens/access-token-panel/access-token-panel.component.html index b4ade155e8d6a72988db6f4aacb1524e14381b25..aeec59959c35ff4c483939302570699a5222634f 100644 --- a/smp-angular/src/app/user-settings/user-access-tokens/access-token-panel/access-token-panel.component.html +++ b/smp-angular/src/app/user-settings/user-access-tokens/access-token-panel/access-token-panel.component.html @@ -46,24 +46,33 @@ <smp-field-error *ngIf="credentialForm.controls.expireOn.hasError('matEndDateInvalid')">Invalid expire on date</smp-field-error > </mat-form-field> </div> - <div style="display: flex;flex-flow: row wrap;"> + <div style="display: flex;flex-flow: row;"> <mat-form-field style="flex-grow: 1"> <mat-label>Seq. failed attempts</mat-label> <input matInput [value]="sequentialLoginFailureCount" id="sequentialTokenLoginFailureCount_id" maxlength="255" disabled readonly> </mat-form-field> - <mat-form-field style="flex-grow: 2"> + <mat-form-field style="flex-grow:2 " floatLabel="always"> <mat-label>Last failed attempt</mat-label> - <input matInput + <input id="LastFailedAttempt_id" matInput [ngxMatDatetimePicker]="LastFailedAttemptPicker" [value]="lastFailedLoginAttempt" - maxlength="255" disabled> + placeholder="---" + readonly> + <mat-datepicker-toggle matSuffix [for]="LastFailedAttemptPicker" style="visibility: hidden"></mat-datepicker-toggle> + <ngx-mat-datetime-picker #LastFailedAttemptPicker [showSpinners]="true" [showSeconds]="false" + [hideTime]="false"></ngx-mat-datetime-picker> </mat-form-field> - <mat-form-field style="flex-grow: 2"> + <mat-form-field style="flex-grow: 2" floatLabel="always"> <mat-label>Suspended until</mat-label> - <input matInput + <input id="SuspendedUtil_id" matInput [ngxMatDatetimePicker]="suspendedUtilPicker" [value]="suspendedUtil" - maxlength="255" disabled> + placeholder="---" + readonly> + <mat-datepicker-toggle matSuffix [for]="suspendedUtilPicker" style="visibility: hidden"></mat-datepicker-toggle> + <ngx-mat-datetime-picker #suspendedUtilPicker [showSpinners]="true" [showSeconds]="false" + [hideTime]="false"></ngx-mat-datetime-picker> + </mat-form-field> </div> </div> diff --git a/smp-angular/src/app/user-settings/user-access-tokens/access-token-panel/access-token-panel.component.ts b/smp-angular/src/app/user-settings/user-access-tokens/access-token-panel/access-token-panel.component.ts index 9a96fadb7b17fb7b70d9e55c83733d7ccfcb13c8..34028ee83fcc95cc6bfafe19455684a30b6c62a2 100644 --- a/smp-angular/src/app/user-settings/user-access-tokens/access-token-panel/access-token-panel.component.ts +++ b/smp-angular/src/app/user-settings/user-access-tokens/access-token-panel/access-token-panel.component.ts @@ -77,14 +77,12 @@ export class AccessTokenPanelComponent implements BeforeLeaveGuard { this._credential.sequentialLoginFailureCount + "" : "0"; } - get suspendedUtil(): string { - return this._credential && this._credential.suspendedUtil ? - this._credential.suspendedUtil.toLocaleDateString() : "---"; + get suspendedUtil(): Date { + return this._credential?.suspendedUtil; } - get lastFailedLoginAttempt(): string { - return this._credential && this._credential.lastFailedLoginAttempt ? - this._credential.lastFailedLoginAttempt.toLocaleDateString() : "---"; + get lastFailedLoginAttempt(): Date { + return this._credential?.lastFailedLoginAttempt } isDirty(): boolean { diff --git a/smp-server-library/src/main/java/eu/europa/ec/edelivery/smp/conversion/DBUserToUserROConverter.java b/smp-server-library/src/main/java/eu/europa/ec/edelivery/smp/conversion/DBUserToUserROConverter.java index b81423a6246700286177e98e736f33aabef414b1..6d978c7453e18ae504b7ad1fa86de61724a1d168 100644 --- a/smp-server-library/src/main/java/eu/europa/ec/edelivery/smp/conversion/DBUserToUserROConverter.java +++ b/smp-server-library/src/main/java/eu/europa/ec/edelivery/smp/conversion/DBUserToUserROConverter.java @@ -1,13 +1,18 @@ package eu.europa.ec.edelivery.smp.conversion; +import eu.europa.ec.edelivery.smp.data.dao.CredentialDao; +import eu.europa.ec.edelivery.smp.data.enums.CredentialTargetType; +import eu.europa.ec.edelivery.smp.data.enums.CredentialType; import eu.europa.ec.edelivery.smp.data.model.user.DBCredential; import eu.europa.ec.edelivery.smp.data.model.user.DBUser; import eu.europa.ec.edelivery.smp.data.ui.UserRO; +import eu.europa.ec.edelivery.smp.services.ConfigurationService; import eu.europa.ec.edelivery.smp.utils.SessionSecurityUtils; import org.springframework.core.convert.converter.Converter; import org.springframework.stereotype.Component; import java.time.OffsetDateTime; +import java.util.List; /** @@ -16,6 +21,13 @@ import java.time.OffsetDateTime; @Component public class DBUserToUserROConverter implements Converter<DBUser, UserRO> { + private final CredentialDao credentialDao; + private final ConfigurationService configurationService; + + public DBUserToUserROConverter(CredentialDao credentialDao, ConfigurationService configurationService) { + this.credentialDao = credentialDao; + this.configurationService = configurationService; + } @Override public UserRO convert(DBUser source) { @@ -32,6 +44,18 @@ public class DBUserToUserROConverter implements Converter<DBUser, UserRO> { target.setSmpTheme(source.getSmpTheme()); target.setSmpLocale(source.getSmpLocale()); + List<DBCredential> credentials = credentialDao.findUserCredentialForByUserIdTypeAndTarget(source.getId(), CredentialType.USERNAME_PASSWORD, CredentialTargetType.UI); + if (!credentials.isEmpty()) { + // expected only one username/password + DBCredential credential = credentials.get(0); + target.setPasswordUpdatedOn(credential.getChangedOn()); + target.setPasswordExpireOn(credential.getExpireOn()); + target.setPasswordExpired(isCredentialExpired(credential)); + target.setSequentialLoginFailureCount(credential.getSequentialLoginFailureCount()); + target.setLastFailedLoginAttempt(credential.getLastFailedLoginAttempt()); + target.setSuspendedUtil(getSuspensionUntilDate(credential.getLastFailedLoginAttempt(), credential.getSequentialLoginFailureCount(), + configurationService.getLoginSuspensionTimeInSeconds(), configurationService.getLoginMaxAttempts())); + } return target; } diff --git a/smp-server-library/src/main/java/eu/europa/ec/edelivery/smp/data/ui/UserRO.java b/smp-server-library/src/main/java/eu/europa/ec/edelivery/smp/data/ui/UserRO.java index 91c698633cc6dd86385e88a3df74442e5926270b..cf9f15a50e4471b28b6e6f2d107c95dbf12d4809 100644 --- a/smp-server-library/src/main/java/eu/europa/ec/edelivery/smp/data/ui/UserRO.java +++ b/smp-server-library/src/main/java/eu/europa/ec/edelivery/smp/data/ui/UserRO.java @@ -31,21 +31,15 @@ public class UserRO extends BaseRO { private Integer sequentialLoginFailureCount; private OffsetDateTime lastFailedLoginAttempt; private OffsetDateTime suspendedUtil; - private String accessTokenId; - private OffsetDateTime accessTokenExpireOn; - private Integer sequentialTokenLoginFailureCount; - private OffsetDateTime lastTokenFailedLoginAttempt; - private OffsetDateTime tokenSuspendedUtil; + private OffsetDateTime passwordUpdatedOn; private Collection<SMPAuthority> authorities; - private CertificateRO certificate; private int statusPassword = EntityROStatus.PERSISTED.getStatusNumber(); private boolean passwordExpired = false; private boolean showPasswordExpirationWarning = false; private boolean forceChangeExpiredPassword = false; - /** * Get DB user hash value. It can be used as unique ID for the user. Use hash value for the webservice/ui and do not * expose internal database user identity @@ -117,15 +111,6 @@ public class UserRO extends BaseRO { this.smpLocale = smpLocale; } - public String getAccessTokenId() { - return accessTokenId; - } - - public void setAccessTokenId(String accessTokenId) { - this.accessTokenId = accessTokenId; - } - - public boolean isPasswordExpired() { return passwordExpired; } @@ -143,20 +128,12 @@ public class UserRO extends BaseRO { this.passwordExpireOn = passwordExpireOn; } - public OffsetDateTime getAccessTokenExpireOn() { - return accessTokenExpireOn; + public OffsetDateTime getPasswordUpdatedOn() { + return passwordUpdatedOn; } - public void setAccessTokenExpireOn(OffsetDateTime accessTokenExpireOn) { - this.accessTokenExpireOn = accessTokenExpireOn; - } - - public CertificateRO getCertificate() { - return certificate; - } - - public void setCertificate(CertificateRO certificate) { - this.certificate = certificate; + public void setPasswordUpdatedOn(OffsetDateTime passwordUpdatedOn) { + this.passwordUpdatedOn = passwordUpdatedOn; } public Collection<SMPAuthority> getAuthorities() { @@ -230,28 +207,4 @@ public class UserRO extends BaseRO { public void setSuspendedUtil(OffsetDateTime suspendedUtil) { this.suspendedUtil = suspendedUtil; } - - public Integer getSequentialTokenLoginFailureCount() { - return sequentialTokenLoginFailureCount; - } - - public void setSequentialTokenLoginFailureCount(Integer sequentialTokenLoginFailureCount) { - this.sequentialTokenLoginFailureCount = sequentialTokenLoginFailureCount; - } - - public OffsetDateTime getLastTokenFailedLoginAttempt() { - return lastTokenFailedLoginAttempt; - } - - public void setLastTokenFailedLoginAttempt(OffsetDateTime lastTokenFailedLoginAttempt) { - this.lastTokenFailedLoginAttempt = lastTokenFailedLoginAttempt; - } - - public OffsetDateTime getTokenSuspendedUtil() { - return tokenSuspendedUtil; - } - - public void setTokenSuspendedUtil(OffsetDateTime tokenSuspendedUtil) { - this.tokenSuspendedUtil = tokenSuspendedUtil; - } } diff --git a/smp-server-library/src/main/java/eu/europa/ec/edelivery/smp/services/ui/UIUserService.java b/smp-server-library/src/main/java/eu/europa/ec/edelivery/smp/services/ui/UIUserService.java index 3a5e71bc0d44254f90ef191fde02774a9a8e2f4b..87bc116bec139ca95c9f55f9a16f3777d59ea74f 100644 --- a/smp-server-library/src/main/java/eu/europa/ec/edelivery/smp/services/ui/UIUserService.java +++ b/smp-server-library/src/main/java/eu/europa/ec/edelivery/smp/services/ui/UIUserService.java @@ -94,6 +94,7 @@ public class UIUserService extends UIServiceBase<DBUser, UserRO> { } protected void updateUserStatus(UserRO user) { + /* // never return password even if is hashed... if (user.getCertificate() != null && !StringUtils.isBlank(user.getCertificate().getCertificateId())) { // validate certificate @@ -111,18 +112,8 @@ public class UIUserService extends UIServiceBase<DBUser, UserRO> { } } } - } - public X509Certificate getX509CertificateFromCertificateRO(CertificateRO certificateRO) { - if (certificateRO == null || certificateRO.getEncodedValue() == null) { - return null; - } - try { - return X509CertificateUtils.getX509Certificate(Base64.getMimeDecoder().decode(certificateRO.getEncodedValue())); - } catch (CertificateException e) { - LOG.error("Error occurred while parsing the certificate encoded value for certificate id:[" + certificateRO.getCertificateId() + "].", e); - return null; - } + */ } public AccessTokenRO createAccessTokenForUser(Long userId, CredentialRO credInit) { @@ -397,7 +388,10 @@ public class UIUserService extends UIServiceBase<DBUser, UserRO> { @Transactional(readOnly = true) public UserRO getUserById(Long userId) { DBUser user = userDao.findUser(userId).orElseThrow(() -> new SMPRuntimeException(ErrorCode.USER_NOT_EXISTS)); - return convertToRo(user); + UserRO result = convertToRo(user); + + return result; + } public List<CredentialRO> getUserCredentials(Long userId, diff --git a/smp-server-library/src/test/java/eu/europa/ec/edelivery/smp/conversion/DBUserToUserROConverterTest.java b/smp-server-library/src/test/java/eu/europa/ec/edelivery/smp/conversion/DBUserToUserROConverterTest.java index 306a5c2e3a8f72e37d770b09b2abb34e8368f89e..d8ab5f970eafbc1f8f3e6d229838539a9f49d488 100644 --- a/smp-server-library/src/test/java/eu/europa/ec/edelivery/smp/conversion/DBUserToUserROConverterTest.java +++ b/smp-server-library/src/test/java/eu/europa/ec/edelivery/smp/conversion/DBUserToUserROConverterTest.java @@ -1,5 +1,6 @@ package eu.europa.ec.edelivery.smp.conversion; +import eu.europa.ec.edelivery.smp.data.dao.CredentialDao; import eu.europa.ec.edelivery.smp.data.enums.CredentialType; import eu.europa.ec.edelivery.smp.data.model.user.DBCertificate; import eu.europa.ec.edelivery.smp.data.model.user.DBCredential; @@ -12,6 +13,7 @@ import org.junit.platform.commons.util.StringUtils; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; import org.springframework.core.convert.ConversionService; @@ -32,10 +34,12 @@ public class DBUserToUserROConverterTest { private DBUser source; private UserRO target; + CredentialDao credentialDao = Mockito.mock(CredentialDao.class); + ConfigurationService configurationService = Mockito.mock(ConfigurationService.class); @InjectMocks - private DBUserToUserROConverter converter = new DBUserToUserROConverter(); + private DBUserToUserROConverter converter = new DBUserToUserROConverter(credentialDao, configurationService); @Test public void returnsThePasswordAsNotExpiredForCertificateOnlyUsers() { diff --git a/smp-webapp/src/main/java/eu/europa/ec/edelivery/smp/auth/SMPAuthorizationService.java b/smp-webapp/src/main/java/eu/europa/ec/edelivery/smp/auth/SMPAuthorizationService.java index f0379df693001cf806c6be00f8d69e8ecc9955e1..97009a35fef09e3b772bf0952cfb72093cd2f112 100644 --- a/smp-webapp/src/main/java/eu/europa/ec/edelivery/smp/auth/SMPAuthorizationService.java +++ b/smp-webapp/src/main/java/eu/europa/ec/edelivery/smp/auth/SMPAuthorizationService.java @@ -148,20 +148,6 @@ public class SMPAuthorizationService { SMPUserDetails userDetails = getAndValidateUserDetails(); Long entityId = getIdFromEncryptedString(userId, true); return entityId.equals(userDetails.getUser().getId()); - - } - - public boolean isAuthorizedForManagingTheServiceMetadataGroup(Long serviceMetadataId) { - SMPUserDetails userDetails = getAndValidateUserDetails(); - if (hasSessionUserRole(S_AUTHORITY_TOKEN_USER, userDetails)) { - LOG.debug("SMP admin is authorized to manage service metadata: [{}]", serviceMetadataId); - return true; - - } - Long userId = userDetails.getUser().getId(); - //return serviceGroupService.isServiceGroupOwnerForMetadataID(userId, serviceMetadataId); - return false; - } diff --git a/smp-webapp/src/main/java/eu/europa/ec/edelivery/smp/ui/external/ServiceGroupResource.java b/smp-webapp/src/main/java/eu/europa/ec/edelivery/smp/ui/external/ServiceGroupResource.java deleted file mode 100644 index c0a639a1d59f41aff6a4de4c5499f2a3dfb883a4..0000000000000000000000000000000000000000 --- a/smp-webapp/src/main/java/eu/europa/ec/edelivery/smp/ui/external/ServiceGroupResource.java +++ /dev/null @@ -1,134 +0,0 @@ -package eu.europa.ec.edelivery.smp.ui.external; - - -import eu.europa.ec.edelivery.smp.auth.SMPAuthorizationService; -import eu.europa.ec.edelivery.smp.auth.SMPUserDetails; -import eu.europa.ec.edelivery.smp.data.dao.DomainDao; -import eu.europa.ec.edelivery.smp.data.dao.UserDao; -import eu.europa.ec.edelivery.smp.data.ui.ServiceGroupRO; -import eu.europa.ec.edelivery.smp.data.ui.ServiceGroupValidationRO; -import eu.europa.ec.edelivery.smp.data.ui.ServiceResult; -import eu.europa.ec.edelivery.smp.data.ui.auth.SMPAuthority; -import eu.europa.ec.edelivery.smp.logging.SMPLogger; -import eu.europa.ec.edelivery.smp.logging.SMPLoggerFactory; -import eu.europa.ec.edelivery.smp.services.ui.UIServiceGroupService; -import eu.europa.ec.edelivery.smp.services.ui.filters.ResourceFilter; -import eu.europa.ec.edelivery.smp.ui.ResourceConstants; -import eu.europa.ec.edelivery.smp.utils.SessionSecurityUtils; -import org.apache.commons.lang3.StringUtils; -import org.springframework.security.access.annotation.Secured; -import org.springframework.util.MimeTypeUtils; -import org.springframework.web.bind.annotation.*; - -import java.io.UnsupportedEncodingException; -import java.net.URLDecoder; -import java.util.Arrays; - -import static eu.europa.ec.edelivery.smp.ui.ResourceConstants.*; - -/** - * @author Joze Rihtarsic - * @since 4.1 - */ -@RestController -@RequestMapping(value = ResourceConstants.CONTEXT_PATH_PUBLIC_SERVICE_GROUP) -public class ServiceGroupResource { - - private static final SMPLogger LOG = SMPLoggerFactory.getLogger(ServiceGroupResource.class); - - private final UIServiceGroupService uiServiceGroupService; - private final DomainDao domainDao; - private final UserDao userDao; - private final SMPAuthorizationService authorizationService; - - public ServiceGroupResource(UIServiceGroupService uiServiceGroupService, DomainDao domainDao, UserDao userDao, SMPAuthorizationService authorizationService) { - this.uiServiceGroupService = uiServiceGroupService; - this.domainDao = domainDao; - this.userDao = userDao; - this.authorizationService = authorizationService; - } - - @GetMapping(produces = MimeTypeUtils.APPLICATION_JSON_VALUE) - @Secured({SMPAuthority.S_AUTHORITY_TOKEN_USER}) - public ServiceResult<ServiceGroupRO> getServiceGroupList( - @RequestParam(value = PARAM_PAGINATION_PAGE, defaultValue = "0") int page, - @RequestParam(value = PARAM_PAGINATION_PAGE_SIZE, defaultValue = "10") int pageSize, - @RequestParam(value = PARAM_PAGINATION_ORDER_BY, required = false) String orderBy, - @RequestParam(value = PARAM_PAGINATION_ORDER_TYPE, defaultValue = "asc", required = false) String orderType, - @RequestParam(value = PARAM_QUERY_PARTC_ID, required = false) String participantIdentifier, - @RequestParam(value = PARAM_QUERY_PARTC_SCHEME, required = false) String participantScheme, - @RequestParam(value = PARAM_QUERY_DOMAIN_CODE, required = false) String domainCode) { - - String participantIdentifierDecoded = decodeUrlToUTF8(participantIdentifier); - String participantSchemeDecoded = decodeUrlToUTF8(participantScheme); - String domainCodeDecoded = decodeUrlToUTF8(domainCode); - - LOG.info("Search for page: {}, page size: {}, part. id: {}, part sch: {}, domain {}", page, pageSize, participantIdentifierDecoded, - participantSchemeDecoded, domainCodeDecoded); - ResourceFilter sgf = new ResourceFilter(); - sgf.setIdentifierValueLike(participantIdentifierDecoded); - sgf.setIdentifierSchemeLike(participantSchemeDecoded); - // add domain search parameter - sgf.setDomain(domainDao.validateDomainCode(domainCodeDecoded)); - - // check if logged user is ServiceGroup admin if yes return only his servicegroups - // show all service groups only for SMP Admin - // SMP admin can edit all service groups. For others return only services groups they own. - if (!authorizationService.isSMPAdministrator()) { - authorizationService.getAndValidateUserDetails(); - SMPUserDetails user = SessionSecurityUtils.getSessionUserDetails(); - sgf.setOwner(userDao.find(user.getUser().getId())); - } - return uiServiceGroupService.getTableList(page, pageSize, orderBy, orderType, sgf); - } - - @GetMapping(path = "{serviceGroupId}", produces = MimeTypeUtils.APPLICATION_JSON_VALUE) - @Secured({SMPAuthority.S_AUTHORITY_TOKEN_USER}) - public ServiceGroupRO getServiceGroupById(@PathVariable Long serviceGroupId) { - LOG.info("Get service group [{}]", serviceGroupId); - // SMP administrators are authorized by default - if (authorizationService.isSMPAdministrator()){ - return uiServiceGroupService.getServiceGroupById(serviceGroupId); - } else { - // if not authorized by default check if is it an owner - authorizationService.getAndValidateUserDetails(); - SMPUserDetails user = SessionSecurityUtils.getSessionUserDetails(); - return uiServiceGroupService.getOwnedServiceGroupById(user.getUser().getId(), serviceGroupId); - } - } - - @GetMapping(path = "{service-group-id}/extension", produces = MimeTypeUtils.APPLICATION_JSON_VALUE) - @Secured({SMPAuthority.S_AUTHORITY_TOKEN_USER}) - public ServiceGroupValidationRO getExtensionServiceGroupById(@PathVariable("service-group-id") Long sgId) { - LOG.info("Get service group extension [{}]", sgId); - return uiServiceGroupService.getServiceGroupExtensionById(sgId); - } - - @PostMapping(path = "extension/validate", produces = MimeTypeUtils.APPLICATION_JSON_VALUE) - @Secured({SMPAuthority.S_AUTHORITY_TOKEN_USER}) - public ServiceGroupValidationRO getValidateExtensionService(@RequestBody ServiceGroupValidationRO sg) { - LOG.info("Validate service group extension"); - LOG.debug("Extension: [{}]", sg.getExtension()); - return uiServiceGroupService.validateServiceGroup(sg); - } - - @PutMapping(produces = MimeTypeUtils.APPLICATION_JSON_VALUE) - @Secured({SMPAuthority.S_AUTHORITY_TOKEN_USER}) - public void updateServiceGroupList(@RequestBody ServiceGroupRO[] updateEntities) { - LOG.info("Update ServiceGroupRO count: " + updateEntities.length); - uiServiceGroupService.updateServiceGroupList(Arrays.asList(updateEntities), authorizationService.isSMPAdministrator()); - } - - private String decodeUrlToUTF8(String value) { - if (StringUtils.isBlank(value)) { - return null; - } - try { - return URLDecoder.decode(value, "UTF-8"); - } catch (UnsupportedEncodingException ex) { - LOG.error("Unsupported UTF-8 encoding while converting: " + value, ex); - } - return value; - } -} - diff --git a/smp-webapp/src/main/java/eu/europa/ec/edelivery/smp/ui/external/ServiceMetadataResource.java b/smp-webapp/src/main/java/eu/europa/ec/edelivery/smp/ui/external/ServiceMetadataResource.java deleted file mode 100644 index 6cb5937d3a3541f73d259f83d9b5157dfb2d0bb9..0000000000000000000000000000000000000000 --- a/smp-webapp/src/main/java/eu/europa/ec/edelivery/smp/ui/external/ServiceMetadataResource.java +++ /dev/null @@ -1,47 +0,0 @@ -package eu.europa.ec.edelivery.smp.ui.external; - - -import eu.europa.ec.edelivery.smp.data.ui.auth.SMPAuthority; -import eu.europa.ec.edelivery.smp.data.ui.ServiceMetadataRO; -import eu.europa.ec.edelivery.smp.data.ui.ServiceMetadataValidationRO; -import eu.europa.ec.edelivery.smp.logging.SMPLogger; -import eu.europa.ec.edelivery.smp.logging.SMPLoggerFactory; -import eu.europa.ec.edelivery.smp.services.ui.UIServiceMetadataService; -import eu.europa.ec.edelivery.smp.ui.ResourceConstants; -import org.springframework.security.access.annotation.Secured; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.util.MimeTypeUtils; -import org.springframework.web.bind.annotation.*; - -/** - * @author Joze Rihtarsic - * @since 4.1 - */ - -@RestController -@RequestMapping(value = ResourceConstants.CONTEXT_PATH_PUBLIC_SERVICE_METADATA) -public class ServiceMetadataResource { - - private static final SMPLogger LOG = SMPLoggerFactory.getLogger(ServiceMetadataResource.class); - - final private UIServiceMetadataService uiServiceMetadataService; - - public ServiceMetadataResource(UIServiceMetadataService uiServiceMetadataService) { - this.uiServiceMetadataService = uiServiceMetadataService; - } - - @GetMapping(path = "{serviceMetadataId}", produces = MimeTypeUtils.APPLICATION_JSON_VALUE) - @PreAuthorize("@smpAuthorizationService.isAuthorizedForManagingTheServiceMetadataGroup(#serviceMetadataId)") - public ServiceMetadataRO getServiceGroupMetadataById(@PathVariable Long serviceMetadataId) { - LOG.info("Get service group metadata [{}]", serviceMetadataId); - return uiServiceMetadataService.getServiceMetadataXMLById(serviceMetadataId); - } - - @PostMapping(path = "validate", produces = MimeTypeUtils.APPLICATION_JSON_VALUE) - @Secured({SMPAuthority.S_AUTHORITY_TOKEN_USER}) - public ServiceMetadataValidationRO validateServiceMetadata(@RequestBody ServiceMetadataValidationRO serviceMetadataValidationRO) { - LOG.info("Validate service group metadata"); - return uiServiceMetadataService.validateServiceMetadata(serviceMetadataValidationRO); - } -} - diff --git a/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/auth/SMPAuthorizationServiceTest.java b/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/auth/SMPAuthorizationServiceTest.java index fb225d5fff35949ce69f943204143b0c176d6060..26d550c7afc41c483b5940f07eaa71c7f500adb3 100644 --- a/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/auth/SMPAuthorizationServiceTest.java +++ b/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/auth/SMPAuthorizationServiceTest.java @@ -107,24 +107,6 @@ public class SMPAuthorizationServiceTest { assertTrue(bVal); } - @Test - public void isAuthorizedForManagingTheServiceMetadataGroupSMPAdmin() throws Exception { - // given - SecurityContextHolder.setContext(mockSecurityContextSMPAdmin); - // when then smp admin is always authorized to manage SMP - boolean bVal = testInstance.isAuthorizedForManagingTheServiceMetadataGroup(10L); - assertTrue(bVal); - } - - @Test - public void isAuthorizedForManagingTheServiceMetadataGroupSYSAdmin() throws Exception { - // given - SecurityContextHolder.setContext(mockSecurityContextSystemAdmin); - // when then system admin is not authorized to manage SMP - boolean bVal = testInstance.isAuthorizedForManagingTheServiceMetadataGroup(10L); - assertFalse(bVal); - } - @Test public void testGetUpdatedUserData() { UserRO user = new UserRO(); diff --git a/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/ui/external/ServiceGroupResourceIntegrationTest.java b/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/ui/external/ServiceGroupResourceIntegrationTest.java deleted file mode 100644 index d400daed83c944207203968d0e42fce7a1a5334b..0000000000000000000000000000000000000000 --- a/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/ui/external/ServiceGroupResourceIntegrationTest.java +++ /dev/null @@ -1,195 +0,0 @@ -package eu.europa.ec.edelivery.smp.ui.external; - -import com.fasterxml.jackson.databind.ObjectMapper; -import eu.europa.ec.edelivery.smp.data.dao.ResourceDao; -import eu.europa.ec.edelivery.smp.data.model.doc.DBResource; -import eu.europa.ec.edelivery.smp.data.ui.ServiceGroupRO; -import eu.europa.ec.edelivery.smp.data.ui.ServiceGroupValidationRO; -import eu.europa.ec.edelivery.smp.data.ui.ServiceResult; -import eu.europa.ec.edelivery.smp.test.SmpTestWebAppConfig; -import eu.europa.ec.edelivery.smp.test.testutils.MockMvcUtils; -import eu.europa.ec.edelivery.smp.ui.ResourceConstants; -import org.apache.commons.io.IOUtils; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.mock.web.MockHttpSession; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.jdbc.Sql; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.context.web.WebAppConfiguration; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.MvcResult; -import org.springframework.web.context.WebApplicationContext; - -import java.io.IOException; -import java.util.Arrays; - -import static eu.europa.ec.edelivery.smp.test.testutils.MockMvcUtils.*; -import static org.junit.Assert.*; -import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; -import static org.springframework.test.context.jdbc.Sql.ExecutionPhase.BEFORE_TEST_METHOD; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -/** - * @author Joze Rihtarsic - * @since 4.1 - */ -@RunWith(SpringRunner.class) -@WebAppConfiguration -@ContextConfiguration(classes = {SmpTestWebAppConfig.class}) -@Sql(scripts = { - "classpath:/cleanup-database.sql", - "classpath:/webapp_integration_test_data.sql"}, - executionPhase = BEFORE_TEST_METHOD) -public class ServiceGroupResourceIntegrationTest { - - @Autowired - ResourceDao serviceGroupDao; - - private static final String PATH_PUBLIC = ResourceConstants.CONTEXT_PATH_PUBLIC_SERVICE_GROUP; - - private static final String IDENTIFIER_VALUE = "urn:australia:ncpb"; - private static final String IDENTIFIER_SCHEME = "ehealth-actorid-qns"; - - private String validExtension = null; - - @Autowired - private WebApplicationContext webAppContext; - - private MockMvc mvc; - @Before - public void setup() throws IOException { - mvc = MockMvcUtils.initializeMockMvc(webAppContext); - validExtension = new String(IOUtils.toByteArray(ServiceGroupResourceIntegrationTest.class.getResourceAsStream("/input/extensionMarshal.xml"))); - } - - @Test - public void getServiceGroupListForSMPAdmin() throws Exception { - // given when - MockHttpSession sessionAdmin = loginWithUserGroupAdmin(mvc); - MvcResult result = mvc.perform(get(PATH_PUBLIC) - .session(sessionAdmin).with(csrf()) - ).andExpect(status().isOk()).andReturn(); - - //them - ObjectMapper mapper = new ObjectMapper(); - ServiceResult res = mapper.readValue(result.getResponse().getContentAsString(), ServiceResult.class); - - - assertNotNull(res); - assertEquals(2, res.getServiceEntities().size()); - res.getServiceEntities().forEach(sgMap -> { - ServiceGroupRO sgro = mapper.convertValue(sgMap, ServiceGroupRO.class); - assertNotNull(sgro.getId()); - assertNotNull(sgro.getParticipantScheme()); - assertNotNull(sgro.getParticipantIdentifier()); - }); - } - - @Test - public void getServiceGroupListForServiceGroupAdmin() throws Exception { - // given when - MockHttpSession sessionAdmin = loginWithUserGroupAdmin(mvc); - MvcResult result = mvc.perform(get(PATH_PUBLIC) - .session(sessionAdmin).with(csrf()) - ).andExpect(status().isOk()).andReturn(); - - //them - ObjectMapper mapper = new ObjectMapper(); - ServiceResult res = mapper.readValue(result.getResponse().getContentAsString(), ServiceResult.class); - - assertNotNull(res); - assertFalse(res.getServiceEntities().isEmpty()); - res.getServiceEntities().forEach(sgMap -> { - ServiceGroupRO sgro = mapper.convertValue(sgMap, ServiceGroupRO.class); - assertNotNull(sgro.getId()); - assertNotNull(sgro.getParticipantScheme()); - assertNotNull(sgro.getParticipantIdentifier()); - assertTrue(Arrays.asList("urn:australia:ncpb","urn:brazil:ncpb").contains(sgro.getParticipantIdentifier())); - }); - } - - @Test - public void getServiceGroupById() throws Exception { - // given when - MockHttpSession sessionAdmin = loginWithUserGroupAdmin(mvc); - MvcResult result = mvc.perform(get(PATH_PUBLIC + "/100000") - .session(sessionAdmin).with(csrf())). - andExpect(status().isOk()).andReturn(); - - //them - ObjectMapper mapper = new ObjectMapper(); - ServiceGroupRO res = mapper.readValue(result.getResponse().getContentAsString(), ServiceGroupRO.class); - - assertNotNull(res); - assertEquals(100000, res.getId().intValue()); - assertEquals(IDENTIFIER_VALUE, res.getParticipantIdentifier()); - assertEquals(IDENTIFIER_SCHEME, res.getParticipantScheme()); - assertEquals(1, res.getServiceMetadata().size()); - assertEquals("doc_7", res.getServiceMetadata().get(0).getDocumentIdentifier()); - } - - @Test - public void getExtensionServiceGroupById() throws Exception { -/* - DBResource sg = serviceGroupDao.findServiceGroup(IDENTIFIER_VALUE, IDENTIFIER_SCHEME).get(); - sg.setExtension(validExtension.getBytes()); - serviceGroupDao.update(sg); - - // given when - MockHttpSession sessionAdmin = loginWithUserGroupAdmin(mvc); - MvcResult result = mvc.perform(get(PATH_PUBLIC + "/100000/extension") - .session(sessionAdmin).with(csrf())) - .andExpect(status().isOk()).andReturn(); - - //them - ObjectMapper mapper = new ObjectMapper(); - ServiceGroupValidationRO res = mapper.readValue(result.getResponse().getContentAsString(), ServiceGroupValidationRO.class); - - assertNotNull(res); - assertEquals(100000, res.getServiceGroupId().longValue()); - assertEquals(IDENTIFIER_VALUE, res.getParticipantIdentifier()); - assertEquals(IDENTIFIER_SCHEME, res.getParticipantScheme()); - assertEquals(new String(sg.getExtension()), res.getExtension()); - - */ - } - - @Test - public void getExtensionServiceGroupByIdNotAuthorizedBasicAuthentication() throws Exception { - // given when - MvcResult result = mvc.perform(get(PATH_PUBLIC + "/100000/extension") - .with(getHttpBasicSMPAdminCredentials()).with(csrf())) - .andExpect(status().isUnauthorized()).andReturn(); - } - - @Test - @Ignore - public void testValidateInvalid() throws Exception { - ObjectMapper mapper = new ObjectMapper(); - ServiceGroupValidationRO validate = new ServiceGroupValidationRO(); - validate.setExtension(validExtension + "<ADFA>sdfadsf"); - - // given when - MockHttpSession sessionAdmin = loginWithUserGroupAdmin(mvc); - MvcResult result = mvc.perform(post(PATH_PUBLIC + "/extension/validate") - .session(sessionAdmin) - .header("Content-Type","application/json") - .content(mapper.writeValueAsString(validate)) - .with(csrf())) - .andExpect(status().isOk()).andReturn(); - - //then - ServiceGroupValidationRO res = mapper.readValue(result.getResponse().getContentAsString(), ServiceGroupValidationRO.class); - - assertNotNull(res); - assertNotNull(res.getErrorMessage()); - } - - -} diff --git a/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/ui/external/ServiceMetadataResourceIntegrationTest.java b/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/ui/external/ServiceMetadataResourceIntegrationTest.java deleted file mode 100644 index 2f1564bc33bf2bf53e90a8f046386ef6ae4ecfe8..0000000000000000000000000000000000000000 --- a/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/ui/external/ServiceMetadataResourceIntegrationTest.java +++ /dev/null @@ -1,139 +0,0 @@ -package eu.europa.ec.edelivery.smp.ui.external; - -import com.fasterxml.jackson.databind.ObjectMapper; -import eu.europa.ec.edelivery.smp.data.ui.ServiceMetadataRO; -import eu.europa.ec.edelivery.smp.data.ui.ServiceMetadataValidationRO; -import eu.europa.ec.edelivery.smp.test.SmpTestWebAppConfig; -import eu.europa.ec.edelivery.smp.test.testutils.MockMvcUtils; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.mock.web.MockHttpSession; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.jdbc.Sql; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.context.web.WebAppConfiguration; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.MvcResult; -import org.springframework.web.context.WebApplicationContext; - -import javax.ws.rs.core.MediaType; - -import static eu.europa.ec.edelivery.smp.test.testutils.MockMvcUtils.*; -import static eu.europa.ec.edelivery.smp.ui.ResourceConstants.CONTEXT_PATH_PUBLIC_SERVICE_METADATA; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; -import static org.springframework.test.context.jdbc.Sql.ExecutionPhase.BEFORE_TEST_METHOD; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -@RunWith(SpringRunner.class) -@WebAppConfiguration -@ContextConfiguration(classes = {SmpTestWebAppConfig.class}) -@Sql(scripts = { - "classpath:/cleanup-database.sql", - "classpath:/webapp_integration_test_data.sql"}, - executionPhase = BEFORE_TEST_METHOD) -@Ignore -public class ServiceMetadataResourceIntegrationTest { - - - // For the following test data see the: webapp_integration_test_data.sql - private static final Long SERVICE_METADATA_ID = 1000L; - private static final String DOC_IDENTIFIER = "doc_7"; - private static final String DOC_SCHEME = "busdox-docid-qns"; - - - @Autowired - private WebApplicationContext webAppContext; - - private MockMvc mvc; - ObjectMapper mapper = new ObjectMapper(); - - @Before - public void setup() { - mvc = MockMvcUtils.initializeMockMvc(webAppContext); - } - - @Test - public void getServiceGroupMetadataById() throws Exception { - // given when - MockHttpSession sessionAdmin = loginWithUserGroupAdmin(mvc); - MvcResult result = mvc.perform(get(CONTEXT_PATH_PUBLIC_SERVICE_METADATA + "/" + SERVICE_METADATA_ID) - .session(sessionAdmin).with(csrf()) - ).andExpect(status().isOk()).andReturn(); - - //them - ObjectMapper mapper = new ObjectMapper(); - ServiceMetadataRO res = mapper.readValue(result.getResponse().getContentAsString(), ServiceMetadataRO.class); - - assertNotNull(res); - assertNotNull(res.getXmlContent()); - assertEquals(SERVICE_METADATA_ID, res.getId()); - assertEquals(DOC_IDENTIFIER, res.getDocumentIdentifier()); - assertEquals(DOC_SCHEME, res.getDocumentIdentifierScheme()); - } - - @Test - public void getServiceGroupMetadataByIdNotAuthorized() throws Exception { - // given when - MockHttpSession session = loginWithUser2(mvc); - MvcResult result = mvc.perform(get(CONTEXT_PATH_PUBLIC_SERVICE_METADATA + "/" + SERVICE_METADATA_ID) - .session(session).with(csrf()) - ).andExpect(status().isUnauthorized()).andReturn(); - } - - @Test - public void getServiceGroupMetadataByIdNotAuthorizedForBasicAuthentication() throws Exception { - // given when - MvcResult result = mvc.perform(get(CONTEXT_PATH_PUBLIC_SERVICE_METADATA + "/" + SERVICE_METADATA_ID) - .with(getHttpBasicSMPAdminCredentials()).with(csrf()) - ).andExpect(status().isUnauthorized()).andReturn(); - } - - @Test - public void validateServiceMetadataUnauthorized() throws Exception { - ServiceMetadataValidationRO smv = new ServiceMetadataValidationRO(); - smv.setDocumentIdentifier("documentId"); - smv.setDocumentIdentifierScheme("documentScheme"); - smv.setParticipantIdentifier("partId"); - smv.setParticipantScheme("partSch"); - smv.setXmlContent("Invalid content"); - - mvc.perform(post(CONTEXT_PATH_PUBLIC_SERVICE_METADATA + "/validate") - .with(csrf()) - .contentType(MediaType.APPLICATION_JSON) - .content(mapper.writeValueAsString(smv)) - ).andExpect(status().isUnauthorized()).andReturn(); - } - - @Test - @Ignore - public void validateServiceMetadata() throws Exception { - ServiceMetadataValidationRO smv = new ServiceMetadataValidationRO(); - smv.setDocumentIdentifier("documentId"); - smv.setDocumentIdentifierScheme("documentScheme"); - smv.setParticipantIdentifier("partId"); - smv.setParticipantScheme("partSch"); - smv.setXmlContent("Invalid content"); - - MockHttpSession session = loginWithUserGroupAdmin(mvc); - - MvcResult result = mvc.perform(post(CONTEXT_PATH_PUBLIC_SERVICE_METADATA + "/validate") - .session(session) - .with(csrf()) - .contentType(MediaType.APPLICATION_JSON) - .content(mapper.writeValueAsString(smv)) - ).andExpect(status().isOk()).andReturn(); - - - ServiceMetadataValidationRO res = mapper.readValue(result.getResponse().getContentAsString(), - ServiceMetadataValidationRO.class); - - assertEquals("SAXParseException: Content is not allowed in prolog.", res.getErrorMessage()); - } -} diff --git a/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/ui/external/UserResourceIntegrationTest.java b/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/ui/external/UserResourceIntegrationTest.java index 802262a5b66e415bb231007dbb76e1b9eb50100a..f88ad1bff9ef8772913decbdd764eec66718a253 100644 --- a/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/ui/external/UserResourceIntegrationTest.java +++ b/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/ui/external/UserResourceIntegrationTest.java @@ -71,10 +71,7 @@ public class UserResourceIntegrationTest { UserRO userRO = getLoggedUserData(mvc, session); userRO.setActive(!userRO.isActive()); userRO.setEmailAddress("test@mail.com"); - if (userRO.getCertificate() == null) { - userRO.setCertificate(new CertificateRO()); - } - userRO.getCertificate().setCertificateId(UUID.randomUUID().toString()); + mvc.perform(put(PATH_PUBLIC + "/" + userRO.getUserId()) .with(csrf()) .session(session) @@ -94,10 +91,7 @@ public class UserResourceIntegrationTest { // when userRO.setActive(!userRO.isActive()); userRO.setEmailAddress("test@mail.com"); - if (userRO.getCertificate() == null) { - userRO.setCertificate(new CertificateRO()); - } - userRO.getCertificate().setCertificateId(UUID.randomUUID().toString()); + mvc.perform(put(PATH_PUBLIC + "/" + userRO.getUserId()) .with(getHttpBasicSystemAdminCredentials()) // authenticate with system admin @@ -129,10 +123,7 @@ public class UserResourceIntegrationTest { UserRO updateUserData = mapper.readValue(resultUser.getResponse().getContentAsString(), UserRO.class); AccessTokenRO resAccessToken = mapper.readValue(result.getResponse().getContentAsString(), AccessTokenRO.class); assertNotNull(resAccessToken); - assertNotEquals(userRO.getAccessTokenId(), resAccessToken.getIdentifier()); - assertNotEquals(userRO.getAccessTokenExpireOn(), resAccessToken.getExpireOn()); - assertEquals(updateUserData.getAccessTokenId(), resAccessToken.getIdentifier()); - assertEquals(updateUserData.getAccessTokenExpireOn(), resAccessToken.getExpireOn()); + } @Test