You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@archiva.apache.org by ol...@apache.org on 2012/04/06 11:59:32 UTC
svn commit: r1310268 [15/42] - in /archiva/redback/redback-core/trunk: ./
redback-authentication/ redback-authentication/redback-authentication-api/
redback-authentication/redback-authentication-api/src/
redback-authentication/redback-authentication-ap...
Added: archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/main/java/org/codehaus/redback/rest/services/interceptors/AuthenticationInterceptor.java
URL: http://svn.apache.org/viewvc/archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/main/java/org/codehaus/redback/rest/services/interceptors/AuthenticationInterceptor.java?rev=1310268&view=auto
==============================================================================
--- archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/main/java/org/codehaus/redback/rest/services/interceptors/AuthenticationInterceptor.java (added)
+++ archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/main/java/org/codehaus/redback/rest/services/interceptors/AuthenticationInterceptor.java Fri Apr 6 09:58:14 2012
@@ -0,0 +1,165 @@
+package org.codehaus.redback.rest.services.interceptors;
+
+/*
+* Copyright 2011 The Codehaus.
+*
+* 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.
+*/
+
+
+import org.apache.cxf.jaxrs.ext.RequestHandler;
+import org.apache.cxf.jaxrs.model.ClassResourceInfo;
+import org.apache.cxf.message.Message;
+import org.codehaus.plexus.redback.authentication.AuthenticationException;
+import org.codehaus.plexus.redback.authentication.AuthenticationResult;
+import org.codehaus.plexus.redback.authorization.RedbackAuthorization;
+import org.codehaus.plexus.redback.policy.AccountLockedException;
+import org.codehaus.plexus.redback.policy.MustChangePasswordException;
+import org.codehaus.plexus.redback.system.SecuritySession;
+import org.codehaus.plexus.redback.users.User;
+import org.codehaus.plexus.redback.users.UserManager;
+import org.codehaus.plexus.redback.users.UserNotFoundException;
+import org.codehaus.redback.integration.filter.authentication.HttpAuthenticationException;
+import org.codehaus.redback.integration.filter.authentication.basic.HttpBasicAuthentication;
+import org.codehaus.redback.rest.services.RedbackAuthenticationThreadLocal;
+import org.codehaus.redback.rest.services.RedbackRequestInformation;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Service;
+
+import javax.inject.Inject;
+import javax.inject.Named;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.ws.rs.core.Response;
+
+/**
+ * This interceptor will check if the user is already logged in the session.
+ * If not ask the redback system to authentication trough BASIC http
+ * If the user is logged the AuthenticationResult will in the cxf message with the key AuthenticationResult.class
+ *
+ * @author Olivier Lamy
+ * @since 1.3
+ */
+@Service( "authenticationInterceptor#rest" )
+public class AuthenticationInterceptor
+ extends AbstractInterceptor
+ implements RequestHandler
+{
+ @Inject
+ @Named( value = "userManager#configurable" )
+ private UserManager userManager;
+
+ @Inject
+ @Named( value = "httpAuthenticator#basic" )
+ private HttpBasicAuthentication httpAuthenticator;
+
+ private Logger log = LoggerFactory.getLogger( getClass() );
+
+ public Response handleRequest( Message message, ClassResourceInfo classResourceInfo )
+ {
+
+ RedbackAuthorization redbackAuthorization = getRedbackAuthorization( message );
+ if ( redbackAuthorization == null )
+ {
+ log.warn( "http path {} doesn't contain any informations regarding permissions ",
+ message.get( Message.REQUEST_URI ) );
+ // here we failed to authenticate so 403 as there is no detail on karma for this
+ // it must be marked as it's exposed
+ return Response.status( Response.Status.FORBIDDEN ).build();
+ }
+ HttpServletRequest request = getHttpServletRequest( message );
+ HttpServletResponse response = getHttpServletResponse( message );
+
+ if ( redbackAuthorization.noRestriction() )
+ {
+ // maybe session exists so put it in threadLocal
+ // some services need the current user if logged
+ SecuritySession securitySession = httpAuthenticator.getSecuritySession( request.getSession( true ) );
+
+ if ( securitySession != null )
+ {
+ RedbackRequestInformation redbackRequestInformation =
+ new RedbackRequestInformation( securitySession.getUser(), request.getRemoteAddr() );
+ RedbackAuthenticationThreadLocal.set( redbackRequestInformation );
+ }
+ else
+ {
+ // maybe there is some authz in the request so try it but not fail so catch Exception !
+ try
+ {
+ AuthenticationResult authenticationResult =
+ httpAuthenticator.getAuthenticationResult( request, response );
+
+ if ( ( authenticationResult == null ) || ( !authenticationResult.isAuthenticated() ) )
+ {
+ return null;
+ }
+ // FIXME this is already called previously but authenticationResult doesn't return that
+ User user = userManager.findUser( (String) authenticationResult.getPrincipal() );
+ RedbackRequestInformation redbackRequestInformation =
+ new RedbackRequestInformation( user, request.getRemoteAddr() );
+
+ RedbackAuthenticationThreadLocal.set( redbackRequestInformation );
+ message.put( AuthenticationResult.class, authenticationResult );
+ }
+ catch ( Exception e )
+ {
+ // ignore here
+ }
+ }
+ return null;
+ }
+
+ try
+ {
+ AuthenticationResult authenticationResult = httpAuthenticator.getAuthenticationResult( request, response );
+
+ if ( ( authenticationResult == null ) || ( !authenticationResult.isAuthenticated() ) )
+ {
+ throw new HttpAuthenticationException( "You are not authenticated." );
+ }
+ // FIXME this is already called previously but authenticationResult doesn't return that
+ User user = userManager.findUser( (String) authenticationResult.getPrincipal() );
+ RedbackRequestInformation redbackRequestInformation =
+ new RedbackRequestInformation( user, request.getRemoteAddr() );
+
+ RedbackAuthenticationThreadLocal.set( redbackRequestInformation );
+ message.put( AuthenticationResult.class, authenticationResult );
+
+ return null;
+ }
+ catch ( UserNotFoundException e )
+ {
+ log.debug( "UserNotFoundException for path {}", message.get( Message.REQUEST_URI ) );
+ return Response.status( Response.Status.FORBIDDEN ).build();
+ }
+ catch ( AccountLockedException e )
+ {
+ log.debug( "account locked for path {}", message.get( Message.REQUEST_URI ) );
+ return Response.status( Response.Status.FORBIDDEN ).build();
+
+ }
+ catch ( MustChangePasswordException e )
+ {
+ log.debug( "must change password for path {}", message.get( Message.REQUEST_URI ) );
+ return Response.status( Response.Status.FORBIDDEN ).build();
+
+ }
+ catch ( AuthenticationException e )
+ {
+ log.debug( "failed to authenticate for path {}", message.get( Message.REQUEST_URI ) );
+ return Response.status( Response.Status.FORBIDDEN ).build();
+ }
+ }
+}
Propchange: archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/main/java/org/codehaus/redback/rest/services/interceptors/AuthenticationInterceptor.java
------------------------------------------------------------------------------
svn:eol-style = native
Propchange: archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/main/java/org/codehaus/redback/rest/services/interceptors/AuthenticationInterceptor.java
------------------------------------------------------------------------------
svn:keywords = Author Date Id Revision
Added: archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/main/java/org/codehaus/redback/rest/services/interceptors/DebugJAXRSInInterceptor.java
URL: http://svn.apache.org/viewvc/archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/main/java/org/codehaus/redback/rest/services/interceptors/DebugJAXRSInInterceptor.java?rev=1310268&view=auto
==============================================================================
--- archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/main/java/org/codehaus/redback/rest/services/interceptors/DebugJAXRSInInterceptor.java (added)
+++ archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/main/java/org/codehaus/redback/rest/services/interceptors/DebugJAXRSInInterceptor.java Fri Apr 6 09:58:14 2012
@@ -0,0 +1,17 @@
+package org.codehaus.redback.rest.services.interceptors;
+
+import org.apache.cxf.jaxrs.interceptor.JAXRSInInterceptor;
+import org.apache.cxf.message.Message;
+
+/**
+ * @author Olivier Lamy
+ * @since 1.3
+ */
+public class DebugJAXRSInInterceptor extends JAXRSInInterceptor
+{
+ @Override
+ public void handleMessage( Message message )
+ {
+ super.handleMessage( message );
+ }
+}
Propchange: archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/main/java/org/codehaus/redback/rest/services/interceptors/DebugJAXRSInInterceptor.java
------------------------------------------------------------------------------
svn:eol-style = native
Propchange: archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/main/java/org/codehaus/redback/rest/services/interceptors/DebugJAXRSInInterceptor.java
------------------------------------------------------------------------------
svn:keywords = Author Date Id Revision
Added: archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/main/java/org/codehaus/redback/rest/services/interceptors/JacksonJsonConfigurator.java
URL: http://svn.apache.org/viewvc/archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/main/java/org/codehaus/redback/rest/services/interceptors/JacksonJsonConfigurator.java?rev=1310268&view=auto
==============================================================================
--- archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/main/java/org/codehaus/redback/rest/services/interceptors/JacksonJsonConfigurator.java (added)
+++ archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/main/java/org/codehaus/redback/rest/services/interceptors/JacksonJsonConfigurator.java Fri Apr 6 09:58:14 2012
@@ -0,0 +1,46 @@
+package org.codehaus.redback.rest.services.interceptors;
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+import org.codehaus.jackson.map.DeserializationConfig;
+import org.codehaus.jackson.map.ObjectMapper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Service;
+
+import javax.inject.Inject;
+
+/**
+ * to setup some ObjectMapper configuration
+ *
+ * @author Olivier Lamy
+ * @since 1.5
+ */
+@Service("redbackJacksonJsonConfigurator")
+public class JacksonJsonConfigurator
+{
+ private Logger log = LoggerFactory.getLogger( getClass() );
+
+ @Inject
+ public JacksonJsonConfigurator( ObjectMapper objectMapper )
+ {
+ log.info( "configure jackson ObjectMapper" );
+ objectMapper.configure( DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false );
+ }
+}
Propchange: archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/main/java/org/codehaus/redback/rest/services/interceptors/JacksonJsonConfigurator.java
------------------------------------------------------------------------------
svn:eol-style = native
Propchange: archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/main/java/org/codehaus/redback/rest/services/interceptors/JacksonJsonConfigurator.java
------------------------------------------------------------------------------
svn:keywords = Author Date Id Revision
Added: archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/main/java/org/codehaus/redback/rest/services/interceptors/PasswordRuleViolationExceptionMapper.java
URL: http://svn.apache.org/viewvc/archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/main/java/org/codehaus/redback/rest/services/interceptors/PasswordRuleViolationExceptionMapper.java?rev=1310268&view=auto
==============================================================================
--- archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/main/java/org/codehaus/redback/rest/services/interceptors/PasswordRuleViolationExceptionMapper.java (added)
+++ archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/main/java/org/codehaus/redback/rest/services/interceptors/PasswordRuleViolationExceptionMapper.java Fri Apr 6 09:58:14 2012
@@ -0,0 +1,55 @@
+package org.codehaus.redback.rest.services.interceptors;
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+import org.codehaus.plexus.redback.policy.PasswordRuleViolationException;
+import org.codehaus.plexus.redback.policy.PasswordRuleViolations;
+import org.codehaus.redback.rest.api.model.ErrorMessage;
+import org.codehaus.redback.rest.api.model.RedbackRestError;
+import org.springframework.stereotype.Service;
+
+import javax.ws.rs.core.Response;
+import javax.ws.rs.ext.ExceptionMapper;
+import javax.ws.rs.ext.Provider;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * @author Olivier Lamy
+ * @since 1.4
+ */
+@Provider
+@Service( "passwordRuleViolationExceptionMapper" )
+public class PasswordRuleViolationExceptionMapper
+ implements ExceptionMapper<PasswordRuleViolationException>
+{
+ public Response toResponse( PasswordRuleViolationException e )
+ {
+ RedbackRestError restError = new RedbackRestError();
+
+ List<ErrorMessage> errorMessages = new ArrayList<ErrorMessage>( e.getViolations().getViolations().size() );
+ for ( PasswordRuleViolations.MessageReference messageReference : e.getViolations().getViolations() )
+ {
+ errorMessages.add( new ErrorMessage( messageReference.getKey(), messageReference.getArgs() ) );
+ }
+ restError.setErrorMessages( errorMessages );
+ Response.ResponseBuilder responseBuilder = Response.status( 500 ).entity( restError );
+ return responseBuilder.build();
+ }
+}
Propchange: archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/main/java/org/codehaus/redback/rest/services/interceptors/PasswordRuleViolationExceptionMapper.java
------------------------------------------------------------------------------
svn:eol-style = native
Propchange: archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/main/java/org/codehaus/redback/rest/services/interceptors/PasswordRuleViolationExceptionMapper.java
------------------------------------------------------------------------------
svn:keywords = Author Date Id Revision
Added: archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/main/java/org/codehaus/redback/rest/services/interceptors/PermissionsInterceptor.java
URL: http://svn.apache.org/viewvc/archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/main/java/org/codehaus/redback/rest/services/interceptors/PermissionsInterceptor.java?rev=1310268&view=auto
==============================================================================
--- archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/main/java/org/codehaus/redback/rest/services/interceptors/PermissionsInterceptor.java (added)
+++ archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/main/java/org/codehaus/redback/rest/services/interceptors/PermissionsInterceptor.java Fri Apr 6 09:58:14 2012
@@ -0,0 +1,130 @@
+package org.codehaus.redback.rest.services.interceptors;
+
+/*
+* Copyright 2011 The Codehaus.
+*
+* 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.
+*/
+
+
+import org.apache.commons.lang.StringUtils;
+import org.apache.cxf.jaxrs.ext.RequestHandler;
+import org.apache.cxf.jaxrs.model.ClassResourceInfo;
+import org.apache.cxf.message.Message;
+import org.codehaus.plexus.redback.authentication.AuthenticationResult;
+import org.codehaus.plexus.redback.authorization.AuthorizationException;
+import org.codehaus.plexus.redback.authorization.RedbackAuthorization;
+import org.codehaus.plexus.redback.system.SecuritySession;
+import org.codehaus.plexus.redback.system.SecuritySystem;
+import org.codehaus.redback.integration.filter.authentication.basic.HttpBasicAuthentication;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Service;
+
+import javax.inject.Inject;
+import javax.inject.Named;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.core.Response;
+
+/**
+ * @author Olivier Lamy
+ * @since 1.3
+ */
+@Service( "permissionInterceptor#rest" )
+public class PermissionsInterceptor
+ extends AbstractInterceptor
+ implements RequestHandler
+{
+
+ @Inject
+ @Named( value = "securitySystem" )
+ private SecuritySystem securitySystem;
+
+ @Inject
+ @Named( value = "httpAuthenticator#basic" )
+ private HttpBasicAuthentication httpAuthenticator;
+
+ private Logger log = LoggerFactory.getLogger( getClass() );
+
+ public Response handleRequest( Message message, ClassResourceInfo classResourceInfo )
+ {
+ RedbackAuthorization redbackAuthorization = getRedbackAuthorization( message );
+
+ if ( redbackAuthorization != null )
+ {
+ if ( redbackAuthorization.noRestriction() )
+ {
+ // we are fine this services is marked as non restrictive acces
+ return null;
+ }
+ String[] permissions = redbackAuthorization.permissions();
+ //olamy: no value is an array with an empty String
+ if ( permissions != null && permissions.length > 0 && !( permissions.length == 1 && StringUtils.isEmpty(
+ permissions[0] ) ) )
+ {
+ HttpServletRequest request = getHttpServletRequest( message );
+ SecuritySession session = httpAuthenticator.getSecuritySession( request.getSession() );
+ AuthenticationResult authenticationResult = message.get( AuthenticationResult.class );
+ if ( authenticationResult != null && authenticationResult.isAuthenticated() )
+ {
+ for ( String permission : permissions )
+ {
+ if ( StringUtils.isBlank( permission ) )
+ {
+ continue;
+ }
+ try
+ {
+ if ( securitySystem.isAuthorized( session, permission,
+ StringUtils.isBlank( redbackAuthorization.resource() )
+ ? null
+ : redbackAuthorization.resource() ) )
+ {
+ return null;
+ }
+ else
+ {
+ log.debug( "user {} not authorized for permission {}", session.getUser().getPrincipal(),
+ permission );
+ }
+ }
+ catch ( AuthorizationException e )
+ {
+ log.debug( e.getMessage(), e );
+ return Response.status( Response.Status.FORBIDDEN ).build();
+ }
+ }
+
+ }
+ else
+ {
+ log.debug( "user {} not authenticated", session.getUser().getUsername() );
+ }
+ }
+ else
+ {
+ if ( redbackAuthorization.noPermission() )
+ {
+ log.debug( "path {} doesn't need special permission", message.get( Message.REQUEST_URI ) );
+ return null;
+ }
+ return Response.status( Response.Status.FORBIDDEN ).build();
+ }
+ }
+ log.warn( "http path {} doesn't contain any informations regarding permissions ",
+ message.get( Message.REQUEST_URI ) );
+ // here we failed to authenticate so 403 as there is no detail on karma for this
+ // it must be marked as it's exposed
+ return Response.status( Response.Status.FORBIDDEN ).build();
+ }
+}
Propchange: archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/main/java/org/codehaus/redback/rest/services/interceptors/PermissionsInterceptor.java
------------------------------------------------------------------------------
svn:eol-style = native
Propchange: archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/main/java/org/codehaus/redback/rest/services/interceptors/PermissionsInterceptor.java
------------------------------------------------------------------------------
svn:keywords = Author Date Id Revision
Added: archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/main/java/org/codehaus/redback/rest/services/interceptors/RedbackServiceExceptionMapper.java
URL: http://svn.apache.org/viewvc/archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/main/java/org/codehaus/redback/rest/services/interceptors/RedbackServiceExceptionMapper.java?rev=1310268&view=auto
==============================================================================
--- archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/main/java/org/codehaus/redback/rest/services/interceptors/RedbackServiceExceptionMapper.java (added)
+++ archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/main/java/org/codehaus/redback/rest/services/interceptors/RedbackServiceExceptionMapper.java Fri Apr 6 09:58:14 2012
@@ -0,0 +1,66 @@
+package org.codehaus.redback.rest.services.interceptors;
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+import org.codehaus.redback.rest.api.model.ErrorMessage;
+import org.codehaus.redback.rest.api.model.RedbackRestError;
+import org.codehaus.redback.rest.api.services.RedbackServiceException;
+import org.springframework.stereotype.Service;
+
+import javax.ws.rs.core.Response;
+import javax.ws.rs.ext.ExceptionMapper;
+import javax.ws.rs.ext.Provider;
+
+/**
+ * @author Olivier Lamy
+ * @since 1.4-M2
+ */
+@Provider
+@Service( "redbackServiceExceptionMapper" )
+public class RedbackServiceExceptionMapper
+ implements ExceptionMapper<RedbackServiceException>
+{
+ public Response toResponse( final RedbackServiceException e )
+ {
+ RedbackRestError restError = new RedbackRestError( e );
+
+ Response.ResponseBuilder responseBuilder = Response.status( e.getHttpErrorCode() ).entity( restError );
+ if ( e.getMessage() != null )
+ {
+ responseBuilder = responseBuilder.status( new Response.StatusType()
+ {
+ public int getStatusCode()
+ {
+ return e.getHttpErrorCode();
+ }
+
+ public Response.Status.Family getFamily()
+ {
+ return Response.Status.Family.SERVER_ERROR;
+ }
+
+ public String getReasonPhrase()
+ {
+ return e.getMessage();
+ }
+ } );
+ }
+ return responseBuilder.build();
+ }
+}
Propchange: archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/main/java/org/codehaus/redback/rest/services/interceptors/RedbackServiceExceptionMapper.java
------------------------------------------------------------------------------
svn:eol-style = native
Propchange: archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/main/java/org/codehaus/redback/rest/services/interceptors/RedbackServiceExceptionMapper.java
------------------------------------------------------------------------------
svn:keywords = Author Date Id Revision
Added: archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/main/java/org/codehaus/redback/rest/services/interceptors/ThreadLocalUserCleaner.java
URL: http://svn.apache.org/viewvc/archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/main/java/org/codehaus/redback/rest/services/interceptors/ThreadLocalUserCleaner.java?rev=1310268&view=auto
==============================================================================
--- archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/main/java/org/codehaus/redback/rest/services/interceptors/ThreadLocalUserCleaner.java (added)
+++ archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/main/java/org/codehaus/redback/rest/services/interceptors/ThreadLocalUserCleaner.java Fri Apr 6 09:58:14 2012
@@ -0,0 +1,79 @@
+package org.codehaus.redback.rest.services.interceptors;
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+
+import org.apache.cxf.interceptor.Fault;
+import org.apache.cxf.jaxrs.interceptor.JAXRSInInterceptor;
+import org.apache.cxf.jaxrs.model.OperationResourceInfo;
+import org.apache.cxf.message.Message;
+import org.apache.cxf.phase.AbstractPhaseInterceptor;
+import org.apache.cxf.phase.Phase;
+import org.apache.cxf.phase.PhaseInterceptor;
+import org.codehaus.redback.rest.services.RedbackAuthenticationThreadLocal;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Service;
+
+import javax.ws.rs.core.Response;
+
+/**
+ * @author Olivier Lamy
+ * @since 1.4
+ */
+@Service( "threadLocalUserCleaner#rest" )
+public class ThreadLocalUserCleaner
+ extends AbstractPhaseInterceptor<Message>
+ implements PhaseInterceptor<Message>
+{
+ private Logger log = LoggerFactory.getLogger( getClass() );
+
+ public ThreadLocalUserCleaner( String phase )
+ {
+ super( phase );
+ addAfter( JAXRSInInterceptor.class.getName() );
+ }
+
+
+ public ThreadLocalUserCleaner()
+ {
+ super( Phase.PRE_STREAM );
+ addAfter( JAXRSInInterceptor.class.getName() );
+ }
+
+
+ public Response handleResponse( Message message, OperationResourceInfo operationResourceInfo, Response response )
+ {
+ log.debug( "handleResponse" );
+ cleanup();
+ return null;
+ }
+
+ private void cleanup()
+ {
+ RedbackAuthenticationThreadLocal.set( null );
+ }
+
+ public void handleMessage( Message message )
+ throws Fault
+ {
+ log.debug( "handleMessage" );
+ cleanup();
+ }
+}
Propchange: archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/main/java/org/codehaus/redback/rest/services/interceptors/ThreadLocalUserCleaner.java
------------------------------------------------------------------------------
svn:eol-style = native
Propchange: archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/main/java/org/codehaus/redback/rest/services/interceptors/ThreadLocalUserCleaner.java
------------------------------------------------------------------------------
svn:keywords = Author Date Id Revision
Added: archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/main/java/org/codehaus/redback/rest/services/utils/EnvironmentChecker.java
URL: http://svn.apache.org/viewvc/archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/main/java/org/codehaus/redback/rest/services/utils/EnvironmentChecker.java?rev=1310268&view=auto
==============================================================================
--- archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/main/java/org/codehaus/redback/rest/services/utils/EnvironmentChecker.java (added)
+++ archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/main/java/org/codehaus/redback/rest/services/utils/EnvironmentChecker.java Fri Apr 6 09:58:14 2012
@@ -0,0 +1,76 @@
+package org.codehaus.redback.rest.services.utils;
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+import org.codehaus.plexus.redback.system.check.EnvironmentCheck;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.context.ApplicationContext;
+import org.springframework.stereotype.Service;
+
+import javax.inject.Inject;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+
+/**
+ * @author Olivier Lamy
+ * @since 1.4
+ */
+@Service("environmentChecker#rest")
+public class EnvironmentChecker
+{
+
+ private Logger log = LoggerFactory.getLogger( getClass() );
+
+
+ @Inject
+ public EnvironmentChecker( ApplicationContext applicationContext )
+ {
+ Collection<EnvironmentCheck> checkers = applicationContext.getBeansOfType( EnvironmentCheck.class ).values();
+
+ if ( checkers != null )
+ {
+ List<String> violations = new ArrayList<String>();
+
+ for ( EnvironmentCheck check : checkers )
+ {
+ check.validateEnvironment( violations );
+ }
+
+ if ( !violations.isEmpty() )
+ {
+ StringBuilder msg = new StringBuilder();
+ msg.append( "EnvironmentCheck Failure.\n" );
+ msg.append( "======================================================================\n" );
+ msg.append( " ENVIRONMENT FAILURE !! \n" );
+ msg.append( "\n" );
+
+ for ( String v : violations )
+ {
+ msg.append( v ).append( "\n" );
+ }
+
+ msg.append( "\n" );
+ msg.append( "======================================================================" );
+ log.error( msg.toString() );
+ }
+ }
+ }
+}
Propchange: archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/main/java/org/codehaus/redback/rest/services/utils/EnvironmentChecker.java
------------------------------------------------------------------------------
svn:eol-style = native
Propchange: archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/main/java/org/codehaus/redback/rest/services/utils/EnvironmentChecker.java
------------------------------------------------------------------------------
svn:keywords = Author Date Id Revision
Added: archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/main/java/org/codehaus/redback/rest/services/utils/PasswordValidator.java
URL: http://svn.apache.org/viewvc/archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/main/java/org/codehaus/redback/rest/services/utils/PasswordValidator.java?rev=1310268&view=auto
==============================================================================
--- archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/main/java/org/codehaus/redback/rest/services/utils/PasswordValidator.java (added)
+++ archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/main/java/org/codehaus/redback/rest/services/utils/PasswordValidator.java Fri Apr 6 09:58:14 2012
@@ -0,0 +1,103 @@
+package org.codehaus.redback.rest.services.utils;
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+import org.codehaus.plexus.redback.policy.PasswordEncoder;
+import org.codehaus.plexus.redback.policy.PasswordRuleViolationException;
+import org.codehaus.plexus.redback.policy.PasswordRuleViolations;
+import org.codehaus.plexus.redback.system.SecuritySystem;
+import org.codehaus.plexus.redback.users.User;
+import org.codehaus.plexus.redback.users.UserNotFoundException;
+import org.codehaus.redback.rest.api.model.ErrorMessage;
+import org.codehaus.redback.rest.api.services.RedbackServiceException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Service;
+
+import javax.inject.Inject;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * @author Olivier Lamy
+ * @since 1.4
+ */
+@Service( "passwordValidator#rest" )
+public class PasswordValidator
+{
+
+ private Logger log = LoggerFactory.getLogger( getClass() );
+
+ @Inject
+ private SecuritySystem securitySystem;
+
+ /**
+ *
+ * @param password
+ * @param principal
+ * @return encoded password
+ * @throws RedbackServiceException
+ */
+ public String validatePassword( String password, String principal )
+ throws RedbackServiceException
+ {
+ try
+ {
+ // password validation with a tmp user
+ User tempUser = securitySystem.getUserManager().createUser( "temp", "temp", "temp" );
+ tempUser.setPassword( password );
+ securitySystem.getPolicy().validatePassword( tempUser );
+
+ PasswordEncoder encoder = securitySystem.getPolicy().getPasswordEncoder();
+
+ User user = securitySystem.getUserManager().findUser( principal );
+ String encodedPassword = encoder.encodePassword( password );
+ user.setEncodedPassword( encodedPassword );
+ user.setPassword( password );
+
+ securitySystem.getPolicy().validatePassword( user );
+
+ return encodedPassword;
+ }
+ catch ( UserNotFoundException e )
+ {
+ log.info( "user {} not found", e.getMessage() );
+ List<ErrorMessage> errorMessages = new ArrayList<ErrorMessage>( 2 );
+ ErrorMessage errorMessage = new ErrorMessage( "cannot.update.user.not.found", new String[]{ principal } );
+ errorMessages.add( errorMessage );
+ errorMessage = new ErrorMessage( "admin.deleted.account" );
+ errorMessages.add( errorMessage );
+ throw new RedbackServiceException( errorMessages );
+ }
+ catch ( PasswordRuleViolationException e )
+ {
+ PasswordRuleViolations violations = e.getViolations();
+ List<ErrorMessage> errorMessages = new ArrayList<ErrorMessage>( violations.getViolations().size() );
+ if ( violations != null )
+ {
+ for ( String violation : violations.getLocalizedViolations() )
+ {
+ errorMessages.add( new ErrorMessage( violation ) );
+ }
+ }
+ throw new RedbackServiceException( errorMessages );
+ }
+
+ }
+}
Propchange: archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/main/java/org/codehaus/redback/rest/services/utils/PasswordValidator.java
------------------------------------------------------------------------------
svn:eol-style = native
Propchange: archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/main/java/org/codehaus/redback/rest/services/utils/PasswordValidator.java
------------------------------------------------------------------------------
svn:keywords = Author Date Id Revision
Added: archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/main/resources/META-INF/spring-context.xml
URL: http://svn.apache.org/viewvc/archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/main/resources/META-INF/spring-context.xml?rev=1310268&view=auto
==============================================================================
--- archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/main/resources/META-INF/spring-context.xml (added)
+++ archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/main/resources/META-INF/spring-context.xml Fri Apr 6 09:58:14 2012
@@ -0,0 +1,70 @@
+<?xml version="1.0"?>
+
+<!--
+ ~ Licensed to the Apache Software Foundation (ASF) under one
+ ~ or more contributor license agreements. See the NOTICE file
+ ~ distributed with this work for additional information
+ ~ regarding copyright ownership. The ASF licenses this file
+ ~ to you 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.
+ -->
+<beans xmlns="http://www.springframework.org/schema/beans"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xmlns:context="http://www.springframework.org/schema/context"
+ xmlns:jaxrs="http://cxf.apache.org/jaxrs"
+ xsi:schemaLocation="http://www.springframework.org/schema/beans
+ http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+ http://www.springframework.org/schema/context
+ http://www.springframework.org/schema/context/spring-context-3.0.xsd
+ http://cxf.apache.org/jaxrs
+ http://cxf.apache.org/schemas/jaxrs.xsd">
+
+ <import resource="classpath:META-INF/cxf/cxf.xml"/>
+ <!--
+ <import resource="classpath:META-INF/cxf/cxf-extension-jaxrs-binding.xml"/>
+ -->
+ <import resource="classpath:META-INF/cxf/cxf-servlet.xml"/>
+
+ <context:annotation-config />
+ <context:component-scan
+ base-package="org.codehaus.redback.rest.services"/>
+
+ <bean id="jsonProvider" class="org.codehaus.jackson.jaxrs.JacksonJsonProvider">
+ <property name="mapper" ref="redbackJacksonMapper"/>
+ </bean>
+
+ <bean id="redbackJacksonMapper" class="org.codehaus.jackson.map.ObjectMapper">
+ </bean>
+
+ <jaxrs:server id="redbackServices" address="/redbackServices">
+
+ <jaxrs:serviceBeans>
+ <ref bean="userService#rest"/>
+ <ref bean="loginService#rest"/>
+ <ref bean="roleManagementService#rest"/>
+ <ref bean="utilServices#rest"/>
+ <ref bean="passwordService#rest"/>
+ </jaxrs:serviceBeans>
+ <jaxrs:outInterceptors>
+ <ref bean="threadLocalUserCleaner#rest"/>
+ </jaxrs:outInterceptors>
+ <jaxrs:providers>
+ <ref bean="jsonProvider"/>
+ <ref bean="authenticationInterceptor#rest"/>
+ <ref bean="permissionInterceptor#rest"/>
+ <ref bean="redbackServiceExceptionMapper"/>
+ <ref bean="passwordRuleViolationExceptionMapper"/>
+ </jaxrs:providers>
+ </jaxrs:server>
+
+</beans>
\ No newline at end of file
Propchange: archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/main/resources/META-INF/spring-context.xml
------------------------------------------------------------------------------
svn:eol-style = native
Propchange: archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/main/resources/META-INF/spring-context.xml
------------------------------------------------------------------------------
svn:keywords = Author Date Id Revision
Added: archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/test/java/org/codehaus/redback/rest/services/AbstractRestServicesTest.java
URL: http://svn.apache.org/viewvc/archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/test/java/org/codehaus/redback/rest/services/AbstractRestServicesTest.java?rev=1310268&view=auto
==============================================================================
--- archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/test/java/org/codehaus/redback/rest/services/AbstractRestServicesTest.java (added)
+++ archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/test/java/org/codehaus/redback/rest/services/AbstractRestServicesTest.java Fri Apr 6 09:58:14 2012
@@ -0,0 +1,220 @@
+package org.codehaus.redback.rest.services;
+
+/*
+ * Copyright 2011 The Codehaus.
+ *
+ * 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.
+ */
+
+import junit.framework.TestCase;
+import org.apache.commons.lang.StringUtils;
+import org.apache.cxf.common.util.Base64Utility;
+import org.apache.cxf.jaxrs.client.JAXRSClientFactory;
+import org.apache.cxf.jaxrs.client.WebClient;
+import org.apache.cxf.transport.servlet.CXFServlet;
+import org.codehaus.jackson.jaxrs.JacksonJaxbJsonProvider;
+import org.codehaus.redback.integration.security.role.RedbackRoleConstants;
+import org.codehaus.redback.rest.api.model.User;
+import org.codehaus.redback.rest.api.services.LoginService;
+import org.codehaus.redback.rest.api.services.RoleManagementService;
+import org.codehaus.redback.rest.api.services.UserService;
+import org.eclipse.jetty.server.Connector;
+import org.eclipse.jetty.server.Server;
+import org.eclipse.jetty.server.session.SessionHandler;
+import org.eclipse.jetty.servlet.ServletContextHandler;
+import org.eclipse.jetty.servlet.ServletHolder;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.web.context.ContextLoaderListener;
+
+import javax.ws.rs.core.MediaType;
+import java.util.Collections;
+
+/**
+ * @author Olivier Lamy
+ */
+@RunWith( JUnit4.class )
+public abstract class AbstractRestServicesTest
+ extends TestCase
+{
+ protected Logger log = LoggerFactory.getLogger( getClass() );
+
+ public Server server = null;
+
+ //private Tomcat tomcat;
+
+ public int port;
+
+ public String authorizationHeader = getAdminAuthzHeader();
+
+
+ public static String encode( String uid, String password )
+ {
+ return "Basic " + Base64Utility.encode( ( uid + ":" + password ).getBytes() );
+ }
+
+ public static String getAdminAuthzHeader()
+ {
+ String adminPwdSysProps = System.getProperty( "rest.admin.pwd" );
+ if ( StringUtils.isBlank( adminPwdSysProps ) )
+ {
+ return encode( RedbackRoleConstants.ADMINISTRATOR_ACCOUNT_NAME, FakeCreateAdminService.ADMIN_TEST_PWD );
+ }
+ return encode( RedbackRoleConstants.ADMINISTRATOR_ACCOUNT_NAME, adminPwdSysProps );
+ }
+
+ protected String getSpringConfigLocation()
+ {
+ return "classpath*:META-INF/spring-context.xml";
+ }
+
+
+ protected String getRestServicesPath()
+ {
+ return "restServices";
+ }
+
+ static boolean useTomcat = Boolean.getBoolean( "test.useTomcat" );
+
+ @Before
+ public void startServer()
+ throws Exception
+ {
+
+ this.server = new Server( 0 );
+
+ ServletContextHandler context = new ServletContextHandler();
+
+ context.setContextPath( "/" );
+
+ context.setInitParameter( "contextConfigLocation", getSpringConfigLocation() );
+
+ ContextLoaderListener contextLoaderListener = new ContextLoaderListener();
+
+ context.addEventListener( contextLoaderListener );
+
+ ServletHolder sh = new ServletHolder( CXFServlet.class );
+
+ SessionHandler sessionHandler = new SessionHandler();
+
+ context.setSessionHandler( sessionHandler );
+
+ context.addServlet( sh, "/" + getRestServicesPath() + "/*" );
+ server.setHandler( context );
+ this.server.start();
+ Connector connector = this.server.getConnectors()[0];
+ this.port = connector.getLocalPort();
+
+ log.info( "start server on port " + this.port );
+
+ UserService userService = getUserService();
+
+ User adminUser = new User();
+ adminUser.setUsername( RedbackRoleConstants.ADMINISTRATOR_ACCOUNT_NAME );
+ adminUser.setPassword( FakeCreateAdminServiceImpl.ADMIN_TEST_PWD );
+ adminUser.setFullName( "the admin user" );
+ adminUser.setEmail( "toto@toto.fr" );
+ Boolean res = userService.createAdminUser( adminUser );
+
+ FakeCreateAdminService fakeCreateAdminService = getFakeCreateAdminService();
+ //assertTrue( res.booleanValue() );
+
+ }
+
+ protected FakeCreateAdminService getFakeCreateAdminService()
+ {
+ return JAXRSClientFactory.create(
+ "http://localhost:" + port + "/" + getRestServicesPath() + "/fakeCreateAdminService/",
+ FakeCreateAdminService.class, Collections.singletonList( new JacksonJaxbJsonProvider() ) );
+ }
+
+ @After
+ public void stopServer()
+ throws Exception
+ {
+ if ( this.server != null && this.server.isRunning() )
+ {
+ this.server.stop();
+ }
+ }
+
+ protected UserService getUserService()
+ {
+ return getUserService( null );
+ }
+
+ protected UserService getUserService( String authzHeader )
+ {
+ UserService service =
+ JAXRSClientFactory.create( "http://localhost:" + port + "/" + getRestServicesPath() + "/redbackServices/",
+ UserService.class, Collections.singletonList( new JacksonJaxbJsonProvider() ) );
+
+ // for debuging purpose
+ WebClient.getConfig( service ).getHttpConduit().getClient().setReceiveTimeout( 100000 );
+
+ if ( authzHeader != null )
+ {
+ WebClient.client( service ).header( "Authorization", authzHeader );
+ }
+ WebClient.client( service ).accept( MediaType.APPLICATION_JSON_TYPE );
+ WebClient.client( service ).type( MediaType.APPLICATION_JSON_TYPE );
+
+ return service;
+ }
+
+ protected RoleManagementService getRoleManagementService( String authzHeader )
+ {
+ RoleManagementService service =
+ JAXRSClientFactory.create( "http://localhost:" + port + "/" + getRestServicesPath() + "/redbackServices/",
+ RoleManagementService.class,
+ Collections.singletonList( new JacksonJaxbJsonProvider() ) );
+
+ // for debuging purpose
+ WebClient.getConfig( service ).getHttpConduit().getClient().setReceiveTimeout( 100000 );
+
+ if ( authzHeader != null )
+ {
+ WebClient.client( service ).header( "Authorization", authzHeader );
+ }
+
+ WebClient.client( service ).accept( MediaType.APPLICATION_JSON_TYPE );
+ WebClient.client( service ).type( MediaType.APPLICATION_JSON_TYPE );
+
+ return service;
+ }
+
+ protected LoginService getLoginService( String authzHeader )
+ {
+ LoginService service =
+ JAXRSClientFactory.create( "http://localhost:" + port + "/" + getRestServicesPath() + "/redbackServices/",
+ LoginService.class, Collections.singletonList( new JacksonJaxbJsonProvider() ) );
+
+ // for debuging purpose
+ WebClient.getConfig( service ).getHttpConduit().getClient().setReceiveTimeout( 100000 );
+
+ if ( authzHeader != null )
+ {
+ WebClient.client( service ).header( "Authorization", authzHeader );
+ }
+
+ WebClient.client( service ).accept( MediaType.APPLICATION_JSON_TYPE );
+ WebClient.client( service ).type( MediaType.APPLICATION_JSON_TYPE );
+
+ return service;
+ }
+
+}
Propchange: archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/test/java/org/codehaus/redback/rest/services/AbstractRestServicesTest.java
------------------------------------------------------------------------------
svn:eol-style = native
Propchange: archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/test/java/org/codehaus/redback/rest/services/AbstractRestServicesTest.java
------------------------------------------------------------------------------
svn:keywords = Author Date Id Revision
Added: archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/test/java/org/codehaus/redback/rest/services/FakeCreateAdminService.java
URL: http://svn.apache.org/viewvc/archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/test/java/org/codehaus/redback/rest/services/FakeCreateAdminService.java?rev=1310268&view=auto
==============================================================================
--- archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/test/java/org/codehaus/redback/rest/services/FakeCreateAdminService.java (added)
+++ archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/test/java/org/codehaus/redback/rest/services/FakeCreateAdminService.java Fri Apr 6 09:58:14 2012
@@ -0,0 +1,42 @@
+package org.codehaus.redback.rest.services;
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+import org.codehaus.plexus.redback.authorization.RedbackAuthorization;
+
+import javax.ws.rs.GET;
+import javax.ws.rs.Path;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.MediaType;
+
+/**
+ * @author Olivier Lamy
+ */
+@Path( "fakeCreateAdminService" )
+public interface FakeCreateAdminService
+{
+
+ public static final String ADMIN_TEST_PWD = "rose210208";
+
+ @Path( "/testAuthzWithoutKarmasNeeded" )
+ @GET
+ @Produces( { MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_PLAIN } )
+ @RedbackAuthorization( noRestriction = false, noPermission = true )
+ Boolean testAuthzWithoutKarmasNeededButAuthz();
+}
Propchange: archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/test/java/org/codehaus/redback/rest/services/FakeCreateAdminService.java
------------------------------------------------------------------------------
svn:eol-style = native
Propchange: archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/test/java/org/codehaus/redback/rest/services/FakeCreateAdminService.java
------------------------------------------------------------------------------
svn:keywords = Author Date Id Revision
Added: archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/test/java/org/codehaus/redback/rest/services/FakeCreateAdminServiceImpl.java
URL: http://svn.apache.org/viewvc/archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/test/java/org/codehaus/redback/rest/services/FakeCreateAdminServiceImpl.java?rev=1310268&view=auto
==============================================================================
--- archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/test/java/org/codehaus/redback/rest/services/FakeCreateAdminServiceImpl.java (added)
+++ archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/test/java/org/codehaus/redback/rest/services/FakeCreateAdminServiceImpl.java Fri Apr 6 09:58:14 2012
@@ -0,0 +1,59 @@
+package org.codehaus.redback.rest.services;
+
+/*
+ * Copyright 2011 The Codehaus.
+ *
+ * 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.
+ */
+
+import org.codehaus.plexus.redback.configuration.UserConfiguration;
+import org.codehaus.plexus.redback.rbac.RBACManager;
+import org.codehaus.plexus.redback.role.RoleManager;
+import org.codehaus.plexus.redback.users.User;
+import org.codehaus.plexus.redback.users.UserManager;
+import org.codehaus.plexus.redback.users.UserNotFoundException;
+import org.codehaus.redback.integration.security.role.RedbackRoleConstants;
+import org.codehaus.redback.rest.api.services.UserService;
+
+import javax.inject.Inject;
+import javax.inject.Named;
+
+/**
+ * @author Olivier Lamy
+ */
+//Service( "fakeCreateAdminService" )
+public class FakeCreateAdminServiceImpl
+ implements FakeCreateAdminService
+{
+ @Inject
+ @Named( value = "rBACManager#jdo" )
+ private RBACManager rbacManager;
+
+ @Inject
+ @Named( value = "userManager#jdo" )
+ private UserManager userManager;
+
+ @Inject
+ private UserConfiguration config;
+
+ @Inject
+ private RoleManager roleManager;
+
+ @Inject
+ private UserService userService;
+
+ public Boolean testAuthzWithoutKarmasNeededButAuthz()
+ {
+ return Boolean.TRUE;
+ }
+}
Propchange: archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/test/java/org/codehaus/redback/rest/services/FakeCreateAdminServiceImpl.java
------------------------------------------------------------------------------
svn:eol-style = native
Propchange: archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/test/java/org/codehaus/redback/rest/services/FakeCreateAdminServiceImpl.java
------------------------------------------------------------------------------
svn:keywords = Author Date Id Revision
Added: archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/test/java/org/codehaus/redback/rest/services/LoginServiceTest.java
URL: http://svn.apache.org/viewvc/archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/test/java/org/codehaus/redback/rest/services/LoginServiceTest.java?rev=1310268&view=auto
==============================================================================
--- archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/test/java/org/codehaus/redback/rest/services/LoginServiceTest.java (added)
+++ archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/test/java/org/codehaus/redback/rest/services/LoginServiceTest.java Fri Apr 6 09:58:14 2012
@@ -0,0 +1,71 @@
+package org.codehaus.redback.rest.services;
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+import org.codehaus.redback.integration.security.role.RedbackRoleConstants;
+import org.codehaus.redback.rest.api.model.User;
+import org.codehaus.redback.rest.api.services.UserService;
+import org.junit.Test;
+
+/**
+ * @author Olivier Lamy
+ */
+public class LoginServiceTest
+ extends AbstractRestServicesTest
+{
+ @Test
+ public void loginAdmin( )
+ throws Exception
+ {
+ assertNotNull( getLoginService( null ).logIn( RedbackRoleConstants.ADMINISTRATOR_ACCOUNT_NAME,
+ FakeCreateAdminService.ADMIN_TEST_PWD ) );
+ }
+
+ @Test
+ public void createUserThenLog( )
+ throws Exception
+ {
+ try
+ {
+
+ // START SNIPPET: create-user
+ User user = new User( "toto", "toto the king", "toto@toto.fr", false, false );
+ user.setPassword( "foo123" );
+ user.setPermanent( false );
+ user.setPasswordChangeRequired( false );
+ user.setLocked( false );
+ user.setValidated( true );
+ UserService userService = getUserService( authorizationHeader );
+ userService.createUser( user );
+ // END SNIPPET: create-user
+ user = userService.getUser( "toto" );
+ assertNotNull( user );
+ assertEquals( "toto the king", user.getFullName( ) );
+ assertEquals( "toto@toto.fr", user.getEmail( ) );
+ getLoginService( encode( "toto", "foo123" ) ).pingWithAutz( );
+ }
+ finally
+ {
+ getUserService( authorizationHeader ).deleteUser( "toto" );
+ getUserService( authorizationHeader ).removeFromCache( "toto" );
+ assertNull( getUserService( authorizationHeader ).getUser( "toto" ) );
+ }
+ }
+
+}
Propchange: archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/test/java/org/codehaus/redback/rest/services/LoginServiceTest.java
------------------------------------------------------------------------------
svn:eol-style = native
Propchange: archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/test/java/org/codehaus/redback/rest/services/LoginServiceTest.java
------------------------------------------------------------------------------
svn:keywords = Author Date Id Revision
Added: archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/test/java/org/codehaus/redback/rest/services/RoleManagementServiceTest.java
URL: http://svn.apache.org/viewvc/archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/test/java/org/codehaus/redback/rest/services/RoleManagementServiceTest.java?rev=1310268&view=auto
==============================================================================
--- archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/test/java/org/codehaus/redback/rest/services/RoleManagementServiceTest.java (added)
+++ archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/test/java/org/codehaus/redback/rest/services/RoleManagementServiceTest.java Fri Apr 6 09:58:14 2012
@@ -0,0 +1,264 @@
+package org.codehaus.redback.rest.services;
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+import org.apache.commons.lang.StringUtils;
+import org.apache.cxf.jaxrs.client.ServerWebApplicationException;
+import org.codehaus.redback.rest.api.model.ApplicationRoles;
+import org.codehaus.redback.rest.api.model.Role;
+import org.codehaus.redback.rest.api.model.User;
+import org.codehaus.redback.rest.api.services.RoleManagementService;
+import org.codehaus.redback.rest.api.services.UserService;
+import org.junit.Test;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+/**
+ * @author Olivier Lamy
+ */
+public class RoleManagementServiceTest
+ extends AbstractRestServicesTest
+{
+
+
+ @Test
+ public void roleExist()
+ throws Exception
+ {
+ assertTrue( getRoleManagementService( authorizationHeader ).roleExists( "guest" ) );
+ assertFalse( getRoleManagementService( authorizationHeader ).roleExists( "foo" ) );
+ }
+
+ @Test( expected = ServerWebApplicationException.class )
+ public void roleExistBadAuthz()
+ throws Exception
+ {
+ try
+ {
+ assertTrue( getRoleManagementService( null ).roleExists( "guest" ) );
+ }
+ catch ( ServerWebApplicationException e )
+ {
+ assertEquals( 403, e.getStatus() );
+ throw e;
+ }
+ }
+
+ @Test
+ public void createUserThenAssignRole()
+ throws Exception
+ {
+ try
+ {
+ User user = new User( "toto", "toto the king", "toto@toto.fr", false, false );
+ user.setPassword( "foo123" );
+ UserService userService = getUserService( authorizationHeader );
+ userService.createUser( user );
+ user = userService.getUser( "toto" );
+ user.setPasswordChangeRequired( false );
+ userService.updateUser( user );
+ assertNotNull( user );
+ assertEquals( "toto the king", user.getFullName() );
+ assertEquals( "toto@toto.fr", user.getEmail() );
+
+ // should fail toto doesn't have karma
+ try
+ {
+ getUserService( encode( "toto", "foo123" ) ).getUsers();
+ fail( "should fail with 403" );
+ }
+ catch ( ServerWebApplicationException e )
+ {
+ assertEquals( 403, e.getStatus() );
+
+ }
+
+ // assign the role and retry
+ getRoleManagementService( authorizationHeader ).assignRole( "user-administrator", "toto" );
+
+ userService.removeFromCache( "toto" );
+
+ getUserService( encode( "toto", "foo123" ) ).getUsers();
+
+ List<Role> roles = getRoleManagementService( authorizationHeader ).getEffectivelyAssignedRoles( "toto" );
+
+ log.info( "toto roles:" + roles );
+
+ assertTrue( roles.contains( new Role( "User Administrator" ) ) );
+ }
+ finally
+ {
+ getUserService( authorizationHeader ).deleteUser( "toto" );
+ getUserService( authorizationHeader ).removeFromCache( "toto" );
+ assertNull( getUserService( authorizationHeader ).getUser( "toto" ) );
+ }
+
+ }
+
+ @Test
+ public void allRoles()
+ throws Exception
+ {
+ List<Role> roles = getRoleManagementService( authorizationHeader ).getAllRoles();
+
+ log.info( "all roles" );
+
+ for ( Role role : roles )
+ {
+ log.info( "role:" + role );
+ }
+ }
+
+ @Test
+ public void getRole()
+ throws Exception
+ {
+ Role role = getRoleManagementService( authorizationHeader ).getRole( "User Administrator" );
+
+ log.info( "role:" + role );
+
+ }
+
+ @Test
+ public void updateRoleDescription()
+ throws Exception
+ {
+ String name = "User Administrator";
+ Role role = getRoleManagementService( authorizationHeader ).getRole( name );
+ assertTrue( StringUtils.isEmpty( role.getDescription() ) );
+
+ getRoleManagementService( authorizationHeader ).updateRoleDescription( name, "foo" );
+
+ role = getRoleManagementService( authorizationHeader ).getRole( name );
+
+ assertEquals( "foo", role.getDescription() );
+
+ getRoleManagementService( authorizationHeader ).updateRoleDescription( name, null );
+
+ role = getRoleManagementService( authorizationHeader ).getRole( name );
+
+ assertTrue( StringUtils.isEmpty( role.getDescription() ) );
+
+ }
+
+ @Test
+ public void updateRoleUsers()
+ throws Exception
+ {
+ String name = "User Administrator";
+ Role role = getRoleManagementService( authorizationHeader ).getRole( name );
+
+ assertEquals( 0, role.getUsers().size() );
+
+ role.setUsers( Arrays.asList( getUserService( authorizationHeader ).getUser( "admin" ) ) );
+
+ getRoleManagementService( authorizationHeader ).updateRoleUsers( role );
+
+ role = getRoleManagementService( authorizationHeader ).getRole( name );
+
+ assertEquals( 1, role.getUsers().size() );
+
+ role.setRemovedUsers( Arrays.asList( getUserService( authorizationHeader ).getUser( "admin" ) ) );
+ role.setUsers( Collections.<User>emptyList() );
+
+ getRoleManagementService( authorizationHeader ).updateRoleUsers( role );
+
+ role = getRoleManagementService( authorizationHeader ).getRole( name );
+
+ assertEquals( 0, role.getUsers().size() );
+
+ }
+
+ @Test
+ public void applicationRoles()
+ throws Exception
+ {
+ RoleManagementService roleManagementService = getRoleManagementService( authorizationHeader );
+
+
+ List<Role> allRoles = roleManagementService.getAllRoles();
+
+ assertNotNull( allRoles );
+
+ int initialSize = allRoles.size();
+
+ roleManagementService.createTemplatedRole( "archiva-repository-observer", "internal" );
+
+ allRoles = roleManagementService.getAllRoles();
+
+ assertNotNull( allRoles );
+
+ assertEquals( initialSize + 1, allRoles.size() );
+
+ assertRoleExist( "Repository Observer - internal", allRoles );
+
+ roleManagementService.createTemplatedRole( "archiva-repository-manager", "internal" );
+
+ allRoles = roleManagementService.getAllRoles();
+
+ assertNotNull( allRoles );
+
+ assertEquals( initialSize + 2, allRoles.size() );
+
+ assertRoleExist( "Repository Manager - internal", allRoles );
+
+ roleManagementService.createTemplatedRole( "archiva-repository-observer", "snapshots" );
+
+ allRoles = roleManagementService.getAllRoles();
+
+ assertNotNull( allRoles );
+
+ assertEquals( initialSize + 3, allRoles.size() );
+
+ assertRoleExist( "Repository Observer - snapshots", allRoles );
+
+ roleManagementService.createTemplatedRole( "archiva-repository-manager", "snapshots" );
+
+ allRoles = roleManagementService.getAllRoles();
+
+ assertNotNull( allRoles );
+
+ assertEquals( initialSize + 4, allRoles.size() );
+
+ assertRoleExist( "Repository Manager - snapshots", allRoles );
+
+ List<ApplicationRoles> applicationRoleList = roleManagementService.getApplicationRoles( "guest" );
+
+ assertNotNull( applicationRoleList );
+
+ for ( ApplicationRoles applicationRoles : applicationRoleList )
+ {
+ log.info( "applicationRoles:" + applicationRoles );
+ }
+ }
+
+ private void assertRoleExist( String roleName, List<Role> allRoles )
+ {
+ for ( Role role : allRoles )
+ {
+ if ( StringUtils.equals( roleName, role.getName() ) )
+ {
+ return;
+ }
+ }
+ fail( "role " + roleName + " not exists" );
+ }
+}
Propchange: archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/test/java/org/codehaus/redback/rest/services/RoleManagementServiceTest.java
------------------------------------------------------------------------------
svn:eol-style = native
Propchange: archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/test/java/org/codehaus/redback/rest/services/RoleManagementServiceTest.java
------------------------------------------------------------------------------
svn:keywords = Author Date Id Revision
Added: archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/test/java/org/codehaus/redback/rest/services/UserServiceTest.java
URL: http://svn.apache.org/viewvc/archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/test/java/org/codehaus/redback/rest/services/UserServiceTest.java?rev=1310268&view=auto
==============================================================================
--- archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/test/java/org/codehaus/redback/rest/services/UserServiceTest.java (added)
+++ archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/test/java/org/codehaus/redback/rest/services/UserServiceTest.java Fri Apr 6 09:58:14 2012
@@ -0,0 +1,329 @@
+package org.codehaus.redback.rest.services;
+
+/*
+ * Copyright 2011 The Codehaus.
+ *
+ * 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.
+ */
+
+import org.apache.cxf.jaxrs.client.JAXRSClientFactory;
+import org.apache.cxf.jaxrs.client.ServerWebApplicationException;
+import org.apache.cxf.jaxrs.client.WebClient;
+import org.codehaus.jackson.jaxrs.JacksonJaxbJsonProvider;
+import org.codehaus.redback.rest.api.model.Operation;
+import org.codehaus.redback.rest.api.model.Permission;
+import org.codehaus.redback.rest.api.model.User;
+import org.codehaus.redback.rest.api.services.UserService;
+import org.codehaus.redback.rest.services.mock.EmailMessage;
+import org.codehaus.redback.rest.services.mock.ServicesAssert;
+import org.junit.Test;
+
+import javax.ws.rs.core.MediaType;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+
+/**
+ * @author Olivier Lamy
+ */
+public class UserServiceTest
+ extends AbstractRestServicesTest
+{
+
+
+ @Test
+ public void ping()
+ throws Exception
+ {
+ Boolean res = getUserService().ping();
+ assertTrue( res.booleanValue() );
+ }
+
+ @Test
+ public void getUsers()
+ throws Exception
+ {
+ UserService userService = getUserService();
+
+ WebClient.client( userService ).header( "Authorization", authorizationHeader );
+
+ List<User> users = userService.getUsers();
+ assertTrue( users != null );
+ assertFalse( users.isEmpty() );
+ }
+
+ @Test( expected = ServerWebApplicationException.class )
+ public void getUsersWithoutAuthz()
+ throws Exception
+ {
+ UserService userService = getUserService();
+ try
+ {
+ userService.getUsers();
+ }
+ catch ( ServerWebApplicationException e )
+ {
+ assertEquals( 403, e.getStatus() );
+ throw e;
+ }
+
+ }
+
+ @Test
+ public void getNoPermissionNotAuthz()
+ throws Exception
+ {
+
+ try
+ {
+ getFakeCreateAdminService().testAuthzWithoutKarmasNeededButAuthz();
+ }
+ catch ( ServerWebApplicationException e )
+ {
+ assertEquals( 403, e.getStatus() );
+ }
+ }
+
+ @Test
+ public void getNoPermissionAuthz()
+ throws Exception
+ {
+
+ try
+ {
+ FakeCreateAdminService service = getFakeCreateAdminService();
+
+ WebClient.client( service ).header( "Authorization", authorizationHeader );
+
+ assertTrue( service.testAuthzWithoutKarmasNeededButAuthz().booleanValue() );
+
+ }
+ catch ( ServerWebApplicationException e )
+ {
+ assertEquals( 403, e.getStatus() );
+ }
+ }
+
+ @Test
+ public void register()
+ throws Exception
+ {
+ try
+ {
+ UserService service = getUserService();
+ User u = new User();
+ u.setFullName( "the toto" );
+ u.setUsername( "toto" );
+ u.setEmail( "toto@toto.fr" );
+ u.setPassword( "toto123" );
+ u.setConfirmPassword( "toto123" );
+ String key = service.registerUser( u ).getKey();
+
+ assertFalse( key.equals( "-1" ) );
+
+ ServicesAssert assertService =
+ JAXRSClientFactory.create( "http://localhost:" + port + "/" + getRestServicesPath() + "/testsService/",
+ ServicesAssert.class,
+ Collections.singletonList( new JacksonJaxbJsonProvider() ) );
+
+ List<EmailMessage> emailMessages = assertService.getEmailMessageSended();
+ assertEquals( 1, emailMessages.size() );
+ assertEquals( "toto@toto.fr", emailMessages.get( 0 ).getTos().get( 0 ) );
+
+ assertEquals( "Welcome", emailMessages.get( 0 ).getSubject() );
+ assertTrue(
+ emailMessages.get( 0 ).getText().contains( "Use the following URL to validate your account." ) );
+
+ assertTrue( service.validateUserFromKey( key ) );
+
+ service = getUserService( authorizationHeader );
+
+ u = service.getUser( "toto" );
+
+ assertNotNull( u );
+ assertTrue( u.isValidated() );
+ assertTrue( u.isPasswordChangeRequired() );
+
+ assertTrue( service.validateUserFromKey( key ) );
+
+ }
+ catch ( Exception e )
+ {
+ log.error( e.getMessage(), e );
+ throw e;
+ }
+ finally
+ {
+ getUserService( authorizationHeader ).deleteUser( "toto" );
+ }
+
+ }
+
+ @Test
+ public void resetPassword()
+ throws Exception
+ {
+ try
+ {
+ UserService service = getUserService();
+ User u = new User();
+ u.setFullName( "the toto" );
+ u.setUsername( "toto" );
+ u.setEmail( "toto@toto.fr" );
+ u.setPassword( "toto123" );
+ u.setConfirmPassword( "toto123" );
+ String key = service.registerUser( u ).getKey();
+
+ assertFalse( key.equals( "-1" ) );
+
+ ServicesAssert assertService =
+ JAXRSClientFactory.create( "http://localhost:" + port + "/" + getRestServicesPath() + "/testsService/",
+ ServicesAssert.class,
+ Collections.singletonList( new JacksonJaxbJsonProvider() ) );
+
+ WebClient.client( assertService ).accept( MediaType.APPLICATION_JSON_TYPE );
+ WebClient.client( assertService ).type( MediaType.APPLICATION_JSON_TYPE );
+
+ List<EmailMessage> emailMessages = assertService.getEmailMessageSended();
+ assertEquals( 1, emailMessages.size() );
+ assertEquals( "toto@toto.fr", emailMessages.get( 0 ).getTos().get( 0 ) );
+
+ assertEquals( "Welcome", emailMessages.get( 0 ).getSubject() );
+ assertTrue(
+ emailMessages.get( 0 ).getText().contains( "Use the following URL to validate your account." ) );
+
+ assertTrue( service.validateUserFromKey( key ) );
+
+ service = getUserService( authorizationHeader );
+
+ u = service.getUser( "toto" );
+
+ assertNotNull( u );
+ assertTrue( u.isValidated() );
+ assertTrue( u.isPasswordChangeRequired() );
+
+ assertTrue( service.validateUserFromKey( key ) );
+
+ assertTrue( service.resetPassword( "toto" ) );
+
+ emailMessages = assertService.getEmailMessageSended();
+ assertEquals( 2, emailMessages.size() );
+ assertEquals( "toto@toto.fr", emailMessages.get( 1 ).getTos().get( 0 ) );
+
+ assertTrue( emailMessages.get( 1 ).getText().contains( "Password Reset" ) );
+ assertTrue( emailMessages.get( 1 ).getText().contains( "Username: toto" ) );
+
+
+ }
+ catch ( Exception e )
+ {
+ log.error( e.getMessage(), e );
+ throw e;
+ }
+ finally
+ {
+ getUserService( authorizationHeader ).deleteUser( "toto" );
+ }
+
+ }
+
+ @Test
+ public void getAdminPermissions()
+ throws Exception
+ {
+ Collection<Permission> permissions = getUserService( authorizationHeader ).getUserPermissions( "admin" );
+ log.info( "admin permisssions:" + permissions );
+ }
+
+ @Test
+ public void getGuestPermissions()
+ throws Exception
+ {
+ createGuestIfNeeded();
+ Collection<Permission> permissions = getUserService().getCurrentUserPermissions();
+ log.info( "guest permisssions:" + permissions );
+ }
+
+ @Test
+ public void getAdminOperations()
+ throws Exception
+ {
+ Collection<Operation> operations = getUserService( authorizationHeader ).getUserOperations( "admin" );
+ log.info( "admin operations:" + operations );
+ }
+
+ @Test
+ public void getGuestOperations()
+ throws Exception
+ {
+ createGuestIfNeeded();
+ Collection<Operation> operations = getUserService().getCurrentUserOperations();
+ log.info( "guest operations:" + operations );
+ }
+
+ @Test
+ public void updateMe()
+ throws Exception
+ {
+ User u = new User();
+ u.setFullName( "the toto" );
+ u.setUsername( "toto" );
+ u.setEmail( "toto@toto.fr" );
+ u.setPassword( "toto123" );
+ u.setConfirmPassword( "toto123" );
+ u.setValidated( true );
+ getUserService( authorizationHeader ).createUser( u );
+
+ u.setFullName( "the toto123" );
+ u.setEmail( "toto@titi.fr" );
+ u.setPassword( "toto1234" );
+ u.setPreviousPassword( "toto123" );
+ getUserService( encode( "toto", "toto123" ) ).updateMe( u );
+
+ u = getUserService( authorizationHeader ).getUser( "toto" );
+ assertEquals( "the toto123", u.getFullName() );
+ assertEquals( "toto@titi.fr", u.getEmail() );
+
+ u.setFullName( "the toto1234" );
+ u.setEmail( "toto@tititi.fr" );
+ u.setPassword( "toto12345" );
+ u.setPreviousPassword( "toto1234" );
+ getUserService( encode( "toto", "toto1234" ) ).updateMe( u );
+
+ u = getUserService( authorizationHeader ).getUser( "toto" );
+ assertEquals( "the toto1234", u.getFullName() );
+ assertEquals( "toto@tititi.fr", u.getEmail() );
+
+ getUserService( authorizationHeader ).deleteUser( "toto" );
+ }
+
+ public void guestUserCreate()
+ throws Exception
+ {
+ UserService userService = getUserService( authorizationHeader );
+ assertNull( userService.getGuestUser() );
+ assertNull( userService.createGuestUser() );
+
+ }
+
+ protected void createGuestIfNeeded()
+ throws Exception
+ {
+ UserService userService = getUserService( authorizationHeader );
+ if ( userService.getGuestUser() == null )
+ {
+ userService.createGuestUser();
+ }
+ }
+
+}
Propchange: archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/test/java/org/codehaus/redback/rest/services/UserServiceTest.java
------------------------------------------------------------------------------
svn:eol-style = native
Propchange: archiva/redback/redback-core/trunk/redback-integrations/redback-rest/redback-rest-services/src/test/java/org/codehaus/redback/rest/services/UserServiceTest.java
------------------------------------------------------------------------------
svn:keywords = Author Date Id Revision