Skip to content

Commit

Permalink
Merge 81637fb into a440405
Browse files Browse the repository at this point in the history
  • Loading branch information
bukajsytlos committed May 6, 2017
2 parents a440405 + 81637fb commit 5d9869c
Show file tree
Hide file tree
Showing 16 changed files with 385 additions and 118 deletions.
16 changes: 16 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# EditorConfig helps developers define and maintain consistent
# coding styles between different editors and IDEs
# editorconfig.org

root = true

[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true

[*.md]
trim_trailing_whitespace = false
4 changes: 3 additions & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ dependencies {
compile("de.codecentric:spring-boot-admin-starter-client:${springBootAdminClientVersion}")

compile("com.github.FAForever:faf-java-commons:${fafCommonsVersion}")
compile("org.kohsuke:github-api:1.84")
compile("org.kohsuke:github-api:${githubApiVersion}")
compile("org.jolokia:jolokia-core:${jolokiaVersion}")
compile("org.springframework.security:spring-security-jwt:${springSecurityJwtVersion}")
compile("org.springframework.security.oauth:spring-security-oauth2:${springSecurityOauth2Version}")
Expand Down Expand Up @@ -195,6 +195,8 @@ dependencies {
testCompile("org.springframework.restdocs:spring-restdocs-mockmvc")
testCompile("org.springframework.security:spring-security-test")
testCompile("com.h2database:h2:${h2Version}")
testCompile("com.jayway.jsonpath:json-path:${jsonPath}")
testCompile("com.jayway.jsonpath:json-path-assert:${jsonPathAssert}")

codacy("com.github.codacy:codacy-coverage-reporter:-SNAPSHOT")
}
2 changes: 2 additions & 0 deletions gradle.properties
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,5 @@ jacksonDatatypeJsr310Version=2.8.6
mockitoVersion=2.7.0
lutungVersion=0.0.7
commonsCompressVersion=1.13
jsonPath=2.2.0
jsonPathAssert=2.2.0
2 changes: 1 addition & 1 deletion src/main/java/com/faforever/api/clan/ClanService.java
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ public String generatePlayerInvitationToken(Player requester, int newMemberId, i
Clan clan = clanRepository.findOne(clanId);

if (clan == null) {
throw new ApiException(new Error(ErrorCode.CLAN_NOT_EXISTS));
throw new ApiException(new Error(ErrorCode.CLAN_NOT_EXISTS, clanId));
}
if (requester.getId() != clan.getLeader().getId()) {
throw new ApiException(new Error(ErrorCode.CLAN_NOT_LEADER, clanId));
Expand Down

This file was deleted.

9 changes: 0 additions & 9 deletions src/main/java/com/faforever/api/config/error/ErrorResult.java

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package com.faforever.api.config.security.oauth2;

import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.security.oauth2.http.converter.jaxb.JaxbOAuth2ExceptionMessageConverter;
import org.springframework.security.oauth2.provider.error.DefaultOAuth2ExceptionRenderer;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

public class JsonApiOauthExceptionRenderer extends DefaultOAuth2ExceptionRenderer {
public JsonApiOauthExceptionRenderer() {
setMessageConverters(createMessageConverters());
}

private List<HttpMessageConverter<?>> createMessageConverters() {
List<HttpMessageConverter<?>> result = new ArrayList<HttpMessageConverter<?>>();
result.add(new JsonApiOauthMessageConverter());
result.addAll(new RestTemplate().getMessageConverters());
result.add(new JaxbOAuth2ExceptionMessageConverter());
return result;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package com.faforever.api.config.security.oauth2;

import com.faforever.api.error.ErrorResponse;
import com.faforever.api.error.ErrorResult;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;

import java.io.IOException;


public class JsonApiOauthMessageConverter extends MappingJackson2HttpMessageConverter {

@Override
protected void writeInternal(Object object, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
super.writeInternal(transformObject(object), outputMessage);
}

protected Object transformObject(Object object) {
ErrorResponse response = new ErrorResponse();
if (object instanceof OAuth2Exception) {
OAuth2Exception oAuth2Exception = (OAuth2Exception) object;

final ErrorResult newError = new ErrorResult(
String.valueOf(oAuth2Exception.getHttpErrorCode()),
oAuth2Exception.getOAuth2ErrorCode(),
oAuth2Exception.getMessage()
);
response.addError(newError);
newError.setMeta(ErrorResult.createMeta(null, oAuth2Exception.getAdditionalInformation()).orElse(null));
} else {
response.addError(new ErrorResult(
String.valueOf(HttpStatus.INTERNAL_SERVER_ERROR.value()),
"Error",
object.toString()
));
}
return response;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenStore;

Expand Down Expand Up @@ -44,9 +45,12 @@ public OAuthAuthorizationServerConfig(AuthenticationManager authenticationManage

@Override
public void configure(AuthorizationServerSecurityConfigurer oAuthServer) throws Exception {
final OAuth2AuthenticationEntryPoint oAuth2AuthenticationEntryPoint = new OAuth2AuthenticationEntryPoint();
oAuth2AuthenticationEntryPoint.setExceptionRenderer(new JsonApiOauthExceptionRenderer());
oAuthServer
.tokenKeyAccess("isAnonymous() || hasAuthority('ROLE_TRUSTED_CLIENT')")
.checkTokenAccess("hasAuthority('ROLE_TRUSTED_CLIENT')");
.tokenKeyAccess("isAnonymous() || hasAuthority('ROLE_TRUSTED_CLIENT')")
.checkTokenAccess("hasAuthority('ROLE_TRUSTED_CLIENT')")
.authenticationEntryPoint(oAuth2AuthenticationEntryPoint);
}

@Override
Expand All @@ -57,9 +61,9 @@ public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints
.userDetailsService(userDetailsService)
.tokenStore(tokenStore)
.tokenEnhancer(tokenEnhancer)
.authenticationManager(authenticationManager);
.userDetailsService(userDetailsService)
.tokenStore(tokenStore)
.tokenEnhancer(tokenEnhancer)
.authenticationManager(authenticationManager);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint;
import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices;
import org.springframework.security.web.util.matcher.RequestMatcher;

Expand All @@ -26,6 +27,7 @@ public class OAuthResourceServerConfig extends ResourceServerConfigurerAdapter {

private final String resourceId;
private final ResourceServerTokenServices tokenServices;

@Inject
public OAuthResourceServerConfig(FafApiProperties fafApiProperties, ResourceServerTokenServices tokenServices) {
this.resourceId = fafApiProperties.getOAuth2().getResourceId();
Expand All @@ -34,16 +36,19 @@ public OAuthResourceServerConfig(FafApiProperties fafApiProperties, ResourceServ

@Override
public void configure(ResourceServerSecurityConfigurer resources) {
final OAuth2AuthenticationEntryPoint oAuth2AuthenticationEntryPoint = new OAuth2AuthenticationEntryPoint();
oAuth2AuthenticationEntryPoint.setExceptionRenderer(new JsonApiOauthExceptionRenderer());
resources.resourceId(resourceId)
.tokenServices(tokenServices);
.tokenServices(tokenServices)
.authenticationEntryPoint(oAuth2AuthenticationEntryPoint);
}

@Override
public void configure(HttpSecurity http) throws Exception {
http.requestMatcher(new OAuthRequestedMatcher())
.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS).permitAll()
.anyRequest().authenticated();
.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS).permitAll()
.anyRequest().authenticated();
}

private static class OAuthRequestedMatcher implements RequestMatcher {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.faforever.api.config.error;
package com.faforever.api.error;

import lombok.Data;

Expand Down
40 changes: 40 additions & 0 deletions src/main/java/com/faforever/api/error/ErrorResult.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package com.faforever.api.error;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.RequiredArgsConstructor;

import java.util.Map;
import java.util.Optional;

@Data
@RequiredArgsConstructor
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ErrorResult {
@JsonProperty("status")
private final String httpStatusCode;
private final String title;
private final String detail;
@JsonProperty("code")
private String appCode;
private Meta meta;

public static Optional<Meta> createMeta(Object[] args, Map<String, String> additionalInfo) {
if ((args == null || args.length == 0) && (additionalInfo == null || additionalInfo.isEmpty())) {
return Optional.empty();
}
return Optional.of(new Meta(args, additionalInfo));
}

@Data
@RequiredArgsConstructor
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public static class Meta {
private Object[] args;
private Map<String, String> additionalInfo;
}
}
Loading

0 comments on commit 5d9869c

Please sign in to comment.