Repository: iainporter/rest-java Branch: master Commit: 30a904561b85 Files: 146 Total size: 368.0 KB Directory structure: gitextract_6sr2pa59/ ├── .gitignore ├── LICENSE.md ├── README.md ├── build.gradle ├── gradle/ │ └── wrapper/ │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradle.properties ├── gradlew ├── gradlew.bat └── src/ ├── main/ │ ├── config/ │ │ └── ci/ │ │ └── gradle.properties │ ├── java/ │ │ └── com/ │ │ └── porterhead/ │ │ └── rest/ │ │ ├── api/ │ │ │ ├── ErrorResponse.java │ │ │ ├── PagedQueryRequest.java │ │ │ ├── PagedResponse.java │ │ │ └── ValidationError.java │ │ ├── authorization/ │ │ │ ├── AuthorizationRequestContext.java │ │ │ ├── AuthorizationService.java │ │ │ ├── exception/ │ │ │ │ └── InvalidAuthorizationHeaderException.java │ │ │ └── impl/ │ │ │ ├── RequestSigningAuthorizationService.java │ │ │ ├── SecurityContextImpl.java │ │ │ └── SessionTokenAuthorizationService.java │ │ ├── config/ │ │ │ ├── ApplicationConfig.java │ │ │ ├── ApplicationDevConfig.java │ │ │ ├── ApplicationProductionConfig.java │ │ │ └── ApplicationStagingConfig.java │ │ ├── exception/ │ │ │ ├── ApplicationRuntimeException.java │ │ │ ├── BaseWebApplicationException.java │ │ │ ├── NotFoundException.java │ │ │ └── ValidationException.java │ │ ├── filter/ │ │ │ ├── ResourceFilterFactory.java │ │ │ └── SecurityContextFilter.java │ │ ├── gateway/ │ │ │ └── EmailServicesGateway.java │ │ ├── model/ │ │ │ └── BaseEntity.java │ │ ├── resource/ │ │ │ ├── GenericExceptionMapper.java │ │ │ └── HealthCheckResource.java │ │ ├── service/ │ │ │ └── BaseService.java │ │ ├── user/ │ │ │ ├── EmailServiceTokenModel.java │ │ │ ├── SocialUserRepository.java │ │ │ ├── UserRepository.java │ │ │ ├── UserService.java │ │ │ ├── UserServiceImpl.java │ │ │ ├── VerificationTokenRepository.java │ │ │ ├── VerificationTokenService.java │ │ │ ├── VerificationTokenServiceImpl.java │ │ │ ├── api/ │ │ │ │ ├── AuthenticatedUserToken.java │ │ │ │ ├── CreateUserRequest.java │ │ │ │ ├── EmailVerificationRequest.java │ │ │ │ ├── ExternalUser.java │ │ │ │ ├── LoginRequest.java │ │ │ │ ├── LostPasswordRequest.java │ │ │ │ ├── OAuth2Request.java │ │ │ │ ├── PasswordRequest.java │ │ │ │ ├── SocialProfile.java │ │ │ │ └── UpdateUserRequest.java │ │ │ ├── domain/ │ │ │ │ ├── AuthorizationToken.java │ │ │ │ ├── Role.java │ │ │ │ ├── SocialUser.java │ │ │ │ ├── SocialUserBuilder.java │ │ │ │ ├── User.java │ │ │ │ └── VerificationToken.java │ │ │ ├── exception/ │ │ │ │ ├── AlreadyVerifiedException.java │ │ │ │ ├── AuthenticationException.java │ │ │ │ ├── AuthorizationException.java │ │ │ │ ├── DuplicateUserException.java │ │ │ │ ├── TokenHasExpiredException.java │ │ │ │ ├── TokenNotFoundException.java │ │ │ │ └── UserNotFoundException.java │ │ │ ├── mail/ │ │ │ │ ├── MailSenderService.java │ │ │ │ ├── MockJavaMailSender.java │ │ │ │ └── impl/ │ │ │ │ └── MailSenderServiceImpl.java │ │ │ ├── resource/ │ │ │ │ ├── PasswordResource.java │ │ │ │ ├── UserResource.java │ │ │ │ └── VerificationResource.java │ │ │ └── social/ │ │ │ ├── JpaConnectionRepository.java │ │ │ ├── JpaUsersConnectionRepository.java │ │ │ └── SocialConfig.java │ │ └── util/ │ │ ├── DateUtil.java │ │ ├── HashUtil.java │ │ └── StringUtil.java │ ├── resources/ │ │ ├── META-INF/ │ │ │ ├── persistence.xml │ │ │ ├── spring/ │ │ │ │ ├── component-scan-context.xml │ │ │ │ ├── data-context.xml │ │ │ │ ├── email-services-context.xml │ │ │ │ ├── email-template-context.xml │ │ │ │ ├── root-context.xml │ │ │ │ └── social-configuration-context.xml │ │ │ └── velocity/ │ │ │ ├── LostPasswordEmail.vm │ │ │ ├── RegistrationEmail.vm │ │ │ └── VerifyEmail.vm │ │ ├── logback.xml │ │ ├── properties/ │ │ │ ├── app.properties │ │ │ ├── dev-app.properties │ │ │ ├── production-app.properties │ │ │ └── staging-app.properties │ │ └── schema/ │ │ ├── indexes.sql │ │ ├── message_store.sql │ │ └── truncate_data.sql │ └── webapp/ │ ├── META-INF/ │ │ └── MANIFEST.MF │ ├── WEB-INF/ │ │ ├── spring/ │ │ │ └── appservlet/ │ │ │ └── servlet-context.xml │ │ └── web.xml │ ├── css/ │ │ └── styles.css │ ├── dashboard.html │ ├── forgot_password.html │ ├── index.html │ ├── js/ │ │ ├── bootstrap.js │ │ ├── cookie.js │ │ ├── enc-base64-min.js │ │ ├── grid.locale-en.js │ │ ├── javarest.js │ │ ├── jquery-full-house.js │ │ ├── sha256.js │ │ ├── store.js │ │ ├── user.js │ │ └── verify.js │ ├── request_email.html │ ├── reset_password.html │ ├── signup.html │ └── validate.html └── test/ ├── groovy/ │ ├── BaseIntegrationTst.groovy │ └── UserIntegrationTest.groovy ├── java/ │ └── com/ │ └── porterhead/ │ └── rest/ │ ├── authorization/ │ │ ├── BaseAuthorizationTst.java │ │ ├── RequestSigningAuthorizationServiceTest.java │ │ ├── SecurityContextTest.java │ │ └── SessionTokenAuthorizationServiceTest.java │ ├── filter/ │ │ └── SecurityContextFilterTest.java │ ├── mock/ │ │ └── AppMockConfiguration.java │ ├── resource/ │ │ ├── BaseResourceTst.java │ │ ├── ConsumerSimpleSecurityFilter.java │ │ ├── HealthCheckResourceTest.java │ │ └── SimpleSecurityFilter.java │ └── user/ │ ├── BaseServiceTest.java │ ├── MailSenderServiceTest.java │ ├── UserServiceTest.java │ ├── VerificationServiceTest.java │ ├── api/ │ │ ├── CreateUserRequestTest.java │ │ ├── LoginRequestTest.java │ │ ├── PasswordRequestTest.java │ │ └── ValidationTst.java │ ├── builder/ │ │ └── ExternalUserBuilder.java │ ├── resource/ │ │ ├── PasswordResourceTest.java │ │ ├── UserResourceTest.java │ │ └── VerificationResourceTest.java │ └── social/ │ ├── AbstractSocialTst.java │ ├── JpaConnectionRepositoryTest.java │ └── JpaUsersConnectionRepositoryTest.java └── resources/ ├── integration-test-context.xml └── social-test-context.xml ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ .DS_Store .gradle/* build/* out/* *.iml *.ipr *.iws /build/ /bin/ # eclipse .settings/ .project .classpath # Intellij .idea/ *.iml *.iws ================================================ FILE: LICENSE.md ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright {yyyy} {name of copyright owner} Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: README.md ================================================ JAVA REST Application ==================== Simple and easily understandable web project that demonstrates the use of: * Jersey + JAX-RS * Spring Integration * Spring Data + Hibernate * Groovy Integration tests * OAuth * Velocity + Java Mail * Facebook Login * Password Reset * Login/Sign Up + Email Verification * JSR 303 Validation NOTE. For a similar project that uses most of the same components but is built around OAuth2 see Securing Rest Services with OAuth2 and Spring Security to build: gradle clean build integrationTest or use the gradle wrapper: ./gradlew clean build integrationTest go to /build/reports/emma for test coverage reports to run: gradle tomcatRun navigate to http://localhost:8080/java-rest/ see blog posts: THANK YOU
* Authorization: :
*
*
* The signed request hash is comprised of the session token + : + the relative url + , + the Http method + , + Date + , + nonce
* This string is then Sha-256 encoded and then Base64 encoded
*
* An example:
*
* Example:
* 9fbc6f9a-af1b-4767-a492-c8462fd2a4d9:user/2e2ce9e8-798e-42b6-9326-fd2e56aef7aa/cards,POST,2012-06-30T12:00:00+01:00,34e321a7c4
*
*
*
* This will be SHA-256 hashed and then Base64 encoded to produce:
*
*
* HR/3DJp8RCGo50Wu+/3cr7ibdoNXKg1eYMt3HO5QoP4=
*
*
* Authorization: 2e2ce9e8-798e-42b6-9326-fd2e56aef7aa:HR/3DJp8RCGo50Wu+/3cr7ibdoNXKg1eYMt3HO5QoP4=
*
* @author: Iain Porter
*/
public class RequestSigningAuthorizationService implements AuthorizationService {
Logger LOG = LoggerFactory.getLogger(RequestSigningAuthorizationService.class);
/**
* If the nonce already exists in the cache the difference between its timestamp and the current time will be
* greater than this value
*/
private static final int NONCE_CHECK_TOLERANCE_IN_MILLIS = 20;
/**
* Maximum Number of Nonce values in the cache
* The capacity will never be reached as long as the number of requests is below this value within the time range specified by
* ApplicationConfig.getSessionDateOffsetInMinutes()
*/
private static final int NONCE_CACHE_SIZE = 10000;
/**
* A an expiry cache that evicts nonce values after a configurable time period
*/
private LoadingCache
* Example:
* 9fbc6f9a-af1b-4767-a492-c8462fd2a4d9:user/2e2ce9e8-798e-42b6-9326-fd2e56aef7aa,GET,2012-06-30T12:00:00+01:00,34e321a7c4
*
*
*
* This will be SHA-256 hashed and then Base64 encoded to produce:
*
*
* HR/3DJp8RCGo50Wu+/3cr7ibdoNXKg1eYMt3HO5QoP4=
*
*
* @param user should have a session token that will validate the request signature
* @param authorizationRequest the request containing all the details needed to authorize the request
* @param hashedToken the token to match against
* @return true if the token is authorized
*/
private boolean isAuthorized(User user, AuthorizationRequestContext authorizationRequest, String hashedToken) {
Assert.notNull(user);
Assert.notNull(authorizationRequest.getAuthorizationToken());
String unEncodedString = composeUnEncodedRequest(authorizationRequest);
AuthorizationToken authorizationToken = user.getAuthorizationToken();
String userTokenHash = encodeAuthToken(authorizationToken.getToken(), unEncodedString);
if (hashedToken.equals(userTokenHash)) {
return true;
}
LOG.error("Hash check failed for hashed token: {} for the following request: {} for user: {}",
new Object[]{authorizationRequest.getAuthorizationToken(), unEncodedString, user.getId()});
return false;
}
/**
* Encode the token by prefixing it with the User's Session Token
*
* @param token
* @return encoded token
*/
private String encodeAuthToken(String token, String unencodedRequest) {
byte[] digest = DigestUtils.sha256(token + ":" + unencodedRequest);
return new String(Base64.encodeBase64(digest));
}
/**
* The recipe to compose a signed request
*
* @param authRequest
* @return the string value to hash
*/
private String composeUnEncodedRequest(AuthorizationRequestContext authRequest) {
StringBuilder sb = new StringBuilder();
sb.append(authRequest.getRequestUrl());
sb.append(',');
sb.append(authRequest.getHttpMethod().toUpperCase());
sb.append(',');
sb.append(authRequest.getRequestDateString());
sb.append(',').append(authRequest.getNonceToken());
return sb.toString();
}
/**
* Ensure that the date of the request falls within the configured range
* @param requestDateString
*/
private void validateRequestDate(String requestDateString) {
Date date = DateUtil.getDateFromIso8061DateString(requestDateString);
DateTime now = new DateTime();
DateTime offset = new DateTime(date);
if (!(offset.isAfter(now.minusMinutes(config.getSessionDateOffsetInMinutes())) &&
offset.isBefore(now.plusMinutes(config.getSessionDateOffsetInMinutes())))) {
LOG.error("Date in header is out of range: {}", requestDateString);
throw new AuthorizationException("Date in header is out of range: " + requestDateString);
}
}
/**
* The nonce value sent by the client and used in the request signature should be unique across the system
* Nonce values will only be considered unique within the time limits of the cache.
* The value will be protected if the cache expiry time is within the limits of the request date range.
* If the date in the request is stale then the nonce value wil be irrelevant
*
* Note that the caching strategy will not work in a cluster. A distributed cache will be needed.
*
* @param nonceValue
*/
private void validateNonce(String nonceValue) {
Nonce nonce = nonceCache.getUnchecked(nonceValue);
Duration tolerance = new Duration(nonce.timestamp, new DateTime());
if (tolerance.isLongerThan(Duration.millis(NONCE_CHECK_TOLERANCE_IN_MILLIS))) {
LOG.error("Nonce value was not unique: {}", nonceValue);
throw new AuthorizationException("Nonce value is not unique");
}
}
private static class Nonce {
private DateTime timestamp;
private String nonceValue;
Nonce(DateTime time, String nonce) {
this.timestamp = time;
this.nonceValue = nonce;
}
}
}
================================================
FILE: src/main/java/com/porterhead/rest/authorization/impl/SecurityContextImpl.java
================================================
package com.porterhead.rest.authorization.impl;
import com.porterhead.rest.authorization.exception.InvalidAuthorizationHeaderException;
import com.porterhead.rest.user.api.ExternalUser;
import com.porterhead.rest.user.domain.Role;
import javax.ws.rs.core.SecurityContext;
import java.security.Principal;
/**
* Implementation of {@link javax.ws.rs.core.SecurityContext}
*
* User: porter
* Date: 16/03/2012
* Time: 16:13
*/
public class SecurityContextImpl implements SecurityContext {
private final ExternalUser user;
public SecurityContextImpl(ExternalUser user) {
this.user = user;
}
public Principal getUserPrincipal() {
return user;
}
public boolean isUserInRole(String role) {
if(role.equalsIgnoreCase(Role.anonymous.name())) {
return true;
}
if(user == null) {
throw new InvalidAuthorizationHeaderException();
}
return user.getRole().equalsIgnoreCase(role);
}
public boolean isSecure() {
return false;
}
public String getAuthenticationScheme() {
return SecurityContext.BASIC_AUTH;
}
}
================================================
FILE: src/main/java/com/porterhead/rest/authorization/impl/SessionTokenAuthorizationService.java
================================================
package com.porterhead.rest.authorization.impl;
import com.porterhead.rest.authorization.AuthorizationRequestContext;
import com.porterhead.rest.authorization.AuthorizationService;
import com.porterhead.rest.user.UserRepository;
import com.porterhead.rest.user.api.ExternalUser;
import com.porterhead.rest.user.domain.AuthorizationToken;
import com.porterhead.rest.user.domain.User;
import com.porterhead.rest.user.exception.AuthorizationException;
import java.util.Date;
/**
*
* Simple authorization service that requires a session token in the Authorization header
* This is then matched to a user
*
* @version 1.0
* @author: Iain Porter
* @since 29/01/2013
*/
public class SessionTokenAuthorizationService implements AuthorizationService {
/**
* directly access user objects
*/
private final UserRepository userRepository;
public SessionTokenAuthorizationService(UserRepository repository) {
this.userRepository = repository;
}
public ExternalUser authorize(AuthorizationRequestContext securityContext) {
String token = securityContext.getAuthorizationToken();
ExternalUser externalUser = null;
if(token == null) {
return externalUser;
}
User user = userRepository.findBySession(token);
if(user == null) {
throw new AuthorizationException("Session token not valid");
}
AuthorizationToken authorizationToken = user.getAuthorizationToken();
if (authorizationToken.getToken().equals(token)) {
externalUser = new ExternalUser(user);
}
return externalUser;
}
}
================================================
FILE: src/main/java/com/porterhead/rest/config/ApplicationConfig.java
================================================
package com.porterhead.rest.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
/**
* User: porter
* Date: 17/05/2012
* Time: 19:07
*/
@Configuration
@PropertySource({"classpath:/properties/app.properties"})
public class ApplicationConfig {
private final static String HOSTNAME_PROPERTY = "hostNameUrl";
private final static String SECURITY_AUTHORIZATION_REQUIRE_SIGNED_REQUESTS = "security.authorization.requireSignedRequests";
private final static String AUTHORIZATION_EXPIRY_DURATION = "authorization.timeToLive.inSeconds";
private final static String SESSION_DATE_OFFSET_IN_MINUTES = "session.date.offset.inMinutes";
private final static String TOKEN_EMAIL_REGISTRATION_DURATION = "token.emailRegistration.timeToLive.inMinutes";
private final static String TOKEN_EMAIL_VERIFICATION_DURATION = "token.emailVerification.timeToLive.inMinutes";
private final static String TOKEN_LOST_PASSWORD_DURATION = "token.lostPassword.timeToLive.inMinutes";
private final static String EMAIL_SERVICES_FROM_ADDRESS = "email.services.fromAddress";
private final static String EMAIL_SERVICES_REPLYTO_ADDRESS = "email.services.replyTo";
private final static String EMAIL_SERVICES_VERIFICATION_EMAIL_SUBJECT_TEXT = "email.services.emailVerificationSubjectText";
private final static String EMAIL_SERVICES_REGISTRATION_EMAIL_SUBJECT_TEXT = "email.services.emailRegistrationSubjectText";
private final static String EMAIL_SERVICES_LOST_PASSWORD_SUBJECT_TEXT = "email.services.lostPasswordSubjectText";
@Autowired
protected Environment environment;
public String getHostNameUrl() {
return environment.getProperty(HOSTNAME_PROPERTY);
}
public String getFacebookClientId() {
return environment.getProperty("facebook.clientId");
}
public String getFacebookClientSecret() {
return environment.getProperty("facebook.clientSecret");
}
public int getAuthorizationExpiryTimeInSeconds() {
return Integer.parseInt(environment.getProperty(AUTHORIZATION_EXPIRY_DURATION));
}
public int getSessionDateOffsetInMinutes() {
return Integer.parseInt(environment.getProperty(SESSION_DATE_OFFSET_IN_MINUTES));
}
public int getEmailRegistrationTokenExpiryTimeInMinutes() {
return Integer.parseInt(environment.getProperty(TOKEN_EMAIL_REGISTRATION_DURATION));
}
public int getEmailVerificationTokenExpiryTimeInMinutes() {
return Integer.parseInt(environment.getProperty(TOKEN_EMAIL_VERIFICATION_DURATION));
}
public int getLostPasswordTokenExpiryTimeInMinutes() {
return Integer.parseInt(environment.getProperty(TOKEN_LOST_PASSWORD_DURATION));
}
public String getEmailVerificationSubjectText() {
return environment.getProperty(EMAIL_SERVICES_VERIFICATION_EMAIL_SUBJECT_TEXT);
}
public String getEmailRegistrationSubjectText() {
return environment.getProperty(EMAIL_SERVICES_REGISTRATION_EMAIL_SUBJECT_TEXT);
}
public String getLostPasswordSubjectText() {
return environment.getProperty(EMAIL_SERVICES_LOST_PASSWORD_SUBJECT_TEXT);
}
public String getEmailFromAddress() {
return environment.getProperty(EMAIL_SERVICES_FROM_ADDRESS);
}
public String getEmailReplyToAddress() {
return environment.getProperty(EMAIL_SERVICES_REPLYTO_ADDRESS);
}
public Boolean requireSignedRequests() {
return environment.getProperty(SECURITY_AUTHORIZATION_REQUIRE_SIGNED_REQUESTS).equalsIgnoreCase("true");
}
}
================================================
FILE: src/main/java/com/porterhead/rest/config/ApplicationDevConfig.java
================================================
package com.porterhead.rest.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.context.annotation.PropertySource;
import org.springframework.security.crypto.encrypt.Encryptors;
import org.springframework.security.crypto.encrypt.TextEncryptor;
/**
* @version 1.0
* @author: Iain Porter iain.porter@porterhead.com
* @since 21/09/2012
*/
@Configuration
@Profile(value={"dev", "local"})
@PropertySource({"classpath:/properties/dev-app.properties"})
public class ApplicationDevConfig {
@Bean
public TextEncryptor textEncryptor() {
return Encryptors.noOpText();
}
}
================================================
FILE: src/main/java/com/porterhead/rest/config/ApplicationProductionConfig.java
================================================
package com.porterhead.rest.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.security.crypto.encrypt.Encryptors;
import org.springframework.security.crypto.encrypt.TextEncryptor;
/**
* @version 1.0
* @author: Iain Porter iain.porter@porterhead.com
* @since 21/09/2012
*/
@Configuration
@Profile(value="production")
@PropertySource({"classpath:/properties/production-app.properties"})
public class ApplicationProductionConfig {
@Autowired
Environment environment;
@Bean
public TextEncryptor textEncryptor() {
return Encryptors.queryableText(environment.getProperty("security.encryptPassword"),
environment.getProperty("security.encryptSalt"));
}
}
================================================
FILE: src/main/java/com/porterhead/rest/config/ApplicationStagingConfig.java
================================================
package com.porterhead.rest.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.security.crypto.encrypt.Encryptors;
import org.springframework.security.crypto.encrypt.TextEncryptor;
/**
*
* @version 1.0
* @author: Iain Porter iain.porter@porterhead.com
* @since 21/09/2012
*/
@Configuration
@Profile(value="staging")
@PropertySource({"classpath:/properties/staging-app.properties"})
public class ApplicationStagingConfig {
@Autowired
Environment environment;
@Bean
public TextEncryptor textEncryptor() {
return Encryptors.queryableText(environment.getProperty("security.encryptPassword"),
environment.getProperty("security.encryptSalt"));
}
}
================================================
FILE: src/main/java/com/porterhead/rest/exception/ApplicationRuntimeException.java
================================================
package com.porterhead.rest.exception;
public class ApplicationRuntimeException extends BaseWebApplicationException {
public ApplicationRuntimeException(String applicationMessage) {
super(500, "50002", "Internal System error", applicationMessage);
}
}
================================================
FILE: src/main/java/com/porterhead/rest/exception/BaseWebApplicationException.java
================================================
package com.porterhead.rest.exception;
import com.porterhead.rest.api.ErrorResponse;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
/**
* @version 1.0
* @author: Iain Porter iain.porter@porterhead.com
* @since 19/10/2012
*/
public abstract class BaseWebApplicationException extends WebApplicationException {
private final int status;
private final String errorMessage;
private final String errorCode;
private final String developerMessage;
public BaseWebApplicationException(int httpStatus, String errorCode, String errorMessage, String developerMessage) {
this.status = httpStatus;
this.errorMessage = errorMessage;
this.errorCode = errorCode;
this.developerMessage = developerMessage;
}
@Override
public Response getResponse() {
return Response.status(status).type(MediaType.APPLICATION_JSON_TYPE).entity(getErrorResponse()).build();
}
public ErrorResponse getErrorResponse() {
ErrorResponse response = new ErrorResponse();
response.setErrorCode(errorCode);
response.setApplicationMessage(developerMessage);
response.setConsumerMessage(errorMessage);
return response;
}
}
================================================
FILE: src/main/java/com/porterhead/rest/exception/NotFoundException.java
================================================
package com.porterhead.rest.exception;
import javax.ws.rs.WebApplicationException;
/**
* User: porter
* Date: 03/05/2012
* Time: 12:27
*/
public class NotFoundException extends WebApplicationException {
public NotFoundException() {
super(404);
}
}
================================================
FILE: src/main/java/com/porterhead/rest/exception/ValidationException.java
================================================
package com.porterhead.rest.exception;
import com.porterhead.rest.api.ErrorResponse;
import com.porterhead.rest.api.ValidationError;
import javax.validation.ConstraintViolation;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
/**
* User: porter
* Date: 03/05/2012
* Time: 21:43
*/
public class ValidationException extends WebApplicationException {
private final int status = 400;
private String errorMessage;
private String developerMessage;
private List
*
com.sun.jersey.spi.container.ResourceFilters
com.porterhead.com.porterhead.rest.filter.ResourceFilterFactory
*
*
*
* @author: Iain Porter
*/
@Component
@Provider
public class ResourceFilterFactory extends RolesAllowedResourceFilterFactory {
@Autowired
private SecurityContextFilter securityContextFilter;
@Override
public List
* /user/1883c578-76be-47fb-a5c1-7bbea3bf7fd0 using uuid as the identifier
*
* /user/jsmith using the username as the identifier
*
*
*
* @return Object unique identifier for the object
*/
public Object getIdentifier() {
return getUuid().toString();
}
public int getVersion() {
return version;
}
public Date getTimeCreated() {
return timeCreated;
}
}
================================================
FILE: src/main/java/com/porterhead/rest/resource/GenericExceptionMapper.java
================================================
package com.porterhead.rest.resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
/**
* User: porter
* Date: 22/03/2012
* Time: 15:56
*/
@Provider
public class GenericExceptionMapper implements ExceptionMapper
| ||||||
|
| ||||||