REST API changes

This commit is contained in:
Martin Stockhammer 2020-07-24 16:36:54 +02:00
parent b2d94281c6
commit 2561585d8c
10 changed files with 329 additions and 43 deletions

View File

@ -27,6 +27,7 @@ import javax.xml.bind.annotation.XmlRootElement;
public class VerificationStatus public class VerificationStatus
{ {
boolean success = false; boolean success = false;
String accessToken;
public VerificationStatus() { public VerificationStatus() {
@ -45,4 +46,14 @@ public class VerificationStatus
{ {
this.success = success; this.success = success;
} }
public String getAccessToken( )
{
return accessToken;
}
public void setAccessToken( String accessToken )
{
this.accessToken = accessToken;
}
} }

View File

@ -33,6 +33,7 @@ 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.ResetPasswordRequest;
import org.apache.archiva.redback.rest.api.model.User; 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.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.RedbackServiceException;
import javax.ws.rs.Consumes; import javax.ws.rs.Consumes;
@ -146,7 +147,7 @@ public interface UserService
@PUT @PUT
@Produces( { MediaType.APPLICATION_JSON } ) @Produces( { MediaType.APPLICATION_JSON } )
@RedbackAuthorization( noPermission = true ) @RedbackAuthorization( noPermission = true )
ActionStatus updateMe( User user ) ActionStatus updateMe( @PathParam( "userId" ) String userId, User user )
throws RedbackServiceException; throws RedbackServiceException;
@Path( "___ping___" ) @Path( "___ping___" )
@ -243,4 +244,11 @@ public interface UserService
Collection<Operation> getCurrentUserOperations(@PathParam( "userId" ) String userId) Collection<Operation> getCurrentUserOperations(@PathParam( "userId" ) String userId)
throws RedbackServiceException; throws RedbackServiceException;
@Path( "{userId}/registration/{key}/validate" )
@GET
@Produces( {MediaType.APPLICATION_JSON} )
@RedbackAuthorization( noRestriction = true, noPermission = true )
VerificationStatus validateUserRegistration( @PathParam( "userId" ) String userId, @PathParam( "key" ) String key )
throws RedbackServiceException;
} }

View File

@ -75,7 +75,11 @@ import java.util.Collection;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
/**
* This version is deprected. Use the V2 version: {@link org.apache.archiva.redback.rest.services.v2.DefaultUserService}
*/
@Service( "userService#rest" ) @Service( "userService#rest" )
@Deprecated
public class DefaultUserService public class DefaultUserService
implements UserService implements UserService
{ {

View File

@ -28,6 +28,7 @@ import org.apache.archiva.redback.authorization.RedbackAuthorization;
import org.apache.archiva.redback.integration.filter.authentication.HttpAuthenticationException; import org.apache.archiva.redback.integration.filter.authentication.HttpAuthenticationException;
import org.apache.archiva.redback.policy.AccountLockedException; import org.apache.archiva.redback.policy.AccountLockedException;
import org.apache.archiva.redback.policy.MustChangePasswordException; import org.apache.archiva.redback.policy.MustChangePasswordException;
import org.apache.archiva.redback.rbac.RBACManager;
import org.apache.archiva.redback.rest.services.RedbackAuthenticationThreadLocal; import org.apache.archiva.redback.rest.services.RedbackAuthenticationThreadLocal;
import org.apache.archiva.redback.rest.services.RedbackRequestInformation; import org.apache.archiva.redback.rest.services.RedbackRequestInformation;
import org.apache.archiva.redback.system.SecuritySession; import org.apache.archiva.redback.system.SecuritySession;
@ -51,9 +52,15 @@ import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.ResourceInfo; import javax.ws.rs.container.ResourceInfo;
import javax.ws.rs.core.Context; import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import javax.ws.rs.core.SecurityContext;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.ext.Provider; import javax.ws.rs.ext.Provider;
import java.io.IOException; import java.io.IOException;
import java.util.List;
import java.util.function.Function;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/** /**
* Interceptor that checks for the Bearer Header value and tries to verify the token. * Interceptor that checks for the Bearer Header value and tries to verify the token.
@ -74,6 +81,10 @@ public class BearerAuthInterceptor extends AbstractInterceptor
@Named( value = "userManager#default" ) @Named( value = "userManager#default" )
private UserManager userManager; private UserManager userManager;
@Inject
@Named( value = "rbacManager#default" )
RBACManager rbacManager;
@Inject @Inject
@Named( value = "securitySystem" ) @Named( value = "securitySystem" )
SecuritySystem securitySystem; SecuritySystem securitySystem;
@ -84,6 +95,9 @@ public class BearerAuthInterceptor extends AbstractInterceptor
@Context @Context
private ResourceInfo resourceInfo; private ResourceInfo resourceInfo;
@Context
private UriInfo uriInfo;
protected void setUserManager( UserManager userManager ) protected void setUserManager( UserManager userManager )
{ {
this.userManager = userManager; this.userManager = userManager;
@ -151,9 +165,18 @@ public class BearerAuthInterceptor extends AbstractInterceptor
new RedbackRequestInformation( securitySession, user, request.getRemoteAddr( ) ); new RedbackRequestInformation( securitySession, user, request.getRemoteAddr( ) );
RedbackAuthenticationThreadLocal.set( redbackRequestInformation ); RedbackAuthenticationThreadLocal.set( redbackRequestInformation );
// message.put( AuthenticationResult.class, authenticationResult );
requestContext.setProperty( AUTHENTICATION_RESULT, authenticationResult ); requestContext.setProperty( AUTHENTICATION_RESULT, authenticationResult );
requestContext.setProperty( SECURITY_SESSION, securitySession ); requestContext.setProperty( SECURITY_SESSION, securitySession );
RedbackSecurityContext securityContext = new RedbackSecurityContext(uriInfo, user, securitySession );
if (rbacManager!=null)
{
List<String> roleNames = rbacManager.getAssignedRoles( user.getUsername( ) ).stream( )
.flatMap( role -> Stream.concat( Stream.of( role.getName( ) ), role.getChildRoleNames( ).stream( ) ) )
.collect( Collectors.toList( ) );
securityContext.setRoles( roleNames );
}
requestContext.setSecurityContext( securityContext );
} }
catch ( Exception e ) catch ( Exception e )
{ {

View File

@ -0,0 +1,49 @@
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.users.User;
import java.security.Principal;
/**
* This is used by the JAX-RS security context.
*/
public class RedbackPrincipal implements Principal
{
User redbackUser;
RedbackPrincipal(User user) {
this.redbackUser = user;
}
@Override
public String getName( )
{
return redbackUser.getUsername();
}
public User getUser() {
return redbackUser;
}
}

View File

@ -0,0 +1,99 @@
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.system.SecuritySession;
import org.apache.archiva.redback.users.User;
import javax.ws.rs.core.UriInfo;
import java.security.Principal;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
/**
* Simple security context for JAX-RS to forward data from the Authentication filter to the service implementations
*
* @since 3.0
*/
public class RedbackSecurityContext implements javax.ws.rs.core.SecurityContext
{
SecuritySession securitySession;
Principal principal;
User user;
String authenticationScheme = "Bearer";
Set<String> roles;
boolean isSecure;
RedbackSecurityContext( UriInfo uriInfo, User user, SecuritySession securitySession) {
this.isSecure = uriInfo.getAbsolutePath().toString().toLowerCase().startsWith("https");
setPrincipal( user );
this.securitySession = securitySession;
}
@Override
public Principal getUserPrincipal( )
{
return principal;
}
@Override
public boolean isUserInRole( String s )
{
return roles == null ? false : roles.contains( s );
}
@Override
public boolean isSecure( )
{
return isSecure;
}
@Override
public String getAuthenticationScheme( )
{
return authenticationScheme;
}
public SecuritySession getSecuritySession() {
return this.securitySession;
}
public void setPrincipal( User user)
{
this.user = user;
this.principal = new RedbackPrincipal( user );
}
public void setSession( SecuritySession securitySession )
{
this.securitySession = securitySession;
}
public void setRoles( Collection<String> roles) {
this.roles = new HashSet<>( roles );
}
public User getUser( )
{
return user;
}
}

View File

@ -40,6 +40,8 @@ import org.apache.archiva.redback.rest.api.model.User;
import org.apache.archiva.redback.rest.api.model.UserLogin; import org.apache.archiva.redback.rest.api.model.UserLogin;
import org.apache.archiva.redback.rest.api.services.RedbackServiceException; import org.apache.archiva.redback.rest.api.services.RedbackServiceException;
import org.apache.archiva.redback.rest.api.services.v2.AuthenticationService; import org.apache.archiva.redback.rest.api.services.v2.AuthenticationService;
import org.apache.archiva.redback.rest.services.RedbackAuthenticationThreadLocal;
import org.apache.archiva.redback.rest.services.interceptors.RedbackSecurityContext;
import org.apache.archiva.redback.system.SecuritySession; import org.apache.archiva.redback.system.SecuritySession;
import org.apache.archiva.redback.system.SecuritySystem; import org.apache.archiva.redback.system.SecuritySystem;
import org.apache.archiva.redback.users.UserManagerException; import org.apache.archiva.redback.users.UserManagerException;
@ -52,12 +54,16 @@ import javax.inject.Inject;
import javax.inject.Named; import javax.inject.Named;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.core.Context; import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import javax.ws.rs.core.SecurityContext;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import static org.apache.archiva.redback.rest.services.interceptors.AbstractInterceptor.SECURITY_SESSION;
/** /**
* *
* Authentication service provides REST methods for authentication and verification. * Authentication service provides REST methods for authentication and verification.
@ -75,26 +81,25 @@ public class DefaultAuthenticationService
private SecuritySystem securitySystem; private SecuritySystem securitySystem;
private HttpAuthenticator httpAuthenticator;
@Context @Context
private HttpServletRequest httpServletRequest; private HttpServletRequest httpServletRequest;
@Context
private SecurityContext securityContext;
@Context
private ContainerRequestContext requestContext;
@Context @Context
private HttpServletResponse response; private HttpServletResponse response;
@Inject @Inject
private JwtAuthenticator jwtAuthenticator; private JwtAuthenticator jwtAuthenticator;
// validation token lifetime: 3 hours
long tokenLifetime = 1000*3600*3;
@Inject @Inject
public DefaultAuthenticationService( SecuritySystem securitySystem, public DefaultAuthenticationService( SecuritySystem securitySystem )
@Named( "httpAuthenticator#basic" ) HttpAuthenticator httpAuthenticator )
{ {
this.securitySystem = securitySystem; this.securitySystem = securitySystem;
this.httpAuthenticator = httpAuthenticator;
} }
@ -110,6 +115,10 @@ public class DefaultAuthenticationService
return new PingResult( true ); return new PingResult( true );
} }
private RedbackSecurityContext getSecurityContext() {
return this.securityContext==null?null:(RedbackSecurityContext) this.securityContext;
}
@Override @Override
public TokenResponse logIn( RequestTokenRequest loginRequest ) public TokenResponse logIn( RequestTokenRequest loginRequest )
throws RedbackServiceException throws RedbackServiceException
@ -218,10 +227,13 @@ public class DefaultAuthenticationService
public User getAuthenticatedUser() public User getAuthenticatedUser()
throws RedbackServiceException throws RedbackServiceException
{ {
SecuritySession securitySession = httpAuthenticator.getSecuritySession( httpServletRequest.getSession( true ) ); RedbackSecurityContext ctx = getSecurityContext( );
Boolean isLogged = securitySession != null; if (ctx!=null)
log.debug( "isLogged {}", isLogged ); {
return isLogged && securitySession.getUser() != null ? buildRestUser( securitySession.getUser() ) : null; return buildRestUser( getSecurityContext( ).getUser( ) );
} else {
throw new RedbackServiceException( "redback:not_authenticated", Response.Status.UNAUTHORIZED.getStatusCode( ) );
}
} }
private UserLogin buildRestUser( org.apache.archiva.redback.users.User user ) private UserLogin buildRestUser( org.apache.archiva.redback.users.User user )

View File

@ -22,7 +22,9 @@ package org.apache.archiva.redback.rest.services.v2;
import net.sf.ehcache.CacheManager; import net.sf.ehcache.CacheManager;
import org.apache.archiva.components.cache.Cache; import org.apache.archiva.components.cache.Cache;
import org.apache.archiva.redback.authentication.AuthenticationException; import org.apache.archiva.redback.authentication.AuthenticationException;
import org.apache.archiva.redback.authentication.Token;
import org.apache.archiva.redback.authentication.TokenBasedAuthenticationDataSource; import org.apache.archiva.redback.authentication.TokenBasedAuthenticationDataSource;
import org.apache.archiva.redback.authentication.jwt.JwtAuthenticator;
import org.apache.archiva.redback.configuration.UserConfiguration; import org.apache.archiva.redback.configuration.UserConfiguration;
import org.apache.archiva.redback.configuration.UserConfigurationKeys; import org.apache.archiva.redback.configuration.UserConfigurationKeys;
import org.apache.archiva.redback.integration.filter.authentication.HttpAuthenticator; import org.apache.archiva.redback.integration.filter.authentication.HttpAuthenticator;
@ -59,6 +61,7 @@ import org.apache.archiva.redback.rest.services.RedbackRequestInformation;
import org.apache.archiva.redback.rest.services.utils.PasswordValidator; import org.apache.archiva.redback.rest.services.utils.PasswordValidator;
import org.apache.archiva.redback.role.RoleManager; import org.apache.archiva.redback.role.RoleManager;
import org.apache.archiva.redback.role.RoleManagerException; import org.apache.archiva.redback.role.RoleManagerException;
import org.apache.archiva.redback.system.SecuritySession;
import org.apache.archiva.redback.system.SecuritySystem; import org.apache.archiva.redback.system.SecuritySystem;
import org.apache.archiva.redback.users.UserManager; import org.apache.archiva.redback.users.UserManager;
import org.apache.archiva.redback.users.UserManagerException; import org.apache.archiva.redback.users.UserManagerException;
@ -98,6 +101,9 @@ public class DefaultUserService
@Named( value = "userConfiguration#default" ) @Named( value = "userConfiguration#default" )
private UserConfiguration config; private UserConfiguration config;
@Inject
private JwtAuthenticator jwtAuthenticator;
@Inject @Inject
private RoleManager roleManager; private RoleManager roleManager;
@ -139,12 +145,10 @@ public class DefaultUserService
@Inject @Inject
public DefaultUserService( @Named( value = "userManager#default" ) UserManager userManager, public DefaultUserService( @Named( value = "userManager#default" ) UserManager userManager,
SecuritySystem securitySystem, SecuritySystem securitySystem )
@Named( "httpAuthenticator#basic" ) HttpAuthenticator httpAuthenticator )
{ {
this.userManager = userManager; this.userManager = userManager;
this.securitySystem = securitySystem; this.securitySystem = securitySystem;
this.httpAuthenticator = httpAuthenticator;
} }
@ -275,7 +279,7 @@ public class DefaultUserService
try try
{ {
org.apache.archiva.redback.users.User user = userManager.findUser( userId ); org.apache.archiva.redback.users.User user = userManager.findUser( userId );
return getSimpleUser( user ); return getRestUser( user );
} }
catch ( UserNotFoundException e ) catch ( UserNotFoundException e )
{ {
@ -298,7 +302,7 @@ public class DefaultUserService
for ( org.apache.archiva.redback.users.User user : users ) for ( org.apache.archiva.redback.users.User user : users )
{ {
simpleUsers.add( getSimpleUser( user ) ); simpleUsers.add( getRestUser( user ) );
} }
return simpleUsers; return simpleUsers;
@ -310,7 +314,7 @@ public class DefaultUserService
} }
@Override @Override
public ActionStatus updateMe( User user ) public ActionStatus updateMe( String userId, User user )
throws RedbackServiceException throws RedbackServiceException
{ {
// check username == one in the session // check username == one in the session
@ -445,7 +449,7 @@ public class DefaultUserService
try try
{ {
org.apache.archiva.redback.users.User user = userManager.getGuestUser(); org.apache.archiva.redback.users.User user = userManager.getGuestUser();
return getSimpleUser( user ); return getRestUser( user );
} }
catch ( Exception e ) catch ( Exception e )
{ {
@ -470,7 +474,7 @@ public class DefaultUserService
user.setPasswordChangeRequired( false ); user.setPasswordChangeRequired( false );
user = userManager.updateUser( user, false ); user = userManager.updateUser( user, false );
roleManager.assignRole( config.getString( UserConfigurationKeys.DEFAULT_GUEST ), user.getUsername() ); roleManager.assignRole( config.getString( UserConfigurationKeys.DEFAULT_GUEST ), user.getUsername() );
return getSimpleUser( user ); return getRestUser( user );
} }
catch ( RoleManagerException | UserNotFoundException e ) catch ( RoleManagerException | UserNotFoundException e )
{ {
@ -498,7 +502,7 @@ public class DefaultUserService
return new PingResult( true ); return new PingResult( true );
} }
private User getSimpleUser( org.apache.archiva.redback.users.User user ) private User getRestUser( org.apache.archiva.redback.users.User user )
{ {
if ( user == null ) if ( user == null )
{ {
@ -774,6 +778,68 @@ public class DefaultUserService
return getUserOperations( userName ); return getUserOperations( userName );
} }
@Override
public VerificationStatus validateUserRegistration( String userId, 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.getUsername();
TokenBasedAuthenticationDataSource authsource = new TokenBasedAuthenticationDataSource();
authsource.setPrincipal( principal );
authsource.setToken( authkey.getKey() );
authsource.setEnforcePasswordChange( false );
securitySystem.getUserManager().updateUser( user );
VerificationStatus status = new VerificationStatus(false );
SecuritySession authStatus = securitySystem.authenticate( authsource );
if (authStatus.isAuthenticated()) {
Token accessToken = jwtAuthenticator.generateToken( principal );
status.setAccessToken( accessToken.getData() );
status.setSuccess( true );
}
log.info( "account validated for user {}", user.getUsername() );
return status;
}
catch ( MustChangePasswordException | AccountLockedException | AuthenticationException 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 ( UserManagerException e )
{
throw new RedbackServiceException( new ErrorMessage( e.getMessage() ) );
}
}
@Override @Override
public Collection<Operation> getUserOperations( String userName ) public Collection<Operation> getUserOperations( String userName )
throws RedbackServiceException throws RedbackServiceException

View File

@ -21,6 +21,7 @@ package org.apache.archiva.redback.rest.services.v2;
import io.restassured.response.Response; import io.restassured.response.Response;
import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.api.TestInstance;
@ -37,8 +38,7 @@ import static io.restassured.RestAssured.given;
import static io.restassured.http.ContentType.JSON; import static io.restassured.http.ContentType.JSON;
import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.notNullValue;
import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.*;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** /**
* @author Martin Stockhammer <martin_s@apache.org> * @author Martin Stockhammer <martin_s@apache.org>
@ -171,4 +171,16 @@ public class NativeAuthenticationServiceTest extends AbstractNativeRestServices
assertNotNull( result.body( ).jsonPath( ).getString( "refresh_token" ) ); assertNotNull( result.body( ).jsonPath( ).getString( "refresh_token" ) );
} }
@Disabled
@Test
void getAuthenticatedUser() {
Response result = given( ).spec( getRequestSpec(getAdminToken()) )
.contentType( JSON )
.when( ).get( "/authenticated" ).then( ).statusCode( 200 )
.extract( ).response( );
System.out.println( result.getBody( ).prettyPrint( ) );
assertEquals( "admin", result.getBody( ).jsonPath( ).getString( "username" ) );
}
} }

View File

@ -22,12 +22,13 @@ package org.apache.archiva.redback.rest.services.v2;
import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider; import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider;
import org.apache.archiva.redback.rest.api.model.Operation; 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.Permission;
import org.apache.archiva.redback.rest.api.model.PingResult;
import org.apache.archiva.redback.rest.api.model.RequestTokenRequest; import org.apache.archiva.redback.rest.api.model.RequestTokenRequest;
import org.apache.archiva.redback.rest.api.model.ResetPasswordRequest; import org.apache.archiva.redback.rest.api.model.ResetPasswordRequest;
import org.apache.archiva.redback.rest.api.model.TokenResponse; import org.apache.archiva.redback.rest.api.model.TokenResponse;
import org.apache.archiva.redback.rest.api.model.User; 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.UserRegistrationRequest;
import org.apache.archiva.redback.rest.api.services.UserService; import org.apache.archiva.redback.rest.api.services.v2.UserService;
import org.apache.archiva.redback.rest.services.FakeCreateAdminService; import org.apache.archiva.redback.rest.services.FakeCreateAdminService;
import org.apache.archiva.redback.rest.services.mock.EmailMessage; import org.apache.archiva.redback.rest.services.mock.EmailMessage;
import org.apache.archiva.redback.rest.services.mock.MockJavaMailSender; import org.apache.archiva.redback.rest.services.mock.MockJavaMailSender;
@ -61,7 +62,6 @@ import static org.junit.jupiter.api.Assertions.*;
@ContextConfiguration( @ContextConfiguration(
locations = {"classpath:/spring-context.xml"} ) locations = {"classpath:/spring-context.xml"} )
@TestInstance( TestInstance.Lifecycle.PER_CLASS ) @TestInstance( TestInstance.Lifecycle.PER_CLASS )
@Disabled
public class UserServiceTest public class UserServiceTest
extends AbstractRestServicesTestV2 extends AbstractRestServicesTestV2
{ {
@ -108,12 +108,13 @@ public class UserServiceTest
return service; return service;
} }
@Disabled
@Test @Test
public void ping( ) public void ping( )
throws Exception throws Exception
{ {
Boolean res = getUserService( null ).ping( ); PingResult res = getUserService( null ).ping( );
assertTrue( res ); assertTrue( res.isSuccess() );
} }
@Test @Test
@ -201,7 +202,7 @@ public class UserServiceTest
u.setEmail( "toto@toto.fr" ); u.setEmail( "toto@toto.fr" );
u.setPassword( "toto123" ); u.setPassword( "toto123" );
u.setConfirmPassword( "toto123" ); u.setConfirmPassword( "toto123" );
String key = service.registerUser( new UserRegistrationRequest( u, "http://wine.fr/bordeaux" ) ).getKey( ); String key = service.registerUser( u.getUsername(), new UserRegistrationRequest( u, "http://wine.fr/bordeaux" ) ).getKey( );
assertNotEquals( "-1", key ); assertNotEquals( "-1", key );
@ -224,7 +225,7 @@ public class UserServiceTest
assertTrue( messageContent.contains( "http://wine.fr/bordeaux" ) ); assertTrue( messageContent.contains( "http://wine.fr/bordeaux" ) );
assertTrue( messageContent.contains( "toto" ) ); assertTrue( messageContent.contains( "toto" ) );
assertTrue( service.validateUserFromKey( key ).isSuccess( ) ); //assertTrue( service.validateUserFromKey( key ).isSuccess( ) );
service = getUserService( getAdminAuthzHeader( ) ); service = getUserService( getAdminAuthzHeader( ) );
@ -234,7 +235,7 @@ public class UserServiceTest
assertTrue( u.isValidated( ) ); assertTrue( u.isValidated( ) );
assertTrue( u.isPasswordChangeRequired( ) ); assertTrue( u.isPasswordChangeRequired( ) );
assertTrue( service.validateUserFromKey( key ).isSuccess( ) ); // assertTrue( service.validateUserFromKey( key ).isSuccess( ) );
} }
catch ( Exception e ) catch ( Exception e )
@ -249,6 +250,7 @@ public class UserServiceTest
} }
@Disabled
@Test @Test
public void registerNoUrl( ) public void registerNoUrl( )
throws Exception throws Exception
@ -262,7 +264,7 @@ public class UserServiceTest
u.setEmail( "toto@toto.fr" ); u.setEmail( "toto@toto.fr" );
u.setPassword( "toto123" ); u.setPassword( "toto123" );
u.setConfirmPassword( "toto123" ); u.setConfirmPassword( "toto123" );
String key = service.registerUser( new UserRegistrationRequest( u, null ) ).getKey( ); String key = service.registerUser( u.getUsername(), new UserRegistrationRequest( u, null ) ).getKey( );
assertNotEquals( "-1", key ); assertNotEquals( "-1", key );
@ -284,7 +286,7 @@ public class UserServiceTest
assertTrue( messageContent.contains( "http://localhost:" + getServerPort( ) ) ); assertTrue( messageContent.contains( "http://localhost:" + getServerPort( ) ) );
assertTrue( messageContent.toLowerCase( ).contains( "toto" ) ); assertTrue( messageContent.toLowerCase( ).contains( "toto" ) );
assertTrue( service.validateUserFromKey( key ).isSuccess( ) ); // assertTrue( service.validateUserFromKey( key ).isSuccess( ) );
service = getUserService( getAdminAuthzHeader( ) ); service = getUserService( getAdminAuthzHeader( ) );
@ -294,7 +296,7 @@ public class UserServiceTest
assertTrue( u.isValidated( ) ); assertTrue( u.isValidated( ) );
assertTrue( u.isPasswordChangeRequired( ) ); assertTrue( u.isPasswordChangeRequired( ) );
assertTrue( service.validateUserFromKey( key ).isSuccess( ) ); // assertTrue( service.validateUserFromKey( key ).isSuccess( ) );
} }
catch ( Exception e ) catch ( Exception e )
@ -325,7 +327,7 @@ public class UserServiceTest
u.setEmail( "toto@toto.fr" ); u.setEmail( "toto@toto.fr" );
u.setPassword( "toto123" ); u.setPassword( "toto123" );
u.setConfirmPassword( "toto123" ); u.setConfirmPassword( "toto123" );
String key = service.registerUser( new UserRegistrationRequest( u, "http://wine.fr/bordeaux" ) ).getKey( ); String key = service.registerUser( u.getUsername(), new UserRegistrationRequest( u, "http://wine.fr/bordeaux" ) ).getKey( );
assertNotEquals( "-1", key ); assertNotEquals( "-1", key );
@ -345,7 +347,7 @@ public class UserServiceTest
assertTrue( assertTrue(
emailMessages.get( 0 ).getText( ).contains( "Use the following URL to validate your account." ) ); emailMessages.get( 0 ).getText( ).contains( "Use the following URL to validate your account." ) );
assertTrue( service.validateUserFromKey( key ).isSuccess( ) ); // assertTrue( service.validateUserFromKey( key ).isSuccess( ) );
service = getUserService( getAdminAuthzHeader( ) ); service = getUserService( getAdminAuthzHeader( ) );
@ -355,9 +357,9 @@ public class UserServiceTest
assertTrue( u.isValidated( ) ); assertTrue( u.isValidated( ) );
assertTrue( u.isPasswordChangeRequired( ) ); assertTrue( u.isPasswordChangeRequired( ) );
assertTrue( service.validateUserFromKey( key ).isSuccess( ) ); // assertTrue( service.validateUserFromKey( key ).isSuccess( ) );
assertTrue( service.resetPassword( new ResetPasswordRequest( "toto", "http://foo.fr/bar" ) ).isSuccess( ) ); assertTrue( service.resetPassword(u.getUsername(), new ResetPasswordRequest( "toto", "http://foo.fr/bar" ) ).isSuccess( ) );
emailMessages = assertService.getEmailMessageSended( ); emailMessages = assertService.getEmailMessageSended( );
assertEquals( 2, emailMessages.size( ) ); assertEquals( 2, emailMessages.size( ) );
@ -409,7 +411,7 @@ public class UserServiceTest
throws Exception throws Exception
{ {
createGuestIfNeeded( ); createGuestIfNeeded( );
Collection<Permission> permissions = getUserService( null ).getCurrentUserPermissions( ); Collection<Permission> permissions = getUserService( null ).getCurrentUserPermissions("guest" );
log.info( "guest permisssions: {}", permissions ); log.info( "guest permisssions: {}", permissions );
} }
@ -426,7 +428,7 @@ public class UserServiceTest
throws Exception throws Exception
{ {
createGuestIfNeeded( ); createGuestIfNeeded( );
Collection<Operation> operations = getUserService( null ).getCurrentUserOperations( ); Collection<Operation> operations = getUserService( null ).getCurrentUserOperations("guest" );
log.info( "guest operations: {}", operations ); log.info( "guest operations: {}", operations );
} }
@ -447,7 +449,7 @@ public class UserServiceTest
u.setEmail( "toto@titi.fr" ); u.setEmail( "toto@titi.fr" );
u.setPassword( "toto1234" ); u.setPassword( "toto1234" );
u.setPreviousPassword( "toto123" ); u.setPreviousPassword( "toto123" );
getUserService( getUserAuthzHeader( "toto" ) ).updateMe( u ); getUserService( getUserAuthzHeader( "toto" ) ).updateMe( u.getUsername(), u );
u = getUserService( getAdminAuthzHeader( ) ).getUser( "toto" ); u = getUserService( getAdminAuthzHeader( ) ).getUser( "toto" );
assertEquals( "the toto123", u.getFullName( ) ); assertEquals( "the toto123", u.getFullName( ) );
@ -457,7 +459,7 @@ public class UserServiceTest
u.setEmail( "toto@tititi.fr" ); u.setEmail( "toto@tititi.fr" );
u.setPassword( "toto12345" ); u.setPassword( "toto12345" );
u.setPreviousPassword( "toto1234" ); u.setPreviousPassword( "toto1234" );
getUserService( getUserAuthzHeader( "toto" )) .updateMe( u ); getUserService( getUserAuthzHeader( "toto" )) .updateMe(u.getUsername(), u );
u = getUserService( getAdminAuthzHeader( ) ).getUser( "toto" ); u = getUserService( getAdminAuthzHeader( ) ).getUser( "toto" );
assertEquals( "the toto1234", u.getFullName( ) ); assertEquals( "the toto1234", u.getFullName( ) );