Skip to content

Commit

Permalink
Merge pull request #405 from PavlidisLab/feature-recaptcha-and-email-…
Browse files Browse the repository at this point in the history
…validation

Add reCAPTCHA and email domain validation
  • Loading branch information
arteymix authored Dec 15, 2023
2 parents ec54d98 + 8f5adc6 commit be0db80
Show file tree
Hide file tree
Showing 21 changed files with 1,023 additions and 24 deletions.
62 changes: 54 additions & 8 deletions docs/customization.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,50 @@
# Customize your instance

This section contains instruction to customize your RDP registry.

## Allowed email providers (new in 1.5.8)

You may restrict which email providers can be used for creating new accounts by specifying a list or a file
containing allowed domains. Matches are performed in a case-insensitive manner. Only printable ASCII characters are
allowed.

```ini
rdp.settings.allowed-email-domains=example.com
rdp.settings.allowed-email-domains-file=file:swot.txt
rdp.settings.allowed-email-domains-file-refresh-delay=3600
```

The default refresh delay is set to one hour. Disable it by setting it to an empty value. A value of `0` will cause a
refresh on every validation.

This feature is disabled by default.

### Internationalized domain names

To use [internationalized domain names](https://en.wikipedia.org/wiki/Internationalized_domain_name) in email addresses,
add their Punycode to the list or file and set the following setting:

```ini
rdp.settings.allow-internationalized-email-domains=true
```

For example, to allow users from `universität.example.com` to register, add `xn--universitt-y5a.example.com` to the
file.

## reCAPTCHA (new in 1.5.8)

RDP supports [reCAPTCHA v2](https://www.google.com/recaptcha/about/) to mitigate the registration of accounts by bots.
To enable it, add the reCAPTCHA token and secret to your configuration.

```ini
rdp.site.recaptcha-token=mytoken
rdp.site.recaptcha-secret=mysecret
```

This feature is disabled by default.

## Cached data

Most of the data used by the application is retrieved remotely at startup and subsequently updated on a monthly basis.

To prevent data from being loaded on startup and/or recurrently, set the following parameter in
Expand All @@ -12,6 +57,8 @@ rdp.settings.cache.enabled=false
You should deploy your RDP instance at least once to have initial data before setting this property and whenever you
update the software.

The following sections will cover in details individual data sources that can be imported in your registry.

## Gene information and GO terms

By default, RDP will retrieve the latest gene information from NCBI, and GO terms
Expand Down Expand Up @@ -271,19 +318,20 @@ The page lists some basic stats at the very top and provides few action buttons:

![Actions available for simple categories.](images/simple-category-actions.png)

- "Deactivate" (or "Deactivate All Terms" in the case of an ontology category): this will remove the category from the Profile and Search pages. This action is reversible, as the category can be easily re-activated. This action is recommended in cases where a category cannot be deleted because it has already been used by some users.
- "Deactivate" (or "Deactivate All Terms" in the case of an ontology category): this will remove the category from the
Profile and Search pages. This action is reversible, as the category can be easily re-activated. This action is
recommended in cases where a category cannot be deleted because it has already been used by some users.

- Update from "source": Update the ontology category using the original URL (if available)

- Download as OBO: Download the category as an OBO file



The number of used terms indicate how many terms in the ontology have been associated with associated with users.

In the Edit window on the Manage Profile Category page, you can add a definition/description of the category, which
is used in a tooltip on the Profile Page. You can also specify if this category will be used as a filter on the Gene
Search page. While all active categories will be available on the Researcher Search page, only categories that have "Available for gene search?" checked will be displayed on the Gene Search page.
Search page. While all active categories will be available on the Researcher Search page, only categories that have "
Available for gene search?" checked will be displayed on the Gene Search page.

![Interface for editing the properties of an ontology.](images/edit-an-ontology.png)

Expand Down Expand Up @@ -348,8 +396,6 @@ values. A warning will be displayed in the admin section if this is the case.
Read more about configuring messages in [Customizing the application messages](#customizing-the-applications-messages)
section of this page.



### Resolving external URLs

By default, ontologies and terms are resolved from [OLS](https://www.ebi.ac.uk/ols/index). Reactome pathways get a
Expand Down Expand Up @@ -402,7 +448,6 @@ settings will retrieve all the necessary files relative to the working directory
#this setting relates only to gene info files. Files for all taxons will be stord under gene/
rdp.settings.cache.load-from-disk=true
rdp.settings.cache.gene-files-location=file:genes/

#file for GO ontology
rdp.settings.cache.term-file=file:go.obo
#file for gene GO annotation
Expand Down Expand Up @@ -537,7 +582,8 @@ rdp.faq.questions.<q_key>=A relevant question.
rdp.faq.answers.<q_key>=A plausible answer.
```

The provided default file can be found in [faq.properties](https://github.com/PavlidisLab/rdp/tree/{{ config.extra.git_ref }}/src/main/resources/faq.properties).
The provided default file can be found in [faq.properties](https://github.com/PavlidisLab/rdp/tree/{{
config.extra.git_ref }}/src/main/resources/faq.properties).

### Ordering FAQ entries

Expand Down
75 changes: 75 additions & 0 deletions src/main/java/ubc/pavlab/rdp/ValidationConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
package ubc.pavlab.rdp;

import lombok.extern.apachecommons.CommonsLog;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.convert.DurationUnit;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.http.converter.FormHttpMessageConverter;
import org.springframework.web.client.RestTemplate;
import ubc.pavlab.rdp.validation.*;

import java.io.IOException;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
* This configuration provides a few {@link org.springframework.validation.Validator} beans.
*/
@CommonsLog
@Configuration
public class ValidationConfig {

@Bean
public EmailValidator emailValidator(
@Value("${rdp.settings.allowed-email-domains}") List<String> allowedEmailDomains,
@Value("${rdp.settings.allowed-email-domains-file}") Resource allowedEmailDomainsFile,
@Value("${rdp.settings.allowed-email-domains-file-refresh-delay}") @DurationUnit(ChronoUnit.SECONDS) Duration refreshDelay,
@Value("${rdp.settings.allow-internationalized-email-domains}") boolean allowIdn ) throws IOException {
List<AllowedDomainStrategy> strategies = new ArrayList<>();
if ( allowedEmailDomains != null && !allowedEmailDomains.isEmpty() ) {
SetBasedAllowedDomainStrategy strategy = new SetBasedAllowedDomainStrategy( allowedEmailDomains );
strategies.add( strategy );
log.info( String.format( "Email validation is configured to accept addresses from: %s.", String.join( ", ",
strategy.getAllowedDomains() ) ) );
}
if ( allowedEmailDomainsFile != null ) {
log.info( "Reading allowed email domains from " + allowedEmailDomainsFile + "..." );
if ( refreshDelay.isZero() ) {
log.warn( "The refresh delay for reading " + allowedEmailDomainsFile + " is set to zero: the file will be re-read for every email domain validation." );
}
ResourceBasedAllowedDomainStrategy strategy = new ResourceBasedAllowedDomainStrategy( allowedEmailDomainsFile, refreshDelay );
strategy.refresh();
Set<String> allowedDomains = strategy.getAllowedDomains();
strategies.add( strategy );
if ( strategy.getAllowedDomains().size() <= 5 ) {
log.info( String.format( "Email validation is configured to accept addresses from: %s.", String.join( ", ", allowedDomains ) ) );
} else {
log.info( String.format( "Email validation is configured to accept addresses from a list of %d domains.", allowedDomains.size() ) );
}
}
AllowedDomainStrategy strategy;
if ( strategies.isEmpty() ) {
strategy = ( domain ) -> true;
log.warn( "No allowed email domains file specified, all domains will be allowed for newly registered users." );
} else if ( strategies.size() == 1 ) {
strategy = strategies.iterator().next();
} else {
strategy = domain -> strategies.stream().anyMatch( s -> s.allows( domain ) );
}
return new EmailValidator( strategy, allowIdn );
}

@Bean
@ConditionalOnProperty("rdp.site.recaptcha-secret")
public RecaptchaValidator recaptchaValidator( @Value("${rdp.site.recaptcha-secret}") String secret ) {
RestTemplate rt = new RestTemplate();
rt.getMessageConverters().add( new FormHttpMessageConverter() );
return new RecaptchaValidator( rt, secret );
}
}
81 changes: 76 additions & 5 deletions src/main/java/ubc/pavlab/rdp/controllers/LoginController.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,16 @@

import lombok.extern.apachecommons.CommonsLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.*;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import ubc.pavlab.rdp.exception.TokenException;
Expand All @@ -24,9 +22,14 @@
import ubc.pavlab.rdp.services.PrivacyService;
import ubc.pavlab.rdp.services.UserService;
import ubc.pavlab.rdp.settings.ApplicationSettings;
import ubc.pavlab.rdp.validation.EmailValidator;
import ubc.pavlab.rdp.validation.Recaptcha;
import ubc.pavlab.rdp.validation.RecaptchaValidator;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;

/**
* Created by mjacobson on 16/01/18.
Expand All @@ -44,9 +47,43 @@ public class LoginController {
@Autowired
private ApplicationSettings applicationSettings;

@Autowired
private EmailValidator emailValidator;

@Autowired(required = false)
private RecaptchaValidator recaptchaValidator;

@Autowired
private MessageSource messageSource;

/**
* Wraps a {@link EmailValidator} so that it can be applied to the {@code user.email} nested path.
*/
private class UserEmailValidator implements Validator {

@Override
public boolean supports( Class<?> clazz ) {
return User.class.isAssignableFrom( clazz );
}

@Override
public void validate( Object target, Errors errors ) {
User user = (User) target;
if ( user.getEmail() != null ) {
try {
errors.pushNestedPath( "email" );
ValidationUtils.invokeValidator( emailValidator, user.getEmail(), errors );
} finally {
errors.popNestedPath();
}
}
}
}

@InitBinder("user")
public void configureUserDataBinder( WebDataBinder dataBinder ) {
dataBinder.setAllowedFields( "email", "password", "profile.name", "profile.lastName" );
dataBinder.addValidators( new UserEmailValidator() );
}

@GetMapping("/login")
Expand All @@ -73,9 +110,24 @@ public ModelAndView registration() {
@PostMapping("/registration")
public ModelAndView createNewUser( @Validated(User.ValidationUserAccount.class) User user,
BindingResult bindingResult,
@RequestParam(name = "g-recaptcha-response", required = false) String recaptchaResponse,
@RequestHeader(name = "X-Forwarded-For", required = false) List<String> clientIp,
RedirectAttributes redirectAttributes,
Locale locale ) {
ModelAndView modelAndView = new ModelAndView( "registration" );

if ( recaptchaValidator != null ) {
Recaptcha recaptcha = new Recaptcha( recaptchaResponse, clientIp != null ? clientIp.iterator().next() : null );
BindingResult recaptchaBindingResult = new BeanPropertyBindingResult( recaptcha, "recaptcha" );
recaptchaValidator.validate( recaptcha, recaptchaBindingResult );
if ( recaptchaBindingResult.hasErrors() ) {
modelAndView.setStatus( HttpStatus.BAD_REQUEST );
modelAndView.addObject( "message", recaptchaBindingResult.getAllErrors().stream().map( oe -> messageSource.getMessage( oe, locale ) ).collect( Collectors.joining( "<br>" ) ) );
modelAndView.addObject( "error", Boolean.TRUE );
return modelAndView;
}
}

User existingUser = userService.findUserByEmailNoAuth( user.getEmail() );

// profile can be missing of no profile.* fields have been set
Expand All @@ -87,6 +139,9 @@ public ModelAndView createNewUser( @Validated(User.ValidationUserAccount.class)

// initialize a basic user profile
Profile userProfile = user.getProfile();
if ( userProfile == null ) {
userProfile = new Profile();
}
userProfile.setPrivacyLevel( privacyService.getDefaultPrivacyLevel() );
userProfile.setShared( applicationSettings.getPrivacy().isDefaultSharing() );
userProfile.setHideGenelist( false );
Expand All @@ -105,6 +160,22 @@ public ModelAndView createNewUser( @Validated(User.ValidationUserAccount.class)

if ( bindingResult.hasErrors() ) {
modelAndView.setStatus( HttpStatus.BAD_REQUEST );
// indicate to the mode
boolean isDomainNotAllowed = bindingResult.getFieldErrors( "email" ).stream()
.map( FieldError::getCode )
.anyMatch( "EmailValidator.domainNotAllowed"::equals );
modelAndView.addObject( "domainNotAllowed", isDomainNotAllowed );
if ( isDomainNotAllowed ) {
// this code is not set if the email is not minimally valid, so we can safely parse it
String domain = user.getEmail().split( "@", 2 )[1];
modelAndView.addObject( "domainNotAllowedFrom", user.getEmail() );
modelAndView.addObject( "domainNotAllowedSubject",
messageSource.getMessage( "LoginController.domainNotAllowedSubject",
new String[]{ domain }, locale ) );
modelAndView.addObject( "domainNotAllowedBody",
messageSource.getMessage( "LoginController.domainNotAllowedBody",
new String[]{ user.getEmail(), domain, user.getProfile().getFullName() }, locale ) );
}
} else {
user = userService.create( user );
userService.createVerificationTokenForUser( user, locale );
Expand Down
6 changes: 1 addition & 5 deletions src/main/java/ubc/pavlab/rdp/model/User.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,13 @@
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonUnwrapped;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.media.SchemaProperty;
import lombok.*;
import lombok.extern.apachecommons.CommonsLog;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.annotations.NaturalId;
import org.hibernate.validator.constraints.Email;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import org.springframework.util.StringUtils;
import ubc.pavlab.rdp.model.enums.PrivacyLevelType;
import ubc.pavlab.rdp.model.enums.TierType;
import ubc.pavlab.rdp.model.ontology.Ontology;
Expand Down Expand Up @@ -89,7 +85,6 @@ public static Comparator<User> getComparator() {
@NaturalId
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
@Column(name = "email", unique = true, nullable = false)
@Email(message = "Your email address is not valid.", groups = { ValidationUserAccount.class })
@NotNull(message = "Please provide an email address.", groups = { ValidationUserAccount.class, ValidationServiceAccount.class })
@Size(min = 1, message = "Please provide an email address.", groups = { ValidationUserAccount.class, ValidationServiceAccount.class })
private String email;
Expand Down Expand Up @@ -144,6 +139,7 @@ public static Comparator<User> getComparator() {
private final Set<PasswordResetToken> passwordResetTokens = new HashSet<>();

@Valid
@NotNull
@Embedded
@JsonUnwrapped
private Profile profile;
Expand Down
Loading

0 comments on commit be0db80

Please sign in to comment.