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

Integration of Google reCAPTCHA into DSpace Feedback Form #3101 #3369

Open
wants to merge 17 commits into
base: main
Choose a base branch
from
Open
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
40 changes: 39 additions & 1 deletion src/app/core/feedback/feedback-data.service.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
import { HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Store } from '@ngrx/store';
import { Observable } from 'rxjs';
import {
find,
map,
Observable,
} from 'rxjs';
import { hasValue } from 'src/app/shared/empty.util';

import { NotificationsService } from '../../shared/notifications/notifications.service';
import { RemoteDataBuildService } from '../cache/builders/remote-data-build.service';
Expand All @@ -12,9 +18,12 @@ import {
} from '../data/base/create-data';
import { IdentifiableDataService } from '../data/base/identifiable-data.service';
import { RemoteData } from '../data/remote-data';
import { PostRequest } from '../data/request.models';
import { RequestService } from '../data/request.service';
import { HttpOptions } from '../dspace-rest/dspace-rest.service';
import { HALEndpointService } from '../shared/hal-endpoint.service';
import {
getFirstCompletedRemoteData,
getFirstSucceededRemoteData,
getRemoteDataPayload,
} from '../shared/operators';
Expand Down Expand Up @@ -61,4 +70,33 @@ export class FeedbackDataService extends IdentifiableDataService<Feedback> imple
public create(object: Feedback, ...params: RequestParam[]): Observable<RemoteData<Feedback>> {
return this.createData.create(object, ...params);
}

/**
* Create a new object on the server, and store the response in the object cache
*
* @param object The object to create
* @param captchaToken ReCaptchaToken if the verification is enabled
*/
public registerFeedback(object: Feedback, captchaToken: string = null): Observable<RemoteData<Feedback>> {
let headers = new HttpHeaders();
const options: HttpOptions = Object.create({});
if (captchaToken) {
headers = headers.append('X-Recaptcha-Token', captchaToken);
}
options.headers = headers;
const requestId = this.requestService.generateRequestId();


this.getEndpoint().pipe(
find((href: string) => hasValue(href)),
map((href: string) => {
const request = new PostRequest(requestId, href, object, options);
this.requestService.send(request);
}),
).subscribe();

return this.rdbService.buildFromRequestUUID<Feedback>(requestId).pipe(
getFirstCompletedRemoteData(),
);
}
}
18 changes: 15 additions & 3 deletions src/app/core/google-recaptcha/google-recaptcha.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
import {
BehaviorSubject,
combineLatest,
combineLatest as observableCombineLatest,
EMPTY,
Observable,
of,
Expand All @@ -32,6 +33,7 @@ import { getFirstCompletedRemoteData } from '../shared/operators';

export const CAPTCHA_COOKIE = '_GRECAPTCHA';
export const CAPTCHA_NAME = 'google-recaptcha';
export const CAPTCHA_FEEDBACK_NAME = 'google-recaptcha-feedback';

/**
* A GoogleRecaptchaService used to send action and get a token from REST
Expand Down Expand Up @@ -86,8 +88,15 @@ export class GoogleRecaptchaService {
return res.hasSucceeded && res.payload && isNotEmpty(res.payload.values) && res.payload.values[0].toLowerCase() === 'true';
}),
);
registrationVerification$.pipe(
switchMap((registrationVerification: boolean) => registrationVerification ? this.loadRecaptchaProperties() : EMPTY),
const feedBackVerification$ = this.configService.findByPropertyName('feedback.verification.enabled').pipe(
take(1),
getFirstCompletedRemoteData(),
map((res: RemoteData<ConfigurationProperty>) => {
return res.hasSucceeded && res.payload && isNotEmpty(res.payload.values) && res.payload.values[0].toLowerCase() === 'true';
}),
);
observableCombineLatest([registrationVerification$,feedBackVerification$]).pipe(
switchMap(([registrationVerification ,feedBackVerification]) => (registrationVerification || feedBackVerification) ? this.loadRecaptchaProperties() : EMPTY),
).subscribe();
}

Expand All @@ -105,7 +114,10 @@ export class GoogleRecaptchaService {
tap(([recaptchaVersionRD, recaptchaModeRD, recaptchaKeyRD]) => {

if (
this.cookieService.get('klaro-anonymous') && this.cookieService.get('klaro-anonymous')[CAPTCHA_NAME] &&
this.cookieService.get('klaro-anonymous') &&
(this.cookieService.get('klaro-anonymous')[CAPTCHA_NAME] || this.cookieService.get('klaro-anonymous')[CAPTCHA_FEEDBACK_NAME])
&&

recaptchaKeyRD.hasSucceeded && recaptchaVersionRD.hasSucceeded &&
isNotEmpty(recaptchaVersionRD.payload?.values) && isNotEmpty(recaptchaKeyRD.payload?.values)
) {
Expand Down
28 changes: 23 additions & 5 deletions src/app/info/feedback/feedback-form/feedback-form.component.html
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
<div class="col-xs-12 col-sm-12 col-md-9">
<h1>{{ 'info.feedback.head' | translate }}</h1>
<p>{{ 'info.feedback.info' | translate }}</p>
<form [formGroup]="feedbackForm" (ngSubmit)="createFeedback()" class="col p-0">
<form [formGroup]="feedbackForm" (ngSubmit)="send()" class="col p-0">
<div class="row mt-3">
<div class="control-group col-sm-12">
<label class="control-label" for="email">{{ 'info.feedback.email-label' | translate }}&nbsp;</label>
Expand Down Expand Up @@ -38,12 +38,30 @@ <h1>{{ 'info.feedback.head' | translate }}</h1>
<small class="text-muted">{{ 'info.feedback.page_help' | translate }}</small>
</div>
</div>
<ds-alert [type]="AlertTypeEnum.Warning" *ngIf="registrationVerification && !isRecaptchaCookieAccepted()">
<p class="m-0" [innerHTML]="MESSAGE_PREFIX + '.google-recaptcha.must-accept-cookies' | translate"></p>
<p class="m-0"><a href="javascript:void(0);" (click)="this.klaroService.showSettings()">{{ MESSAGE_PREFIX + '.google-recaptcha.open-cookie-settings' | translate }}</a></p>
</ds-alert>

<div class="row mt-3">
<div class="control-group col-sm-12 text-right">
<button [disabled]="!feedbackForm.valid" class="btn btn-primary" name="submit" type="submit">{{ 'info.feedback.send' | translate }}</button>
</div>
<div class="my-3" *ngIf="isRecaptchaCookieAccepted() && (googleRecaptchaService.captchaVersion() | async) === 'v2'">
<ds-google-recaptcha [captchaMode]="(googleRecaptchaService.captchaMode() | async)"
(executeRecaptcha)="send($event)" (checkboxChecked)="onCheckboxChecked($event)"
(showNotification)="showNotification($event)"></ds-google-recaptcha>
</div>

<ng-container *ngIf="(!registrationVerification || ((googleRecaptchaService.captchaVersion() | async) !== 'v2' && (googleRecaptchaService.captchaMode() | async) === 'invisible')); else v2Invisible">
<button type="submit" class="btn btn-primary" [disabled]="feedbackForm.invalid || registrationVerification && !isRecaptchaCookieAccepted() || disableUntilChecked">
{{ MESSAGE_PREFIX + '.submit' | translate }}
</button>
</ng-container>

<ng-template #v2Invisible>
<div class="row mt-3">
<div class="control-group col-sm-12 text-right">
<button [disabled]="feedbackForm.invalid" (click)="executeRecaptcha()" class="btn btn-primary" name="submit" type="submit">{{ 'info.feedback.send' | translate }}</button>
</div>
</div>
</ng-template>
</form>
</div>
</div>
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,17 @@ import { TranslateModule } from '@ngx-translate/core';
import { of } from 'rxjs';

import { AuthService } from '../../../core/auth/auth.service';
import { ConfigurationDataService } from '../../../core/data/configuration-data.service';
import { FeedbackDataService } from '../../../core/feedback/feedback-data.service';
import { Feedback } from '../../../core/feedback/models/feedback.model';
import { GoogleRecaptchaService } from '../../../core/google-recaptcha/google-recaptcha.service';
import { CookieService } from '../../../core/services/cookie.service';
import { RouteService } from '../../../core/services/route.service';
import { NativeWindowService } from '../../../core/services/window.service';
import { CookieServiceMock } from '../../../shared/mocks/cookie.service.mock';
import { NativeWindowMockFactory } from '../../../shared/mocks/mock-native-window-ref';
import { RouterMock } from '../../../shared/mocks/router.mock';
import { NotificationsService } from '../../../shared/notifications/notifications.service';
import { createSuccessfulRemoteDataObject$ } from '../../../shared/remote-data.utils';
import { AuthServiceStub } from '../../../shared/testing/auth-service.stub';
import { EPersonMock } from '../../../shared/testing/eperson.mock';
import { NotificationsServiceStub } from '../../../shared/testing/notifications-service.stub';
Expand All @@ -33,14 +37,31 @@ describe('FeedbackFormComponent', () => {
let fixture: ComponentFixture<FeedbackFormComponent>;
let de: DebugElement;
const notificationService = new NotificationsServiceStub();
const feedbackDataServiceStub = jasmine.createSpyObj('feedbackDataService', {
create: of(new Feedback()),


const feedbackDataService = jasmine.createSpyObj('feedbackDataService', {
registerFeedback: createSuccessfulRemoteDataObject$({}),
});
const captchaVersion$ = of('v3');
const captchaMode$ = of('invisible');
const confFeedbackVerificationEnabled$ = createSuccessfulRemoteDataObject$({ values: ['false'] });
const authService: AuthServiceStub = Object.assign(new AuthServiceStub(), {
getAuthenticatedUserFromStore: () => {
return of(EPersonMock);
},
});

const configurationDataService = jasmine.createSpyObj('configurationDataService', {
findByPropertyName: jasmine.createSpy('findByPropertyName'),
});

const googleRecaptchaService = jasmine.createSpyObj('googleRecaptchaService', {
getRecaptchaToken: Promise.resolve('googleRecaptchaToken'),
executeRecaptcha: Promise.resolve('googleRecaptchaToken'),
getRecaptchaTokenResponse: Promise.resolve('googleRecaptchaToken'),
captchaVersion: captchaVersion$,
captchaMode: captchaMode$,
});
const routerStub = new RouterMock();

beforeEach(waitForAsync(() => {
Expand All @@ -50,10 +71,13 @@ describe('FeedbackFormComponent', () => {
{ provide: RouteService, useValue: routeServiceStub },
{ provide: UntypedFormBuilder, useValue: new UntypedFormBuilder() },
{ provide: NotificationsService, useValue: notificationService },
{ provide: FeedbackDataService, useValue: feedbackDataServiceStub },
{ provide: FeedbackDataService, useValue: feedbackDataService },
{ provide: AuthService, useValue: authService },
{ provide: NativeWindowService, useFactory: NativeWindowMockFactory },
{ provide: Router, useValue: routerStub },
{ provide: CookieService, useValue: new CookieServiceMock() },
{ provide: GoogleRecaptchaService, useValue: googleRecaptchaService },
{ provide: ConfigurationDataService, useValue: configurationDataService },
],
schemas: [NO_ERRORS_SCHEMA],
}).compileComponents();
Expand All @@ -63,6 +87,9 @@ describe('FeedbackFormComponent', () => {
fixture = TestBed.createComponent(FeedbackFormComponent);
component = fixture.componentInstance;
de = fixture.debugElement;
googleRecaptchaService.captchaVersion$ = captchaVersion$;
googleRecaptchaService.captchaMode$ = captchaMode$;
configurationDataService.findByPropertyName.and.returnValues(confFeedbackVerificationEnabled$);
fixture.detectChanges();
});

Expand Down Expand Up @@ -96,7 +123,7 @@ describe('FeedbackFormComponent', () => {
it('on submit should call createFeedback of feedbackDataServiceStub service', () => {
component.createFeedback();
fixture.detectChanges();
expect(feedbackDataServiceStub.create).toHaveBeenCalled();
expect(feedbackDataService.registerFeedback).toHaveBeenCalled();
});
});

Expand Down
Loading
Loading