Defining REST V2 User Service

This commit is contained in:
Martin Stockhammer 2020-07-16 21:07:55 +02:00
parent 5305aa7fae
commit f7a2e7467d
8 changed files with 1074 additions and 95 deletions

View File

@ -20,18 +20,16 @@ package org.apache.archiva.redback.rest.api.services.v2;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.SecuritySchemeType;
import io.swagger.v3.oas.annotations.headers.Header;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.security.SecurityScheme;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.archiva.redback.authorization.RedbackAuthorization;
import org.apache.archiva.redback.integration.security.role.RedbackRoleConstants;
import org.apache.archiva.redback.rest.api.model.ActionStatus;
import org.apache.archiva.redback.rest.api.model.Group;
import org.apache.archiva.redback.rest.api.model.GroupMappingUpdateRequest;
import org.apache.archiva.redback.rest.api.model.v2.GroupMapping;
import org.apache.archiva.redback.rest.api.model.PagedResult;
import org.apache.archiva.redback.rest.api.model.v2.GroupMapping;
import org.apache.archiva.redback.rest.api.services.RedbackServiceException;
import javax.ws.rs.Consumes;
@ -44,7 +42,9 @@ import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriInfo;
import java.util.List;
/**
@ -52,7 +52,6 @@ import java.util.List;
* @since 2.1
*/
@Path( "/groups" )
@SecurityScheme( scheme = "BearerAuth", type = SecuritySchemeType.HTTP )
@Tag(name = "v2")
@Tag(name = "v2/Groups")
@SecurityRequirement(name = "BearerAuth")
@ -95,12 +94,17 @@ public interface GroupService
@RedbackAuthorization( permissions = RedbackRoleConstants.CONFIGURATION_EDIT_OPERATION )
@Operation( summary = "Adds a group mapping",
responses = {
@ApiResponse( responseCode = "201", description = "If the group addition was successful" ),
@ApiResponse( responseCode = "201",
description = "If the group addition was successful",
headers = {
@Header( name="Location", description = "The URL of the created mapping")
}
),
@ApiResponse( responseCode = "405", description = "Invalid input" )
}
)
ActionStatus addGroupMapping( @Parameter( description = "The data of the group mapping", required = true )
GroupMapping groupMapping )
GroupMapping groupMapping, @Context UriInfo uriInfo )
throws RedbackServiceException;
@Path( "mappings/{group}" )

View File

@ -19,6 +19,8 @@ package org.apache.archiva.redback.rest.api.services.v2;
* under the License.
*/
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.archiva.redback.authorization.RedbackAuthorization;
import org.apache.archiva.redback.integration.security.role.RedbackRoleConstants;
import org.apache.archiva.redback.rest.api.model.ActionStatus;
@ -31,12 +33,13 @@ import org.apache.archiva.redback.rest.api.model.RegistrationKey;
import org.apache.archiva.redback.rest.api.model.ResetPasswordRequest;
import org.apache.archiva.redback.rest.api.model.User;
import org.apache.archiva.redback.rest.api.model.UserRegistrationRequest;
import org.apache.archiva.redback.rest.api.model.VerificationStatus;
import org.apache.archiva.redback.rest.api.services.RedbackServiceException;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
@ -44,28 +47,31 @@ import javax.ws.rs.core.MediaType;
import java.util.Collection;
import java.util.List;
@Path( "/userService/" )
@Path( "/users" )
@Tag(name = "v2")
@Tag(name = "v2/Users")
@SecurityRequirement(name = "BearerAuth")
public interface UserService
{
@Path( "getUser/{userName}" )
@Path( "{userId}" )
@GET
@Produces( { MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML } )
@Produces( { MediaType.APPLICATION_JSON } )
@RedbackAuthorization( permissions = RedbackRoleConstants.USER_MANAGEMENT_USER_EDIT_OPERATION )
User getUser( @PathParam( "userName" ) String username )
User getUser( @PathParam( "userId" ) String userId )
throws RedbackServiceException;
@Path( "getUsers" )
@Path( "" )
@GET
@Produces( { MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML } )
@Produces( { MediaType.APPLICATION_JSON } )
@RedbackAuthorization( permissions = RedbackRoleConstants.USER_MANAGEMENT_USER_LIST_OPERATION )
List<User> getUsers()
throws RedbackServiceException;
@Path( "createUser" )
@Path( "" )
@POST
@Produces( { MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_PLAIN } )
@Consumes( { MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML } )
@Produces( { MediaType.APPLICATION_JSON } )
@Consumes( { MediaType.APPLICATION_JSON } )
@RedbackAuthorization( permissions = RedbackRoleConstants.USER_MANAGEMENT_USER_CREATE_OPERATION )
ActionStatus createUser( User user )
throws RedbackServiceException;
@ -74,15 +80,15 @@ public interface UserService
/**
* will create admin user only if not exists !! if exists will return false
*/
@Path( "createAdminUser" )
@Path( "admin" )
@POST
@Produces( { MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_PLAIN } )
@Consumes( { MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML } )
@Produces( { MediaType.APPLICATION_JSON } )
@Consumes( { MediaType.APPLICATION_JSON } )
@RedbackAuthorization( noRestriction = true )
ActionStatus createAdminUser( User user )
throws RedbackServiceException;
@Path( "isAdminUserExists" )
@Path( "admin/exists" )
@GET
@Produces( { MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_PLAIN } )
@RedbackAuthorization( noRestriction = true )
@ -90,49 +96,49 @@ public interface UserService
throws RedbackServiceException;
@Path( "deleteUser/{userName}" )
@GET
@Produces( { MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_PLAIN } )
@Path( "{userId}" )
@DELETE
@Produces( { MediaType.APPLICATION_JSON } )
@RedbackAuthorization( permissions = RedbackRoleConstants.USER_MANAGEMENT_USER_DELETE_OPERATION )
ActionStatus deleteUser( @PathParam( "userName" ) String username )
ActionStatus deleteUser( @PathParam( "userId" ) String userId )
throws RedbackServiceException;
@Path( "updateUser" )
@Path( "{userId}" )
@PUT
@Produces( { MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_PLAIN } )
@RedbackAuthorization( permissions = RedbackRoleConstants.USER_MANAGEMENT_USER_EDIT_OPERATION )
ActionStatus updateUser( @PathParam( "userId" ) String userId, User user )
throws RedbackServiceException;
/**
* @since 2.0
*/
@Path( "{userId}/lock" )
@POST
@Produces( { MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_PLAIN } )
@Produces( { MediaType.APPLICATION_JSON } )
@RedbackAuthorization( permissions = RedbackRoleConstants.USER_MANAGEMENT_USER_EDIT_OPERATION )
ActionStatus updateUser( User user )
ActionStatus lockUser( @PathParam( "userId" ) String userId )
throws RedbackServiceException;
/**
* @since 2.0
*/
@Path( "lockUser/{username}" )
@Path( "{userId}/unlock" )
@GET
@Produces( { MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_PLAIN } )
@Produces( { MediaType.APPLICATION_JSON } )
@RedbackAuthorization( permissions = RedbackRoleConstants.USER_MANAGEMENT_USER_EDIT_OPERATION )
ActionStatus lockUser( @PathParam( "username" ) String username )
throws RedbackServiceException;
/**
* @since 2.0
*/
@Path( "unlockUser/{username}" )
@GET
@Produces( { MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_PLAIN } )
@RedbackAuthorization( permissions = RedbackRoleConstants.USER_MANAGEMENT_USER_EDIT_OPERATION )
ActionStatus unlockUser( @PathParam( "username" ) String username )
ActionStatus unlockUser( @PathParam( "userId" ) String userId )
throws RedbackServiceException;
/**
* @since 2.0
*/
@Path( "passwordChangeRequired/{username}" )
@Path( "{userId}/passwordStatus" )
@GET
@Produces( { MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_PLAIN } )
@Produces( { MediaType.APPLICATION_JSON } )
@RedbackAuthorization( permissions = RedbackRoleConstants.USER_MANAGEMENT_USER_EDIT_OPERATION )
PasswordStatus passwordChangeRequired( @PathParam( "username" ) String username )
PasswordStatus passwordChangeRequired( @PathParam( "userId" ) String username )
throws RedbackServiceException;
/**
@ -140,37 +146,37 @@ public interface UserService
* the service verify the curent logged user with the one passed in the method
* @since 1.4
*/
@Path( "updateMe" )
@POST
@Produces( { MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_PLAIN } )
@RedbackAuthorization( noRestriction = false, noPermission = true )
@Path( "{userId}" )
@PUT
@Produces( { MediaType.APPLICATION_JSON } )
@RedbackAuthorization( noPermission = true )
ActionStatus updateMe( User user )
throws RedbackServiceException;
@Path( "ping" )
@Path( "___ping___" )
@GET
@Produces( { MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_PLAIN } )
@Produces( { MediaType.APPLICATION_JSON } )
@RedbackAuthorization( noRestriction = true )
PingResult ping()
throws RedbackServiceException;
@Path( "removeFromCache/{userName}" )
@GET
@Produces( { MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_PLAIN } )
@Path( "{userId}/clearCache" )
@POST
@Produces( { MediaType.APPLICATION_JSON } )
@RedbackAuthorization( permissions = RedbackRoleConstants.USER_MANAGEMENT_USER_EDIT_OPERATION )
ActionStatus removeFromCache( @PathParam( "userName" ) String username )
ActionStatus removeFromCache( @PathParam( "userId" ) String userId )
throws RedbackServiceException;
@Path( "getGuestUser" )
@Path( "guest" )
@GET
@Produces( { MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_PLAIN } )
@Produces( { MediaType.APPLICATION_JSON } )
@RedbackAuthorization( permissions = RedbackRoleConstants.USER_MANAGEMENT_USER_EDIT_OPERATION )
User getGuestUser()
throws RedbackServiceException;
@Path( "createGuestUser" )
@GET
@Produces( { MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_PLAIN } )
@Path( "guest" )
@POST
@Produces( { MediaType.APPLICATION_JSON } )
@RedbackAuthorization( permissions = RedbackRoleConstants.USER_MANAGEMENT_USER_EDIT_OPERATION )
User createGuestUser()
throws RedbackServiceException;
@ -179,25 +185,11 @@ public interface UserService
* if redback is not configured for email validation is required, -1 is returned as key
* @since 1.4
*/
@Path( "registerUser" )
@Path( "{userId}/register" )
@POST
@Produces( { MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML } )
@Produces( { MediaType.APPLICATION_JSON } )
@RedbackAuthorization( noRestriction = true, noPermission = true )
RegistrationKey registerUser( UserRegistrationRequest userRegistrationRequest )
throws RedbackServiceException;
/**
* validate the key and the user with forcing a password change for next login.
* http session is created.
* @param key authentication key
* @since 1.4
*/
@Path( "validateKey/{key}" )
@GET
@Produces( { MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_PLAIN } )
@RedbackAuthorization( noRestriction = true, noPermission = true )
VerificationStatus validateUserFromKey( @PathParam( "key" ) String key )
RegistrationKey registerUser( @PathParam( "userId" ) String userId, UserRegistrationRequest userRegistrationRequest )
throws RedbackServiceException;
/**
@ -205,54 +197,54 @@ public interface UserService
* @param resetPasswordRequest contains username for send a password reset email
* @since 1.4
*/
@Path( "resetPassword" )
@Path( "{userId}/resetPassword" )
@POST
@Produces( { MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_PLAIN } )
@Consumes( { MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML } )
@Produces( { MediaType.APPLICATION_JSON } )
@Consumes( { MediaType.APPLICATION_JSON } )
@RedbackAuthorization( noRestriction = true, noPermission = true )
ActionStatus resetPassword( ResetPasswordRequest resetPasswordRequest )
ActionStatus resetPassword( @PathParam( "userId" )String userId, ResetPasswordRequest resetPasswordRequest )
throws RedbackServiceException;
/**
* @since 1.4
*/
@Path( "getUserPermissions/{userName}" )
@Path( "{userId}/permissions" )
@GET
@Produces( { MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_PLAIN } )
@Produces( { MediaType.APPLICATION_JSON } )
@RedbackAuthorization( permissions = RedbackRoleConstants.USER_MANAGEMENT_USER_LIST_OPERATION )
Collection<Permission> getUserPermissions( @PathParam( "userName" ) String userName )
Collection<Permission> getUserPermissions( @PathParam( "userId" ) String userName )
throws RedbackServiceException;
/**
* @since 1.4
*/
@Path( "getUserOperations/{userName}" )
@Path( "{userId}/operations" )
@GET
@Produces( { MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_PLAIN } )
@Produces( { MediaType.APPLICATION_JSON } )
@RedbackAuthorization( permissions = RedbackRoleConstants.USER_MANAGEMENT_USER_LIST_OPERATION )
Collection<Operation> getUserOperations( @PathParam( "userName" ) String userName )
Collection<Operation> getUserOperations( @PathParam( "userId" ) String userName )
throws RedbackServiceException;
/**
* @return the current logged user permissions, if no logged user guest permissions are returned
* @since 1.4
*/
@Path( "getCurrentUserPermissions" )
@Path( "{userId}/self/permissions" )
@GET
@Produces( { MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_PLAIN } )
@Produces( { MediaType.APPLICATION_JSON } )
@RedbackAuthorization( noRestriction = true, noPermission = true )
Collection<Permission> getCurrentUserPermissions()
Collection<Permission> getCurrentUserPermissions(@PathParam( "userId" ) String userId)
throws RedbackServiceException;
/**
* @return the current logged user operations, if no logged user guest operations are returned
* @since 1.4
*/
@Path( "getCurrentUserOperations" )
@Path( "{userId}/self/operations" )
@GET
@Produces( { MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_PLAIN } )
@Produces( { MediaType.APPLICATION_JSON } )
@RedbackAuthorization( noRestriction = true, noPermission = true )
Collection<Operation> getCurrentUserOperations()
Collection<Operation> getCurrentUserOperations(@PathParam( "userId" ) String userId)
throws RedbackServiceException;
}

View File

@ -41,9 +41,11 @@ import javax.inject.Inject;
import javax.inject.Named;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
@ -67,6 +69,9 @@ public class DefaultGroupService
@Context //injected response proxy supporting multiple threads
private HttpServletResponse response;
@Context
private HttpServletRequest request;
@Inject
@Named(value = "ldapRoleMapper#default")
private LdapRoleMapper ldapRoleMapper;
@ -169,7 +174,7 @@ public class DefaultGroupService
}
@Override
public ActionStatus addGroupMapping( GroupMapping ldapGroupMapping )
public ActionStatus addGroupMapping( GroupMapping ldapGroupMapping, UriInfo uriInfo)
throws RedbackServiceException
{
try
@ -177,6 +182,10 @@ public class DefaultGroupService
ldapRoleMapperConfiguration.addLdapMapping( ldapGroupMapping.getGroupName(),
new ArrayList<>( ldapGroupMapping.getRoles() ) );
response.setStatus( Response.Status.CREATED.getStatusCode() );
if (uriInfo!=null)
{
response.setHeader( "Location", uriInfo.getAbsolutePathBuilder( ).path( ldapGroupMapping.getGroupName( ) ).build( ).toString( ) );
}
}
catch ( MappingException e )
{

View File

@ -0,0 +1,966 @@
package org.apache.archiva.redback.rest.services.v2;
/*
* 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.components.cache.Cache;
import org.apache.archiva.redback.authentication.AuthenticationException;
import org.apache.archiva.redback.authentication.TokenBasedAuthenticationDataSource;
import org.apache.archiva.redback.configuration.UserConfiguration;
import org.apache.archiva.redback.configuration.UserConfigurationKeys;
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.keys.AuthenticationKey;
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.AccountLockedException;
import org.apache.archiva.redback.policy.MustChangePasswordException;
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.RbacManagerException;
import org.apache.archiva.redback.rbac.UserAssignment;
import org.apache.archiva.redback.rest.api.model.ActionStatus;
import org.apache.archiva.redback.rest.api.model.AvailabilityStatus;
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.PasswordStatus;
import org.apache.archiva.redback.rest.api.model.Permission;
import org.apache.archiva.redback.rest.api.model.PingResult;
import org.apache.archiva.redback.rest.api.model.RegistrationKey;
import org.apache.archiva.redback.rest.api.model.ResetPasswordRequest;
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.model.UserRegistrationRequest;
import org.apache.archiva.redback.rest.api.model.VerificationStatus;
import org.apache.archiva.redback.rest.api.services.RedbackServiceException;
import org.apache.archiva.redback.rest.api.services.v2.UserService;
import org.apache.archiva.redback.rest.services.RedbackAuthenticationThreadLocal;
import org.apache.archiva.redback.rest.services.RedbackRequestInformation;
import org.apache.archiva.redback.rest.services.utils.PasswordValidator;
import org.apache.archiva.redback.role.RoleManager;
import org.apache.archiva.redback.role.RoleManagerException;
import org.apache.archiva.redback.system.SecuritySystem;
import org.apache.archiva.redback.users.UserManager;
import org.apache.archiva.redback.users.UserManagerException;
import org.apache.archiva.redback.users.UserNotFoundException;
import org.apache.commons.lang3.StringUtils;
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( "v2.userService#rest" )
public class DefaultUserService
implements UserService
{
private final Logger log = LoggerFactory.getLogger( getClass() );
private static final String VALID_USERNAME_CHARS = "[a-zA-Z_0-9\\-.@]*";
private UserManager userManager;
private SecuritySystem securitySystem;
@Inject
@Named( value = "userConfiguration#default" )
private UserConfiguration config;
@Inject
private RoleManager roleManager;
/**
* cache used for user assignments
*/
@Inject
@Named( value = "cache#userAssignments" )
private Cache<String, ? extends UserAssignment> userAssignmentsCache;
/**
* cache used for user permissions
*/
@Inject
@Named( value = "cache#userPermissions" )
private Cache<String, ? extends Permission> userPermissionsCache;
/**
* Cache used for users
*/
@Inject
@Named( value = "cache#users" )
private Cache<String, ? extends User> usersCache;
@Inject
private Mailer mailer;
@Inject
@Named( value = "rbacManager#default" )
private RBACManager rbacManager;
private HttpAuthenticator httpAuthenticator;
@Inject
private PasswordValidator passwordValidator;
@Context
private HttpServletRequest httpServletRequest;
@Inject
public DefaultUserService( @Named( value = "userManager#default" ) UserManager userManager,
SecuritySystem securitySystem,
@Named( "httpAuthenticator#basic" ) HttpAuthenticator httpAuthenticator )
{
this.userManager = userManager;
this.securitySystem = securitySystem;
this.httpAuthenticator = httpAuthenticator;
}
@Override
public ActionStatus 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() );
}
catch ( UserManagerException e )
{
throw new RedbackServiceException( new ErrorMessage( e.getMessage() ) );
}
// 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" ) );
}
try
{
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() );
}
}
roleManager.assignRole( RedbackRoleConstants.REGISTERED_USER_ROLE_ID, u.getUsername() );
}
catch ( RoleManagerException rpe )
{
log.error( "RoleProfile Error: {}", rpe.getMessage(), rpe );
throw new RedbackServiceException( new ErrorMessage( "assign.role.failure", null ) );
}
catch ( UserManagerException e )
{
throw new RedbackServiceException( new ErrorMessage( e.getMessage() ) );
}
return ActionStatus.SUCCESS;
}
@Override
public ActionStatus deleteUser( String userId )
throws RedbackServiceException
{
try
{
if ( rbacManager.userAssignmentExists( userId ) )
{
UserAssignment assignment = rbacManager.getUserAssignment( userId );
rbacManager.removeUserAssignment( assignment );
}
}
catch ( RbacManagerException e )
{
log.error( e.getMessage(), e );
throw new RedbackServiceException( e.getMessage() );
}
try
{
userManager.deleteUser( userId );
return ActionStatus.SUCCESS;
}
catch ( UserNotFoundException e )
{
log.error( e.getMessage(), e );
throw new RedbackServiceException( e.getMessage() );
}
catch ( UserManagerException e )
{
throw new RedbackServiceException( new ErrorMessage( e.getMessage() ) );
}
finally
{
removeFromCache( userId );
}
}
@Override
public User getUser( String userId )
throws RedbackServiceException
{
try
{
org.apache.archiva.redback.users.User user = userManager.findUser( userId );
return getSimpleUser( user );
}
catch ( UserNotFoundException e )
{
return null;
}
catch ( UserManagerException e )
{
throw new RedbackServiceException( new ErrorMessage( e.getMessage() ) );
}
}
@Override
public List<User> getUsers()
throws RedbackServiceException
{
try
{
List<? extends org.apache.archiva.redback.users.User> users = userManager.getUsers();
List<User> simpleUsers = new ArrayList<>( users.size( ) );
for ( org.apache.archiva.redback.users.User user : users )
{
simpleUsers.add( getSimpleUser( user ) );
}
return simpleUsers;
}
catch ( UserManagerException e )
{
throw new RedbackServiceException( new ErrorMessage( e.getMessage() ) );
}
}
@Override
public ActionStatus updateMe( User user )
throws RedbackServiceException
{
// check username == one in the session
RedbackRequestInformation redbackRequestInformation = RedbackAuthenticationThreadLocal.get();
if ( redbackRequestInformation == null || redbackRequestInformation.getUser() == null )
{
log.warn( "RedbackRequestInformation from ThreadLocal is 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(), false ).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() );
}
catch ( UserManagerException e )
{
throw new RedbackServiceException( new ErrorMessage( e.getMessage() ) );
}
// 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.getUsername(), realUser );
return ActionStatus.SUCCESS;
}
@Override
public ActionStatus updateUser( String userId, User user )
throws RedbackServiceException
{
try
{
org.apache.archiva.redback.users.User rawUser = userManager.findUser( user.getUsername(), false );
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 ActionStatus.SUCCESS;
}
catch ( UserNotFoundException e )
{
throw new RedbackServiceException( e.getMessage() );
}
catch ( UserManagerException e )
{
throw new RedbackServiceException( new ErrorMessage( e.getMessage() ) );
}
}
@Override
public ActionStatus removeFromCache( String userId )
throws RedbackServiceException
{
if ( userAssignmentsCache != null )
{
userAssignmentsCache.remove( userId );
}
if ( userPermissionsCache != null )
{
userPermissionsCache.remove( userId );
}
if ( usersCache != null )
{
usersCache.remove( userId );
}
CacheManager cacheManager = CacheManager.getInstance();
String[] caches = cacheManager.getCacheNames();
for ( String cacheName : caches )
{
if ( StringUtils.startsWith( cacheName, "org.apache.archiva.redback.rbac.jdo" ) )
{
cacheManager.getCache( cacheName ).removeAll();
}
}
return ActionStatus.SUCCESS;
}
@Override
public User getGuestUser()
throws RedbackServiceException
{
try
{
org.apache.archiva.redback.users.User user = userManager.getGuestUser();
return getSimpleUser( user );
}
catch ( Exception e )
{
return null;
}
}
@Override
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( config.getString( UserConfigurationKeys.DEFAULT_GUEST ), user.getUsername() );
return getSimpleUser( user );
}
catch ( RoleManagerException | UserNotFoundException e )
{
log.error( e.getMessage(), e );
throw new RedbackServiceException( e.getMessage() );
}
catch ( UserManagerException e )
{
throw new RedbackServiceException( new ErrorMessage( e.getMessage() ) );
}
finally
{
if ( !securitySystem.getPolicy().isEnabled() )
{
securitySystem.getPolicy().setEnabled( true );
}
}
}
@Override
public PingResult ping()
throws RedbackServiceException
{
return new PingResult( true );
}
private User getSimpleUser( org.apache.archiva.redback.users.User user )
{
if ( user == null )
{
return null;
}
return new User( user );
}
@Override
public ActionStatus createAdminUser( User adminUser )
throws RedbackServiceException
{
if ( isAdminUserExists().isExists() )
{
log.warn( "Admin user exists already" );
return ActionStatus.FAIL;
}
log.debug("Creating admin admin user '{}'", adminUser.getUsername());
if (!RedbackRoleConstants.ADMINISTRATOR_ACCOUNT_NAME.equals(adminUser.getUsername())) {
log.error("Wrong admin user name {}", adminUser.getUsername());
throw new RedbackServiceException(new ErrorMessage("admin.wrongUsername"));
}
try
{
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 );
roleManager.assignRole( "system-administrator", user.getUsername() );
}
catch ( RoleManagerException e )
{
throw new RedbackServiceException( e.getMessage() );
}
catch ( UserManagerException e )
{
throw new RedbackServiceException( new ErrorMessage( e.getMessage() ) );
}
return ActionStatus.SUCCESS;
}
@Override
public AvailabilityStatus isAdminUserExists()
throws RedbackServiceException
{
try
{
userManager.findUser( config.getString( UserConfigurationKeys.DEFAULT_ADMIN ) );
return new AvailabilityStatus( true );
}
catch ( UserNotFoundException e )
{
// ignore
}
catch ( UserManagerException e )
{
Throwable cause = e.getCause();
if ( cause != null && cause instanceof UserNotFoundException )
{
return new AvailabilityStatus( false );
}
throw new RedbackServiceException( new ErrorMessage( e.getMessage() ) );
}
return new AvailabilityStatus( false );
}
@Override
public ActionStatus resetPassword( String userId, ResetPasswordRequest resetPasswordRequest )
throws RedbackServiceException
{
String username = resetPasswordRequest.getUsername();
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() );
String applicationUrl = resetPasswordRequest.getApplicationUrl();
if ( StringUtils.isBlank( applicationUrl ) )
{
applicationUrl = getBaseUrl();
}
mailer.sendPasswordResetEmail( Arrays.asList( user.getEmail() ), authkey, applicationUrl );
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" ) );
}
catch ( UserManagerException e )
{
throw new RedbackServiceException( new ErrorMessage( e.getMessage() ) );
}
return ActionStatus.SUCCESS;
}
@Override
public RegistrationKey registerUser( String userId, UserRegistrationRequest userRegistrationRequest )
throws RedbackServiceException
{
User user = userRegistrationRequest.getUser();
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 );
}
org.apache.archiva.redback.users.User u = null;
try
{
// 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() } ) );
}
u = userManager.createUser( user.getUsername(), user.getFullName(), user.getEmail() );
u.setPassword( user.getPassword() );
u.setValidated( false );
u.setLocked( false );
roleManager.assignRole( RedbackRoleConstants.REGISTERED_USER_ROLE_ID, u.getUsername() );
}
catch ( RoleManagerException rpe )
{
log.error( "RoleProfile Error: {}", rpe.getMessage(), rpe );
throw new RedbackServiceException( new ErrorMessage( "assign.role.failure", null ) );
}
catch ( UserManagerException e )
{
throw new RedbackServiceException( new ErrorMessage( e.getMessage() ) );
}
if ( emailValidationRequired )
{
u.setLocked( true );
try
{
AuthenticationKey authkey =
securitySystem.getKeyManager().createKey( u.getUsername(), "New User Email Validation",
securityPolicy.getUserValidationSettings().getEmailValidationTimeout() );
String baseUrl = userRegistrationRequest.getApplicationUrl();
if ( StringUtils.isBlank( baseUrl ) )
{
baseUrl = getBaseUrl();
}
log.debug( "register user {} with email {} and app url {}", u.getUsername(), u.getEmail(), baseUrl );
mailer.sendAccountValidationEmail( Arrays.asList( u.getEmail() ), authkey, baseUrl );
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 ) );
}
catch ( UserManagerException e )
{
throw new RedbackServiceException( new ErrorMessage( e.getMessage() ) );
}
finally
{
securityPolicy.setEnabled( true );
}
}
else
{
try
{
userManager.addUser( u );
return new RegistrationKey( "-1" );
}
catch ( UserManagerException e )
{
throw new RedbackServiceException( new ErrorMessage( e.getMessage() ) );
}
}
// FIXME log this event
/*
AuditEvent event = new AuditEvent( getText( "log.account.create" ) );
event.setAffectedUser( username );
event.log();
*/
}
@Override
public Collection<Permission> getCurrentUserPermissions(String userId)
throws RedbackServiceException
{
RedbackRequestInformation redbackRequestInformation = RedbackAuthenticationThreadLocal.get();
String userName = UserManager.GUEST_USERNAME;
if ( redbackRequestInformation != null && redbackRequestInformation.getUser() != null )
{
userName = redbackRequestInformation.getUser().getUsername();
}
else
{
log.warn( "RedbackRequestInformation from ThreadLocal is null" );
}
return getUserPermissions( userName );
}
@Override
public Collection<Operation> getCurrentUserOperations(String userId)
throws RedbackServiceException
{
RedbackRequestInformation redbackRequestInformation = RedbackAuthenticationThreadLocal.get();
String userName = UserManager.GUEST_USERNAME;
if ( redbackRequestInformation != null && redbackRequestInformation.getUser() != null )
{
userName = redbackRequestInformation.getUser().getUsername();
}
else
{
log.warn( "RedbackRequestInformation from ThreadLocal is null" );
}
return getUserOperations( userName );
}
@Override
public Collection<Operation> getUserOperations( String userName )
throws RedbackServiceException
{
Collection<Permission> permissions = getUserPermissions( userName );
List<Operation> operations = new ArrayList<>( permissions.size( ) );
for ( Permission permission : permissions )
{
if ( permission.getOperation() != null )
{
Operation operation = new Operation();
operation.setName( permission.getOperation().getName() );
operations.add( operation );
}
}
return operations;
}
@Override
public Collection<Permission> getUserPermissions( String userName )
throws RedbackServiceException
{
try
{
Set<? extends org.apache.archiva.redback.rbac.Permission> permissions =
rbacManager.getAssignedPermissions( userName );
// FIXME return guest permissions !!
List<Permission> userPermissions = new ArrayList<>( 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 ( 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 ( 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 ( StringUtils.isEmpty( user.getFullName() ) )
{
redbackServiceException.addErrorMessage( new ErrorMessage( "fullName.required", null ) );
}
if ( StringUtils.isEmpty( user.getEmail() ) )
{
redbackServiceException.addErrorMessage( new ErrorMessage( "email.required", null ) );
}
if ( !StringUtils.equals( user.getPassword(), user.getConfirmPassword() ) )
{
redbackServiceException.addErrorMessage( new ErrorMessage( "passwords.does.not.match", null ) );
}
try
{
if ( !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 );
try
{
org.apache.archiva.redback.users.User tmpuser =
userManager.createUser( user.getUsername(), user.getFullName(), user.getEmail() );
user.setPassword( user.getPassword() );
securitySystem.getPolicy().validatePassword( tmpuser );
if ( ( StringUtils.isEmpty( user.getPassword() ) ) )
{
throw new RedbackServiceException( new ErrorMessage( "password.required", null ) );
}
}
catch ( UserManagerException e )
{
throw new RedbackServiceException( new ErrorMessage( e.getMessage() ) );
}
}
private String getBaseUrl()
{
if ( httpServletRequest != null )
{
if ( httpServletRequest != null )
{
return httpServletRequest.getScheme() + "://" + httpServletRequest.getServerName() + (
httpServletRequest.getServerPort() == 80
? ""
: ":" + httpServletRequest.getServerPort() ) + httpServletRequest.getContextPath();
}
}
return null;
}
@Override
public ActionStatus unlockUser( String userId )
throws RedbackServiceException
{
User user = getUser( userId );
if ( user != null )
{
user.setLocked( false );
updateUser( user.getUsername(), user );
return ActionStatus.SUCCESS;
}
return ActionStatus.FAIL;
}
@Override
public ActionStatus lockUser( String userId )
throws RedbackServiceException
{
User user = getUser( userId );
if ( user != null )
{
user.setLocked( true );
updateUser( user.getUsername(), user );
return ActionStatus.SUCCESS;
}
return ActionStatus.FAIL;
}
@Override
public PasswordStatus passwordChangeRequired( String username )
throws RedbackServiceException
{
User user = getUser( username );
if ( user == null )
{
user.setPasswordChangeRequired( true );
updateUser( user.getUsername(), user );
return new PasswordStatus( true );
}
return new PasswordStatus( false );
}
}

View File

@ -82,7 +82,7 @@
<jaxrs:server address="/v2/redback">
<jaxrs:serviceBeans>
<ref bean="userService#rest"/>
<ref bean="v2.userService#rest"/>
<ref bean="v2.authenticationService#rest"/>
<ref bean="roleManagementService#rest"/>
<ref bean="utilServices#rest"/>

View File

@ -25,6 +25,7 @@ import org.apache.archiva.redback.rest.api.services.v2.GroupService;
import org.apache.commons.lang3.StringUtils;
import org.apache.cxf.jaxrs.client.JAXRSClientFactory;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.cxf.jaxrs.impl.UriInfoImpl;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
@ -45,6 +46,7 @@ import javax.naming.directory.BasicAttributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriInfo;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
@ -350,7 +352,7 @@ public class GroupServiceTest
GroupMapping groupMapping = new GroupMapping( "ldap group", "cn=ldap group,ou=archiva,ou=apache,ou=org", Arrays.asList( "redback role" ) );
service.addGroupMapping( groupMapping );
service.addGroupMapping( groupMapping, null );
mappings = service.getGroupMappings( );

View File

@ -18,6 +18,7 @@ package org.apache.archiva.redback.rest.services.v2;
* under the License.
*/
import io.restassured.filter.log.UrlDecoder;
import io.restassured.http.ContentType;
import io.restassured.response.Response;
import org.apache.archiva.components.apacheds.ApacheDs;
@ -49,6 +50,7 @@ import javax.naming.directory.BasicAttribute;
import javax.naming.directory.BasicAttributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Hashtable;
@ -397,6 +399,9 @@ public class NativeGroupServiceTest extends AbstractNativeRestServices
.then( ).statusCode( 201 ).extract( ).response( );
assertNotNull( response );
assertTrue( response.getBody( ).jsonPath( ).getBoolean( "success" ) );
assertNotNull( response.getHeader( "Location" ) );
assertTrue( UrlDecoder.urlDecode( response.getHeader( "Location" ), Charset.forName( "UTF-8" ), false ).endsWith( "/mappings/ldap group" ) );
} finally {
given( ).spec( getRequestSpec( token ) ).contentType( JSON )
.when( )

View File

@ -61,6 +61,7 @@ import static org.junit.jupiter.api.Assertions.*;
@ContextConfiguration(
locations = {"classpath:/spring-context.xml"} )
@TestInstance( TestInstance.Lifecycle.PER_CLASS )
@Disabled
public class UserServiceTest
extends AbstractRestServicesTestV2
{