--- /dev/null
+package org.apache.archiva.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.archiva.redback.authentication.AuthenticationException;
+import org.apache.archiva.redback.keys.KeyManager;
+import org.apache.archiva.redback.policy.AccountLockedException;
+import org.apache.archiva.redback.policy.MustChangePasswordException;
+import org.apache.archiva.redback.users.UserNotFoundException;
+import org.apache.archiva.redback.authentication.PasswordBasedAuthenticationDataSource;
+import org.apache.archiva.redback.keys.AuthenticationKey;
+import org.codehaus.plexus.redback.keys.jdo.JdoAuthenticationKey;
+import org.apache.archiva.redback.keys.memory.MemoryAuthenticationKey;
+import org.apache.archiva.redback.keys.memory.MemoryKeyManager;
+import org.apache.archiva.redback.system.SecuritySession;
+import org.apache.archiva.redback.system.SecuritySystem;
+import org.apache.archiva.redback.integration.filter.authentication.HttpAuthenticator;
+import org.apache.archiva.redback.rest.api.model.User;
+import org.apache.archiva.redback.rest.api.services.LoginService;
+import org.apache.archiva.redback.rest.api.services.RedbackServiceException;
+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.HttpSession;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.Response;
+import java.util.Calendar;
+import java.util.TimeZone;
+
+/**
+ * @author Olivier Lamy
+ * @since 1.3
+ */
+@Service( "loginService#rest" )
+public class DefaultLoginService
+ implements LoginService
+{
+
+ private Logger log = LoggerFactory.getLogger( getClass() );
+
+ private SecuritySystem securitySystem;
+
+ private HttpAuthenticator httpAuthenticator;
+
+ @Context
+ private HttpServletRequest httpServletRequest;
+
+ @Inject
+ public DefaultLoginService( SecuritySystem securitySystem,
+ @Named( "httpAuthenticator#basic" ) HttpAuthenticator httpAuthenticator )
+ {
+ this.securitySystem = securitySystem;
+ this.httpAuthenticator = httpAuthenticator;
+ }
+
+
+ public String addAuthenticationKey( String providedKey, String principal, String purpose, int expirationMinutes )
+ throws RedbackServiceException
+ {
+ KeyManager keyManager = securitySystem.getKeyManager();
+ AuthenticationKey key;
+
+ if ( keyManager instanceof MemoryKeyManager )
+ {
+ key = new MemoryAuthenticationKey();
+ }
+ else
+ {
+ key = new JdoAuthenticationKey();
+ }
+
+ key.setKey( providedKey );
+ key.setForPrincipal( principal );
+ key.setPurpose( purpose );
+
+ Calendar now = getNowGMT();
+ key.setDateCreated( now.getTime() );
+
+ if ( expirationMinutes >= 0 )
+ {
+ Calendar expiration = getNowGMT();
+ expiration.add( Calendar.MINUTE, expirationMinutes );
+ key.setDateExpires( expiration.getTime() );
+ }
+
+ keyManager.addKey( key );
+
+ return key.getKey();
+ }
+
+ public Boolean ping()
+ throws RedbackServiceException
+ {
+ return Boolean.TRUE;
+ }
+
+ public Boolean pingWithAutz()
+ throws RedbackServiceException
+ {
+ return Boolean.TRUE;
+ }
+
+ public User logIn( String userName, String password )
+ throws RedbackServiceException
+ {
+ PasswordBasedAuthenticationDataSource authDataSource =
+ new PasswordBasedAuthenticationDataSource( userName, password );
+ try
+ {
+ SecuritySession securitySession = securitySystem.authenticate( authDataSource );
+ if ( securitySession.getAuthenticationResult().isAuthenticated() )
+ {
+ org.apache.archiva.redback.users.User user = securitySession.getUser();
+ if ( !user.isValidated() )
+ {
+ log.info( "user {} not validated", user.getUsername() );
+ return null;
+ }
+ User restUser = buildRestUser( user );
+
+ // here create an http session
+ httpAuthenticator.authenticate( authDataSource, httpServletRequest.getSession( true ) );
+ return restUser;
+ }
+ return null;
+ }
+ catch ( AuthenticationException e )
+ {
+ throw new RedbackServiceException( e.getMessage(), Response.Status.FORBIDDEN.getStatusCode() );
+ }
+ catch ( UserNotFoundException e )
+ {
+ throw new RedbackServiceException( e.getMessage() );
+ }
+ catch ( AccountLockedException e )
+ {
+ throw new RedbackServiceException( e.getMessage() );
+ }
+ catch ( MustChangePasswordException e )
+ {
+ return buildRestUser( e.getUser() );
+ }
+ }
+
+ public Boolean isLogged()
+ throws RedbackServiceException
+ {
+ Boolean isLogged = httpAuthenticator.getSecuritySession( httpServletRequest.getSession( true ) ) != null;
+ log.debug( "isLogged {}", isLogged );
+ return isLogged;
+ }
+
+ public Boolean logout()
+ throws RedbackServiceException
+ {
+ HttpSession httpSession = httpServletRequest.getSession();
+ if ( httpSession != null )
+ {
+ httpSession.invalidate();
+ }
+ return Boolean.TRUE;
+ }
+
+ private Calendar getNowGMT()
+ {
+ return Calendar.getInstance( TimeZone.getTimeZone( "GMT" ) );
+ }
+
+ private User buildRestUser( org.apache.archiva.redback.users.User user )
+ {
+ User restUser = new User();
+ restUser.setEmail( user.getEmail() );
+ restUser.setUsername( user.getUsername() );
+ restUser.setPasswordChangeRequired( user.isPasswordChangeRequired() );
+ restUser.setLocked( user.isLocked() );
+ restUser.setValidated( user.isValidated() );
+ restUser.setFullName( user.getFullName() );
+ return restUser;
+ }
+}
--- /dev/null
+package org.apache.archiva.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.archiva.redback.policy.PasswordEncoder;
+import org.apache.archiva.redback.policy.PasswordRuleViolationException;
+import org.apache.archiva.redback.policy.PasswordRuleViolations;
+import org.apache.archiva.redback.users.User;
+import org.apache.commons.lang.StringUtils;
+import org.apache.archiva.redback.keys.AuthenticationKey;
+import org.apache.archiva.redback.keys.KeyManagerException;
+import org.apache.archiva.redback.system.SecuritySystem;
+import org.apache.archiva.redback.users.UserNotFoundException;
+import org.apache.archiva.redback.integration.filter.authentication.HttpAuthenticator;
+import org.apache.archiva.redback.rest.api.model.ErrorMessage;
+import org.apache.archiva.redback.rest.api.services.PasswordService;
+import org.apache.archiva.redback.rest.api.services.RedbackServiceException;
+import org.apache.archiva.redback.rest.services.utils.PasswordValidator;
+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.Context;
+import javax.ws.rs.core.Response;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * @author Olivier Lamy
+ * @since 1.4
+ */
+@Service( "passwordService#rest" )
+public class DefaultPasswordService
+ implements PasswordService
+{
+
+ private Logger log = LoggerFactory.getLogger( getClass() );
+
+ private SecuritySystem securitySystem;
+
+ private HttpAuthenticator httpAuthenticator;
+
+ private PasswordValidator passwordValidator;
+
+ @Context
+ private HttpServletRequest httpServletRequest;
+
+ @Inject
+ public DefaultPasswordService( SecuritySystem securitySystem,
+ @Named( "httpAuthenticator#basic" ) HttpAuthenticator httpAuthenticator,
+ PasswordValidator passwordValidator )
+ {
+ this.securitySystem = securitySystem;
+ this.httpAuthenticator = httpAuthenticator;
+ this.passwordValidator = passwordValidator;
+ }
+
+ public org.apache.archiva.redback.rest.api.model.User changePasswordWithKey( String password, String passwordConfirmation,
+ String key )
+ throws RedbackServiceException
+ {
+
+
+ //RedbackRequestInformation redbackRequestInformation = RedbackAuthenticationThreadLocal.get();
+
+ String principal = null;
+
+ if ( StringUtils.isEmpty( password ) )
+ {
+ throw new RedbackServiceException( "password cannot be empty", Response.Status.FORBIDDEN.getStatusCode() );
+ }
+ if ( StringUtils.isEmpty( passwordConfirmation ) )
+ {
+ throw new RedbackServiceException( "password confirmation cannot be empty",
+ Response.Status.FORBIDDEN.getStatusCode() );
+ }
+ if ( !StringUtils.equals( password, passwordConfirmation ) )
+ {
+ throw new RedbackServiceException( "password confirmation must be same as password",
+ Response.Status.FORBIDDEN.getStatusCode() );
+ }
+
+ try
+ {
+ AuthenticationKey authKey = securitySystem.getKeyManager().findKey( key );
+
+ principal = authKey.getForPrincipal();
+
+ String encodedPassword = passwordValidator.validatePassword( password, principal );
+
+ User user = securitySystem.getUserManager().findUser( principal );
+ user.setPassword( password );
+ user.setEncodedPassword( encodedPassword );
+ user = securitySystem.getUserManager().updateUser( user );
+
+ return new org.apache.archiva.redback.rest.api.model.User( user );
+
+ }
+ catch ( KeyManagerException e )
+ {
+ log.info( "issue to find key {}: {}", key, e.getMessage() );
+ throw new RedbackServiceException( "issue with key", Response.Status.FORBIDDEN.getStatusCode() );
+ }
+ 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 );
+ }
+
+ }
+
+ public org.apache.archiva.redback.rest.api.model.User changePassword( String userName, String previousPassword,
+ String password, String passwordConfirmation )
+ throws RedbackServiceException
+ {
+ if ( StringUtils.isEmpty( userName ) )
+ {
+ throw new RedbackServiceException( new ErrorMessage( "username.cannot.be.empty" ),
+ Response.Status.BAD_REQUEST.getStatusCode() );
+ }
+ if ( StringUtils.isEmpty( previousPassword ) )
+ {
+ throw new RedbackServiceException( new ErrorMessage( "password.previous.empty" ),
+ Response.Status.BAD_REQUEST.getStatusCode() );
+ }
+ if ( StringUtils.isEmpty( password ) )
+ {
+ throw new RedbackServiceException( new ErrorMessage( "password.empty" ),
+ Response.Status.BAD_REQUEST.getStatusCode() );
+ }
+ if ( StringUtils.isEmpty( passwordConfirmation ) )
+ {
+ throw new RedbackServiceException( new ErrorMessage( "password.confirmation.empty" ),
+ Response.Status.BAD_REQUEST.getStatusCode() );
+ }
+
+ if ( !StringUtils.equals( password, passwordConfirmation ) )
+ {
+ throw new RedbackServiceException( new ErrorMessage( "password.confirmation.same" ),
+ Response.Status.BAD_REQUEST.getStatusCode() );
+ }
+ try
+ {
+ User u = securitySystem.getUserManager().findUser( userName );
+
+ String previousEncodedPassword = u.getEncodedPassword();
+
+ // check oldPassword with the current one
+
+ PasswordEncoder encoder = securitySystem.getPolicy().getPasswordEncoder();
+
+ if ( !encoder.isPasswordValid( previousEncodedPassword, previousPassword ) )
+ {
+
+ throw new RedbackServiceException( new ErrorMessage( "password.provided.does.not.match.existing" ),
+ Response.Status.BAD_REQUEST.getStatusCode() );
+ }
+
+ u.setPassword( password );
+
+ u = securitySystem.getUserManager().updateUser( u );
+ return new org.apache.archiva.redback.rest.api.model.User( u );
+ }
+ catch ( UserNotFoundException e )
+ {
+ throw new RedbackServiceException( new ErrorMessage( "user.not.found" ),
+ Response.Status.BAD_REQUEST.getStatusCode() );
+ }
+
+ }
+}
--- /dev/null
+package org.apache.archiva.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.archiva.redback.rbac.Permission;
+import org.apache.archiva.redback.rbac.RBACManager;
+import org.apache.archiva.redback.rbac.RbacManagerException;
+import org.apache.archiva.redback.rbac.Resource;
+import org.apache.archiva.redback.rbac.UserAssignment;
+import org.apache.archiva.redback.role.RoleManager;
+import org.apache.archiva.redback.role.RoleManagerException;
+import org.apache.archiva.redback.users.User;
+import org.apache.archiva.redback.users.UserManager;
+import org.apache.archiva.redback.users.UserNotFoundException;
+import org.apache.commons.lang.StringUtils;
+import org.codehaus.plexus.redback.role.model.ModelApplication;
+import org.codehaus.plexus.redback.role.model.ModelRole;
+import org.codehaus.plexus.redback.role.model.ModelTemplate;
+import org.apache.archiva.redback.integration.model.AdminEditUserCredentials;
+import org.apache.archiva.redback.integration.security.role.RedbackRoleConstants;
+import org.apache.archiva.redback.integration.util.RoleSorter;
+import org.apache.archiva.redback.rest.api.model.Application;
+import org.apache.archiva.redback.rest.api.model.ApplicationRoles;
+import org.apache.archiva.redback.rest.api.model.ErrorMessage;
+import org.apache.archiva.redback.rest.api.model.Role;
+import org.apache.archiva.redback.rest.api.model.RoleTemplate;
+import org.apache.archiva.redback.rest.api.services.RedbackServiceException;
+import org.apache.archiva.redback.rest.api.services.RoleManagementService;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Service;
+
+import javax.inject.Inject;
+import javax.inject.Named;
+import javax.ws.rs.core.Response;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * @author Olivier Lamy
+ * @since 1.3
+ */
+@Service( "roleManagementService#rest" )
+public class DefaultRoleManagementService
+ implements RoleManagementService
+{
+
+ private Logger log = LoggerFactory.getLogger( getClass() );
+
+ private RoleManager roleManager;
+
+ private RBACManager rbacManager;
+
+ private UserManager userManager;
+
+ @Inject
+ public DefaultRoleManagementService( RoleManager roleManager,
+ @Named( value = "rBACManager#cached" ) RBACManager rbacManager,
+ @Named( value = "userManager#cached" ) UserManager userManager )
+ {
+ this.roleManager = roleManager;
+ this.rbacManager = rbacManager;
+ this.userManager = userManager;
+ }
+
+ public Boolean createTemplatedRole( String templateId, String resource )
+ throws RedbackServiceException
+ {
+ try
+ {
+ roleManager.createTemplatedRole( templateId, resource );
+ }
+ catch ( RoleManagerException e )
+ {
+ throw new RedbackServiceException( e.getMessage() );
+ }
+ return Boolean.TRUE;
+ }
+
+ public Boolean removeTemplatedRole( String templateId, String resource )
+ throws RedbackServiceException
+ {
+
+ try
+ {
+ roleManager.removeTemplatedRole( templateId, resource );
+ }
+ catch ( RoleManagerException e )
+ {
+ throw new RedbackServiceException( e.getMessage() );
+ }
+ return Boolean.TRUE;
+ }
+
+ public Boolean updateRole( String templateId, String oldResource, String newResource )
+ throws RedbackServiceException
+ {
+ try
+ {
+ roleManager.updateRole( templateId, oldResource, newResource );
+ }
+ catch ( RoleManagerException e )
+ {
+ throw new RedbackServiceException( e.getMessage() );
+ }
+ return Boolean.TRUE;
+ }
+
+ public Boolean assignRole( String roleId, String principal )
+ throws RedbackServiceException
+ {
+ try
+ {
+ roleManager.assignRole( roleId, principal );
+ }
+ catch ( RoleManagerException e )
+ {
+ throw new RedbackServiceException( e.getMessage() );
+ }
+ return Boolean.TRUE;
+ }
+
+ public Boolean assignRoleByName( String roleName, String principal )
+ throws RedbackServiceException
+ {
+ try
+ {
+ roleManager.assignRoleByName( roleName, principal );
+ }
+ catch ( RoleManagerException e )
+ {
+ throw new RedbackServiceException( e.getMessage() );
+ }
+ return Boolean.TRUE;
+ }
+
+ public Boolean assignTemplatedRole( String templateId, String resource, String principal )
+ throws RedbackServiceException
+ {
+ try
+ {
+ roleManager.assignTemplatedRole( templateId, resource, principal );
+ }
+ catch ( RoleManagerException e )
+ {
+ throw new RedbackServiceException( e.getMessage() );
+ }
+ return Boolean.TRUE;
+ }
+
+ public Boolean unassignRole( String roleId, String principal )
+ throws RedbackServiceException
+ {
+ try
+ {
+ roleManager.unassignRole( roleId, principal );
+ }
+ catch ( RoleManagerException e )
+ {
+ throw new RedbackServiceException( e.getMessage() );
+ }
+ return Boolean.TRUE;
+ }
+
+ public Boolean unassignRoleByName( String roleName, String principal )
+ throws RedbackServiceException
+ {
+ try
+ {
+ roleManager.unassignRoleByName( roleName, principal );
+ }
+ catch ( RoleManagerException e )
+ {
+ throw new RedbackServiceException( e.getMessage() );
+ }
+ return Boolean.TRUE;
+ }
+
+ public Boolean roleExists( String roleId )
+ throws RedbackServiceException
+ {
+ try
+ {
+ return roleManager.roleExists( roleId );
+ }
+ catch ( RoleManagerException e )
+ {
+ throw new RedbackServiceException( e.getMessage() );
+ }
+ }
+
+ public Boolean templatedRoleExists( String templateId, String resource )
+ throws RedbackServiceException
+ {
+ try
+ {
+ return roleManager.templatedRoleExists( templateId, resource );
+ }
+ catch ( RoleManagerException e )
+ {
+ throw new RedbackServiceException( e.getMessage() );
+ }
+
+ }
+
+ public Boolean verifyTemplatedRole( String templateId, String resource )
+ throws RedbackServiceException
+ {
+ try
+ {
+ roleManager.verifyTemplatedRole( templateId, resource );
+ }
+ catch ( RoleManagerException e )
+ {
+ throw new RedbackServiceException( e.getMessage() );
+ }
+ return Boolean.TRUE;
+ }
+
+ public List<Role> getEffectivelyAssignedRoles( String username )
+ throws RedbackServiceException
+ {
+ if ( StringUtils.isEmpty( username ) )
+ {
+ throw new RedbackServiceException( new ErrorMessage( "user.cannot.be.null" ) );
+ }
+ try
+ {
+ List<org.apache.archiva.redback.rbac.Role> roles =
+ filterAssignableRoles( rbacManager.getEffectivelyAssignedRoles( username ) );
+
+ List<Role> effectivelyAssignedRoles = new ArrayList<Role>( roles.size() );
+
+ for ( org.apache.archiva.redback.rbac.Role r : roles )
+ {
+ effectivelyAssignedRoles.add( new Role( r ) );
+ }
+ return effectivelyAssignedRoles;
+ }
+ catch ( RbacManagerException rme )
+ {
+ // ignore, this can happen when the user has no roles assigned
+ }
+ return new ArrayList<Role>( 0 );
+ }
+
+
+ public List<Application> getApplications( String username )
+ throws RedbackServiceException
+ {
+
+ List<ModelApplication> modelApplications = roleManager.getModel().getApplications();
+
+ List<Application> applications = new ArrayList<Application>( modelApplications.size() );
+
+ for ( ModelApplication modelApplication : modelApplications )
+ {
+ Application application = new Application();
+ application.setDescription( modelApplication.getDescription() );
+ application.setId( modelApplication.getId() );
+ application.setLongDescription( modelApplication.getLongDescription() );
+ application.setVersion( modelApplication.getVersion() );
+ applications.add( application );
+ }
+
+ return applications;
+ }
+
+ public List<Role> getAllRoles()
+ throws RedbackServiceException
+ {
+ try
+ {
+ List<org.apache.archiva.redback.rbac.Role> roles = rbacManager.getAllRoles();
+
+ if ( roles == null )
+ {
+ return Collections.emptyList();
+ }
+
+ roles = filterRolesForCurrentUserAccess( roles );
+
+ List<Role> res = new ArrayList<Role>( roles.size() );
+
+ for ( org.apache.archiva.redback.rbac.Role r : roles )
+ {
+ res.add( new Role( r ) );
+ }
+ return res;
+
+ }
+ catch ( RbacManagerException e )
+ {
+ throw new RedbackServiceException( e.getMessage() );
+ }
+ }
+
+ public List<Role> getDetailedAllRoles()
+ throws RedbackServiceException
+ {
+ try
+ {
+ List<org.apache.archiva.redback.rbac.Role> roles = rbacManager.getAllRoles();
+
+ if ( roles == null )
+ {
+ return Collections.emptyList();
+ }
+
+ roles = filterRolesForCurrentUserAccess( roles );
+
+ List<Role> res = new ArrayList<Role>( roles.size() );
+
+ for ( org.apache.archiva.redback.rbac.Role r : roles )
+ {
+ res.add( getRole( r.getName() ) );
+ }
+ return res;
+
+ }
+ catch ( RbacManagerException e )
+ {
+ throw new RedbackServiceException( e.getMessage() );
+ }
+ }
+
+ private List<org.apache.archiva.redback.rbac.Role> filterAssignableRoles(
+ Collection<org.apache.archiva.redback.rbac.Role> roles )
+ {
+ List<org.apache.archiva.redback.rbac.Role> assignableRoles =
+ new ArrayList<org.apache.archiva.redback.rbac.Role>( roles.size() );
+ for ( org.apache.archiva.redback.rbac.Role r : roles )
+ {
+ if ( r.isAssignable() )
+ {
+ assignableRoles.add( r );
+ }
+ }
+ return assignableRoles;
+ }
+
+ public Role getRole( String roleName )
+ throws RedbackServiceException
+ {
+ try
+ {
+ org.apache.archiva.redback.rbac.Role rbacRole = rbacManager.getRole( roleName );
+ Role role = new Role( rbacRole );
+
+ Map<String, org.apache.archiva.redback.rbac.Role> parentRoles = rbacManager.getParentRoles( rbacRole );
+ for ( String parentRoleName : parentRoles.keySet() )
+ {
+ role.getParentRoleNames().add( parentRoleName );
+ }
+
+ List<UserAssignment> userAssignments = rbacManager.getUserAssignmentsForRoles( Arrays.asList( roleName ) );
+
+ if ( userAssignments != null )
+ {
+ for ( UserAssignment userAssignment : userAssignments )
+ {
+ try
+ {
+ User user = userManager.findUser( userAssignment.getPrincipal() );
+ role.getUsers().add( new org.apache.archiva.redback.rest.api.model.User( user ) );
+ }
+ catch ( UserNotFoundException e )
+ {
+ log.warn( "User '" + userAssignment.getPrincipal() + "' doesn't exist.", e );
+ }
+ }
+ }
+
+ if ( !role.getParentRoleNames().isEmpty() )
+ {
+ List<UserAssignment> userParentAssignments =
+ rbacManager.getUserAssignmentsForRoles( parentRoles.keySet() );
+ if ( userParentAssignments != null )
+ {
+ for ( UserAssignment userAssignment : userParentAssignments )
+ {
+ try
+ {
+ User user = userManager.findUser( userAssignment.getPrincipal() );
+ role.getParentsRolesUsers().add( new org.apache.archiva.redback.rest.api.model.User( user ) );
+ }
+ catch ( UserNotFoundException e )
+ {
+ log.warn( "User '" + userAssignment.getPrincipal() + "' doesn't exist.", e );
+ }
+ }
+ }
+ }
+
+ List<org.apache.archiva.redback.rest.api.model.User> otherUsers =
+ new ArrayList<org.apache.archiva.redback.rest.api.model.User>();
+ for ( User u : userManager.getUsers() )
+ {
+ org.apache.archiva.redback.rest.api.model.User
+ user = new org.apache.archiva.redback.rest.api.model.User( u );
+ if ( role.getParentsRolesUsers().contains( user ) )
+ {
+ continue;
+ }
+ if ( role.getUsers().contains( user ) )
+ {
+ continue;
+ }
+ otherUsers.add( user );
+ }
+
+ role.setOtherUsers( otherUsers );
+
+ return role;
+ }
+ catch ( RbacManagerException e )
+ {
+ throw new RedbackServiceException( new ErrorMessage( e.getMessage() ) );
+ }
+ }
+
+ public Boolean updateRoleDescription( String roleName, String description )
+ throws RedbackServiceException
+ {
+ try
+ {
+ org.apache.archiva.redback.rbac.Role rbacRole = rbacManager.getRole( roleName );
+ rbacRole.setDescription( description );
+ rbacManager.saveRole( rbacRole );
+ }
+ catch ( RbacManagerException e )
+ {
+ throw new RedbackServiceException( new ErrorMessage( e.getMessage() ) );
+ }
+ return Boolean.TRUE;
+ }
+
+ public Boolean updateRoleUsers( Role role )
+ throws RedbackServiceException
+ {
+
+ for ( org.apache.archiva.redback.rest.api.model.User user : role.getUsers() )
+ {
+ String username = user.getUsername();
+ if ( !userManager.userExists( username ) )
+ {
+ log.error( "user {} not exits", username );
+ throw new RedbackServiceException( new ErrorMessage( "user.not.exists", new String[]{ username } ) );
+ }
+
+ try
+ {
+ UserAssignment assignment;
+
+ if ( rbacManager.userAssignmentExists( username ) )
+ {
+ assignment = rbacManager.getUserAssignment( username );
+ }
+ else
+ {
+ assignment = rbacManager.createUserAssignment( username );
+ }
+
+ assignment.addRoleName( role.getName() );
+ assignment = rbacManager.saveUserAssignment( assignment );
+ log.info( "{} role assigned to {}", role.getName(), username );
+ }
+ catch ( RbacManagerException e )
+ {
+ log.error( "error during assign role " + role.getName() + "Â to user " + username, e );
+ throw new RedbackServiceException(
+ new ErrorMessage( "error.assign.role.user", new String[]{ role.getName(), username } ) );
+ }
+ }
+
+ for ( org.apache.archiva.redback.rest.api.model.User user : role.getRemovedUsers() )
+ {
+ String username = user.getUsername();
+ if ( !userManager.userExists( username ) )
+ {
+ log.error( "user {} not exits", username );
+ throw new RedbackServiceException( new ErrorMessage( "user.not.exists", new String[]{ username } ) );
+ }
+
+ try
+ {
+ UserAssignment assignment;
+
+ if ( rbacManager.userAssignmentExists( username ) )
+ {
+ assignment = rbacManager.getUserAssignment( username );
+ }
+ else
+ {
+ assignment = rbacManager.createUserAssignment( username );
+ }
+
+ assignment.removeRoleName( role.getName() );
+ assignment = rbacManager.saveUserAssignment( assignment );
+ log.info( "{} role unassigned to {}", role.getName(), username );
+ }
+ catch ( RbacManagerException e )
+ {
+ log.error( "error during unassign role " + role.getName() + "Â to user " + username, e );
+ throw new RedbackServiceException(
+ new ErrorMessage( "error.unassign.role.user", new String[]{ role.getName(), username } ) );
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ public List<ApplicationRoles> getApplicationRoles( String username )
+ throws RedbackServiceException
+ {
+ AdminEditUserCredentials user = null;
+ if ( StringUtils.isEmpty( username ) )
+ {
+ throw new RedbackServiceException( new ErrorMessage( "rbac.edit.user.empty.principal" ) );
+ }
+
+ if ( !userManager.userExists( username ) )
+ {
+ throw new RedbackServiceException( new ErrorMessage( "user.does.not.exist", new String[]{ username } ) );
+ }
+
+ try
+ {
+ User u = userManager.findUser( username );
+
+ if ( u == null )
+ {
+ throw new RedbackServiceException( new ErrorMessage( "cannot.operate.on.null.user" ) );
+ }
+
+ user = new AdminEditUserCredentials( u );
+ }
+ catch ( UserNotFoundException e )
+ {
+ throw new RedbackServiceException(
+ new ErrorMessage( "user.does.not.exist", new String[]{ username, e.getMessage() } ) );
+ }
+ try
+ {
+ // check first if role assignments for user exist
+ if ( !rbacManager.userAssignmentExists( username ) )
+ {
+ UserAssignment assignment = rbacManager.createUserAssignment( username );
+ rbacManager.saveUserAssignment( assignment );
+ }
+
+ List<org.apache.archiva.redback.rbac.Role> allRoles =
+ filterRolesForCurrentUserAccess( rbacManager.getAllRoles() );
+
+ List<ModelApplication> modelApplications = roleManager.getModel().getApplications();
+
+ List<ApplicationRoles> applicationRolesList = new ArrayList<ApplicationRoles>( modelApplications.size() );
+
+ for ( ModelApplication modelApplication : modelApplications )
+ {
+ ApplicationRoles applicationRoles = new ApplicationRoles();
+
+ applicationRoles.setDescription( modelApplication.getDescription() );
+ applicationRoles.setName( modelApplication.getId() );
+
+ Collection<org.apache.archiva.redback.rbac.Role> appRoles =
+ filterApplicationRoles( modelApplication, allRoles, modelApplication.getTemplates() );
+
+ applicationRoles.setGlobalRoles( toRoleNames( appRoles ) );
+
+ Set<String> resources = discoverResources( modelApplication.getTemplates(), appRoles );
+
+ applicationRoles.setResources( resources );
+
+ applicationRoles.setRoleTemplates( toRoleTemplates( modelApplication.getTemplates() ) );
+
+ // cleanup app roles remove roles coming from templates
+
+ List<String> appRoleNames = new ArrayList<String>( appRoles.size() );
+
+ for (String appRoleName : applicationRoles.getGlobalRoles())
+ {
+ if (!roleFromTemplate( appRoleName, modelApplication.getTemplates() )){
+ appRoleNames.add( appRoleName );
+ }
+ }
+
+ applicationRoles.setGlobalRoles( appRoleNames );
+
+ applicationRolesList.add( applicationRoles );
+ }
+
+ return applicationRolesList;
+
+ }
+ catch ( RbacManagerException e )
+ {
+ RedbackServiceException redbackServiceException =
+ new RedbackServiceException( new ErrorMessage( e.getMessage() ) );
+ redbackServiceException.setHttpErrorCode( Response.Status.INTERNAL_SERVER_ERROR.getStatusCode() );
+ throw redbackServiceException;
+ }
+ }
+
+ public Boolean updateUserRoles( org.apache.archiva.redback.rest.api.model.User user )
+ throws RedbackServiceException
+ {
+
+ String username = user.getUsername();
+
+ if ( StringUtils.isEmpty( username ) )
+ {
+ throw new RedbackServiceException( new ErrorMessage( "rbac.edit.user.empty.principal" ) );
+ }
+
+ if ( !userManager.userExists( username ) )
+ {
+ throw new RedbackServiceException( new ErrorMessage( "user.does.not.exist", new String[]{ username } ) );
+ }
+
+ try
+ {
+ User u = userManager.findUser( username );
+
+ if ( u == null )
+ {
+ throw new RedbackServiceException( new ErrorMessage( "cannot.operate.on.null.user" ) );
+ }
+
+ }
+ catch ( UserNotFoundException e )
+ {
+ throw new RedbackServiceException(
+ new ErrorMessage( "user.does.not.exist", new String[]{ username, e.getMessage() } ) );
+ }
+
+ try
+ {
+
+ UserAssignment assignment;
+
+ if ( rbacManager.userAssignmentExists( username ) )
+ {
+ assignment = rbacManager.getUserAssignment( username );
+ }
+ else
+ {
+ assignment = rbacManager.createUserAssignment( username );
+ }
+
+ assignment.setRoleNames( user.getAssignedRoles() );
+
+ assignment = rbacManager.saveUserAssignment( assignment );
+
+ }
+ catch ( RbacManagerException e )
+ {
+ RedbackServiceException redbackServiceException =
+ new RedbackServiceException( new ErrorMessage( e.getMessage() ) );
+ redbackServiceException.setHttpErrorCode( Response.Status.INTERNAL_SERVER_ERROR.getStatusCode() );
+ throw redbackServiceException;
+ }
+
+ return Boolean.TRUE;
+
+ }
+
+ //----------------------------------------------------------------
+ // Internal methods
+ //----------------------------------------------------------------
+
+ private org.apache.archiva.redback.rbac.Role isInList( String roleName,
+ Collection<org.apache.archiva.redback.rbac.Role> roles )
+ {
+ for ( org.apache.archiva.redback.rbac.Role role : roles )
+ {
+ if ( roleName.equals( role.getName() ) )
+ {
+ return role;
+ }
+ }
+ return null;
+ }
+
+ private Collection<org.apache.archiva.redback.rbac.Role> filterApplicationRoles( ModelApplication application,
+ List<org.apache.archiva.redback.rbac.Role> allRoles,
+ List<ModelTemplate> applicationTemplates )
+ {
+ Set<org.apache.archiva.redback.rbac.Role> applicationRoles =
+ new HashSet<org.apache.archiva.redback.rbac.Role>();
+ List<ModelRole> roles = application.getRoles();
+
+ for ( ModelRole modelRole : roles )
+ {
+ org.apache.archiva.redback.rbac.Role r = isInList( modelRole.getName(), allRoles );
+ if ( r != null )
+ {
+ applicationRoles.add( r );
+ }
+ }
+
+ List<String> roleNames = toRoleNames( allRoles );
+
+ for ( ModelTemplate modelTemplate : applicationTemplates )
+ {
+ for ( org.apache.archiva.redback.rbac.Role r : allRoles )
+ {
+ if ( StringUtils.startsWith( r.getName(),
+ modelTemplate.getNamePrefix() + modelTemplate.getDelimiter() ) )
+ {
+ applicationRoles.add( r );
+ }
+ }
+ }
+
+ return applicationRoles;
+ }
+
+ private boolean roleFromTemplate( String roleName, List<ModelTemplate> applicationTemplates )
+ {
+
+ for ( ModelTemplate modelTemplate : applicationTemplates )
+ {
+ if ( StringUtils.startsWith( roleName, modelTemplate.getNamePrefix() + modelTemplate.getDelimiter() ) )
+ {
+ return true;
+ }
+
+ }
+ return false;
+ }
+
+ private List<String> toRoleNames( Collection<org.apache.archiva.redback.rbac.Role> roles )
+ {
+ List<String> names = new ArrayList<String>( roles.size() );
+
+ for ( org.apache.archiva.redback.rbac.Role r : roles )
+ {
+ names.add( r.getName() );
+ }
+
+ return names;
+ }
+
+ private List<RoleTemplate> toRoleTemplates( List<ModelTemplate> modelTemplates )
+ {
+ if ( modelTemplates == null || modelTemplates.isEmpty() )
+ {
+ return new ArrayList<RoleTemplate>( 0 );
+ }
+
+ List<RoleTemplate> roleTemplates = new ArrayList<RoleTemplate>( modelTemplates.size() );
+
+ for ( ModelTemplate modelTemplate : modelTemplates )
+ {
+ RoleTemplate roleTemplate = new RoleTemplate();
+
+ roleTemplate.setDelimiter( modelTemplate.getDelimiter() );
+ roleTemplate.setDescription( modelTemplate.getDescription() );
+ roleTemplate.setId( modelTemplate.getId() );
+ roleTemplate.setNamePrefix( modelTemplate.getNamePrefix() );
+
+ roleTemplates.add( roleTemplate );
+ }
+
+ return roleTemplates;
+ }
+
+ private Set<String> discoverResources( List<ModelTemplate> applicationTemplates,
+ Collection<org.apache.archiva.redback.rbac.Role> roles )
+ {
+ Set<String> resources = new HashSet<String>();
+ for ( ModelTemplate modelTemplate : applicationTemplates )
+ {
+ for ( org.apache.archiva.redback.rbac.Role role : roles )
+ {
+ String roleName = role.getName();
+ if ( roleName.startsWith( modelTemplate.getNamePrefix() ) )
+ {
+ String delimiter = modelTemplate.getDelimiter();
+ resources.add( roleName.substring( roleName.indexOf( delimiter ) + delimiter.length() ) );
+ }
+ }
+ }
+ return resources;
+ }
+
+ /**
+ * this is a hack. this is a hack around the requirements of putting RBAC constraints into the model. this adds one
+ * very major restriction to this security system, that a role name must contain the identifiers of the resource
+ * that is being constrained for adding and granting of roles, this is unacceptable in the long term and we need to
+ * get the model refactored to include this RBAC concept
+ *
+ * @param roleList
+ * @return
+ * @throws org.apache.archiva.redback.rbac.RbacManagerException
+ *
+ */
+ protected List<org.apache.archiva.redback.rbac.Role> filterRolesForCurrentUserAccess(
+ List<org.apache.archiva.redback.rbac.Role> roleList )
+ throws RedbackServiceException
+ {
+ RedbackRequestInformation redbackRequestInformation = RedbackAuthenticationThreadLocal.get();
+ // olamy: should not happened normally as annotations check this first
+ if ( redbackRequestInformation == null || redbackRequestInformation.getUser() == null )
+ {
+ throw new RedbackServiceException( new ErrorMessage( "login.mandatory" ) );
+ }
+ String currentUser = redbackRequestInformation.getUser().getUsername();
+
+ List<org.apache.archiva.redback.rbac.Role> filteredRoleList =
+ new ArrayList<org.apache.archiva.redback.rbac.Role>();
+ try
+ {
+ Map<String, List<Permission>> assignedPermissionMap = rbacManager.getAssignedPermissionMap( currentUser );
+ List<String> resourceGrants = new ArrayList<String>();
+
+ if ( assignedPermissionMap.containsKey( RedbackRoleConstants.USER_MANAGEMENT_ROLE_GRANT_OPERATION ) )
+ {
+ List<Permission> roleGrantPermissions =
+ assignedPermissionMap.get( RedbackRoleConstants.USER_MANAGEMENT_ROLE_GRANT_OPERATION );
+
+ for ( Permission permission : roleGrantPermissions )
+ {
+ if ( permission.getResource().getIdentifier().equals( Resource.GLOBAL ) )
+ {
+ // the current user has the rights to assign any given role
+ return roleList;
+ }
+ else
+ {
+ resourceGrants.add( permission.getResource().getIdentifier() );
+ }
+ }
+
+ }
+ else
+ {
+ return Collections.emptyList();
+ }
+
+ String delimiter = " - ";
+
+ // we should have a list of resourceGrants now, this will provide us with the information necessary to restrict
+ // the role list
+ for ( org.apache.archiva.redback.rbac.Role role : roleList )
+ {
+ int delimiterIndex = role.getName().indexOf( delimiter );
+ for ( String resourceIdentifier : resourceGrants )
+ {
+
+ if ( ( role.getName().indexOf( resourceIdentifier ) != -1 ) && ( delimiterIndex != -1 ) )
+ {
+ String resourceName = role.getName().substring( delimiterIndex + delimiter.length() );
+ if ( resourceName.equals( resourceIdentifier ) )
+ {
+ filteredRoleList.add( role );
+ }
+ }
+ }
+ }
+ }
+ catch ( RbacManagerException rme )
+ {
+ // ignore, this can happen when the user has no roles assigned
+ }
+ Collections.sort( filteredRoleList, new RoleSorter() );
+ return filteredRoleList;
+ }
+
+
+}
--- /dev/null
+package org.apache.archiva.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 net.sf.ehcache.CacheManager;
+import org.apache.archiva.redback.configuration.UserConfiguration;
+import org.apache.archiva.redback.keys.AuthenticationKey;
+import org.apache.archiva.redback.policy.AccountLockedException;
+import org.apache.archiva.redback.policy.MustChangePasswordException;
+import org.apache.archiva.redback.rbac.RbacManagerException;
+import org.apache.archiva.redback.rbac.UserAssignment;
+import org.apache.archiva.redback.role.RoleManager;
+import org.apache.archiva.redback.role.RoleManagerException;
+import org.apache.archiva.redback.users.UserManager;
+import org.apache.archiva.redback.users.UserNotFoundException;
+import org.apache.commons.lang.StringUtils;
+import org.codehaus.plexus.cache.Cache;
+import org.apache.archiva.redback.authentication.AuthenticationException;
+import org.apache.archiva.redback.authentication.TokenBasedAuthenticationDataSource;
+import org.apache.archiva.redback.keys.KeyManager;
+import org.apache.archiva.redback.keys.KeyManagerException;
+import org.apache.archiva.redback.keys.KeyNotFoundException;
+import org.apache.archiva.redback.policy.PasswordEncoder;
+import org.apache.archiva.redback.policy.UserSecurityPolicy;
+import org.apache.archiva.redback.rbac.RBACManager;
+import org.apache.archiva.redback.rbac.RbacObjectNotFoundException;
+import org.apache.archiva.redback.system.SecuritySystem;
+import org.apache.archiva.redback.integration.filter.authentication.HttpAuthenticator;
+import org.apache.archiva.redback.integration.mail.Mailer;
+import org.apache.archiva.redback.integration.security.role.RedbackRoleConstants;
+import org.apache.archiva.redback.rest.api.model.ErrorMessage;
+import org.apache.archiva.redback.rest.api.model.Operation;
+import org.apache.archiva.redback.rest.api.model.Permission;
+import org.apache.archiva.redback.rest.api.model.RegistrationKey;
+import org.apache.archiva.redback.rest.api.model.Resource;
+import org.apache.archiva.redback.rest.api.model.User;
+import org.apache.archiva.redback.rest.api.services.RedbackServiceException;
+import org.apache.archiva.redback.rest.api.services.UserService;
+import org.apache.archiva.redback.rest.services.utils.PasswordValidator;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Service;
+
+import javax.inject.Inject;
+import javax.inject.Named;
+import javax.mail.internet.AddressException;
+import javax.mail.internet.InternetAddress;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.Response;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.Set;
+
+@Service( "userService#rest" )
+public class DefaultUserService
+ implements UserService
+{
+
+ private Logger log = LoggerFactory.getLogger( getClass() );
+
+ private static final String VALID_USERNAME_CHARS = "[a-zA-Z_0-9\\-.@]*";
+
+ private UserManager userManager;
+
+ private SecuritySystem securitySystem;
+
+ @Inject
+ private UserConfiguration config;
+
+ @Inject
+ private RoleManager roleManager;
+
+ /**
+ * cache used for user assignments
+ */
+ @Inject
+ @Named( value = "cache#userAssignments" )
+ private Cache userAssignmentsCache;
+
+ /**
+ * cache used for user permissions
+ */
+ @Inject
+ @Named( value = "cache#userPermissions" )
+ private Cache userPermissionsCache;
+
+ /**
+ * Cache used for users
+ */
+ @Inject
+ @Named( value = "cache#users" )
+ private Cache usersCache;
+
+ @Inject
+ private Mailer mailer;
+
+ @Inject
+ @Named( value = "rBACManager#cached" )
+ private RBACManager rbacManager;
+
+ private HttpAuthenticator httpAuthenticator;
+
+ @Inject
+ private PasswordValidator passwordValidator;
+
+ @Context
+ private HttpServletRequest httpServletRequest;
+
+ @Inject
+ public DefaultUserService( @Named( value = "userManager#cached" ) UserManager userManager,
+ SecuritySystem securitySystem,
+ @Named( "httpAuthenticator#basic" ) HttpAuthenticator httpAuthenticator )
+ {
+ this.userManager = userManager;
+ this.securitySystem = securitySystem;
+ this.httpAuthenticator = httpAuthenticator;
+ }
+
+
+ public Boolean createUser( User user )
+ throws RedbackServiceException
+ {
+
+ try
+ {
+ org.apache.archiva.redback.users.User u = userManager.findUser( user.getUsername() );
+ if ( u != null )
+ {
+ throw new RedbackServiceException(
+ new ErrorMessage( "user " + user.getUsername() + " already exists" ) );
+ }
+ }
+ catch ( UserNotFoundException e )
+ {
+ //ignore we just want to prevent non human readable error message from backend :-)
+ log.debug( "user {} not exists", user.getUsername() );
+ }
+
+ // data validation
+ if ( StringUtils.isEmpty( user.getUsername() ) )
+ {
+ throw new RedbackServiceException( new ErrorMessage( "username cannot be empty" ) );
+ }
+
+ if ( StringUtils.isEmpty( user.getFullName() ) )
+ {
+ throw new RedbackServiceException( new ErrorMessage( "fullName cannot be empty" ) );
+ }
+
+ if ( StringUtils.isEmpty( user.getEmail() ) )
+ {
+ throw new RedbackServiceException( new ErrorMessage( "email cannot be empty" ) );
+ }
+
+ org.apache.archiva.redback.users.User u =
+ userManager.createUser( user.getUsername(), user.getFullName(), user.getEmail() );
+ u.setPassword( user.getPassword() );
+ u.setLocked( user.isLocked() );
+ u.setPasswordChangeRequired( user.isPasswordChangeRequired() );
+ u.setPermanent( user.isPermanent() );
+ u.setValidated( user.isValidated() );
+ u = userManager.addUser( u );
+ if ( !user.isPasswordChangeRequired() )
+ {
+ u.setPasswordChangeRequired( false );
+ try
+ {
+ u = userManager.updateUser( u );
+ log.debug( "user {} created", u.getUsername() );
+ }
+ catch ( UserNotFoundException e )
+ {
+ throw new RedbackServiceException( e.getMessage() );
+ }
+ }
+ try
+ {
+ roleManager.assignRole( RedbackRoleConstants.REGISTERED_USER_ROLE_ID, u.getPrincipal().toString() );
+ }
+ catch ( RoleManagerException rpe )
+ {
+ log.error( "RoleProfile Error: " + rpe.getMessage(), rpe );
+ throw new RedbackServiceException( new ErrorMessage( "assign.role.failure", null ) );
+ }
+ return Boolean.TRUE;
+ }
+
+ public Boolean deleteUser( String username )
+ throws RedbackServiceException
+ {
+
+ try
+ {
+
+ if ( rbacManager.userAssignmentExists( username ) )
+ {
+ UserAssignment assignment = rbacManager.getUserAssignment( username );
+ rbacManager.removeUserAssignment( assignment );
+ }
+
+ }
+ catch ( RbacManagerException e )
+ {
+ log.error( e.getMessage(), e );
+ throw new RedbackServiceException( e.getMessage() );
+ }
+ try
+ {
+ userManager.deleteUser( username );
+ return Boolean.TRUE;
+ }
+ catch ( UserNotFoundException e )
+ {
+ log.error( e.getMessage(), e );
+ throw new RedbackServiceException( e.getMessage() );
+ }
+ finally
+ {
+ removeFromCache( username );
+ }
+ }
+
+
+ public User getUser( String username )
+ throws RedbackServiceException
+ {
+ try
+ {
+ org.apache.archiva.redback.users.User user = userManager.findUser( username );
+ return getSimpleUser( user );
+ }
+ catch ( UserNotFoundException e )
+ {
+ return null;
+ }
+ }
+
+ public List<User> getUsers()
+ throws RedbackServiceException
+ {
+ List<org.apache.archiva.redback.users.User> users = userManager.getUsers();
+ List<User> simpleUsers = new ArrayList<User>( users.size() );
+
+ for ( org.apache.archiva.redback.users.User user : users )
+ {
+ simpleUsers.add( getSimpleUser( user ) );
+ }
+
+ return simpleUsers;
+ }
+
+ public Boolean updateMe( User user )
+ throws RedbackServiceException
+ {
+ // check username == one in the session
+ RedbackRequestInformation redbackRequestInformation = RedbackAuthenticationThreadLocal.get();
+ if ( redbackRequestInformation == null || redbackRequestInformation.getUser() == null )
+ {
+ throw new RedbackServiceException( new ErrorMessage( "you must be logged to update your profile" ),
+ Response.Status.FORBIDDEN.getStatusCode() );
+ }
+ if ( user == null )
+ {
+ throw new RedbackServiceException( new ErrorMessage( "user parameter is mandatory" ),
+ Response.Status.BAD_REQUEST.getStatusCode() );
+ }
+ if ( !StringUtils.equals( redbackRequestInformation.getUser().getUsername(), user.getUsername() ) )
+ {
+ throw new RedbackServiceException( new ErrorMessage( "you can update only your profile" ),
+ Response.Status.FORBIDDEN.getStatusCode() );
+ }
+
+ if ( StringUtils.isEmpty( user.getPreviousPassword() ) )
+ {
+ throw new RedbackServiceException( new ErrorMessage( "previous password is empty" ),
+ Response.Status.BAD_REQUEST.getStatusCode() );
+ }
+
+ User realUser = getUser( user.getUsername() );
+ try
+ {
+ String previousEncodedPassword =
+ securitySystem.getUserManager().findUser( user.getUsername() ).getEncodedPassword();
+
+ // check oldPassword with the current one
+
+ PasswordEncoder encoder = securitySystem.getPolicy().getPasswordEncoder();
+
+ if ( !encoder.isPasswordValid( previousEncodedPassword, user.getPreviousPassword() ) )
+ {
+
+ throw new RedbackServiceException( new ErrorMessage( "password.provided.does.not.match.existing" ),
+ Response.Status.BAD_REQUEST.getStatusCode() );
+ }
+ }
+ catch ( UserNotFoundException e )
+ {
+ throw new RedbackServiceException( new ErrorMessage( "user not found" ),
+ Response.Status.BAD_REQUEST.getStatusCode() );
+ }
+ // only 3 fields to update
+ realUser.setFullName( user.getFullName() );
+ realUser.setEmail( user.getEmail() );
+ // ui can limit to not update password
+ if ( StringUtils.isNotBlank( user.getPassword() ) )
+ {
+ passwordValidator.validatePassword( user.getPassword(), user.getUsername() );
+
+ realUser.setPassword( user.getPassword() );
+ }
+
+ updateUser( realUser );
+
+ return Boolean.TRUE;
+ }
+
+ public Boolean updateUser( User user )
+ throws RedbackServiceException
+ {
+ try
+ {
+ org.apache.archiva.redback.users.User rawUser = userManager.findUser( user.getUsername() );
+ rawUser.setFullName( user.getFullName() );
+ rawUser.setEmail( user.getEmail() );
+ rawUser.setValidated( user.isValidated() );
+ rawUser.setLocked( user.isLocked() );
+ rawUser.setPassword( user.getPassword() );
+ rawUser.setPasswordChangeRequired( user.isPasswordChangeRequired() );
+ rawUser.setPermanent( user.isPermanent() );
+
+ userManager.updateUser( rawUser );
+ return Boolean.TRUE;
+ }
+ catch ( UserNotFoundException e )
+ {
+ throw new RedbackServiceException( e.getMessage() );
+ }
+ }
+
+ public int removeFromCache( String userName )
+ throws RedbackServiceException
+ {
+ if ( userAssignmentsCache != null )
+ {
+ userAssignmentsCache.remove( userName );
+ }
+ if ( userPermissionsCache != null )
+ {
+ userPermissionsCache.remove( userName );
+ }
+ if ( usersCache != null )
+ {
+ usersCache.remove( userName );
+ }
+
+ CacheManager cacheManager = CacheManager.getInstance();
+ String[] caches = cacheManager.getCacheNames();
+ for ( String cacheName : caches )
+ {
+ if ( StringUtils.startsWith( cacheName, "org.codehaus.plexus.redback.rbac.jdo" ) )
+ {
+ cacheManager.getCache( cacheName ).removeAll();
+ }
+ }
+
+ return 0;
+ }
+
+ public User getGuestUser()
+ throws RedbackServiceException
+ {
+ try
+ {
+ org.apache.archiva.redback.users.User user = userManager.getGuestUser();
+ return getSimpleUser( user );
+ }
+ catch ( Exception e )
+ {
+ return null;
+ }
+ }
+
+ public User createGuestUser()
+ throws RedbackServiceException
+ {
+ User u = getGuestUser();
+ if ( u != null )
+ {
+ return u;
+ }
+ // temporary disable policy during guest creation as no password !
+ try
+ {
+ securitySystem.getPolicy().setEnabled( false );
+ org.apache.archiva.redback.users.User user = userManager.createGuestUser();
+ user.setPasswordChangeRequired( false );
+ user = userManager.updateUser( user, false );
+ roleManager.assignRole( "guest", user.getPrincipal().toString() );
+ return getSimpleUser( user );
+ }
+ catch ( RoleManagerException e )
+ {
+ log.error( e.getMessage(), e );
+ throw new RedbackServiceException( e.getMessage() );
+ }
+ catch ( UserNotFoundException e )
+ {
+ // olamy I wonder how this can happen :-)
+ log.error( e.getMessage(), e );
+ throw new RedbackServiceException( e.getMessage() );
+ }
+ finally
+ {
+
+ if ( !securitySystem.getPolicy().isEnabled() )
+ {
+ securitySystem.getPolicy().setEnabled( true );
+ }
+ }
+ }
+
+ public Boolean ping()
+ throws RedbackServiceException
+ {
+ return Boolean.TRUE;
+ }
+
+ private User getSimpleUser( org.apache.archiva.redback.users.User user )
+ {
+ if ( user == null )
+ {
+ return null;
+ }
+ return new User( user );
+ }
+
+ public Boolean createAdminUser( User adminUser )
+ throws RedbackServiceException
+ {
+ if ( isAdminUserExists() )
+ {
+ return Boolean.FALSE;
+ }
+
+ org.apache.archiva.redback.users.User user =
+ userManager.createUser( RedbackRoleConstants.ADMINISTRATOR_ACCOUNT_NAME, adminUser.getFullName(),
+ adminUser.getEmail() );
+ user.setPassword( adminUser.getPassword() );
+
+ user.setLocked( false );
+ user.setPasswordChangeRequired( false );
+ user.setPermanent( true );
+ user.setValidated( true );
+
+ userManager.addUser( user );
+
+ try
+ {
+ roleManager.assignRole( "system-administrator", user.getPrincipal().toString() );
+ }
+ catch ( RoleManagerException e )
+ {
+ throw new RedbackServiceException( e.getMessage() );
+ }
+ return Boolean.TRUE;
+ }
+
+ public Boolean isAdminUserExists()
+ throws RedbackServiceException
+ {
+ try
+ {
+ userManager.findUser( config.getString( "redback.default.admin" ) );
+ return Boolean.TRUE;
+ }
+ catch ( UserNotFoundException e )
+ {
+ // ignore
+ }
+ return Boolean.FALSE;
+ }
+
+ public Boolean resetPassword( String username )
+ throws RedbackServiceException
+ {
+ if ( StringUtils.isEmpty( username ) )
+ {
+ throw new RedbackServiceException( new ErrorMessage( "username.cannot.be.empty" ) );
+ }
+
+ UserManager userManager = securitySystem.getUserManager();
+ KeyManager keyManager = securitySystem.getKeyManager();
+ UserSecurityPolicy policy = securitySystem.getPolicy();
+
+ try
+ {
+ org.apache.archiva.redback.users.User user = userManager.findUser( username );
+
+ AuthenticationKey authkey = keyManager.createKey( username, "Password Reset Request",
+ policy.getUserValidationSettings().getEmailValidationTimeout() );
+
+ mailer.sendPasswordResetEmail( Arrays.asList( user.getEmail() ), authkey, getBaseUrl() );
+
+ log.info( "password reset request for username {}", username );
+ }
+ catch ( UserNotFoundException e )
+ {
+ log.info( "Password Reset on non-existant user [{}].", username );
+ throw new RedbackServiceException( new ErrorMessage( "password.reset.failure" ) );
+ }
+ catch ( KeyManagerException e )
+ {
+ log.info( "Unable to issue password reset.", e );
+ throw new RedbackServiceException( new ErrorMessage( "password.reset.email.generation.failure" ) );
+ }
+
+ return Boolean.TRUE;
+ }
+
+ public RegistrationKey registerUser( User user )
+ throws RedbackServiceException
+ {
+ if ( user == null )
+ {
+ throw new RedbackServiceException( new ErrorMessage( "invalid.user.credentials", null ) );
+
+ }
+
+ UserSecurityPolicy securityPolicy = securitySystem.getPolicy();
+
+ boolean emailValidationRequired = securityPolicy.getUserValidationSettings().isEmailValidationRequired();
+
+ if ( emailValidationRequired )
+ {
+ validateCredentialsLoose( user );
+ }
+ else
+ {
+ validateCredentialsStrict( user );
+ }
+
+ // NOTE: Do not perform Password Rules Validation Here.
+
+ if ( userManager.userExists( user.getUsername() ) )
+ {
+ throw new RedbackServiceException(
+ new ErrorMessage( "user.already.exists", new String[]{ user.getUsername() } ) );
+ }
+
+ org.apache.archiva.redback.users.User u =
+ userManager.createUser( user.getUsername(), user.getFullName(), user.getEmail() );
+ u.setPassword( user.getPassword() );
+ u.setValidated( false );
+ u.setLocked( false );
+
+ try
+ {
+ roleManager.assignRole( RedbackRoleConstants.REGISTERED_USER_ROLE_ID, u.getPrincipal().toString() );
+ }
+ catch ( RoleManagerException rpe )
+ {
+ log.error( "RoleProfile Error: " + rpe.getMessage(), rpe );
+ throw new RedbackServiceException( new ErrorMessage( "assign.role.failure", null ) );
+ }
+
+ if ( emailValidationRequired )
+ {
+ u.setLocked( true );
+
+ try
+ {
+ AuthenticationKey authkey =
+ securitySystem.getKeyManager().createKey( u.getPrincipal().toString(), "New User Email Validation",
+ securityPolicy.getUserValidationSettings().getEmailValidationTimeout() );
+
+ mailer.sendAccountValidationEmail( Arrays.asList( u.getEmail() ), authkey, getBaseUrl() );
+
+ securityPolicy.setEnabled( false );
+ userManager.addUser( u );
+ return new RegistrationKey( authkey.getKey() );
+
+ }
+ catch ( KeyManagerException e )
+ {
+ log.error( "Unable to register a new user.", e );
+ throw new RedbackServiceException( new ErrorMessage( "cannot.register.user", null ) );
+ }
+ finally
+ {
+ securityPolicy.setEnabled( true );
+ }
+ }
+ else
+ {
+ userManager.addUser( u );
+ return new RegistrationKey( "-1" );
+ }
+
+ // FIXME log this event
+ /*
+ AuditEvent event = new AuditEvent( getText( "log.account.create" ) );
+ event.setAffectedUser( username );
+ event.log();
+ */
+
+ }
+
+ public Boolean validateUserFromKey( String key )
+ throws RedbackServiceException
+ {
+ String principal = null;
+ try
+ {
+ AuthenticationKey authkey = securitySystem.getKeyManager().findKey( key );
+
+ org.apache.archiva.redback.users.User user =
+ securitySystem.getUserManager().findUser( authkey.getForPrincipal() );
+
+ user.setValidated( true );
+ user.setLocked( false );
+ user.setPasswordChangeRequired( true );
+ user.setEncodedPassword( "" );
+
+ principal = user.getPrincipal().toString();
+
+ TokenBasedAuthenticationDataSource authsource = new TokenBasedAuthenticationDataSource();
+ authsource.setPrincipal( principal );
+ authsource.setToken( authkey.getKey() );
+ authsource.setEnforcePasswordChange( false );
+
+ securitySystem.getUserManager().updateUser( user );
+
+ httpAuthenticator.authenticate( authsource, httpServletRequest.getSession( true ) );
+
+ log.info( "account validated for user {}", user.getUsername() );
+
+ return Boolean.TRUE;
+ }
+ catch ( MustChangePasswordException e )
+ {
+ throw new RedbackServiceException( e.getMessage(), Response.Status.FORBIDDEN.getStatusCode() );
+ }
+ catch ( KeyNotFoundException e )
+ {
+ log.info( "Invalid key requested: {}", key );
+ throw new RedbackServiceException( new ErrorMessage( "cannot.find.key" ) );
+ }
+ catch ( KeyManagerException e )
+ {
+ throw new RedbackServiceException( new ErrorMessage( "cannot.find.key.at.the.momment" ) );
+
+ }
+ catch ( UserNotFoundException e )
+ {
+ throw new RedbackServiceException( new ErrorMessage( "cannot.find.user", new String[]{ principal } ) );
+
+ }
+ catch ( AccountLockedException e )
+ {
+ throw new RedbackServiceException( e.getMessage(), Response.Status.FORBIDDEN.getStatusCode() );
+ }
+ catch ( AuthenticationException e )
+ {
+ throw new RedbackServiceException( e.getMessage(), Response.Status.FORBIDDEN.getStatusCode() );
+ }
+ }
+
+ public Collection<Permission> getCurrentUserPermissions()
+ throws RedbackServiceException
+ {
+ RedbackRequestInformation redbackRequestInformation = RedbackAuthenticationThreadLocal.get();
+ String userName = UserManager.GUEST_USERNAME;
+ if ( redbackRequestInformation != null && redbackRequestInformation.getUser() != null )
+ {
+ userName = redbackRequestInformation.getUser().getUsername();
+ }
+
+ return getUserPermissions( userName );
+ }
+
+ public Collection<Operation> getCurrentUserOperations()
+ throws RedbackServiceException
+ {
+ RedbackRequestInformation redbackRequestInformation = RedbackAuthenticationThreadLocal.get();
+ String userName = UserManager.GUEST_USERNAME;
+ if ( redbackRequestInformation != null && redbackRequestInformation.getUser() != null )
+ {
+ userName = redbackRequestInformation.getUser().getUsername();
+ }
+
+ return getUserOperations( userName );
+ }
+
+ public Collection<Operation> getUserOperations( String userName )
+ throws RedbackServiceException
+ {
+ Collection<Permission> permissions = getUserPermissions( userName );
+ List<Operation> operations = new ArrayList<Operation>( permissions.size() );
+ for ( Permission permission : permissions )
+ {
+ if ( permission.getOperation() != null )
+ {
+ Operation operation = new Operation();
+ operation.setName( permission.getOperation().getName() );
+ operations.add( operation );
+ }
+ }
+ return operations;
+ }
+
+ public Collection<Permission> getUserPermissions( String userName )
+ throws RedbackServiceException
+ {
+ try
+ {
+ Set<org.apache.archiva.redback.rbac.Permission> permissions =
+ rbacManager.getAssignedPermissions( userName );
+ // FIXME return guest permissions !!
+ List<Permission> userPermissions = new ArrayList<Permission>( permissions.size() );
+ for ( org.apache.archiva.redback.rbac.Permission p : permissions )
+ {
+ Permission permission = new Permission();
+ permission.setName( p.getName() );
+
+ if ( p.getOperation() != null )
+ {
+ Operation operation = new Operation();
+ operation.setName( p.getOperation().getName() );
+ permission.setOperation( operation );
+ }
+
+ if ( p.getResource() != null )
+ {
+ Resource resource = new Resource();
+ resource.setIdentifier( p.getResource().getIdentifier() );
+ resource.setPattern( p.getResource().isPattern() );
+ permission.setResource( resource );
+ }
+
+ userPermissions.add( permission );
+ }
+ return userPermissions;
+ }
+ catch ( RbacObjectNotFoundException e )
+ {
+ log.error( e.getMessage(), e );
+ throw new RedbackServiceException( e.getMessage() );
+ }
+ catch ( RbacManagerException e )
+ {
+ log.error( e.getMessage(), e );
+ throw new RedbackServiceException( e.getMessage() );
+ }
+ }
+
+ public void validateCredentialsLoose( User user )
+ throws RedbackServiceException
+ {
+ RedbackServiceException redbackServiceException =
+ new RedbackServiceException( "issues during validating user" );
+ if ( org.codehaus.plexus.util.StringUtils.isEmpty( user.getUsername() ) )
+ {
+ redbackServiceException.addErrorMessage( new ErrorMessage( "username.required", null ) );
+ }
+ else
+ {
+ if ( !user.getUsername().matches( VALID_USERNAME_CHARS ) )
+ {
+ redbackServiceException.addErrorMessage( new ErrorMessage( "username.invalid.characters", null ) );
+ }
+ }
+
+ if ( org.codehaus.plexus.util.StringUtils.isEmpty( user.getFullName() ) )
+ {
+ redbackServiceException.addErrorMessage( new ErrorMessage( "fullName.required", null ) );
+ }
+
+ if ( org.codehaus.plexus.util.StringUtils.isEmpty( user.getEmail() ) )
+ {
+ redbackServiceException.addErrorMessage( new ErrorMessage( "email.required", null ) );
+ }
+
+ if ( !org.codehaus.plexus.util.StringUtils.equals( user.getPassword(), user.getConfirmPassword() ) )
+ {
+ redbackServiceException.addErrorMessage( new ErrorMessage( "passwords.does.not.match", null ) );
+ }
+
+ try
+ {
+ if ( !org.codehaus.plexus.util.StringUtils.isEmpty( user.getEmail() ) )
+ {
+ new InternetAddress( user.getEmail(), true );
+ }
+ }
+ catch ( AddressException e )
+ {
+ redbackServiceException.addErrorMessage( new ErrorMessage( "email.invalid", null ) );
+ }
+ if ( !redbackServiceException.getErrorMessages().isEmpty() )
+ {
+ throw redbackServiceException;
+ }
+ }
+
+ public void validateCredentialsStrict( User user )
+ throws RedbackServiceException
+ {
+ validateCredentialsLoose( user );
+
+ org.apache.archiva.redback.users.User tmpuser =
+ userManager.createUser( user.getUsername(), user.getFullName(), user.getEmail() );
+
+ user.setPassword( user.getPassword() );
+
+ securitySystem.getPolicy().validatePassword( tmpuser );
+
+ if ( ( org.codehaus.plexus.util.StringUtils.isEmpty( user.getPassword() ) ) )
+ {
+ throw new RedbackServiceException( new ErrorMessage( "password.required", null ) );
+ }
+ }
+
+ private String getBaseUrl()
+ {
+ if ( httpServletRequest != null )
+ {
+ if ( httpServletRequest != null )
+ {
+ return httpServletRequest.getScheme() + "://" + httpServletRequest.getServerName() + (
+ httpServletRequest.getServerPort() == 80
+ ? ""
+ : ":" + httpServletRequest.getServerPort() ) + httpServletRequest.getContextPath();
+ }
+ }
+ return null;
+ }
+
+ public Boolean unlockUser( String username )
+ throws RedbackServiceException
+ {
+ User user = getUser( username );
+ if ( user == null )
+ {
+ user.setLocked( false );
+ updateUser( user );
+ return Boolean.TRUE;
+ }
+ return Boolean.FALSE;
+ }
+
+ public Boolean lockUser( String username )
+ throws RedbackServiceException
+ {
+ User user = getUser( username );
+ if ( user == null )
+ {
+ user.setLocked( true );
+ updateUser( user );
+ return Boolean.TRUE;
+ }
+ return Boolean.FALSE;
+ }
+
+ public Boolean passwordChangeRequired( String username )
+ throws RedbackServiceException
+ {
+ User user = getUser( username );
+ if ( user == null )
+ {
+ user.setPasswordChangeRequired( true );
+ updateUser( user );
+ return Boolean.TRUE;
+ }
+ return Boolean.FALSE;
+ }
+
+ public Boolean passwordChangeNotRequired( String username )
+ throws RedbackServiceException
+ {
+ User user = getUser( username );
+ if ( user == null )
+ {
+ user.setPasswordChangeRequired( false );
+ updateUser( user );
+ return Boolean.TRUE;
+ }
+ return Boolean.FALSE;
+ }
+}
--- /dev/null
+package org.apache.archiva.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.io.IOUtils;
+import org.apache.commons.lang.StringUtils;
+import org.apache.archiva.redback.rest.api.services.RedbackServiceException;
+import org.apache.archiva.redback.rest.api.services.UtilServices;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.PostConstruct;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Map;
+import java.util.Properties;
+import java.util.concurrent.ConcurrentHashMap;
+
+/**
+ * @author Olivier Lamy
+ * @since 1.4
+ */
+@Service( "utilServices#rest" )
+public class DefaultUtilServices
+ implements UtilServices
+{
+
+ private Logger log = LoggerFactory.getLogger( getClass() );
+
+ private Map<String, String> cachei18n = new ConcurrentHashMap<String, String>();
+
+ @PostConstruct
+ public void init()
+ throws RedbackServiceException
+ {
+
+ // preload i18n en and fr
+ getI18nProperties( "en" );
+ getI18nProperties( "fr" );
+ }
+
+ public String getI18nResources( String locale )
+ throws RedbackServiceException
+ {
+ String cachedi18n = cachei18n.get( StringUtils.isEmpty( locale ) ? "en" : StringUtils.lowerCase( locale ) );
+ if ( cachedi18n != null )
+ {
+ return cachedi18n;
+ }
+
+ Properties properties = new Properties();
+
+ // load redback user api messages
+ try
+ {
+
+ // load default first then requested locale
+ loadResource( properties, "org/codehaus/plexus/redback/users/messages", null );
+ loadResource( properties, "org/codehaus/plexus/redback/users/messages", locale );
+
+ }
+ catch ( IOException e )
+ {
+ log.warn( "skip error loading properties {}", "org/codehaus/plexus/redback/users/messages" );
+ }
+
+ try
+ {
+
+ // load default first then requested locale
+ loadResource( properties, "org/codehaus/redback/i18n/default", null );
+ loadResource( properties, "org/codehaus/redback/i18n/default", locale );
+
+ }
+ catch ( IOException e )
+ {
+ log.warn( "skip error loading properties {}", "org/codehaus/redback/i18n/default" );
+ }
+
+ StringBuilder output = new StringBuilder();
+
+ for ( Map.Entry<Object, Object> entry : properties.entrySet() )
+ {
+ output.append( (String) entry.getKey() ).append( '=' ).append( (String) entry.getValue() );
+ output.append( '\n' );
+ }
+
+ cachei18n.put( StringUtils.isEmpty( locale ) ? "en" : StringUtils.lowerCase( locale ), output.toString() );
+
+ return output.toString();
+ }
+
+ public Properties getI18nProperties( String locale )
+ throws RedbackServiceException
+ {
+ try
+ {
+ Properties properties = new Properties();
+ // load default first then requested locale
+ loadResource( properties, "org/codehaus/plexus/redback/users/messages", null );
+ loadResource( properties, "org/codehaus/plexus/redback/users/messages", locale );
+
+ loadResource( properties, "org/codehaus/redback/i18n/default", null );
+ loadResource( properties, "org/codehaus/redback/i18n/default", locale );
+ return properties;
+ }
+ catch ( IOException e )
+ {
+ throw new RedbackServiceException( e.getMessage() );
+ }
+ }
+
+ private void loadResource( final Properties finalProperties, String resourceName, String locale )
+ throws IOException
+ {
+ InputStream is = null;
+ Properties properties = new Properties();
+ try
+ {
+ if ( StringUtils.isNotEmpty( locale ) )
+ {
+ resourceName = resourceName + "_" + locale;
+ }
+ resourceName = resourceName + ".properties";
+ is = Thread.currentThread().getContextClassLoader().getResourceAsStream( resourceName.toString() );
+ if ( is != null )
+ {
+ properties.load( is );
+ finalProperties.putAll( properties );
+ }
+ else
+ {
+ if ( !StringUtils.equalsIgnoreCase( locale, "en" ) )
+ {
+ log.info( "cannot load resource {}", resourceName );
+ }
+ }
+ }
+ finally
+ {
+ IOUtils.closeQuietly( is );
+ }
+
+ }
+
+
+}
--- /dev/null
+package org.apache.archiva.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.
+ */
+
+/**
+ * @author Olivier Lamy
+ * @since 1.4
+ */
+public class RedbackAuthenticationThreadLocal
+{
+ private static final ThreadLocal<RedbackRequestInformation> userThreadLocal =
+ new ThreadLocal<RedbackRequestInformation>();
+
+ public static void set( RedbackRequestInformation redbackRequestInformation )
+ {
+ userThreadLocal.set( redbackRequestInformation );
+ }
+
+ public static RedbackRequestInformation get()
+ {
+ return userThreadLocal.get();
+ }
+}
--- /dev/null
+package org.apache.archiva.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.archiva.redback.users.User;
+
+/**
+ * @author Olivier Lamy
+ * @since 1.4
+ */
+public class RedbackRequestInformation
+{
+ private User user;
+
+ private String remoteAddr;
+
+ public RedbackRequestInformation( User user, String remoteAddr )
+ {
+ this.user = user;
+ this.remoteAddr = remoteAddr;
+ }
+
+ public User getUser()
+ {
+ return user;
+ }
+
+ public void setUser( User user )
+ {
+ this.user = user;
+ }
+
+ public String getRemoteAddr()
+ {
+ return remoteAddr;
+ }
+
+ public void setRemoteAddr( String remoteAddr )
+ {
+ this.remoteAddr = remoteAddr;
+ }
+}
--- /dev/null
+package org.apache.archiva.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.jaxrs.model.OperationResourceInfo;
+import org.apache.cxf.message.Message;
+import org.apache.archiva.redback.authorization.RedbackAuthorization;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.ws.rs.core.Context;
+import java.lang.reflect.Method;
+
+/**
+ * @author Olivier Lamy
+ * @since 1.3
+ */
+public class AbstractInterceptor
+{
+
+ private Logger log = LoggerFactory.getLogger( getClass() );
+
+ @Context
+ private HttpServletRequest httpServletRequest;
+
+ @Context
+ private HttpServletResponse httpServletResponse;
+
+ public HttpServletRequest getHttpServletRequest( Message message )
+ {
+ return httpServletRequest;
+ }
+
+ public HttpServletResponse getHttpServletResponse( Message message )
+ {
+ return httpServletResponse;
+ }
+
+ public RedbackAuthorization getRedbackAuthorization( Message message )
+ {
+ OperationResourceInfo operationResourceInfo = message.getExchange().get( OperationResourceInfo.class );
+ if ( operationResourceInfo == null )
+ {
+ return null;
+ }
+
+ Method method = operationResourceInfo.getAnnotatedMethod();
+
+ log.debug( " method name {}", method == null ? "null" : method.getName() );
+ RedbackAuthorization redbackAuthorization = method.getAnnotation( RedbackAuthorization.class );
+ return redbackAuthorization;
+ }
+}
--- /dev/null
+package org.apache.archiva.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.archiva.redback.policy.MustChangePasswordException;
+import org.apache.archiva.redback.users.User;
+import org.apache.archiva.redback.users.UserManager;
+import org.apache.cxf.jaxrs.ext.RequestHandler;
+import org.apache.cxf.jaxrs.model.ClassResourceInfo;
+import org.apache.cxf.message.Message;
+import org.apache.archiva.redback.authentication.AuthenticationException;
+import org.apache.archiva.redback.authentication.AuthenticationResult;
+import org.apache.archiva.redback.authorization.RedbackAuthorization;
+import org.apache.archiva.redback.policy.AccountLockedException;
+import org.apache.archiva.redback.system.SecuritySession;
+import org.apache.archiva.redback.users.UserNotFoundException;
+import org.apache.archiva.redback.integration.filter.authentication.HttpAuthenticationException;
+import org.apache.archiva.redback.integration.filter.authentication.basic.HttpBasicAuthentication;
+import org.apache.archiva.redback.rest.services.RedbackAuthenticationThreadLocal;
+import org.apache.archiva.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();
+ }
+ }
+}
--- /dev/null
+package org.apache.archiva.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.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 );
+ }
+}
--- /dev/null
+package org.apache.archiva.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 );
+ }
+}
--- /dev/null
+package org.apache.archiva.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.archiva.redback.policy.PasswordRuleViolationException;
+import org.apache.archiva.redback.policy.PasswordRuleViolations;
+import org.apache.archiva.redback.rest.api.model.ErrorMessage;
+import org.apache.archiva.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();
+ }
+}
--- /dev/null
+package org.apache.archiva.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.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.apache.archiva.redback.authentication.AuthenticationResult;
+import org.apache.archiva.redback.authorization.AuthorizationException;
+import org.apache.archiva.redback.authorization.RedbackAuthorization;
+import org.apache.archiva.redback.system.SecuritySession;
+import org.apache.archiva.redback.system.SecuritySystem;
+import org.apache.archiva.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();
+ }
+}
--- /dev/null
+package org.apache.archiva.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.archiva.redback.rest.api.model.RedbackRestError;
+import org.apache.archiva.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();
+ }
+}
--- /dev/null
+package org.apache.archiva.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.apache.archiva.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();
+ }
+}
--- /dev/null
+package org.apache.archiva.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.apache.archiva.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() );
+ }
+ }
+ }
+}
--- /dev/null
+package org.apache.archiva.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.apache.archiva.redback.policy.PasswordRuleViolations;
+import org.apache.archiva.redback.users.User;
+import org.apache.archiva.redback.users.UserNotFoundException;
+import org.apache.archiva.redback.policy.PasswordEncoder;
+import org.apache.archiva.redback.policy.PasswordRuleViolationException;
+import org.apache.archiva.redback.system.SecuritySystem;
+import org.apache.archiva.redback.rest.api.model.ErrorMessage;
+import org.apache.archiva.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 );
+ }
+
+ }
+}
+++ /dev/null
-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.archiva.redback.authentication.AuthenticationException;
-import org.apache.archiva.redback.keys.KeyManager;
-import org.apache.archiva.redback.policy.AccountLockedException;
-import org.apache.archiva.redback.policy.MustChangePasswordException;
-import org.apache.archiva.redback.users.UserNotFoundException;
-import org.apache.archiva.redback.authentication.PasswordBasedAuthenticationDataSource;
-import org.apache.archiva.redback.keys.AuthenticationKey;
-import org.codehaus.plexus.redback.keys.jdo.JdoAuthenticationKey;
-import org.apache.archiva.redback.keys.memory.MemoryAuthenticationKey;
-import org.apache.archiva.redback.keys.memory.MemoryKeyManager;
-import org.apache.archiva.redback.system.SecuritySession;
-import org.apache.archiva.redback.system.SecuritySystem;
-import org.apache.archiva.redback.integration.filter.authentication.HttpAuthenticator;
-import org.apache.archiva.redback.rest.api.model.User;
-import org.apache.archiva.redback.rest.api.services.LoginService;
-import org.apache.archiva.redback.rest.api.services.RedbackServiceException;
-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.HttpSession;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.Response;
-import java.util.Calendar;
-import java.util.TimeZone;
-
-/**
- * @author Olivier Lamy
- * @since 1.3
- */
-@Service( "loginService#rest" )
-public class DefaultLoginService
- implements LoginService
-{
-
- private Logger log = LoggerFactory.getLogger( getClass() );
-
- private SecuritySystem securitySystem;
-
- private HttpAuthenticator httpAuthenticator;
-
- @Context
- private HttpServletRequest httpServletRequest;
-
- @Inject
- public DefaultLoginService( SecuritySystem securitySystem,
- @Named( "httpAuthenticator#basic" ) HttpAuthenticator httpAuthenticator )
- {
- this.securitySystem = securitySystem;
- this.httpAuthenticator = httpAuthenticator;
- }
-
-
- public String addAuthenticationKey( String providedKey, String principal, String purpose, int expirationMinutes )
- throws RedbackServiceException
- {
- KeyManager keyManager = securitySystem.getKeyManager();
- AuthenticationKey key;
-
- if ( keyManager instanceof MemoryKeyManager )
- {
- key = new MemoryAuthenticationKey();
- }
- else
- {
- key = new JdoAuthenticationKey();
- }
-
- key.setKey( providedKey );
- key.setForPrincipal( principal );
- key.setPurpose( purpose );
-
- Calendar now = getNowGMT();
- key.setDateCreated( now.getTime() );
-
- if ( expirationMinutes >= 0 )
- {
- Calendar expiration = getNowGMT();
- expiration.add( Calendar.MINUTE, expirationMinutes );
- key.setDateExpires( expiration.getTime() );
- }
-
- keyManager.addKey( key );
-
- return key.getKey();
- }
-
- public Boolean ping()
- throws RedbackServiceException
- {
- return Boolean.TRUE;
- }
-
- public Boolean pingWithAutz()
- throws RedbackServiceException
- {
- return Boolean.TRUE;
- }
-
- public User logIn( String userName, String password )
- throws RedbackServiceException
- {
- PasswordBasedAuthenticationDataSource authDataSource =
- new PasswordBasedAuthenticationDataSource( userName, password );
- try
- {
- SecuritySession securitySession = securitySystem.authenticate( authDataSource );
- if ( securitySession.getAuthenticationResult().isAuthenticated() )
- {
- org.apache.archiva.redback.users.User user = securitySession.getUser();
- if ( !user.isValidated() )
- {
- log.info( "user {} not validated", user.getUsername() );
- return null;
- }
- User restUser = buildRestUser( user );
-
- // here create an http session
- httpAuthenticator.authenticate( authDataSource, httpServletRequest.getSession( true ) );
- return restUser;
- }
- return null;
- }
- catch ( AuthenticationException e )
- {
- throw new RedbackServiceException( e.getMessage(), Response.Status.FORBIDDEN.getStatusCode() );
- }
- catch ( UserNotFoundException e )
- {
- throw new RedbackServiceException( e.getMessage() );
- }
- catch ( AccountLockedException e )
- {
- throw new RedbackServiceException( e.getMessage() );
- }
- catch ( MustChangePasswordException e )
- {
- return buildRestUser( e.getUser() );
- }
- }
-
- public Boolean isLogged()
- throws RedbackServiceException
- {
- Boolean isLogged = httpAuthenticator.getSecuritySession( httpServletRequest.getSession( true ) ) != null;
- log.debug( "isLogged {}", isLogged );
- return isLogged;
- }
-
- public Boolean logout()
- throws RedbackServiceException
- {
- HttpSession httpSession = httpServletRequest.getSession();
- if ( httpSession != null )
- {
- httpSession.invalidate();
- }
- return Boolean.TRUE;
- }
-
- private Calendar getNowGMT()
- {
- return Calendar.getInstance( TimeZone.getTimeZone( "GMT" ) );
- }
-
- private User buildRestUser( org.apache.archiva.redback.users.User user )
- {
- User restUser = new User();
- restUser.setEmail( user.getEmail() );
- restUser.setUsername( user.getUsername() );
- restUser.setPasswordChangeRequired( user.isPasswordChangeRequired() );
- restUser.setLocked( user.isLocked() );
- restUser.setValidated( user.isValidated() );
- restUser.setFullName( user.getFullName() );
- return restUser;
- }
-}
+++ /dev/null
-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.archiva.redback.policy.PasswordEncoder;
-import org.apache.archiva.redback.policy.PasswordRuleViolationException;
-import org.apache.archiva.redback.policy.PasswordRuleViolations;
-import org.apache.archiva.redback.users.User;
-import org.apache.commons.lang.StringUtils;
-import org.apache.archiva.redback.keys.AuthenticationKey;
-import org.apache.archiva.redback.keys.KeyManagerException;
-import org.apache.archiva.redback.system.SecuritySystem;
-import org.apache.archiva.redback.users.UserNotFoundException;
-import org.apache.archiva.redback.integration.filter.authentication.HttpAuthenticator;
-import org.apache.archiva.redback.rest.api.model.ErrorMessage;
-import org.apache.archiva.redback.rest.api.services.PasswordService;
-import org.apache.archiva.redback.rest.api.services.RedbackServiceException;
-import org.codehaus.redback.rest.services.utils.PasswordValidator;
-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.Context;
-import javax.ws.rs.core.Response;
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * @author Olivier Lamy
- * @since 1.4
- */
-@Service( "passwordService#rest" )
-public class DefaultPasswordService
- implements PasswordService
-{
-
- private Logger log = LoggerFactory.getLogger( getClass() );
-
- private SecuritySystem securitySystem;
-
- private HttpAuthenticator httpAuthenticator;
-
- private PasswordValidator passwordValidator;
-
- @Context
- private HttpServletRequest httpServletRequest;
-
- @Inject
- public DefaultPasswordService( SecuritySystem securitySystem,
- @Named( "httpAuthenticator#basic" ) HttpAuthenticator httpAuthenticator,
- PasswordValidator passwordValidator )
- {
- this.securitySystem = securitySystem;
- this.httpAuthenticator = httpAuthenticator;
- this.passwordValidator = passwordValidator;
- }
-
- public org.apache.archiva.redback.rest.api.model.User changePasswordWithKey( String password, String passwordConfirmation,
- String key )
- throws RedbackServiceException
- {
-
-
- //RedbackRequestInformation redbackRequestInformation = RedbackAuthenticationThreadLocal.get();
-
- String principal = null;
-
- if ( StringUtils.isEmpty( password ) )
- {
- throw new RedbackServiceException( "password cannot be empty", Response.Status.FORBIDDEN.getStatusCode() );
- }
- if ( StringUtils.isEmpty( passwordConfirmation ) )
- {
- throw new RedbackServiceException( "password confirmation cannot be empty",
- Response.Status.FORBIDDEN.getStatusCode() );
- }
- if ( !StringUtils.equals( password, passwordConfirmation ) )
- {
- throw new RedbackServiceException( "password confirmation must be same as password",
- Response.Status.FORBIDDEN.getStatusCode() );
- }
-
- try
- {
- AuthenticationKey authKey = securitySystem.getKeyManager().findKey( key );
-
- principal = authKey.getForPrincipal();
-
- String encodedPassword = passwordValidator.validatePassword( password, principal );
-
- User user = securitySystem.getUserManager().findUser( principal );
- user.setPassword( password );
- user.setEncodedPassword( encodedPassword );
- user = securitySystem.getUserManager().updateUser( user );
-
- return new org.apache.archiva.redback.rest.api.model.User( user );
-
- }
- catch ( KeyManagerException e )
- {
- log.info( "issue to find key {}: {}", key, e.getMessage() );
- throw new RedbackServiceException( "issue with key", Response.Status.FORBIDDEN.getStatusCode() );
- }
- 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 );
- }
-
- }
-
- public org.apache.archiva.redback.rest.api.model.User changePassword( String userName, String previousPassword,
- String password, String passwordConfirmation )
- throws RedbackServiceException
- {
- if ( StringUtils.isEmpty( userName ) )
- {
- throw new RedbackServiceException( new ErrorMessage( "username.cannot.be.empty" ),
- Response.Status.BAD_REQUEST.getStatusCode() );
- }
- if ( StringUtils.isEmpty( previousPassword ) )
- {
- throw new RedbackServiceException( new ErrorMessage( "password.previous.empty" ),
- Response.Status.BAD_REQUEST.getStatusCode() );
- }
- if ( StringUtils.isEmpty( password ) )
- {
- throw new RedbackServiceException( new ErrorMessage( "password.empty" ),
- Response.Status.BAD_REQUEST.getStatusCode() );
- }
- if ( StringUtils.isEmpty( passwordConfirmation ) )
- {
- throw new RedbackServiceException( new ErrorMessage( "password.confirmation.empty" ),
- Response.Status.BAD_REQUEST.getStatusCode() );
- }
-
- if ( !StringUtils.equals( password, passwordConfirmation ) )
- {
- throw new RedbackServiceException( new ErrorMessage( "password.confirmation.same" ),
- Response.Status.BAD_REQUEST.getStatusCode() );
- }
- try
- {
- User u = securitySystem.getUserManager().findUser( userName );
-
- String previousEncodedPassword = u.getEncodedPassword();
-
- // check oldPassword with the current one
-
- PasswordEncoder encoder = securitySystem.getPolicy().getPasswordEncoder();
-
- if ( !encoder.isPasswordValid( previousEncodedPassword, previousPassword ) )
- {
-
- throw new RedbackServiceException( new ErrorMessage( "password.provided.does.not.match.existing" ),
- Response.Status.BAD_REQUEST.getStatusCode() );
- }
-
- u.setPassword( password );
-
- u = securitySystem.getUserManager().updateUser( u );
- return new org.apache.archiva.redback.rest.api.model.User( u );
- }
- catch ( UserNotFoundException e )
- {
- throw new RedbackServiceException( new ErrorMessage( "user.not.found" ),
- Response.Status.BAD_REQUEST.getStatusCode() );
- }
-
- }
-}
+++ /dev/null
-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.archiva.redback.rbac.Permission;
-import org.apache.archiva.redback.rbac.RBACManager;
-import org.apache.archiva.redback.rbac.RbacManagerException;
-import org.apache.archiva.redback.rbac.Resource;
-import org.apache.archiva.redback.rbac.UserAssignment;
-import org.apache.archiva.redback.role.RoleManager;
-import org.apache.archiva.redback.role.RoleManagerException;
-import org.apache.archiva.redback.users.User;
-import org.apache.archiva.redback.users.UserManager;
-import org.apache.archiva.redback.users.UserNotFoundException;
-import org.apache.commons.lang.StringUtils;
-import org.codehaus.plexus.redback.role.model.ModelApplication;
-import org.codehaus.plexus.redback.role.model.ModelRole;
-import org.codehaus.plexus.redback.role.model.ModelTemplate;
-import org.apache.archiva.redback.integration.model.AdminEditUserCredentials;
-import org.apache.archiva.redback.integration.security.role.RedbackRoleConstants;
-import org.apache.archiva.redback.integration.util.RoleSorter;
-import org.apache.archiva.redback.rest.api.model.Application;
-import org.apache.archiva.redback.rest.api.model.ApplicationRoles;
-import org.apache.archiva.redback.rest.api.model.ErrorMessage;
-import org.apache.archiva.redback.rest.api.model.Role;
-import org.apache.archiva.redback.rest.api.model.RoleTemplate;
-import org.apache.archiva.redback.rest.api.services.RedbackServiceException;
-import org.apache.archiva.redback.rest.api.services.RoleManagementService;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.stereotype.Service;
-
-import javax.inject.Inject;
-import javax.inject.Named;
-import javax.ws.rs.core.Response;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-/**
- * @author Olivier Lamy
- * @since 1.3
- */
-@Service( "roleManagementService#rest" )
-public class DefaultRoleManagementService
- implements RoleManagementService
-{
-
- private Logger log = LoggerFactory.getLogger( getClass() );
-
- private RoleManager roleManager;
-
- private RBACManager rbacManager;
-
- private UserManager userManager;
-
- @Inject
- public DefaultRoleManagementService( RoleManager roleManager,
- @Named( value = "rBACManager#cached" ) RBACManager rbacManager,
- @Named( value = "userManager#cached" ) UserManager userManager )
- {
- this.roleManager = roleManager;
- this.rbacManager = rbacManager;
- this.userManager = userManager;
- }
-
- public Boolean createTemplatedRole( String templateId, String resource )
- throws RedbackServiceException
- {
- try
- {
- roleManager.createTemplatedRole( templateId, resource );
- }
- catch ( RoleManagerException e )
- {
- throw new RedbackServiceException( e.getMessage() );
- }
- return Boolean.TRUE;
- }
-
- public Boolean removeTemplatedRole( String templateId, String resource )
- throws RedbackServiceException
- {
-
- try
- {
- roleManager.removeTemplatedRole( templateId, resource );
- }
- catch ( RoleManagerException e )
- {
- throw new RedbackServiceException( e.getMessage() );
- }
- return Boolean.TRUE;
- }
-
- public Boolean updateRole( String templateId, String oldResource, String newResource )
- throws RedbackServiceException
- {
- try
- {
- roleManager.updateRole( templateId, oldResource, newResource );
- }
- catch ( RoleManagerException e )
- {
- throw new RedbackServiceException( e.getMessage() );
- }
- return Boolean.TRUE;
- }
-
- public Boolean assignRole( String roleId, String principal )
- throws RedbackServiceException
- {
- try
- {
- roleManager.assignRole( roleId, principal );
- }
- catch ( RoleManagerException e )
- {
- throw new RedbackServiceException( e.getMessage() );
- }
- return Boolean.TRUE;
- }
-
- public Boolean assignRoleByName( String roleName, String principal )
- throws RedbackServiceException
- {
- try
- {
- roleManager.assignRoleByName( roleName, principal );
- }
- catch ( RoleManagerException e )
- {
- throw new RedbackServiceException( e.getMessage() );
- }
- return Boolean.TRUE;
- }
-
- public Boolean assignTemplatedRole( String templateId, String resource, String principal )
- throws RedbackServiceException
- {
- try
- {
- roleManager.assignTemplatedRole( templateId, resource, principal );
- }
- catch ( RoleManagerException e )
- {
- throw new RedbackServiceException( e.getMessage() );
- }
- return Boolean.TRUE;
- }
-
- public Boolean unassignRole( String roleId, String principal )
- throws RedbackServiceException
- {
- try
- {
- roleManager.unassignRole( roleId, principal );
- }
- catch ( RoleManagerException e )
- {
- throw new RedbackServiceException( e.getMessage() );
- }
- return Boolean.TRUE;
- }
-
- public Boolean unassignRoleByName( String roleName, String principal )
- throws RedbackServiceException
- {
- try
- {
- roleManager.unassignRoleByName( roleName, principal );
- }
- catch ( RoleManagerException e )
- {
- throw new RedbackServiceException( e.getMessage() );
- }
- return Boolean.TRUE;
- }
-
- public Boolean roleExists( String roleId )
- throws RedbackServiceException
- {
- try
- {
- return roleManager.roleExists( roleId );
- }
- catch ( RoleManagerException e )
- {
- throw new RedbackServiceException( e.getMessage() );
- }
- }
-
- public Boolean templatedRoleExists( String templateId, String resource )
- throws RedbackServiceException
- {
- try
- {
- return roleManager.templatedRoleExists( templateId, resource );
- }
- catch ( RoleManagerException e )
- {
- throw new RedbackServiceException( e.getMessage() );
- }
-
- }
-
- public Boolean verifyTemplatedRole( String templateId, String resource )
- throws RedbackServiceException
- {
- try
- {
- roleManager.verifyTemplatedRole( templateId, resource );
- }
- catch ( RoleManagerException e )
- {
- throw new RedbackServiceException( e.getMessage() );
- }
- return Boolean.TRUE;
- }
-
- public List<Role> getEffectivelyAssignedRoles( String username )
- throws RedbackServiceException
- {
- if ( StringUtils.isEmpty( username ) )
- {
- throw new RedbackServiceException( new ErrorMessage( "user.cannot.be.null" ) );
- }
- try
- {
- List<org.apache.archiva.redback.rbac.Role> roles =
- filterAssignableRoles( rbacManager.getEffectivelyAssignedRoles( username ) );
-
- List<Role> effectivelyAssignedRoles = new ArrayList<Role>( roles.size() );
-
- for ( org.apache.archiva.redback.rbac.Role r : roles )
- {
- effectivelyAssignedRoles.add( new Role( r ) );
- }
- return effectivelyAssignedRoles;
- }
- catch ( RbacManagerException rme )
- {
- // ignore, this can happen when the user has no roles assigned
- }
- return new ArrayList<Role>( 0 );
- }
-
-
- public List<Application> getApplications( String username )
- throws RedbackServiceException
- {
-
- List<ModelApplication> modelApplications = roleManager.getModel().getApplications();
-
- List<Application> applications = new ArrayList<Application>( modelApplications.size() );
-
- for ( ModelApplication modelApplication : modelApplications )
- {
- Application application = new Application();
- application.setDescription( modelApplication.getDescription() );
- application.setId( modelApplication.getId() );
- application.setLongDescription( modelApplication.getLongDescription() );
- application.setVersion( modelApplication.getVersion() );
- applications.add( application );
- }
-
- return applications;
- }
-
- public List<Role> getAllRoles()
- throws RedbackServiceException
- {
- try
- {
- List<org.apache.archiva.redback.rbac.Role> roles = rbacManager.getAllRoles();
-
- if ( roles == null )
- {
- return Collections.emptyList();
- }
-
- roles = filterRolesForCurrentUserAccess( roles );
-
- List<Role> res = new ArrayList<Role>( roles.size() );
-
- for ( org.apache.archiva.redback.rbac.Role r : roles )
- {
- res.add( new Role( r ) );
- }
- return res;
-
- }
- catch ( RbacManagerException e )
- {
- throw new RedbackServiceException( e.getMessage() );
- }
- }
-
- public List<Role> getDetailedAllRoles()
- throws RedbackServiceException
- {
- try
- {
- List<org.apache.archiva.redback.rbac.Role> roles = rbacManager.getAllRoles();
-
- if ( roles == null )
- {
- return Collections.emptyList();
- }
-
- roles = filterRolesForCurrentUserAccess( roles );
-
- List<Role> res = new ArrayList<Role>( roles.size() );
-
- for ( org.apache.archiva.redback.rbac.Role r : roles )
- {
- res.add( getRole( r.getName() ) );
- }
- return res;
-
- }
- catch ( RbacManagerException e )
- {
- throw new RedbackServiceException( e.getMessage() );
- }
- }
-
- private List<org.apache.archiva.redback.rbac.Role> filterAssignableRoles(
- Collection<org.apache.archiva.redback.rbac.Role> roles )
- {
- List<org.apache.archiva.redback.rbac.Role> assignableRoles =
- new ArrayList<org.apache.archiva.redback.rbac.Role>( roles.size() );
- for ( org.apache.archiva.redback.rbac.Role r : roles )
- {
- if ( r.isAssignable() )
- {
- assignableRoles.add( r );
- }
- }
- return assignableRoles;
- }
-
- public Role getRole( String roleName )
- throws RedbackServiceException
- {
- try
- {
- org.apache.archiva.redback.rbac.Role rbacRole = rbacManager.getRole( roleName );
- Role role = new Role( rbacRole );
-
- Map<String, org.apache.archiva.redback.rbac.Role> parentRoles = rbacManager.getParentRoles( rbacRole );
- for ( String parentRoleName : parentRoles.keySet() )
- {
- role.getParentRoleNames().add( parentRoleName );
- }
-
- List<UserAssignment> userAssignments = rbacManager.getUserAssignmentsForRoles( Arrays.asList( roleName ) );
-
- if ( userAssignments != null )
- {
- for ( UserAssignment userAssignment : userAssignments )
- {
- try
- {
- User user = userManager.findUser( userAssignment.getPrincipal() );
- role.getUsers().add( new org.apache.archiva.redback.rest.api.model.User( user ) );
- }
- catch ( UserNotFoundException e )
- {
- log.warn( "User '" + userAssignment.getPrincipal() + "' doesn't exist.", e );
- }
- }
- }
-
- if ( !role.getParentRoleNames().isEmpty() )
- {
- List<UserAssignment> userParentAssignments =
- rbacManager.getUserAssignmentsForRoles( parentRoles.keySet() );
- if ( userParentAssignments != null )
- {
- for ( UserAssignment userAssignment : userParentAssignments )
- {
- try
- {
- User user = userManager.findUser( userAssignment.getPrincipal() );
- role.getParentsRolesUsers().add( new org.apache.archiva.redback.rest.api.model.User( user ) );
- }
- catch ( UserNotFoundException e )
- {
- log.warn( "User '" + userAssignment.getPrincipal() + "' doesn't exist.", e );
- }
- }
- }
- }
-
- List<org.apache.archiva.redback.rest.api.model.User> otherUsers =
- new ArrayList<org.apache.archiva.redback.rest.api.model.User>();
- for ( User u : userManager.getUsers() )
- {
- org.apache.archiva.redback.rest.api.model.User
- user = new org.apache.archiva.redback.rest.api.model.User( u );
- if ( role.getParentsRolesUsers().contains( user ) )
- {
- continue;
- }
- if ( role.getUsers().contains( user ) )
- {
- continue;
- }
- otherUsers.add( user );
- }
-
- role.setOtherUsers( otherUsers );
-
- return role;
- }
- catch ( RbacManagerException e )
- {
- throw new RedbackServiceException( new ErrorMessage( e.getMessage() ) );
- }
- }
-
- public Boolean updateRoleDescription( String roleName, String description )
- throws RedbackServiceException
- {
- try
- {
- org.apache.archiva.redback.rbac.Role rbacRole = rbacManager.getRole( roleName );
- rbacRole.setDescription( description );
- rbacManager.saveRole( rbacRole );
- }
- catch ( RbacManagerException e )
- {
- throw new RedbackServiceException( new ErrorMessage( e.getMessage() ) );
- }
- return Boolean.TRUE;
- }
-
- public Boolean updateRoleUsers( Role role )
- throws RedbackServiceException
- {
-
- for ( org.apache.archiva.redback.rest.api.model.User user : role.getUsers() )
- {
- String username = user.getUsername();
- if ( !userManager.userExists( username ) )
- {
- log.error( "user {} not exits", username );
- throw new RedbackServiceException( new ErrorMessage( "user.not.exists", new String[]{ username } ) );
- }
-
- try
- {
- UserAssignment assignment;
-
- if ( rbacManager.userAssignmentExists( username ) )
- {
- assignment = rbacManager.getUserAssignment( username );
- }
- else
- {
- assignment = rbacManager.createUserAssignment( username );
- }
-
- assignment.addRoleName( role.getName() );
- assignment = rbacManager.saveUserAssignment( assignment );
- log.info( "{} role assigned to {}", role.getName(), username );
- }
- catch ( RbacManagerException e )
- {
- log.error( "error during assign role " + role.getName() + "Â to user " + username, e );
- throw new RedbackServiceException(
- new ErrorMessage( "error.assign.role.user", new String[]{ role.getName(), username } ) );
- }
- }
-
- for ( org.apache.archiva.redback.rest.api.model.User user : role.getRemovedUsers() )
- {
- String username = user.getUsername();
- if ( !userManager.userExists( username ) )
- {
- log.error( "user {} not exits", username );
- throw new RedbackServiceException( new ErrorMessage( "user.not.exists", new String[]{ username } ) );
- }
-
- try
- {
- UserAssignment assignment;
-
- if ( rbacManager.userAssignmentExists( username ) )
- {
- assignment = rbacManager.getUserAssignment( username );
- }
- else
- {
- assignment = rbacManager.createUserAssignment( username );
- }
-
- assignment.removeRoleName( role.getName() );
- assignment = rbacManager.saveUserAssignment( assignment );
- log.info( "{} role unassigned to {}", role.getName(), username );
- }
- catch ( RbacManagerException e )
- {
- log.error( "error during unassign role " + role.getName() + "Â to user " + username, e );
- throw new RedbackServiceException(
- new ErrorMessage( "error.unassign.role.user", new String[]{ role.getName(), username } ) );
- }
- }
-
- return Boolean.TRUE;
- }
-
- public List<ApplicationRoles> getApplicationRoles( String username )
- throws RedbackServiceException
- {
- AdminEditUserCredentials user = null;
- if ( StringUtils.isEmpty( username ) )
- {
- throw new RedbackServiceException( new ErrorMessage( "rbac.edit.user.empty.principal" ) );
- }
-
- if ( !userManager.userExists( username ) )
- {
- throw new RedbackServiceException( new ErrorMessage( "user.does.not.exist", new String[]{ username } ) );
- }
-
- try
- {
- User u = userManager.findUser( username );
-
- if ( u == null )
- {
- throw new RedbackServiceException( new ErrorMessage( "cannot.operate.on.null.user" ) );
- }
-
- user = new AdminEditUserCredentials( u );
- }
- catch ( UserNotFoundException e )
- {
- throw new RedbackServiceException(
- new ErrorMessage( "user.does.not.exist", new String[]{ username, e.getMessage() } ) );
- }
- try
- {
- // check first if role assignments for user exist
- if ( !rbacManager.userAssignmentExists( username ) )
- {
- UserAssignment assignment = rbacManager.createUserAssignment( username );
- rbacManager.saveUserAssignment( assignment );
- }
-
- List<org.apache.archiva.redback.rbac.Role> allRoles =
- filterRolesForCurrentUserAccess( rbacManager.getAllRoles() );
-
- List<ModelApplication> modelApplications = roleManager.getModel().getApplications();
-
- List<ApplicationRoles> applicationRolesList = new ArrayList<ApplicationRoles>( modelApplications.size() );
-
- for ( ModelApplication modelApplication : modelApplications )
- {
- ApplicationRoles applicationRoles = new ApplicationRoles();
-
- applicationRoles.setDescription( modelApplication.getDescription() );
- applicationRoles.setName( modelApplication.getId() );
-
- Collection<org.apache.archiva.redback.rbac.Role> appRoles =
- filterApplicationRoles( modelApplication, allRoles, modelApplication.getTemplates() );
-
- applicationRoles.setGlobalRoles( toRoleNames( appRoles ) );
-
- Set<String> resources = discoverResources( modelApplication.getTemplates(), appRoles );
-
- applicationRoles.setResources( resources );
-
- applicationRoles.setRoleTemplates( toRoleTemplates( modelApplication.getTemplates() ) );
-
- // cleanup app roles remove roles coming from templates
-
- List<String> appRoleNames = new ArrayList<String>( appRoles.size() );
-
- for (String appRoleName : applicationRoles.getGlobalRoles())
- {
- if (!roleFromTemplate( appRoleName, modelApplication.getTemplates() )){
- appRoleNames.add( appRoleName );
- }
- }
-
- applicationRoles.setGlobalRoles( appRoleNames );
-
- applicationRolesList.add( applicationRoles );
- }
-
- return applicationRolesList;
-
- }
- catch ( RbacManagerException e )
- {
- RedbackServiceException redbackServiceException =
- new RedbackServiceException( new ErrorMessage( e.getMessage() ) );
- redbackServiceException.setHttpErrorCode( Response.Status.INTERNAL_SERVER_ERROR.getStatusCode() );
- throw redbackServiceException;
- }
- }
-
- public Boolean updateUserRoles( org.apache.archiva.redback.rest.api.model.User user )
- throws RedbackServiceException
- {
-
- String username = user.getUsername();
-
- if ( StringUtils.isEmpty( username ) )
- {
- throw new RedbackServiceException( new ErrorMessage( "rbac.edit.user.empty.principal" ) );
- }
-
- if ( !userManager.userExists( username ) )
- {
- throw new RedbackServiceException( new ErrorMessage( "user.does.not.exist", new String[]{ username } ) );
- }
-
- try
- {
- User u = userManager.findUser( username );
-
- if ( u == null )
- {
- throw new RedbackServiceException( new ErrorMessage( "cannot.operate.on.null.user" ) );
- }
-
- }
- catch ( UserNotFoundException e )
- {
- throw new RedbackServiceException(
- new ErrorMessage( "user.does.not.exist", new String[]{ username, e.getMessage() } ) );
- }
-
- try
- {
-
- UserAssignment assignment;
-
- if ( rbacManager.userAssignmentExists( username ) )
- {
- assignment = rbacManager.getUserAssignment( username );
- }
- else
- {
- assignment = rbacManager.createUserAssignment( username );
- }
-
- assignment.setRoleNames( user.getAssignedRoles() );
-
- assignment = rbacManager.saveUserAssignment( assignment );
-
- }
- catch ( RbacManagerException e )
- {
- RedbackServiceException redbackServiceException =
- new RedbackServiceException( new ErrorMessage( e.getMessage() ) );
- redbackServiceException.setHttpErrorCode( Response.Status.INTERNAL_SERVER_ERROR.getStatusCode() );
- throw redbackServiceException;
- }
-
- return Boolean.TRUE;
-
- }
-
- //----------------------------------------------------------------
- // Internal methods
- //----------------------------------------------------------------
-
- private org.apache.archiva.redback.rbac.Role isInList( String roleName,
- Collection<org.apache.archiva.redback.rbac.Role> roles )
- {
- for ( org.apache.archiva.redback.rbac.Role role : roles )
- {
- if ( roleName.equals( role.getName() ) )
- {
- return role;
- }
- }
- return null;
- }
-
- private Collection<org.apache.archiva.redback.rbac.Role> filterApplicationRoles( ModelApplication application,
- List<org.apache.archiva.redback.rbac.Role> allRoles,
- List<ModelTemplate> applicationTemplates )
- {
- Set<org.apache.archiva.redback.rbac.Role> applicationRoles =
- new HashSet<org.apache.archiva.redback.rbac.Role>();
- List<ModelRole> roles = application.getRoles();
-
- for ( ModelRole modelRole : roles )
- {
- org.apache.archiva.redback.rbac.Role r = isInList( modelRole.getName(), allRoles );
- if ( r != null )
- {
- applicationRoles.add( r );
- }
- }
-
- List<String> roleNames = toRoleNames( allRoles );
-
- for ( ModelTemplate modelTemplate : applicationTemplates )
- {
- for ( org.apache.archiva.redback.rbac.Role r : allRoles )
- {
- if ( StringUtils.startsWith( r.getName(),
- modelTemplate.getNamePrefix() + modelTemplate.getDelimiter() ) )
- {
- applicationRoles.add( r );
- }
- }
- }
-
- return applicationRoles;
- }
-
- private boolean roleFromTemplate( String roleName, List<ModelTemplate> applicationTemplates )
- {
-
- for ( ModelTemplate modelTemplate : applicationTemplates )
- {
- if ( StringUtils.startsWith( roleName, modelTemplate.getNamePrefix() + modelTemplate.getDelimiter() ) )
- {
- return true;
- }
-
- }
- return false;
- }
-
- private List<String> toRoleNames( Collection<org.apache.archiva.redback.rbac.Role> roles )
- {
- List<String> names = new ArrayList<String>( roles.size() );
-
- for ( org.apache.archiva.redback.rbac.Role r : roles )
- {
- names.add( r.getName() );
- }
-
- return names;
- }
-
- private List<RoleTemplate> toRoleTemplates( List<ModelTemplate> modelTemplates )
- {
- if ( modelTemplates == null || modelTemplates.isEmpty() )
- {
- return new ArrayList<RoleTemplate>( 0 );
- }
-
- List<RoleTemplate> roleTemplates = new ArrayList<RoleTemplate>( modelTemplates.size() );
-
- for ( ModelTemplate modelTemplate : modelTemplates )
- {
- RoleTemplate roleTemplate = new RoleTemplate();
-
- roleTemplate.setDelimiter( modelTemplate.getDelimiter() );
- roleTemplate.setDescription( modelTemplate.getDescription() );
- roleTemplate.setId( modelTemplate.getId() );
- roleTemplate.setNamePrefix( modelTemplate.getNamePrefix() );
-
- roleTemplates.add( roleTemplate );
- }
-
- return roleTemplates;
- }
-
- private Set<String> discoverResources( List<ModelTemplate> applicationTemplates,
- Collection<org.apache.archiva.redback.rbac.Role> roles )
- {
- Set<String> resources = new HashSet<String>();
- for ( ModelTemplate modelTemplate : applicationTemplates )
- {
- for ( org.apache.archiva.redback.rbac.Role role : roles )
- {
- String roleName = role.getName();
- if ( roleName.startsWith( modelTemplate.getNamePrefix() ) )
- {
- String delimiter = modelTemplate.getDelimiter();
- resources.add( roleName.substring( roleName.indexOf( delimiter ) + delimiter.length() ) );
- }
- }
- }
- return resources;
- }
-
- /**
- * this is a hack. this is a hack around the requirements of putting RBAC constraints into the model. this adds one
- * very major restriction to this security system, that a role name must contain the identifiers of the resource
- * that is being constrained for adding and granting of roles, this is unacceptable in the long term and we need to
- * get the model refactored to include this RBAC concept
- *
- * @param roleList
- * @return
- * @throws org.apache.archiva.redback.rbac.RbacManagerException
- *
- */
- protected List<org.apache.archiva.redback.rbac.Role> filterRolesForCurrentUserAccess(
- List<org.apache.archiva.redback.rbac.Role> roleList )
- throws RedbackServiceException
- {
- RedbackRequestInformation redbackRequestInformation = RedbackAuthenticationThreadLocal.get();
- // olamy: should not happened normally as annotations check this first
- if ( redbackRequestInformation == null || redbackRequestInformation.getUser() == null )
- {
- throw new RedbackServiceException( new ErrorMessage( "login.mandatory" ) );
- }
- String currentUser = redbackRequestInformation.getUser().getUsername();
-
- List<org.apache.archiva.redback.rbac.Role> filteredRoleList =
- new ArrayList<org.apache.archiva.redback.rbac.Role>();
- try
- {
- Map<String, List<Permission>> assignedPermissionMap = rbacManager.getAssignedPermissionMap( currentUser );
- List<String> resourceGrants = new ArrayList<String>();
-
- if ( assignedPermissionMap.containsKey( RedbackRoleConstants.USER_MANAGEMENT_ROLE_GRANT_OPERATION ) )
- {
- List<Permission> roleGrantPermissions =
- assignedPermissionMap.get( RedbackRoleConstants.USER_MANAGEMENT_ROLE_GRANT_OPERATION );
-
- for ( Permission permission : roleGrantPermissions )
- {
- if ( permission.getResource().getIdentifier().equals( Resource.GLOBAL ) )
- {
- // the current user has the rights to assign any given role
- return roleList;
- }
- else
- {
- resourceGrants.add( permission.getResource().getIdentifier() );
- }
- }
-
- }
- else
- {
- return Collections.emptyList();
- }
-
- String delimiter = " - ";
-
- // we should have a list of resourceGrants now, this will provide us with the information necessary to restrict
- // the role list
- for ( org.apache.archiva.redback.rbac.Role role : roleList )
- {
- int delimiterIndex = role.getName().indexOf( delimiter );
- for ( String resourceIdentifier : resourceGrants )
- {
-
- if ( ( role.getName().indexOf( resourceIdentifier ) != -1 ) && ( delimiterIndex != -1 ) )
- {
- String resourceName = role.getName().substring( delimiterIndex + delimiter.length() );
- if ( resourceName.equals( resourceIdentifier ) )
- {
- filteredRoleList.add( role );
- }
- }
- }
- }
- }
- catch ( RbacManagerException rme )
- {
- // ignore, this can happen when the user has no roles assigned
- }
- Collections.sort( filteredRoleList, new RoleSorter() );
- return filteredRoleList;
- }
-
-
-}
+++ /dev/null
-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 net.sf.ehcache.CacheManager;
-import org.apache.archiva.redback.configuration.UserConfiguration;
-import org.apache.archiva.redback.keys.AuthenticationKey;
-import org.apache.archiva.redback.policy.AccountLockedException;
-import org.apache.archiva.redback.policy.MustChangePasswordException;
-import org.apache.archiva.redback.rbac.RbacManagerException;
-import org.apache.archiva.redback.rbac.UserAssignment;
-import org.apache.archiva.redback.role.RoleManager;
-import org.apache.archiva.redback.role.RoleManagerException;
-import org.apache.archiva.redback.users.UserManager;
-import org.apache.archiva.redback.users.UserNotFoundException;
-import org.apache.commons.lang.StringUtils;
-import org.codehaus.plexus.cache.Cache;
-import org.apache.archiva.redback.authentication.AuthenticationException;
-import org.apache.archiva.redback.authentication.TokenBasedAuthenticationDataSource;
-import org.apache.archiva.redback.keys.KeyManager;
-import org.apache.archiva.redback.keys.KeyManagerException;
-import org.apache.archiva.redback.keys.KeyNotFoundException;
-import org.apache.archiva.redback.policy.PasswordEncoder;
-import org.apache.archiva.redback.policy.UserSecurityPolicy;
-import org.apache.archiva.redback.rbac.RBACManager;
-import org.apache.archiva.redback.rbac.RbacObjectNotFoundException;
-import org.apache.archiva.redback.system.SecuritySystem;
-import org.apache.archiva.redback.integration.filter.authentication.HttpAuthenticator;
-import org.apache.archiva.redback.integration.mail.Mailer;
-import org.apache.archiva.redback.integration.security.role.RedbackRoleConstants;
-import org.apache.archiva.redback.rest.api.model.ErrorMessage;
-import org.apache.archiva.redback.rest.api.model.Operation;
-import org.apache.archiva.redback.rest.api.model.Permission;
-import org.apache.archiva.redback.rest.api.model.RegistrationKey;
-import org.apache.archiva.redback.rest.api.model.Resource;
-import org.apache.archiva.redback.rest.api.model.User;
-import org.apache.archiva.redback.rest.api.services.RedbackServiceException;
-import org.apache.archiva.redback.rest.api.services.UserService;
-import org.codehaus.redback.rest.services.utils.PasswordValidator;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.stereotype.Service;
-
-import javax.inject.Inject;
-import javax.inject.Named;
-import javax.mail.internet.AddressException;
-import javax.mail.internet.InternetAddress;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.Response;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.List;
-import java.util.Set;
-
-@Service( "userService#rest" )
-public class DefaultUserService
- implements UserService
-{
-
- private Logger log = LoggerFactory.getLogger( getClass() );
-
- private static final String VALID_USERNAME_CHARS = "[a-zA-Z_0-9\\-.@]*";
-
- private UserManager userManager;
-
- private SecuritySystem securitySystem;
-
- @Inject
- private UserConfiguration config;
-
- @Inject
- private RoleManager roleManager;
-
- /**
- * cache used for user assignments
- */
- @Inject
- @Named( value = "cache#userAssignments" )
- private Cache userAssignmentsCache;
-
- /**
- * cache used for user permissions
- */
- @Inject
- @Named( value = "cache#userPermissions" )
- private Cache userPermissionsCache;
-
- /**
- * Cache used for users
- */
- @Inject
- @Named( value = "cache#users" )
- private Cache usersCache;
-
- @Inject
- private Mailer mailer;
-
- @Inject
- @Named( value = "rBACManager#cached" )
- private RBACManager rbacManager;
-
- private HttpAuthenticator httpAuthenticator;
-
- @Inject
- private PasswordValidator passwordValidator;
-
- @Context
- private HttpServletRequest httpServletRequest;
-
- @Inject
- public DefaultUserService( @Named( value = "userManager#cached" ) UserManager userManager,
- SecuritySystem securitySystem,
- @Named( "httpAuthenticator#basic" ) HttpAuthenticator httpAuthenticator )
- {
- this.userManager = userManager;
- this.securitySystem = securitySystem;
- this.httpAuthenticator = httpAuthenticator;
- }
-
-
- public Boolean createUser( User user )
- throws RedbackServiceException
- {
-
- try
- {
- org.apache.archiva.redback.users.User u = userManager.findUser( user.getUsername() );
- if ( u != null )
- {
- throw new RedbackServiceException(
- new ErrorMessage( "user " + user.getUsername() + " already exists" ) );
- }
- }
- catch ( UserNotFoundException e )
- {
- //ignore we just want to prevent non human readable error message from backend :-)
- log.debug( "user {} not exists", user.getUsername() );
- }
-
- // data validation
- if ( StringUtils.isEmpty( user.getUsername() ) )
- {
- throw new RedbackServiceException( new ErrorMessage( "username cannot be empty" ) );
- }
-
- if ( StringUtils.isEmpty( user.getFullName() ) )
- {
- throw new RedbackServiceException( new ErrorMessage( "fullName cannot be empty" ) );
- }
-
- if ( StringUtils.isEmpty( user.getEmail() ) )
- {
- throw new RedbackServiceException( new ErrorMessage( "email cannot be empty" ) );
- }
-
- org.apache.archiva.redback.users.User u =
- userManager.createUser( user.getUsername(), user.getFullName(), user.getEmail() );
- u.setPassword( user.getPassword() );
- u.setLocked( user.isLocked() );
- u.setPasswordChangeRequired( user.isPasswordChangeRequired() );
- u.setPermanent( user.isPermanent() );
- u.setValidated( user.isValidated() );
- u = userManager.addUser( u );
- if ( !user.isPasswordChangeRequired() )
- {
- u.setPasswordChangeRequired( false );
- try
- {
- u = userManager.updateUser( u );
- log.debug( "user {} created", u.getUsername() );
- }
- catch ( UserNotFoundException e )
- {
- throw new RedbackServiceException( e.getMessage() );
- }
- }
- try
- {
- roleManager.assignRole( RedbackRoleConstants.REGISTERED_USER_ROLE_ID, u.getPrincipal().toString() );
- }
- catch ( RoleManagerException rpe )
- {
- log.error( "RoleProfile Error: " + rpe.getMessage(), rpe );
- throw new RedbackServiceException( new ErrorMessage( "assign.role.failure", null ) );
- }
- return Boolean.TRUE;
- }
-
- public Boolean deleteUser( String username )
- throws RedbackServiceException
- {
-
- try
- {
-
- if ( rbacManager.userAssignmentExists( username ) )
- {
- UserAssignment assignment = rbacManager.getUserAssignment( username );
- rbacManager.removeUserAssignment( assignment );
- }
-
- }
- catch ( RbacManagerException e )
- {
- log.error( e.getMessage(), e );
- throw new RedbackServiceException( e.getMessage() );
- }
- try
- {
- userManager.deleteUser( username );
- return Boolean.TRUE;
- }
- catch ( UserNotFoundException e )
- {
- log.error( e.getMessage(), e );
- throw new RedbackServiceException( e.getMessage() );
- }
- finally
- {
- removeFromCache( username );
- }
- }
-
-
- public User getUser( String username )
- throws RedbackServiceException
- {
- try
- {
- org.apache.archiva.redback.users.User user = userManager.findUser( username );
- return getSimpleUser( user );
- }
- catch ( UserNotFoundException e )
- {
- return null;
- }
- }
-
- public List<User> getUsers()
- throws RedbackServiceException
- {
- List<org.apache.archiva.redback.users.User> users = userManager.getUsers();
- List<User> simpleUsers = new ArrayList<User>( users.size() );
-
- for ( org.apache.archiva.redback.users.User user : users )
- {
- simpleUsers.add( getSimpleUser( user ) );
- }
-
- return simpleUsers;
- }
-
- public Boolean updateMe( User user )
- throws RedbackServiceException
- {
- // check username == one in the session
- RedbackRequestInformation redbackRequestInformation = RedbackAuthenticationThreadLocal.get();
- if ( redbackRequestInformation == null || redbackRequestInformation.getUser() == null )
- {
- throw new RedbackServiceException( new ErrorMessage( "you must be logged to update your profile" ),
- Response.Status.FORBIDDEN.getStatusCode() );
- }
- if ( user == null )
- {
- throw new RedbackServiceException( new ErrorMessage( "user parameter is mandatory" ),
- Response.Status.BAD_REQUEST.getStatusCode() );
- }
- if ( !StringUtils.equals( redbackRequestInformation.getUser().getUsername(), user.getUsername() ) )
- {
- throw new RedbackServiceException( new ErrorMessage( "you can update only your profile" ),
- Response.Status.FORBIDDEN.getStatusCode() );
- }
-
- if ( StringUtils.isEmpty( user.getPreviousPassword() ) )
- {
- throw new RedbackServiceException( new ErrorMessage( "previous password is empty" ),
- Response.Status.BAD_REQUEST.getStatusCode() );
- }
-
- User realUser = getUser( user.getUsername() );
- try
- {
- String previousEncodedPassword =
- securitySystem.getUserManager().findUser( user.getUsername() ).getEncodedPassword();
-
- // check oldPassword with the current one
-
- PasswordEncoder encoder = securitySystem.getPolicy().getPasswordEncoder();
-
- if ( !encoder.isPasswordValid( previousEncodedPassword, user.getPreviousPassword() ) )
- {
-
- throw new RedbackServiceException( new ErrorMessage( "password.provided.does.not.match.existing" ),
- Response.Status.BAD_REQUEST.getStatusCode() );
- }
- }
- catch ( UserNotFoundException e )
- {
- throw new RedbackServiceException( new ErrorMessage( "user not found" ),
- Response.Status.BAD_REQUEST.getStatusCode() );
- }
- // only 3 fields to update
- realUser.setFullName( user.getFullName() );
- realUser.setEmail( user.getEmail() );
- // ui can limit to not update password
- if ( StringUtils.isNotBlank( user.getPassword() ) )
- {
- passwordValidator.validatePassword( user.getPassword(), user.getUsername() );
-
- realUser.setPassword( user.getPassword() );
- }
-
- updateUser( realUser );
-
- return Boolean.TRUE;
- }
-
- public Boolean updateUser( User user )
- throws RedbackServiceException
- {
- try
- {
- org.apache.archiva.redback.users.User rawUser = userManager.findUser( user.getUsername() );
- rawUser.setFullName( user.getFullName() );
- rawUser.setEmail( user.getEmail() );
- rawUser.setValidated( user.isValidated() );
- rawUser.setLocked( user.isLocked() );
- rawUser.setPassword( user.getPassword() );
- rawUser.setPasswordChangeRequired( user.isPasswordChangeRequired() );
- rawUser.setPermanent( user.isPermanent() );
-
- userManager.updateUser( rawUser );
- return Boolean.TRUE;
- }
- catch ( UserNotFoundException e )
- {
- throw new RedbackServiceException( e.getMessage() );
- }
- }
-
- public int removeFromCache( String userName )
- throws RedbackServiceException
- {
- if ( userAssignmentsCache != null )
- {
- userAssignmentsCache.remove( userName );
- }
- if ( userPermissionsCache != null )
- {
- userPermissionsCache.remove( userName );
- }
- if ( usersCache != null )
- {
- usersCache.remove( userName );
- }
-
- CacheManager cacheManager = CacheManager.getInstance();
- String[] caches = cacheManager.getCacheNames();
- for ( String cacheName : caches )
- {
- if ( StringUtils.startsWith( cacheName, "org.codehaus.plexus.redback.rbac.jdo" ) )
- {
- cacheManager.getCache( cacheName ).removeAll();
- }
- }
-
- return 0;
- }
-
- public User getGuestUser()
- throws RedbackServiceException
- {
- try
- {
- org.apache.archiva.redback.users.User user = userManager.getGuestUser();
- return getSimpleUser( user );
- }
- catch ( Exception e )
- {
- return null;
- }
- }
-
- public User createGuestUser()
- throws RedbackServiceException
- {
- User u = getGuestUser();
- if ( u != null )
- {
- return u;
- }
- // temporary disable policy during guest creation as no password !
- try
- {
- securitySystem.getPolicy().setEnabled( false );
- org.apache.archiva.redback.users.User user = userManager.createGuestUser();
- user.setPasswordChangeRequired( false );
- user = userManager.updateUser( user, false );
- roleManager.assignRole( "guest", user.getPrincipal().toString() );
- return getSimpleUser( user );
- }
- catch ( RoleManagerException e )
- {
- log.error( e.getMessage(), e );
- throw new RedbackServiceException( e.getMessage() );
- }
- catch ( UserNotFoundException e )
- {
- // olamy I wonder how this can happen :-)
- log.error( e.getMessage(), e );
- throw new RedbackServiceException( e.getMessage() );
- }
- finally
- {
-
- if ( !securitySystem.getPolicy().isEnabled() )
- {
- securitySystem.getPolicy().setEnabled( true );
- }
- }
- }
-
- public Boolean ping()
- throws RedbackServiceException
- {
- return Boolean.TRUE;
- }
-
- private User getSimpleUser( org.apache.archiva.redback.users.User user )
- {
- if ( user == null )
- {
- return null;
- }
- return new User( user );
- }
-
- public Boolean createAdminUser( User adminUser )
- throws RedbackServiceException
- {
- if ( isAdminUserExists() )
- {
- return Boolean.FALSE;
- }
-
- org.apache.archiva.redback.users.User user =
- userManager.createUser( RedbackRoleConstants.ADMINISTRATOR_ACCOUNT_NAME, adminUser.getFullName(),
- adminUser.getEmail() );
- user.setPassword( adminUser.getPassword() );
-
- user.setLocked( false );
- user.setPasswordChangeRequired( false );
- user.setPermanent( true );
- user.setValidated( true );
-
- userManager.addUser( user );
-
- try
- {
- roleManager.assignRole( "system-administrator", user.getPrincipal().toString() );
- }
- catch ( RoleManagerException e )
- {
- throw new RedbackServiceException( e.getMessage() );
- }
- return Boolean.TRUE;
- }
-
- public Boolean isAdminUserExists()
- throws RedbackServiceException
- {
- try
- {
- userManager.findUser( config.getString( "redback.default.admin" ) );
- return Boolean.TRUE;
- }
- catch ( UserNotFoundException e )
- {
- // ignore
- }
- return Boolean.FALSE;
- }
-
- public Boolean resetPassword( String username )
- throws RedbackServiceException
- {
- if ( StringUtils.isEmpty( username ) )
- {
- throw new RedbackServiceException( new ErrorMessage( "username.cannot.be.empty" ) );
- }
-
- UserManager userManager = securitySystem.getUserManager();
- KeyManager keyManager = securitySystem.getKeyManager();
- UserSecurityPolicy policy = securitySystem.getPolicy();
-
- try
- {
- org.apache.archiva.redback.users.User user = userManager.findUser( username );
-
- AuthenticationKey authkey = keyManager.createKey( username, "Password Reset Request",
- policy.getUserValidationSettings().getEmailValidationTimeout() );
-
- mailer.sendPasswordResetEmail( Arrays.asList( user.getEmail() ), authkey, getBaseUrl() );
-
- log.info( "password reset request for username {}", username );
- }
- catch ( UserNotFoundException e )
- {
- log.info( "Password Reset on non-existant user [{}].", username );
- throw new RedbackServiceException( new ErrorMessage( "password.reset.failure" ) );
- }
- catch ( KeyManagerException e )
- {
- log.info( "Unable to issue password reset.", e );
- throw new RedbackServiceException( new ErrorMessage( "password.reset.email.generation.failure" ) );
- }
-
- return Boolean.TRUE;
- }
-
- public RegistrationKey registerUser( User user )
- throws RedbackServiceException
- {
- if ( user == null )
- {
- throw new RedbackServiceException( new ErrorMessage( "invalid.user.credentials", null ) );
-
- }
-
- UserSecurityPolicy securityPolicy = securitySystem.getPolicy();
-
- boolean emailValidationRequired = securityPolicy.getUserValidationSettings().isEmailValidationRequired();
-
- if ( emailValidationRequired )
- {
- validateCredentialsLoose( user );
- }
- else
- {
- validateCredentialsStrict( user );
- }
-
- // NOTE: Do not perform Password Rules Validation Here.
-
- if ( userManager.userExists( user.getUsername() ) )
- {
- throw new RedbackServiceException(
- new ErrorMessage( "user.already.exists", new String[]{ user.getUsername() } ) );
- }
-
- org.apache.archiva.redback.users.User u =
- userManager.createUser( user.getUsername(), user.getFullName(), user.getEmail() );
- u.setPassword( user.getPassword() );
- u.setValidated( false );
- u.setLocked( false );
-
- try
- {
- roleManager.assignRole( RedbackRoleConstants.REGISTERED_USER_ROLE_ID, u.getPrincipal().toString() );
- }
- catch ( RoleManagerException rpe )
- {
- log.error( "RoleProfile Error: " + rpe.getMessage(), rpe );
- throw new RedbackServiceException( new ErrorMessage( "assign.role.failure", null ) );
- }
-
- if ( emailValidationRequired )
- {
- u.setLocked( true );
-
- try
- {
- AuthenticationKey authkey =
- securitySystem.getKeyManager().createKey( u.getPrincipal().toString(), "New User Email Validation",
- securityPolicy.getUserValidationSettings().getEmailValidationTimeout() );
-
- mailer.sendAccountValidationEmail( Arrays.asList( u.getEmail() ), authkey, getBaseUrl() );
-
- securityPolicy.setEnabled( false );
- userManager.addUser( u );
- return new RegistrationKey( authkey.getKey() );
-
- }
- catch ( KeyManagerException e )
- {
- log.error( "Unable to register a new user.", e );
- throw new RedbackServiceException( new ErrorMessage( "cannot.register.user", null ) );
- }
- finally
- {
- securityPolicy.setEnabled( true );
- }
- }
- else
- {
- userManager.addUser( u );
- return new RegistrationKey( "-1" );
- }
-
- // FIXME log this event
- /*
- AuditEvent event = new AuditEvent( getText( "log.account.create" ) );
- event.setAffectedUser( username );
- event.log();
- */
-
- }
-
- public Boolean validateUserFromKey( String key )
- throws RedbackServiceException
- {
- String principal = null;
- try
- {
- AuthenticationKey authkey = securitySystem.getKeyManager().findKey( key );
-
- org.apache.archiva.redback.users.User user =
- securitySystem.getUserManager().findUser( authkey.getForPrincipal() );
-
- user.setValidated( true );
- user.setLocked( false );
- user.setPasswordChangeRequired( true );
- user.setEncodedPassword( "" );
-
- principal = user.getPrincipal().toString();
-
- TokenBasedAuthenticationDataSource authsource = new TokenBasedAuthenticationDataSource();
- authsource.setPrincipal( principal );
- authsource.setToken( authkey.getKey() );
- authsource.setEnforcePasswordChange( false );
-
- securitySystem.getUserManager().updateUser( user );
-
- httpAuthenticator.authenticate( authsource, httpServletRequest.getSession( true ) );
-
- log.info( "account validated for user {}", user.getUsername() );
-
- return Boolean.TRUE;
- }
- catch ( MustChangePasswordException e )
- {
- throw new RedbackServiceException( e.getMessage(), Response.Status.FORBIDDEN.getStatusCode() );
- }
- catch ( KeyNotFoundException e )
- {
- log.info( "Invalid key requested: {}", key );
- throw new RedbackServiceException( new ErrorMessage( "cannot.find.key" ) );
- }
- catch ( KeyManagerException e )
- {
- throw new RedbackServiceException( new ErrorMessage( "cannot.find.key.at.the.momment" ) );
-
- }
- catch ( UserNotFoundException e )
- {
- throw new RedbackServiceException( new ErrorMessage( "cannot.find.user", new String[]{ principal } ) );
-
- }
- catch ( AccountLockedException e )
- {
- throw new RedbackServiceException( e.getMessage(), Response.Status.FORBIDDEN.getStatusCode() );
- }
- catch ( AuthenticationException e )
- {
- throw new RedbackServiceException( e.getMessage(), Response.Status.FORBIDDEN.getStatusCode() );
- }
- }
-
- public Collection<Permission> getCurrentUserPermissions()
- throws RedbackServiceException
- {
- RedbackRequestInformation redbackRequestInformation = RedbackAuthenticationThreadLocal.get();
- String userName = UserManager.GUEST_USERNAME;
- if ( redbackRequestInformation != null && redbackRequestInformation.getUser() != null )
- {
- userName = redbackRequestInformation.getUser().getUsername();
- }
-
- return getUserPermissions( userName );
- }
-
- public Collection<Operation> getCurrentUserOperations()
- throws RedbackServiceException
- {
- RedbackRequestInformation redbackRequestInformation = RedbackAuthenticationThreadLocal.get();
- String userName = UserManager.GUEST_USERNAME;
- if ( redbackRequestInformation != null && redbackRequestInformation.getUser() != null )
- {
- userName = redbackRequestInformation.getUser().getUsername();
- }
-
- return getUserOperations( userName );
- }
-
- public Collection<Operation> getUserOperations( String userName )
- throws RedbackServiceException
- {
- Collection<Permission> permissions = getUserPermissions( userName );
- List<Operation> operations = new ArrayList<Operation>( permissions.size() );
- for ( Permission permission : permissions )
- {
- if ( permission.getOperation() != null )
- {
- Operation operation = new Operation();
- operation.setName( permission.getOperation().getName() );
- operations.add( operation );
- }
- }
- return operations;
- }
-
- public Collection<Permission> getUserPermissions( String userName )
- throws RedbackServiceException
- {
- try
- {
- Set<org.apache.archiva.redback.rbac.Permission> permissions =
- rbacManager.getAssignedPermissions( userName );
- // FIXME return guest permissions !!
- List<Permission> userPermissions = new ArrayList<Permission>( permissions.size() );
- for ( org.apache.archiva.redback.rbac.Permission p : permissions )
- {
- Permission permission = new Permission();
- permission.setName( p.getName() );
-
- if ( p.getOperation() != null )
- {
- Operation operation = new Operation();
- operation.setName( p.getOperation().getName() );
- permission.setOperation( operation );
- }
-
- if ( p.getResource() != null )
- {
- Resource resource = new Resource();
- resource.setIdentifier( p.getResource().getIdentifier() );
- resource.setPattern( p.getResource().isPattern() );
- permission.setResource( resource );
- }
-
- userPermissions.add( permission );
- }
- return userPermissions;
- }
- catch ( RbacObjectNotFoundException e )
- {
- log.error( e.getMessage(), e );
- throw new RedbackServiceException( e.getMessage() );
- }
- catch ( RbacManagerException e )
- {
- log.error( e.getMessage(), e );
- throw new RedbackServiceException( e.getMessage() );
- }
- }
-
- public void validateCredentialsLoose( User user )
- throws RedbackServiceException
- {
- RedbackServiceException redbackServiceException =
- new RedbackServiceException( "issues during validating user" );
- if ( org.codehaus.plexus.util.StringUtils.isEmpty( user.getUsername() ) )
- {
- redbackServiceException.addErrorMessage( new ErrorMessage( "username.required", null ) );
- }
- else
- {
- if ( !user.getUsername().matches( VALID_USERNAME_CHARS ) )
- {
- redbackServiceException.addErrorMessage( new ErrorMessage( "username.invalid.characters", null ) );
- }
- }
-
- if ( org.codehaus.plexus.util.StringUtils.isEmpty( user.getFullName() ) )
- {
- redbackServiceException.addErrorMessage( new ErrorMessage( "fullName.required", null ) );
- }
-
- if ( org.codehaus.plexus.util.StringUtils.isEmpty( user.getEmail() ) )
- {
- redbackServiceException.addErrorMessage( new ErrorMessage( "email.required", null ) );
- }
-
- if ( !org.codehaus.plexus.util.StringUtils.equals( user.getPassword(), user.getConfirmPassword() ) )
- {
- redbackServiceException.addErrorMessage( new ErrorMessage( "passwords.does.not.match", null ) );
- }
-
- try
- {
- if ( !org.codehaus.plexus.util.StringUtils.isEmpty( user.getEmail() ) )
- {
- new InternetAddress( user.getEmail(), true );
- }
- }
- catch ( AddressException e )
- {
- redbackServiceException.addErrorMessage( new ErrorMessage( "email.invalid", null ) );
- }
- if ( !redbackServiceException.getErrorMessages().isEmpty() )
- {
- throw redbackServiceException;
- }
- }
-
- public void validateCredentialsStrict( User user )
- throws RedbackServiceException
- {
- validateCredentialsLoose( user );
-
- org.apache.archiva.redback.users.User tmpuser =
- userManager.createUser( user.getUsername(), user.getFullName(), user.getEmail() );
-
- user.setPassword( user.getPassword() );
-
- securitySystem.getPolicy().validatePassword( tmpuser );
-
- if ( ( org.codehaus.plexus.util.StringUtils.isEmpty( user.getPassword() ) ) )
- {
- throw new RedbackServiceException( new ErrorMessage( "password.required", null ) );
- }
- }
-
- private String getBaseUrl()
- {
- if ( httpServletRequest != null )
- {
- if ( httpServletRequest != null )
- {
- return httpServletRequest.getScheme() + "://" + httpServletRequest.getServerName() + (
- httpServletRequest.getServerPort() == 80
- ? ""
- : ":" + httpServletRequest.getServerPort() ) + httpServletRequest.getContextPath();
- }
- }
- return null;
- }
-
- public Boolean unlockUser( String username )
- throws RedbackServiceException
- {
- User user = getUser( username );
- if ( user == null )
- {
- user.setLocked( false );
- updateUser( user );
- return Boolean.TRUE;
- }
- return Boolean.FALSE;
- }
-
- public Boolean lockUser( String username )
- throws RedbackServiceException
- {
- User user = getUser( username );
- if ( user == null )
- {
- user.setLocked( true );
- updateUser( user );
- return Boolean.TRUE;
- }
- return Boolean.FALSE;
- }
-
- public Boolean passwordChangeRequired( String username )
- throws RedbackServiceException
- {
- User user = getUser( username );
- if ( user == null )
- {
- user.setPasswordChangeRequired( true );
- updateUser( user );
- return Boolean.TRUE;
- }
- return Boolean.FALSE;
- }
-
- public Boolean passwordChangeNotRequired( String username )
- throws RedbackServiceException
- {
- User user = getUser( username );
- if ( user == null )
- {
- user.setPasswordChangeRequired( false );
- updateUser( user );
- return Boolean.TRUE;
- }
- return Boolean.FALSE;
- }
-}
+++ /dev/null
-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.io.IOUtils;
-import org.apache.commons.lang.StringUtils;
-import org.apache.archiva.redback.rest.api.services.RedbackServiceException;
-import org.apache.archiva.redback.rest.api.services.UtilServices;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.stereotype.Service;
-
-import javax.annotation.PostConstruct;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.Map;
-import java.util.Properties;
-import java.util.concurrent.ConcurrentHashMap;
-
-/**
- * @author Olivier Lamy
- * @since 1.4
- */
-@Service( "utilServices#rest" )
-public class DefaultUtilServices
- implements UtilServices
-{
-
- private Logger log = LoggerFactory.getLogger( getClass() );
-
- private Map<String, String> cachei18n = new ConcurrentHashMap<String, String>();
-
- @PostConstruct
- public void init()
- throws RedbackServiceException
- {
-
- // preload i18n en and fr
- getI18nProperties( "en" );
- getI18nProperties( "fr" );
- }
-
- public String getI18nResources( String locale )
- throws RedbackServiceException
- {
- String cachedi18n = cachei18n.get( StringUtils.isEmpty( locale ) ? "en" : StringUtils.lowerCase( locale ) );
- if ( cachedi18n != null )
- {
- return cachedi18n;
- }
-
- Properties properties = new Properties();
-
- // load redback user api messages
- try
- {
-
- // load default first then requested locale
- loadResource( properties, "org/codehaus/plexus/redback/users/messages", null );
- loadResource( properties, "org/codehaus/plexus/redback/users/messages", locale );
-
- }
- catch ( IOException e )
- {
- log.warn( "skip error loading properties {}", "org/codehaus/plexus/redback/users/messages" );
- }
-
- try
- {
-
- // load default first then requested locale
- loadResource( properties, "org/codehaus/redback/i18n/default", null );
- loadResource( properties, "org/codehaus/redback/i18n/default", locale );
-
- }
- catch ( IOException e )
- {
- log.warn( "skip error loading properties {}", "org/codehaus/redback/i18n/default" );
- }
-
- StringBuilder output = new StringBuilder();
-
- for ( Map.Entry<Object, Object> entry : properties.entrySet() )
- {
- output.append( (String) entry.getKey() ).append( '=' ).append( (String) entry.getValue() );
- output.append( '\n' );
- }
-
- cachei18n.put( StringUtils.isEmpty( locale ) ? "en" : StringUtils.lowerCase( locale ), output.toString() );
-
- return output.toString();
- }
-
- public Properties getI18nProperties( String locale )
- throws RedbackServiceException
- {
- try
- {
- Properties properties = new Properties();
- // load default first then requested locale
- loadResource( properties, "org/codehaus/plexus/redback/users/messages", null );
- loadResource( properties, "org/codehaus/plexus/redback/users/messages", locale );
-
- loadResource( properties, "org/codehaus/redback/i18n/default", null );
- loadResource( properties, "org/codehaus/redback/i18n/default", locale );
- return properties;
- }
- catch ( IOException e )
- {
- throw new RedbackServiceException( e.getMessage() );
- }
- }
-
- private void loadResource( final Properties finalProperties, String resourceName, String locale )
- throws IOException
- {
- InputStream is = null;
- Properties properties = new Properties();
- try
- {
- if ( StringUtils.isNotEmpty( locale ) )
- {
- resourceName = resourceName + "_" + locale;
- }
- resourceName = resourceName + ".properties";
- is = Thread.currentThread().getContextClassLoader().getResourceAsStream( resourceName.toString() );
- if ( is != null )
- {
- properties.load( is );
- finalProperties.putAll( properties );
- }
- else
- {
- if ( !StringUtils.equalsIgnoreCase( locale, "en" ) )
- {
- log.info( "cannot load resource {}", resourceName );
- }
- }
- }
- finally
- {
- IOUtils.closeQuietly( is );
- }
-
- }
-
-
-}
+++ /dev/null
-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.
- */
-
-/**
- * @author Olivier Lamy
- * @since 1.4
- */
-public class RedbackAuthenticationThreadLocal
-{
- private static final ThreadLocal<RedbackRequestInformation> userThreadLocal =
- new ThreadLocal<RedbackRequestInformation>();
-
- public static void set( RedbackRequestInformation redbackRequestInformation )
- {
- userThreadLocal.set( redbackRequestInformation );
- }
-
- public static RedbackRequestInformation get()
- {
- return userThreadLocal.get();
- }
-}
+++ /dev/null
-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.archiva.redback.users.User;
-
-/**
- * @author Olivier Lamy
- * @since 1.4
- */
-public class RedbackRequestInformation
-{
- private User user;
-
- private String remoteAddr;
-
- public RedbackRequestInformation( User user, String remoteAddr )
- {
- this.user = user;
- this.remoteAddr = remoteAddr;
- }
-
- public User getUser()
- {
- return user;
- }
-
- public void setUser( User user )
- {
- this.user = user;
- }
-
- public String getRemoteAddr()
- {
- return remoteAddr;
- }
-
- public void setRemoteAddr( String remoteAddr )
- {
- this.remoteAddr = remoteAddr;
- }
-}
+++ /dev/null
-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.jaxrs.model.OperationResourceInfo;
-import org.apache.cxf.message.Message;
-import org.apache.archiva.redback.authorization.RedbackAuthorization;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import javax.ws.rs.core.Context;
-import java.lang.reflect.Method;
-
-/**
- * @author Olivier Lamy
- * @since 1.3
- */
-public class AbstractInterceptor
-{
-
- private Logger log = LoggerFactory.getLogger( getClass() );
-
- @Context
- private HttpServletRequest httpServletRequest;
-
- @Context
- private HttpServletResponse httpServletResponse;
-
- public HttpServletRequest getHttpServletRequest( Message message )
- {
- return httpServletRequest;
- }
-
- public HttpServletResponse getHttpServletResponse( Message message )
- {
- return httpServletResponse;
- }
-
- public RedbackAuthorization getRedbackAuthorization( Message message )
- {
- OperationResourceInfo operationResourceInfo = message.getExchange().get( OperationResourceInfo.class );
- if ( operationResourceInfo == null )
- {
- return null;
- }
-
- Method method = operationResourceInfo.getAnnotatedMethod();
-
- log.debug( " method name {}", method == null ? "null" : method.getName() );
- RedbackAuthorization redbackAuthorization = method.getAnnotation( RedbackAuthorization.class );
- return redbackAuthorization;
- }
-}
+++ /dev/null
-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.archiva.redback.policy.MustChangePasswordException;
-import org.apache.archiva.redback.users.User;
-import org.apache.archiva.redback.users.UserManager;
-import org.apache.cxf.jaxrs.ext.RequestHandler;
-import org.apache.cxf.jaxrs.model.ClassResourceInfo;
-import org.apache.cxf.message.Message;
-import org.apache.archiva.redback.authentication.AuthenticationException;
-import org.apache.archiva.redback.authentication.AuthenticationResult;
-import org.apache.archiva.redback.authorization.RedbackAuthorization;
-import org.apache.archiva.redback.policy.AccountLockedException;
-import org.apache.archiva.redback.system.SecuritySession;
-import org.apache.archiva.redback.users.UserNotFoundException;
-import org.apache.archiva.redback.integration.filter.authentication.HttpAuthenticationException;
-import org.apache.archiva.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();
- }
- }
-}
+++ /dev/null
-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.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 );
- }
-}
+++ /dev/null
-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 );
- }
-}
+++ /dev/null
-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.archiva.redback.policy.PasswordRuleViolationException;
-import org.apache.archiva.redback.policy.PasswordRuleViolations;
-import org.apache.archiva.redback.rest.api.model.ErrorMessage;
-import org.apache.archiva.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();
- }
-}
+++ /dev/null
-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.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.apache.archiva.redback.authentication.AuthenticationResult;
-import org.apache.archiva.redback.authorization.AuthorizationException;
-import org.apache.archiva.redback.authorization.RedbackAuthorization;
-import org.apache.archiva.redback.system.SecuritySession;
-import org.apache.archiva.redback.system.SecuritySystem;
-import org.apache.archiva.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();
- }
-}
+++ /dev/null
-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.archiva.redback.rest.api.model.RedbackRestError;
-import org.apache.archiva.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();
- }
-}
+++ /dev/null
-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();
- }
-}
+++ /dev/null
-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.apache.archiva.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() );
- }
- }
- }
-}
+++ /dev/null
-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.apache.archiva.redback.policy.PasswordRuleViolations;
-import org.apache.archiva.redback.users.User;
-import org.apache.archiva.redback.users.UserNotFoundException;
-import org.apache.archiva.redback.policy.PasswordEncoder;
-import org.apache.archiva.redback.policy.PasswordRuleViolationException;
-import org.apache.archiva.redback.system.SecuritySystem;
-import org.apache.archiva.redback.rest.api.model.ErrorMessage;
-import org.apache.archiva.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 );
- }
-
- }
-}
<context:annotation-config />
<context:component-scan
- base-package="org.codehaus.redback.rest.services"/>
+ base-package="org.apache.archiva.redback.rest.services"/>
<bean id="jsonProvider" class="org.codehaus.jackson.jaxrs.JacksonJsonProvider">
<property name="mapper" ref="redbackJacksonMapper"/>
--- /dev/null
+package org.apache.archiva.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 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.apache.archiva.redback.integration.security.role.RedbackRoleConstants;
+import org.apache.archiva.redback.rest.api.model.User;
+import org.apache.archiva.redback.rest.api.services.LoginService;
+import org.apache.archiva.redback.rest.api.services.RoleManagementService;
+import org.apache.archiva.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;
+ }
+
+}
--- /dev/null
+package org.apache.archiva.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.archiva.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();
+}
--- /dev/null
+package org.apache.archiva.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.archiva.redback.rbac.RBACManager;
+import org.apache.archiva.redback.users.UserManager;
+import org.apache.archiva.redback.configuration.UserConfiguration;
+import org.apache.archiva.redback.role.RoleManager;
+import org.apache.archiva.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;
+ }
+}
--- /dev/null
+package org.apache.archiva.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.archiva.redback.integration.security.role.RedbackRoleConstants;
+import org.apache.archiva.redback.rest.api.model.User;
+import org.apache.archiva.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" ) );
+ }
+ }
+
+}
--- /dev/null
+package org.apache.archiva.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.apache.archiva.redback.rest.api.model.ApplicationRoles;
+import org.apache.archiva.redback.rest.api.model.Role;
+import org.apache.archiva.redback.rest.api.model.User;
+import org.apache.archiva.redback.rest.api.services.RoleManagementService;
+import org.apache.archiva.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" );
+ }
+}
--- /dev/null
+package org.apache.archiva.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.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.apache.archiva.redback.rest.api.model.Operation;
+import org.apache.archiva.redback.rest.api.model.Permission;
+import org.apache.archiva.redback.rest.api.model.User;
+import org.apache.archiva.redback.rest.api.services.UserService;
+import org.apache.archiva.redback.rest.services.mock.EmailMessage;
+import org.apache.archiva.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();
+ }
+ }
+
+}
--- /dev/null
+package org.apache.archiva.redback.rest.services.mock;
+/*
+ * 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 javax.inject.Inject;
+import javax.mail.internet.MimeMessage;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * a rest which contains some methods to do some assert
+ *
+ * @author Olivier Lamy
+ */
+public class DefaultServicesAssert
+ implements ServicesAssert
+{
+
+ @Inject
+ MockJavaMailSender mockJavaMailSender;
+
+ public List<EmailMessage> getEmailMessageSended()
+ throws Exception
+ {
+ List<EmailMessage> emailMessages = new ArrayList<EmailMessage>();
+ for ( MimeMessage mimeMessage : mockJavaMailSender.getSendedEmails() )
+ {
+ emailMessages.add( new EmailMessage( mimeMessage ) );
+ }
+ return emailMessages;
+ }
+
+
+}
--- /dev/null
+package org.apache.archiva.redback.rest.services.mock;
+/*
+ * 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 javax.mail.Address;
+import javax.mail.Message;
+import javax.mail.internet.MimeMessage;
+import javax.xml.bind.annotation.XmlRootElement;
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * @author Olivier Lamy
+ */
+@XmlRootElement( name = "emailMessage" )
+public class EmailMessage
+ implements Serializable
+{
+ private List<String> tos = new ArrayList<String>();
+
+ private String from;
+
+ private String subject;
+
+ private String text;
+
+ public EmailMessage()
+ {
+ // no op
+ }
+
+ public EmailMessage( MimeMessage mimeMessage )
+ throws Exception
+ {
+ this.from = mimeMessage.getFrom()[0].toString();
+ for ( Address address : mimeMessage.getRecipients( Message.RecipientType.TO ) )
+ {
+ tos.add( address.toString() );
+ }
+ this.setSubject( mimeMessage.getSubject() );
+ this.text = (String) mimeMessage.getContent();
+ }
+
+ public List<String> getTos()
+ {
+ return tos;
+ }
+
+ public void setTos( List<String> tos )
+ {
+ this.tos = tos;
+ }
+
+ public String getFrom()
+ {
+ return from;
+ }
+
+ public void setFrom( String from )
+ {
+ this.from = from;
+ }
+
+ public String getSubject()
+ {
+ return subject;
+ }
+
+ public void setSubject( String subject )
+ {
+ this.subject = subject;
+ }
+
+ public String getText()
+ {
+ return text;
+ }
+
+ public void setText( String text )
+ {
+ this.text = text;
+ }
+
+ @Override
+ public String toString()
+ {
+ final StringBuilder sb = new StringBuilder();
+ sb.append( "EmailMessage" );
+ sb.append( "{tos=" ).append( tos );
+ sb.append( ", from='" ).append( from ).append( '\'' );
+ sb.append( ", subject='" ).append( subject ).append( '\'' );
+ sb.append( ", text='" ).append( text ).append( '\'' );
+ sb.append( '}' );
+ return sb.toString();
+ }
+}
--- /dev/null
+package org.apache.archiva.redback.rest.services.mock;
+
+/*
+ * 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.springframework.mail.MailException;
+import org.springframework.mail.javamail.JavaMailSender;
+import org.springframework.mail.javamail.JavaMailSenderImpl;
+import org.springframework.stereotype.Service;
+
+import javax.mail.internet.MimeMessage;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * @author <a href="mailto:olamy@apache.org">olamy</a>
+ * @since 26 sept. 2008
+ * @version $Id$
+ */
+@Service("mockJavaMailSender")
+public class MockJavaMailSender
+ extends JavaMailSenderImpl
+ implements JavaMailSender
+{
+
+ List<MimeMessage> sendedEmails = new ArrayList<MimeMessage>();
+
+ /**
+ *
+ */
+ public MockJavaMailSender()
+ {
+ // no op
+ }
+
+ @Override
+ public void send( MimeMessage mimeMessage )
+ throws MailException
+ {
+ sendedEmails.add( mimeMessage );
+ }
+
+ public List<MimeMessage> getSendedEmails()
+ {
+ return sendedEmails;
+ }
+
+}
--- /dev/null
+package org.apache.archiva.redback.rest.services.mock;
+/*
+ * 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 javax.ws.rs.GET;
+import javax.ws.rs.Path;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.MediaType;
+import java.util.List;
+
+/**
+ * @author Olivier Lamy
+ */
+@Path( "DefaultServicesAssert" )
+public interface ServicesAssert
+{
+ @GET
+ @Produces( { MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML } )
+ List<EmailMessage> getEmailMessageSended()
+ throws Exception;
+}
+++ /dev/null
-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 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.apache.archiva.redback.integration.security.role.RedbackRoleConstants;
-import org.apache.archiva.redback.rest.api.model.User;
-import org.apache.archiva.redback.rest.api.services.LoginService;
-import org.apache.archiva.redback.rest.api.services.RoleManagementService;
-import org.apache.archiva.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;
- }
-
-}
+++ /dev/null
-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.archiva.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();
-}
+++ /dev/null
-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.archiva.redback.rbac.RBACManager;
-import org.apache.archiva.redback.users.UserManager;
-import org.apache.archiva.redback.configuration.UserConfiguration;
-import org.apache.archiva.redback.role.RoleManager;
-import org.apache.archiva.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;
- }
-}
+++ /dev/null
-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.archiva.redback.integration.security.role.RedbackRoleConstants;
-import org.apache.archiva.redback.rest.api.model.User;
-import org.apache.archiva.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" ) );
- }
- }
-
-}
+++ /dev/null
-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.apache.archiva.redback.rest.api.model.ApplicationRoles;
-import org.apache.archiva.redback.rest.api.model.Role;
-import org.apache.archiva.redback.rest.api.model.User;
-import org.apache.archiva.redback.rest.api.services.RoleManagementService;
-import org.apache.archiva.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" );
- }
-}
+++ /dev/null
-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.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.apache.archiva.redback.rest.api.model.Operation;
-import org.apache.archiva.redback.rest.api.model.Permission;
-import org.apache.archiva.redback.rest.api.model.User;
-import org.apache.archiva.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();
- }
- }
-
-}
+++ /dev/null
-package org.codehaus.redback.rest.services.mock;
-/*
- * 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 javax.inject.Inject;
-import javax.mail.internet.MimeMessage;
-import javax.ws.rs.Path;
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * a rest which contains some methods to do some assert
- *
- * @author Olivier Lamy
- */
-public class DefaultServicesAssert
- implements ServicesAssert
-{
-
- @Inject
- MockJavaMailSender mockJavaMailSender;
-
- public List<EmailMessage> getEmailMessageSended()
- throws Exception
- {
- List<EmailMessage> emailMessages = new ArrayList<EmailMessage>();
- for ( MimeMessage mimeMessage : mockJavaMailSender.getSendedEmails() )
- {
- emailMessages.add( new EmailMessage( mimeMessage ) );
- }
- return emailMessages;
- }
-
-
-}
+++ /dev/null
-package org.codehaus.redback.rest.services.mock;
-/*
- * 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 javax.mail.Address;
-import javax.mail.Message;
-import javax.mail.internet.MimeMessage;
-import javax.xml.bind.annotation.XmlRootElement;
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * @author Olivier Lamy
- */
-@XmlRootElement( name = "emailMessage" )
-public class EmailMessage
- implements Serializable
-{
- private List<String> tos = new ArrayList<String>();
-
- private String from;
-
- private String subject;
-
- private String text;
-
- public EmailMessage()
- {
- // no op
- }
-
- public EmailMessage( MimeMessage mimeMessage )
- throws Exception
- {
- this.from = mimeMessage.getFrom()[0].toString();
- for ( Address address : mimeMessage.getRecipients( Message.RecipientType.TO ) )
- {
- tos.add( address.toString() );
- }
- this.setSubject( mimeMessage.getSubject() );
- this.text = (String) mimeMessage.getContent();
- }
-
- public List<String> getTos()
- {
- return tos;
- }
-
- public void setTos( List<String> tos )
- {
- this.tos = tos;
- }
-
- public String getFrom()
- {
- return from;
- }
-
- public void setFrom( String from )
- {
- this.from = from;
- }
-
- public String getSubject()
- {
- return subject;
- }
-
- public void setSubject( String subject )
- {
- this.subject = subject;
- }
-
- public String getText()
- {
- return text;
- }
-
- public void setText( String text )
- {
- this.text = text;
- }
-
- @Override
- public String toString()
- {
- final StringBuilder sb = new StringBuilder();
- sb.append( "EmailMessage" );
- sb.append( "{tos=" ).append( tos );
- sb.append( ", from='" ).append( from ).append( '\'' );
- sb.append( ", subject='" ).append( subject ).append( '\'' );
- sb.append( ", text='" ).append( text ).append( '\'' );
- sb.append( '}' );
- return sb.toString();
- }
-}
+++ /dev/null
-package org.codehaus.redback.rest.services.mock;
-
-/*
- * 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.springframework.mail.MailException;
-import org.springframework.mail.javamail.JavaMailSender;
-import org.springframework.mail.javamail.JavaMailSenderImpl;
-import org.springframework.stereotype.Service;
-
-import javax.mail.internet.MimeMessage;
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * @author <a href="mailto:olamy@apache.org">olamy</a>
- * @since 26 sept. 2008
- * @version $Id$
- */
-@Service("mockJavaMailSender")
-public class MockJavaMailSender
- extends JavaMailSenderImpl
- implements JavaMailSender
-{
-
- List<MimeMessage> sendedEmails = new ArrayList<MimeMessage>();
-
- /**
- *
- */
- public MockJavaMailSender()
- {
- // no op
- }
-
- @Override
- public void send( MimeMessage mimeMessage )
- throws MailException
- {
- sendedEmails.add( mimeMessage );
- }
-
- public List<MimeMessage> getSendedEmails()
- {
- return sendedEmails;
- }
-
-}
+++ /dev/null
-package org.codehaus.redback.rest.services.mock;
-/*
- * 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 javax.ws.rs.GET;
-import javax.ws.rs.Path;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.MediaType;
-import java.util.List;
-
-/**
- * @author Olivier Lamy
- */
-@Path( "DefaultServicesAssert" )
-public interface ServicesAssert
-{
- @GET
- @Produces( { MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML } )
- List<EmailMessage> getEmailMessageSended()
- throws Exception;
-}
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">
</jaxrs:server>
- <bean name="fakeCreateAdminService" class="org.codehaus.redback.rest.services.FakeCreateAdminServiceImpl"/>
+ <bean name="fakeCreateAdminService" class="org.apache.archiva.redback.rest.services.FakeCreateAdminServiceImpl"/>
- <bean name="mockJavaMailSender" class="org.codehaus.redback.rest.services.mock.MockJavaMailSender"/>
+ <bean name="mockJavaMailSender" class="org.apache.archiva.redback.rest.services.mock.MockJavaMailSender"/>
<alias name="mockJavaMailSender" alias="mailSender"/>
- <bean name="servicesAssert" class="org.codehaus.redback.rest.services.mock.DefaultServicesAssert"/>
+ <bean name="servicesAssert" class="org.apache.archiva.redback.rest.services.mock.DefaultServicesAssert"/>
</beans>
\ No newline at end of file