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

[wip] fix/user signup captcha #1

Closed
wants to merge 3 commits into from
Closed
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package com.appsmith.server.configurations;

import lombok.Getter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

@Getter
@Configuration
public class GoogleRecaptchaConfig {

@Value("${google.recaptcha.enabled}")
private boolean isEnabled;

@Value("${google.recaptcha.key.site}")
private String siteKey;

@Value("${google.recaptcha.key.secret}")
private String secretKey;

}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
import com.appsmith.server.dtos.InviteUsersDTO;
import com.appsmith.server.dtos.ResetUserPasswordDTO;
import com.appsmith.server.dtos.ResponseDTO;
import com.appsmith.server.exceptions.AppsmithError;
import com.appsmith.server.exceptions.AppsmithException;
import com.appsmith.server.services.GoogleRecaptchaService;
import com.appsmith.server.services.SessionUserService;
import com.appsmith.server.services.UserDataService;
import com.appsmith.server.services.UserOrganizationService;
Expand All @@ -27,6 +30,12 @@
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import org.springframework.security.web.server.DefaultServerRedirectStrategy;
import org.springframework.security.web.server.ServerRedirectStrategy;
import org.apache.http.client.utils.URIBuilder;
import java.net.URI;
import java.net.URISyntaxException;

import javax.validation.Valid;
import java.util.List;

Expand All @@ -39,33 +48,56 @@ public class UserController extends BaseController<UserService, User, String> {
private final UserOrganizationService userOrganizationService;
private final UserSignup userSignup;
private final UserDataService userDataService;
private final GoogleRecaptchaService googleRecaptchaService;

@Autowired
public UserController(UserService service,
SessionUserService sessionUserService,
UserOrganizationService userOrganizationService,
UserSignup userSignup,
UserDataService userDataService) {
UserDataService userDataService,
GoogleRecaptchaService googleRecaptchaService) {
super(service);
this.sessionUserService = sessionUserService;
this.userOrganizationService = userOrganizationService;
this.userSignup = userSignup;
this.userDataService = userDataService;
this.googleRecaptchaService = googleRecaptchaService;
}

@PostMapping(consumes = {MediaType.APPLICATION_JSON_VALUE})
@ResponseStatus(HttpStatus.CREATED)
public Mono<ResponseDTO<User>> create(@Valid @RequestBody User resource,
@RequestHeader(name = "Origin", required = false) String originHeader,
ServerWebExchange exchange) {
return userSignup.signupAndLogin(resource, exchange)
.map(created -> new ResponseDTO<>(HttpStatus.CREATED.value(), created, null));
return userSignup.signupAndLogin(resource, exchange)
.map(created -> new ResponseDTO<>(HttpStatus.CREATED.value(), created, null));
}

@PostMapping(consumes = {MediaType.APPLICATION_FORM_URLENCODED_VALUE})
@ResponseStatus(HttpStatus.CREATED)
public Mono<Void> createFormEncoded(ServerWebExchange exchange) {
return userSignup.signupAndLoginFromFormData(exchange);
String recaptchaToken = exchange.getRequest().getQueryParams().getFirst("recaptchaToken");

return googleRecaptchaService.verify(recaptchaToken).flatMap(verified -> {
if (verified) {
return userSignup.signupAndLoginFromFormData(exchange);
} else {
return Mono.error(new AppsmithException(AppsmithError.GOOGLE_RECAPTCHA_FAILED));
}
}).onErrorResume(error -> {
final ServerRedirectStrategy redirectStrategy = new DefaultServerRedirectStrategy();
final String referer = exchange.getRequest().getHeaders().getFirst("referer");
final URIBuilder redirectUriBuilder = new URIBuilder(URI.create(referer)).setParameter("error", error.getMessage());
URI redirectUri;
try {
redirectUri = redirectUriBuilder.build();
} catch (URISyntaxException e) {
log.error("Error building redirect URI with error for signup, {}.", e.getMessage(), error);
redirectUri = URI.create(referer);
}
return redirectStrategy.sendRedirect(exchange, redirectUri);
});
}

@PutMapping()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,9 @@ public enum AppsmithError {
PAYLOAD_TOO_LARGE(413, 4028, "The request payload is too large. Max allowed size for request payload is {0} KB", AppsmithErrorAction.DEFAULT),
SIGNUP_DISABLED(403, 4033, "Signup is restricted on this instance of Appsmith. Please contact the administrator to get an invite.", AppsmithErrorAction.DEFAULT),
FAIL_UPDATE_USER_IN_SESSION(500, 5008, "Unable to update user in session.", AppsmithErrorAction.LOG_EXTERNALLY),
// TODO: Fix error codes.
GOOGLE_RECAPTCHA_TIMEOUT(504, 9998, "Google recaptcha verification timeout. Please try again", AppsmithErrorAction.DEFAULT),
GOOGLE_RECAPTCHA_FAILED(401, 9999, "Google recaptcha verification failed. Please try again", AppsmithErrorAction.DEFAULT),
;


Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package com.appsmith.server.services;

import reactor.core.publisher.Mono;

public interface GoogleRecaptchaService {
Mono<Boolean> verify(String recaptchaResponse);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
package com.appsmith.server.services;

import com.appsmith.server.configurations.GoogleRecaptchaConfig;
import com.appsmith.server.exceptions.AppsmithError;
import com.appsmith.server.exceptions.AppsmithException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.http.MediaType;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import java.time.Duration;

@Service
public class GoogleRecaptchaServiceImpl implements GoogleRecaptchaService {
private final WebClient webClient;

private final GoogleRecaptchaConfig googleRecaptchaConfig;

private static String BASE_URL = "https://www.google.com/recaptcha/api/";

private static String VERIFY_PATH = "/siteverify";

private final ObjectMapper objectMapper;

private final Long timeoutInMillis = Long.valueOf(10000);

@Autowired
public GoogleRecaptchaServiceImpl(WebClient.Builder webClientBuilder,
GoogleRecaptchaConfig googleRecaptchaConfig, ObjectMapper objectMapper) {
this.webClient = webClientBuilder.baseUrl(BASE_URL).build();
this.googleRecaptchaConfig = googleRecaptchaConfig;
this.objectMapper = objectMapper;
}

@Override
public Mono<Boolean> verify(String recaptchaResponse){

// if not enabled or secret key is not configured, abort verification.
if (!googleRecaptchaConfig.isEnabled() || googleRecaptchaConfig.getSecretKey() == "") {
return Mono.just(true);
}

return doVerfiy(recaptchaResponse).flatMap(mapBody -> {
return Mono.just((Boolean) mapBody.get("success"));
});
}

// API Docs: https://developers.google.com/recaptcha/docs/v3
private Mono<HashMap<String,Object>> doVerfiy(String recaptchaResponse) {
return webClient
.get()
.uri(uriBuilder -> uriBuilder.path(VERIFY_PATH)
.queryParam("response", recaptchaResponse)
.queryParam("secret", googleRecaptchaConfig.getSecretKey())
.build()
)
.retrieve()
.bodyToMono(String.class)
.flatMap(stringBody -> {
HashMap<String,Object> response = null;
System.out.println(stringBody);
try {
response = objectMapper.readValue(stringBody, HashMap.class);
} catch (JsonProcessingException e) {
return Mono.error(new AppsmithException(AppsmithError.JSON_PROCESSING_ERROR, e));
}
return Mono.just(response);
})
.timeout(Duration.ofMillis(timeoutInMillis))
.doOnError(error -> Mono.error(new AppsmithException(AppsmithError.GOOGLE_RECAPTCHA_TIMEOUT)));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,22 +10,17 @@
import com.appsmith.server.services.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.utils.URIBuilder;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.ReactiveSecurityContextHolder;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.web.server.DefaultServerRedirectStrategy;
import org.springframework.security.web.server.ServerRedirectStrategy;
import org.springframework.security.web.server.WebFilterExchange;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilterChain;
import org.springframework.web.server.WebSession;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.net.URISyntaxException;

import static com.appsmith.server.helpers.ValidationUtils.validateEmail;
import static org.springframework.security.web.server.context.WebSessionServerSecurityContextRepository.DEFAULT_SPRING_SECURITY_CONTEXT_ATTR_NAME;
Expand All @@ -38,8 +33,6 @@ public class UserSignup {
private final UserService userService;
private final AuthenticationSuccessHandler authenticationSuccessHandler;

private static final ServerRedirectStrategy redirectStrategy = new DefaultServerRedirectStrategy();

private static final WebFilterChain EMPTY_WEB_FILTER_CHAIN = serverWebExchange -> Mono.empty();

/**
Expand Down Expand Up @@ -105,20 +98,7 @@ public Mono<Void> signupAndLoginFromFormData(ServerWebExchange exchange) {
}
return user;
})
.flatMap(user -> signupAndLogin(user, exchange))
.then()
.onErrorResume(error -> {
final String referer = exchange.getRequest().getHeaders().getFirst("referer");
final URIBuilder redirectUriBuilder = new URIBuilder(URI.create(referer)).setParameter("error", error.getMessage());
URI redirectUri;
try {
redirectUri = redirectUriBuilder.build();
} catch (URISyntaxException e) {
log.error("Error building redirect URI with error for signup, {}.", e.getMessage(), error);
redirectUri = URI.create(referer);
}
return redirectStrategy.sendRedirect(exchange, redirectUri);
});
.flatMap(user -> signupAndLogin(user, exchange));
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -87,3 +87,8 @@ management.metrics.distribution.sla.[http.server.requests]=1s
# Support disabling signup with an environment variable
signup.disabled = ${APPSMITH_SIGNUP_DISABLED:false}
signup.allowed-domains=${APPSMITH_SIGNUP_ALLOWED_DOMAINS:}

# Google recaptcha config
google.recaptcha.enabled = ${APPSMITH_RECAPTCHA_ENABLED:false}
google.recaptcha.key.site = ${APPSMITH_RECAPTCHA_SITE_KEY}
google.recaptcha.key.secret= ${APPSMITH_RECAPTCHA_SECRET_KEY}
4 changes: 4 additions & 0 deletions app/server/envs/dev.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,7 @@ APPSMITH_ENCRYPTION_SALT=abcd

#APPSMITH_SENTRY_DSN=
#APPSMITH_SENTRY_ENVIRONMENT=

#APPSMITH_RECAPTCHA_ACTIVE=""
#APPSMITH_RECAPTCHA_SITE_KEY=""
#APPSMITH_RECAPTCHA_SECRET_KEY=""
4 changes: 4 additions & 0 deletions app/server/envs/docker.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,7 @@ APPSMITH_MARKETPLACE_PASSWORD=""

APPSMITH_ENCRYPTION_PASSWORD=""
APPSMITH_ENCRYPTION_SALT=""

#APPSMITH_RECAPTCHA_ACTIVE=""
#APPSMITH_RECAPTCHA_SITE_KEY=""
#APPSMITH_RECAPTCHA_SECRET_KEY=""