--- /dev/null
+package org.apache.archiva.redback.struts2.action;
+
+/*
+ * 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.servlet.http.HttpServletRequest;
+
+import org.apache.struts2.ServletActionContext;
+import org.apache.archiva.redback.policy.PasswordRuleViolationException;
+import org.apache.archiva.redback.policy.PasswordRuleViolations;
+import org.apache.archiva.redback.system.SecuritySession;
+import org.apache.archiva.redback.system.SecuritySystemConstants;
+import org.apache.archiva.redback.integration.interceptor.SecureAction;
+import org.apache.archiva.redback.integration.interceptor.SecureActionBundle;
+import org.apache.archiva.redback.integration.interceptor.SecureActionException;
+
+/**
+ * AbstractSecurityAction
+ *
+ * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
+ * @version $Id$
+ */
+public abstract class AbstractSecurityAction
+ extends RedbackActionSupport
+ implements SecureAction
+{
+ protected static final String REQUIRES_AUTHENTICATION = "requires-authentication";
+
+ private SecureActionBundle securityBundle;
+
+ public SecureActionBundle getSecureActionBundle()
+ throws SecureActionException
+ {
+ if ( securityBundle == null )
+ {
+ securityBundle = initSecureActionBundle();
+ }
+
+ return securityBundle;
+ }
+
+ public abstract SecureActionBundle initSecureActionBundle()
+ throws SecureActionException;
+
+ protected void setAuthTokens( SecuritySession securitySession )
+ {
+ session.put( SecuritySystemConstants.SECURITY_SESSION_KEY, securitySession );
+ this.setSession( session );
+ }
+
+ protected SecuritySession getSecuritySession()
+ {
+ return (SecuritySession) session.get( SecuritySystemConstants.SECURITY_SESSION_KEY );
+ }
+
+ // ------------------------------------------------------------------
+ // Internal Support Methods
+ // ------------------------------------------------------------------
+ protected void processPasswordRuleViolations( PasswordRuleViolationException e )
+ {
+ processPasswordRuleViolations( e, "user.password" );
+ }
+
+ protected void processPasswordRuleViolations( PasswordRuleViolationException e, String field )
+ {
+ PasswordRuleViolations violations = e.getViolations();
+
+ if ( violations != null )
+ {
+ for ( String violation : violations.getLocalizedViolations() )
+ {
+ addFieldError( field, violation );
+ }
+ }
+ }
+
+ protected String getBaseUrl()
+ {
+ HttpServletRequest req = ServletActionContext.getRequest();
+ return req.getScheme() + "://" + req.getServerName()
+ + ( req.getServerPort() == 80 ? "" : ":" + req.getServerPort() ) + req.getContextPath();
+ }
+
+ protected String getCurrentUser()
+ {
+ SecuritySession securitySession = getSecuritySession();
+ if ( securitySession != null && securitySession.getUser() != null )
+ {
+ return securitySession.getUser().getPrincipal().toString();
+ }
+ else
+ {
+ return null;
+ }
+ }
+}
--- /dev/null
+package org.apache.archiva.redback.struts2.action;
+
+/*
+ * 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.Resource;
+import org.apache.archiva.redback.rbac.Role;
+import org.apache.archiva.redback.users.User;
+import org.apache.archiva.redback.policy.PasswordRuleViolationException;
+import org.apache.archiva.redback.rbac.RbacManagerException;
+import org.apache.archiva.redback.system.SecuritySystem;
+import org.codehaus.plexus.util.StringUtils;
+import org.apache.archiva.redback.integration.model.UserCredentials;
+import org.apache.archiva.redback.integration.security.role.RedbackRoleConstants;
+import org.apache.archiva.redback.integration.util.RoleSorter;
+
+import javax.inject.Inject;
+import javax.inject.Named;
+import javax.mail.internet.AddressException;
+import javax.mail.internet.InternetAddress;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * AbstractUserCredentialsAction
+ *
+ * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
+ * @version $Id$
+ */
+public abstract class AbstractUserCredentialsAction
+ extends AbstractSecurityAction
+{
+ // ------------------------------------------------------------------
+ // Component Requirements
+ // ------------------------------------------------------------------
+
+ /**
+ *
+ */
+ @Inject
+ @Named( value = "rBACManager#cached" )
+ private RBACManager manager;
+
+ /**
+ *
+ */
+ @Inject
+ protected SecuritySystem securitySystem;
+
+ // ------------------------------------------------------------------
+ // Action Parameters
+ // ------------------------------------------------------------------
+
+ protected UserCredentials internalUser;
+
+ protected final String VALID_USERNAME_CHARS = "[a-zA-Z_0-9\\-.@]*";
+
+ public RBACManager getManager()
+ {
+ return manager;
+ }
+
+ public void setManager( RBACManager manager )
+ {
+ this.manager = manager;
+ }
+
+ public SecuritySystem getSecuritySystem()
+ {
+ return securitySystem;
+ }
+
+ public void setSecuritySystem( SecuritySystem securitySystem )
+ {
+ this.securitySystem = securitySystem;
+ }
+
+ // ------------------------------------------------------------------
+ // Action Entry Points - (aka Names)
+ // ------------------------------------------------------------------
+
+ public void validateCredentialsLoose()
+ {
+ if ( StringUtils.isEmpty( internalUser.getUsername() ) )
+ {
+ addFieldError( "user.username", getText( "username.required" ) );
+ }
+ else
+ {
+ if ( !internalUser.getUsername().matches( VALID_USERNAME_CHARS ) )
+ {
+ addFieldError( "user.username", getText( "username.invalid.characters" ) );
+ }
+ }
+
+ if ( StringUtils.isEmpty( internalUser.getFullName() ) )
+ {
+ addFieldError( "user.fullName", getText( "fullName.required" ) );
+ }
+
+ if ( StringUtils.isEmpty( internalUser.getEmail() ) )
+ {
+ addFieldError( "user.email", getText( "email.required" ) );
+ }
+
+ if ( !StringUtils.equals( internalUser.getPassword(), internalUser.getConfirmPassword() ) )
+ {
+ addFieldError( "user.confirmPassword", getText( "passwords.does.not.match" ) );
+ }
+
+ try
+ {
+ if ( !StringUtils.isEmpty( internalUser.getEmail() ) )
+ {
+ new InternetAddress( internalUser.getEmail(), true );
+ }
+ }
+ catch ( AddressException e )
+ {
+ addFieldError( "user.email", getText( "email.invalid" ) );
+ }
+ }
+
+ public void validateCredentialsStrict()
+ {
+ validateCredentialsLoose();
+
+ User tmpuser = internalUser.createUser( securitySystem.getUserManager() );
+
+ try
+ {
+ securitySystem.getPolicy().validatePassword( tmpuser );
+ }
+ catch ( PasswordRuleViolationException e )
+ {
+ processPasswordRuleViolations( e );
+ }
+
+ if ( ( StringUtils.isEmpty( internalUser.getPassword() ) ) )
+ {
+ addFieldError( "user.password", getText( "password.required" ) );
+ }
+ }
+
+ /**
+ * 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<Role> filterRolesForCurrentUserAccess( List<Role> roleList )
+ throws RbacManagerException
+ {
+ String currentUser = getCurrentUser();
+
+ List<Role> filteredRoleList = new ArrayList<Role>();
+
+ Map<String, List<Permission>> assignedPermissionMap = manager.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 ( 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 );
+ }
+ }
+ }
+ }
+
+ Collections.sort( filteredRoleList, new RoleSorter() );
+ return filteredRoleList;
+ }
+
+ protected List<Role> getFilteredRolesForCurrentUserAccess()
+ throws RbacManagerException
+ {
+ List<Role> roles = manager.getAllRoles();
+
+ if ( roles == null )
+ {
+ return Collections.emptyList();
+ }
+
+ return filterRolesForCurrentUserAccess( roles );
+ }
+}
--- /dev/null
+package org.apache.archiva.redback.struts2.action;
+
+/*
+ * 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 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.DefaultSecuritySession;
+import org.apache.archiva.redback.system.SecuritySession;
+import org.apache.archiva.redback.system.SecuritySystemConstants;
+import org.apache.archiva.redback.users.UserManager;
+import org.codehaus.plexus.util.StringUtils;
+import org.apache.archiva.redback.integration.interceptor.SecureActionBundle;
+import org.apache.archiva.redback.integration.interceptor.SecureActionException;
+import org.apache.archiva.redback.integration.model.EditUserCredentials;
+import org.springframework.context.annotation.Scope;
+import org.springframework.stereotype.Controller;
+
+import java.util.Arrays;
+
+/**
+ * AccountAction
+ *
+ * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
+ * @version $Id$
+ */
+@Controller( "redback-account" )
+@Scope( "prototype" )
+public class AccountAction
+ extends AbstractUserCredentialsAction
+ implements CancellableAction
+{
+ private static final String ACCOUNT_SUCCESS = "security-account-success";
+
+ // ------------------------------------------------------------------
+ // Action Parameters
+ // ------------------------------------------------------------------
+
+ private EditUserCredentials user;
+
+ private String oldPassword;
+
+ // ------------------------------------------------------------------
+ // Action Entry Points - (aka Names)
+ // ------------------------------------------------------------------
+
+ public String show()
+ {
+ SecuritySession session = getSecuritySession();
+
+ if ( !session.isAuthenticated() )
+ {
+ addActionError( getText( "cannot.show.account.login.required" ) );
+ return REQUIRES_AUTHENTICATION;
+ }
+
+ String username = session.getUser().getUsername();
+
+ if ( username == null )
+ {
+ addActionError( getText( "cannot.edit.user.null.username" ) );
+ return ERROR;
+ }
+
+ if ( StringUtils.isEmpty( username ) )
+ {
+ addActionError( getText( "cannot.edit.user.empty.username" ) );
+ return ERROR;
+ }
+
+ UserManager manager = super.securitySystem.getUserManager();
+
+ if ( !manager.userExists( username ) )
+ {
+ // Means that the role name doesn't exist.
+ // We need to fail fast and return to the previous page.
+ addActionError( getText( "user.does.not.exist", Arrays.asList( (Object) username ) ) );
+ return ERROR;
+ }
+
+ internalUser = user;
+
+ try
+ {
+ User u = manager.findUser( username );
+ if ( u == null )
+ {
+ addActionError( getText( "cannot.operate.on.null.user" ) );
+ return ERROR;
+ }
+
+ user = new EditUserCredentials( u );
+ }
+ catch ( UserNotFoundException e )
+ {
+ addActionError( getText( "cannot.get.user", Arrays.asList( (Object) username, e.getMessage() ) ) );
+ return ERROR;
+ }
+
+ return INPUT;
+ }
+
+ public String submit()
+ {
+ SecuritySession session = getSecuritySession();
+
+ if ( !session.isAuthenticated() )
+ {
+ addActionError( getText( "cannot.show.account.login.required" ) );
+ return REQUIRES_AUTHENTICATION;
+ }
+
+ String username = session.getUser().getUsername();
+
+ if ( username == null )
+ {
+ addActionError( getText( "cannot.edit.user.null.username" ) );
+ return ERROR;
+ }
+
+ if ( StringUtils.isEmpty( username ) )
+ {
+ addActionError( getText( "cannot.edit.user.empty.username" ) );
+ return ERROR;
+ }
+
+ if ( user == null )
+ {
+ addActionError( getText( "cannot.edit.user.null.credentials" ) );
+ return ERROR;
+ }
+
+ if ( !user.getPassword().equals( user.getConfirmPassword() ) )
+ {
+ addFieldError( "user.confirmPassword", getText( "password.confimation.failed" ) );
+ return ERROR;
+ }
+
+ UserManager manager = super.securitySystem.getUserManager();
+
+ if ( !manager.userExists( username ) )
+ {
+ // Means that the role name doesn't exist.
+ // We need to fail fast and return to the previous page.
+ addActionError( getText( "user.does.not.exist", Arrays.asList( (Object) username ) ) );
+ return ERROR;
+ }
+
+ internalUser = user;
+
+ try
+ {
+ User u = manager.findUser( username );
+ if ( u == null )
+ {
+ addActionError( getText( "cannot.operate.on.null.user" ) );
+ return ERROR;
+ }
+
+ if ( StringUtils.isNotEmpty( user.getPassword() ) )
+ {
+ PasswordEncoder encoder = securitySystem.getPolicy().getPasswordEncoder();
+
+ if ( !encoder.isPasswordValid( u.getEncodedPassword(), oldPassword ) )
+ {
+ addFieldError( "oldPassword", getText( "password.provided.does.not.match.existing" ) );
+ return ERROR;
+ }
+
+ u.setPassword( user.getPassword() );
+ }
+
+ u.setFullName( user.getFullName() );
+ u.setEmail( user.getEmail() );
+ u.setPassword( user.getPassword() );
+
+ manager.updateUser( u );
+
+ //check if current user then update the session
+ if ( getSecuritySession().getUser().getUsername().equals( u.getUsername() ) )
+ {
+ SecuritySession securitySession =
+ new DefaultSecuritySession( getSecuritySession().getAuthenticationResult(), u );
+
+ this.session.put( SecuritySystemConstants.SECURITY_SESSION_KEY, securitySession );
+
+ setSession( this.session );
+ }
+ }
+ catch ( UserNotFoundException e )
+ {
+ addActionError( getText( "cannot.get.user", Arrays.asList( (Object) username, e.getMessage() ) ) );
+ return ERROR;
+ }
+ catch ( PasswordRuleViolationException e )
+ {
+ processPasswordRuleViolations( e );
+ return ERROR;
+ }
+
+ return ACCOUNT_SUCCESS;
+ }
+
+ public String cancel()
+ {
+ return CANCEL;
+ }
+
+ // ------------------------------------------------------------------
+ // Parameter Accessor Methods
+ // ------------------------------------------------------------------
+
+ public EditUserCredentials getUser()
+ {
+ return user;
+ }
+
+ public void setUser( EditUserCredentials user )
+ {
+ this.user = user;
+ }
+
+ public SecureActionBundle initSecureActionBundle()
+ throws SecureActionException
+ {
+ SecureActionBundle bundle = new SecureActionBundle();
+ bundle.setRequiresAuthentication( true );
+ return bundle;
+ }
+
+ public void setOldPassword( String oldPassword )
+ {
+ this.oldPassword = oldPassword;
+ }
+
+ public boolean isSelf()
+ {
+ return true;
+ }
+}
--- /dev/null
+package org.apache.archiva.redback.struts2.action;
+
+/*
+ * 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.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.slf4j.MDC;
+
+public class AuditEvent
+{
+ private Logger logger = LoggerFactory.getLogger( AuditEvent.class.getName() );
+
+ private final String action;
+
+ private String affectedUser;
+
+ private String role;
+
+ private String currentUser;
+
+ public AuditEvent( String action )
+ {
+ this.action = action;
+ }
+
+ public void setRole( String role )
+ {
+ this.role = role;
+ }
+
+ public String getRole()
+ {
+ return role;
+ }
+
+ public void setAffectedUser( String affectedUser )
+ {
+ this.affectedUser = affectedUser;
+ }
+
+ public String getAffectedUser()
+ {
+ return affectedUser;
+ }
+
+ public void setCurrentUser( String currentUser )
+ {
+ this.currentUser = currentUser;
+ }
+
+ public String getCurrentUser()
+ {
+ return currentUser;
+ }
+
+ public void log()
+ {
+ // TODO: it would be better to push this into the login interceptor so it is always set consistently
+ // (same for IP address)
+ if ( currentUser != null )
+ {
+ MDC.put( "redback.currentUser", currentUser );
+ }
+
+ if ( affectedUser != null )
+ {
+ if ( role != null )
+ {
+ logger.info( action, affectedUser, role );
+ }
+ else
+ {
+ logger.info( action, affectedUser );
+
+ }
+ }
+ }
+}
--- /dev/null
+package org.apache.archiva.redback.struts2.action;
+
+/*
+ * 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.
+ */
+
+public interface CancellableAction
+{
+ public static final String CANCEL = "cancel";
+
+ /**
+ * Returns the cancel result.
+ *
+ * A basic implementation would simply be to return CANCEL.
+ * @return
+ */
+ String cancel();
+}
--- /dev/null
+package org.apache.archiva.redback.struts2.action;
+
+/*
+ * 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.keys.AuthenticationKey;
+import org.apache.archiva.redback.policy.AccountLockedException;
+import org.apache.archiva.redback.users.User;
+import org.apache.struts2.ServletActionContext;
+import org.apache.archiva.redback.authentication.AuthenticationConstants;
+import org.apache.archiva.redback.authentication.AuthenticationDataSource;
+import org.apache.archiva.redback.authentication.AuthenticationException;
+import org.apache.archiva.redback.authentication.AuthenticationResult;
+import org.apache.archiva.redback.authentication.PasswordBasedAuthenticationDataSource;
+import org.apache.archiva.redback.authentication.TokenBasedAuthenticationDataSource;
+import org.apache.archiva.redback.configuration.UserConfiguration;
+import org.apache.archiva.redback.keys.KeyManagerException;
+import org.apache.archiva.redback.keys.KeyNotFoundException;
+import org.apache.archiva.redback.policy.MustChangePasswordException;
+import org.apache.archiva.redback.system.SecuritySession;
+import org.apache.archiva.redback.system.SecuritySystem;
+import org.apache.archiva.redback.users.UserNotFoundException;
+import org.codehaus.plexus.util.StringUtils;
+import org.apache.archiva.redback.integration.interceptor.SecureActionBundle;
+import org.apache.archiva.redback.integration.interceptor.SecureActionException;
+import org.apache.archiva.redback.integration.util.AutoLoginCookies;
+import org.springframework.context.annotation.Scope;
+import org.springframework.stereotype.Controller;
+
+import javax.inject.Inject;
+import java.util.Arrays;
+import java.util.Date;
+
+/**
+ * LoginAction
+ *
+ * @author Jesse McConnell <jmcconnell@apache.org>
+ * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
+ * @version $Id$
+ */
+@Controller( "redback-login" )
+@Scope( "prototype" )
+public class LoginAction
+ extends AbstractSecurityAction
+ implements CancellableAction
+{
+ private static final String LOGIN_SUCCESS = "security-login-success";
+
+ private static final String PASSWORD_CHANGE = "security-must-change-password";
+
+ private static final String ACCOUNT_LOCKED = "security-login-locked";
+
+ // ------------------------------------------------------------------
+ // Component Requirements
+ // ------------------------------------------------------------------
+
+ /**
+ *
+ */
+ @Inject
+ protected SecuritySystem securitySystem;
+
+ private String username;
+
+ private String password;
+
+ private String validateMe;
+
+ private String resetPassword;
+
+ private boolean rememberMe;
+
+ /**
+ *
+ */
+ @Inject
+ private AutoLoginCookies autologinCookies;
+
+ /**
+ *
+ */
+ @Inject
+ private UserConfiguration config;
+
+ // ------------------------------------------------------------------
+ // Action Entry Points - (aka Names)
+ // ------------------------------------------------------------------
+
+ public String show()
+ {
+ return INPUT;
+ }
+
+ /**
+ * 1) check if this is a validation authentication action
+ * 2) check if this is a reset password authentication action
+ * 3) sets up a password based authentication and passes on to webLogin()
+ *
+ * @return
+ */
+ public String login()
+ {
+ if ( StringUtils.isNotEmpty( validateMe ) )
+ {
+ // Process a login / validate request.
+ return validated();
+ }
+
+ if ( StringUtils.isNotEmpty( resetPassword ) )
+ {
+ // Process a login / reset password request.
+ return resetPassword();
+ }
+
+ if ( StringUtils.isEmpty( username ) )
+ {
+ addFieldError( "username", getText( "username.required" ) );
+ return ERROR;
+ }
+
+ PasswordBasedAuthenticationDataSource authdatasource = new PasswordBasedAuthenticationDataSource();
+ authdatasource.setPrincipal( username );
+ authdatasource.setPassword( password );
+
+ return webLogin( authdatasource, rememberMe );
+ }
+
+ /**
+ * 1) sets up a token based authentication
+ * 2) forces a password change requirement to the user
+ * 3) passes on to webLogin()
+ *
+ * @return
+ */
+ public String resetPassword()
+ {
+ if ( StringUtils.isEmpty( resetPassword ) )
+ {
+ addActionError( getText( "reset.password.missing" ) );
+ return ERROR;
+ }
+
+ try
+ {
+ AuthenticationKey authkey = securitySystem.getKeyManager().findKey( resetPassword );
+
+ User user = securitySystem.getUserManager().findUser( authkey.getForPrincipal() );
+
+ user.setPasswordChangeRequired( true );
+ user.setEncodedPassword( "" );
+
+ TokenBasedAuthenticationDataSource authsource = new TokenBasedAuthenticationDataSource();
+ authsource.setPrincipal( user.getPrincipal().toString() );
+ authsource.setToken( authkey.getKey() );
+ authsource.setEnforcePasswordChange( false );
+
+ securitySystem.getUserManager().updateUser( user );
+
+ AuditEvent event = new AuditEvent( getText( "log.password.change" ) );
+ event.setAffectedUser( username );
+ event.log();
+
+ return webLogin( authsource, false );
+ }
+ catch ( KeyNotFoundException e )
+ {
+ log.info( "Invalid key requested: {}", resetPassword );
+ addActionError( getText( "cannot.find.key" ) );
+ return ERROR;
+ }
+ catch ( KeyManagerException e )
+ {
+ addActionError( getText( "cannot.find.key.at.the.moment" ) );
+ log.warn( "Key Manager error: ", e );
+ return ERROR;
+ }
+ catch ( UserNotFoundException e )
+ {
+ addActionError( getText( "cannot.find.user" ) );
+ return ERROR;
+ }
+ }
+
+ /**
+ * 1) sets up a token based authentication
+ * 2) forces a password change requirement to the user
+ * 3) passes on to webLogin()
+ *
+ * @return
+ */
+ public String validated()
+ {
+ if ( StringUtils.isEmpty( validateMe ) )
+ {
+ addActionError( getText( "validation.failure.key.missing" ) );
+ return ERROR;
+ }
+
+ try
+ {
+ AuthenticationKey authkey = securitySystem.getKeyManager().findKey( validateMe );
+
+ User user = securitySystem.getUserManager().findUser( authkey.getForPrincipal() );
+
+ user.setValidated( true );
+ user.setLocked( false );
+ user.setPasswordChangeRequired( true );
+ user.setEncodedPassword( "" );
+
+ TokenBasedAuthenticationDataSource authsource = new TokenBasedAuthenticationDataSource();
+ authsource.setPrincipal( user.getPrincipal().toString() );
+ authsource.setToken( authkey.getKey() );
+ authsource.setEnforcePasswordChange( false );
+
+ securitySystem.getUserManager().updateUser( user );
+ String currentUser = getCurrentUser();
+
+ AuditEvent event = new AuditEvent( getText( "log.account.validation" ) );
+ event.setAffectedUser( username );
+ event.setCurrentUser( currentUser );
+ event.log();
+
+ return webLogin( authsource, false );
+ }
+ catch ( KeyNotFoundException e )
+ {
+ log.info( "Invalid key requested: {}", validateMe );
+ addActionError( getText( "cannot.find.key" ) );
+ return ERROR;
+ }
+ catch ( KeyManagerException e )
+ {
+ addActionError( getText( "cannot.find.key.at.the.momment" ) );
+ return ERROR;
+ }
+ catch ( UserNotFoundException e )
+ {
+ addActionError( getText( "cannot.find.user" ) );
+ return ERROR;
+ }
+ }
+
+ public String cancel()
+ {
+ return CANCEL;
+ }
+
+ public String getUsername()
+ {
+ return username;
+ }
+
+ public void setUsername( String username )
+ {
+ this.username = username;
+ }
+
+ public String getPassword()
+ {
+ return password;
+ }
+
+ public void setPassword( String password )
+ {
+ this.password = password;
+ }
+
+ public String getValidateMe()
+ {
+ return validateMe;
+ }
+
+ public void setValidateMe( String validateMe )
+ {
+ this.validateMe = validateMe;
+ }
+
+ public SecureActionBundle initSecureActionBundle()
+ throws SecureActionException
+ {
+ return SecureActionBundle.OPEN;
+ }
+
+ public String getResetPassword()
+ {
+ return resetPassword;
+ }
+
+ public void setResetPassword( String resetPassword )
+ {
+ this.resetPassword = resetPassword;
+ }
+
+ public boolean isRememberMe()
+ {
+ return rememberMe;
+ }
+
+ public void setRememberMe( boolean rememberMe )
+ {
+ this.rememberMe = rememberMe;
+ }
+
+
+ /**
+ * 1) attempts to authentication based on the passed in data source
+ * 2) if successful sets cookies and returns LOGIN_SUCCESS
+ * 3) if failure then check what kinda failure and return error
+ *
+ * @param authdatasource
+ * @param rememberMe
+ * @return
+ */
+ private String webLogin( AuthenticationDataSource authdatasource, boolean rememberMe )
+ {
+ // An attempt should log out your authentication tokens first!
+ setAuthTokens( null );
+
+ clearErrorsAndMessages();
+
+ // TODO: share this section with AutoLoginInterceptor
+ try
+ {
+ SecuritySession securitySession = securitySystem.authenticate( authdatasource );
+
+ if ( securitySession.isAuthenticated() )
+ {
+ // Success! Create tokens.
+ setAuthTokens( securitySession );
+
+ if ( securitySystem.getPolicy().getUserValidationSettings().isEmailValidationRequired() )
+ {
+ if ( !securitySession.getUser().getUsername().equals(
+ config.getString( "redback.default.admin" ) ) )
+ {
+ if ( !securitySession.getUser().isValidated() )
+ {
+ setAuthTokens( null );
+ // NOTE: this text is the same as incorrect.username.password to avoid exposing actual account existence
+ addActionError( getText( "account.validation.required" ) );
+ return ERROR;
+ }
+ }
+ }
+
+ setCookies( authdatasource, rememberMe );
+
+ AuditEvent event = new AuditEvent( getText( "log.login.success" ) );
+ event.setAffectedUser( username );
+ event.log();
+
+ User user = securitySession.getUser();
+ user.setLastLoginDate( new Date() );
+ securitySystem.getUserManager().updateUser( user );
+
+ if ( StringUtils.isNotEmpty( validateMe ) )
+ {
+ try
+ {
+ //REDBACK-146: delete key after validating so user won't be able to use it the second time around
+ securitySystem.getKeyManager().deleteKey( validateMe );
+ }
+ catch ( KeyManagerException e )
+ {
+ addActionError( getText( "cannot.find.key.at.the.momment" ) );
+ return ERROR;
+ }
+ }
+
+ return LOGIN_SUCCESS;
+ }
+ else
+ {
+ log.debug( "Login Action failed against principal : {}",
+ securitySession.getAuthenticationResult().getPrincipal(),
+ securitySession.getAuthenticationResult().getException() );
+
+ AuthenticationResult result = securitySession.getAuthenticationResult();
+ if ( result.getExceptionsMap() != null && !result.getExceptionsMap().isEmpty() )
+ {
+ if ( result.getExceptionsMap().get( AuthenticationConstants.AUTHN_NO_SUCH_USER ) != null )
+ {
+ addActionError( getText( "incorrect.username.password" ) );
+ }
+ else
+ {
+ addActionError( getText( "authentication.failed" ) );
+ }
+ }
+ else
+ {
+ addActionError( getText( "authentication.failed" ) );
+ }
+
+ AuditEvent event = new AuditEvent( getText( "log.login.fail" ) );
+ event.setAffectedUser( username );
+ event.log();
+
+ return ERROR;
+ }
+ }
+ catch ( AuthenticationException ae )
+ {
+ addActionError( getText( "authentication.exception", Arrays.asList( (Object) ae.getMessage() ) ) );
+ return ERROR;
+ }
+ catch ( UserNotFoundException ue )
+ {
+ addActionError(
+ getText( "user.not.found.exception", Arrays.asList( (Object) username, ue.getMessage() ) ) );
+
+ AuditEvent event = new AuditEvent( getText( "log.login.fail" ) );
+ event.setAffectedUser( username );
+ event.log();
+ return ERROR;
+ }
+ catch ( AccountLockedException e )
+ {
+ addActionError( getText( "account.locked" ) );
+
+ AuditEvent event = new AuditEvent( getText( "log.login.fail.locked" ) );
+ event.setAffectedUser( username );
+ event.log();
+ return ACCOUNT_LOCKED;
+ }
+ catch ( MustChangePasswordException e )
+ {
+ // TODO: preferably we would not set the cookies for this "partial" login state
+ setCookies( authdatasource, rememberMe );
+
+ AuditEvent event = new AuditEvent( getText( "log.login.fail.locked" ) );
+ event.setAffectedUser( username );
+ event.log();
+ return PASSWORD_CHANGE;
+ }
+ }
+
+ private void setCookies( AuthenticationDataSource authdatasource, boolean rememberMe )
+ {
+ if ( rememberMe )
+ {
+ autologinCookies.setRememberMeCookie( authdatasource.getPrincipal(), ServletActionContext.getResponse(),
+ ServletActionContext.getRequest() );
+ }
+ autologinCookies.setSignonCookie( authdatasource.getPrincipal(), ServletActionContext.getResponse(),
+ ServletActionContext.getRequest() );
+ }
+}
--- /dev/null
+package org.apache.archiva.redback.struts2.action;
+
+/*
+ * 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.struts2.ServletActionContext;
+import org.apache.struts2.dispatcher.SessionMap;
+import org.codehaus.plexus.cache.Cache;
+import org.apache.archiva.redback.integration.interceptor.SecureActionBundle;
+import org.apache.archiva.redback.integration.interceptor.SecureActionException;
+import org.apache.archiva.redback.integration.util.AutoLoginCookies;
+import org.springframework.context.annotation.Scope;
+import org.springframework.stereotype.Controller;
+
+import javax.inject.Inject;
+import javax.inject.Named;
+
+/**
+ * LogoutAction
+ *
+ * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
+ * @version $Id$
+ */
+@Controller( "redback-logout" )
+@Scope( "prototype" )
+public class LogoutAction
+ extends AbstractSecurityAction
+{
+ // Result Names.
+ private static final String LOGOUT = "security-logout";
+
+ /**
+ * cache used for user assignments
+ *
+ * role-hint="userAssignments"
+ */
+ @Inject
+ @Named( value = "cache#userAssignments" )
+ private Cache userAssignmentsCache;
+
+ /**
+ * cache used for user permissions
+ *
+ * role-hint="userPermissions"
+ */
+ @Inject
+ @Named( value = "cache#userPermissions" )
+ private Cache userPermissionsCache;
+
+ /**
+ * Cache used for users
+ *
+ * role-hint="users"
+ */
+ @Inject
+ @Named( value = "cache#users" )
+ private Cache usersCache;
+
+ /**
+ *
+ */
+ @Inject
+ private AutoLoginCookies autologinCookies;
+
+ public String logout()
+ {
+ if ( getSecuritySession().getUser() == null )
+ {
+ return LOGOUT;
+ }
+
+ String currentUser = (String) getSecuritySession().getUser().getPrincipal();
+
+ if ( getSecuritySession() != null )
+ {
+ // [PLXREDBACK-65] this is a bit of a hack around the cached managers since they don't have the ability to
+ // purge their caches through the API. Instead try and bring them in here and invalidate
+ // the keys directly. This will not be required once we move to a different model for pre-calculated
+ // permission sets since that will not have the overhead that required these caches in the first place.
+ Object principal = (String) getSecuritySession().getUser().getPrincipal();
+ if ( userAssignmentsCache != null )
+ {
+ userAssignmentsCache.remove( principal );
+ }
+ if ( userPermissionsCache != null )
+ {
+ userPermissionsCache.remove( principal );
+ }
+ if ( usersCache != null )
+ {
+ usersCache.remove( principal );
+ }
+ }
+
+ autologinCookies.removeRememberMeCookie( ServletActionContext.getResponse(),
+ ServletActionContext.getRequest() );
+ autologinCookies.removeSignonCookie( ServletActionContext.getResponse(), ServletActionContext.getRequest() );
+
+ setAuthTokens( null );
+
+ if ( session != null )
+ {
+ ( (SessionMap) session ).invalidate();
+ }
+
+ AuditEvent event = new AuditEvent( getText( "log.logout.success" ) );
+ event.setAffectedUser( currentUser );
+ event.log();
+
+ return LOGOUT;
+ }
+
+ public SecureActionBundle initSecureActionBundle()
+ throws SecureActionException
+ {
+ return SecureActionBundle.OPEN;
+ }
+}
--- /dev/null
+package org.apache.archiva.redback.struts2.action;
+
+/*
+ * 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.PasswordRuleViolations;
+import org.apache.archiva.redback.users.User;
+import org.apache.archiva.redback.policy.PasswordRuleViolationException;
+import org.apache.archiva.redback.system.SecuritySession;
+import org.apache.archiva.redback.system.SecuritySystem;
+import org.apache.archiva.redback.users.UserNotFoundException;
+import org.codehaus.plexus.util.StringUtils;
+import org.apache.archiva.redback.integration.interceptor.SecureActionBundle;
+import org.apache.archiva.redback.integration.interceptor.SecureActionException;
+import org.springframework.context.annotation.Scope;
+import org.springframework.stereotype.Controller;
+
+import javax.inject.Inject;
+import java.util.Arrays;
+import java.util.Map;
+
+/**
+ * PasswordAction
+ *
+ * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
+ * @version $Id$
+ */
+@Controller( "redback-password" )
+@Scope( "prototype" )
+public class PasswordAction
+ extends AbstractSecurityAction
+ implements CancellableAction
+{
+ // ------------------------------------------------------------------
+ // Plexus Component Requirements
+ // ------------------------------------------------------------------
+
+ protected static final String CHANGE_PASSWORD_SUCCESS = "security-change-password-success";
+
+ /**
+ *
+ */
+ @Inject
+ protected SecuritySystem securitySystem;
+
+ // ------------------------------------------------------------------
+ // Action Parameters
+ // ------------------------------------------------------------------
+
+ private String existingPassword;
+
+ private String newPassword;
+
+ private String newPasswordConfirm;
+
+ private String targetUrl;
+
+ private boolean provideExisting;
+
+ public String show()
+ {
+ provideExisting = StringUtils.isNotEmpty( getSecuritySession().getUser().getEncodedPassword() );
+ return INPUT;
+ }
+
+ public String submit()
+ {
+ final SecuritySession securitySession = getSecuritySession();
+
+ provideExisting = StringUtils.isNotEmpty( securitySession.getUser().getEncodedPassword() );
+
+ if ( StringUtils.isEmpty( newPassword ) )
+ {
+ addFieldError( "newPassword", getText( "newPassword.cannot.be.empty" ) );
+ }
+
+ if ( !StringUtils.equals( newPassword, newPasswordConfirm ) )
+ {
+ addFieldError( "newPassword", getText( "password.confimation.failed" ) );
+ }
+
+ User user = securitySession.getUser();
+
+ // Test existing Password.
+ PasswordEncoder encoder = securitySystem.getPolicy().getPasswordEncoder();
+
+ if ( provideExisting )
+ {
+ if ( !encoder.isPasswordValid( user.getEncodedPassword(), existingPassword ) )
+ {
+ addFieldError( "existingPassword", getText( "password.provided.does.not.match.existing" ) );
+ }
+ }
+
+ // Validate the Password.
+ try
+ {
+ User tempUser = securitySystem.getUserManager().createUser( "temp", "temp", "temp" );
+ tempUser.setPassword( newPassword );
+ securitySystem.getPolicy().validatePassword( tempUser );
+ }
+ catch ( PasswordRuleViolationException e )
+ {
+ PasswordRuleViolations violations = e.getViolations();
+
+ if ( violations != null )
+ {
+ for ( String violation : violations.getLocalizedViolations() )
+ {
+ addFieldError( "newPassword", violation );
+ }
+ }
+ }
+
+ // Toss error (if any exists)
+ if ( hasActionErrors() || hasFieldErrors() || hasActionMessages() )
+ {
+ newPassword = "";
+ newPasswordConfirm = "";
+ existingPassword = "";
+ return ERROR;
+ }
+
+ // We can save the new password.
+ try
+ {
+ String encodedPassword = encoder.encodePassword( newPassword );
+ user.setEncodedPassword( encodedPassword );
+ user.setPassword( newPassword );
+ // TODO: (address this) check once more for password policy, some policies may require additional information
+ // only available in the actual user object, perhaps the thing to do is add a deep cloning mechanism
+ // to user so we can validate this with a test user. Its ok to just set and test it here before
+ // setting the updateUser, but logically its better to maintain a clear separation here
+ securitySystem.getPolicy().validatePassword( user );
+ securitySystem.getUserManager().updateUser( user );
+ }
+ catch ( UserNotFoundException e )
+ {
+ addActionError( getText( "cannot.update.user.not.found", Arrays.asList( (Object) user.getUsername() ) ) );
+ addActionError( getText( "admin.deleted.account" ) );
+
+ return ERROR;
+ }
+ catch ( PasswordRuleViolationException e )
+ {
+ PasswordRuleViolations violations = e.getViolations();
+
+ if ( violations != null )
+ {
+ for ( String violation : violations.getLocalizedViolations() )
+ {
+ addFieldError( "newPassword", violation );
+ }
+ }
+ // [REDBACK-30] when the password is one of the previous 6, it throws exception here, but since the user
+ // object is in the session we need to clear out the encodedPassword otherwise the flow will change and think
+ // it needs to have existingPassword which isn't set on some reset password checks
+ if ( !provideExisting )
+ {
+ user.setEncodedPassword( "" );
+ user.setPassword( "" );
+ }
+
+ return ERROR;
+ }
+
+ log.info( "Password Change Request Success." );
+ String currentUser = getCurrentUser();
+ AuditEvent event = new AuditEvent( getText( "log.password.change" ) );
+ event.setAffectedUser( user.getUsername() );
+ event.setCurrentUser( currentUser );
+ event.log();
+
+ if ( !securitySession.isAuthenticated() )
+ {
+ log.debug( "User is not authenticated." );
+ return REQUIRES_AUTHENTICATION;
+ }
+
+ /*
+ * If provide existing is true, then this was a normal password change flow, if it is
+ * false then it is changing the password from the registration flow in which case direct to
+ * external link
+ */
+ if ( !provideExisting )
+ {
+ return CHANGE_PASSWORD_SUCCESS;
+ }
+ else
+ {
+
+ if ( super.session != null )
+ {
+
+ Map<String, Object> map = (Map<String, Object>) super.session;
+ String url = "";
+ if ( map.containsKey( "targetUrl" ) )
+ {
+ url = map.remove( "targetUrl" ).toString();
+ log.info( "targetUrl is retrieved and removed from the session: {}", url );
+ }
+ else
+ {
+ log.info( "targetUrl is empty, redirect to change password success page" );
+ return CHANGE_PASSWORD_SUCCESS;
+ }
+ setTargetUrl( url );
+ }
+ return SUCCESS;
+ }
+ }
+
+ public String cancel()
+ {
+ return CANCEL;
+ }
+
+ // ------------------------------------------------------------------
+ // Parameter Accessor Methods
+ // ------------------------------------------------------------------
+
+ public String getExistingPassword()
+ {
+ return existingPassword;
+ }
+
+ public void setExistingPassword( String existingPassword )
+ {
+ this.existingPassword = existingPassword;
+ }
+
+ public String getNewPassword()
+ {
+ return newPassword;
+ }
+
+ public void setNewPassword( String newPassword )
+ {
+ this.newPassword = newPassword;
+ }
+
+ public String getNewPasswordConfirm()
+ {
+ return newPasswordConfirm;
+ }
+
+ public void setNewPasswordConfirm( String newPasswordConfirm )
+ {
+ this.newPasswordConfirm = newPasswordConfirm;
+ }
+
+ public boolean isProvideExisting()
+ {
+ return provideExisting;
+ }
+
+ public void setProvideExisting( boolean provideExisting )
+ {
+ // Do nothing.
+ }
+
+ public SecureActionBundle initSecureActionBundle()
+ throws SecureActionException
+ {
+ return SecureActionBundle.AUTHONLY;
+ }
+
+ public String getTargetUrl()
+ {
+ return targetUrl;
+ }
+
+ public void setTargetUrl( String targetUrl )
+ {
+ this.targetUrl = targetUrl;
+ }
+}
--- /dev/null
+package org.apache.archiva.redback.struts2.action;
+
+/*
+ * 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.keys.KeyManager;
+import org.apache.archiva.redback.policy.UserSecurityPolicy;
+import org.apache.archiva.redback.users.UserManager;
+import org.apache.archiva.redback.users.UserNotFoundException;
+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.User;
+import org.codehaus.plexus.util.StringUtils;
+import org.apache.archiva.redback.integration.interceptor.SecureActionBundle;
+import org.apache.archiva.redback.integration.interceptor.SecureActionException;
+import org.apache.archiva.redback.integration.mail.Mailer;
+import org.springframework.context.annotation.Scope;
+import org.springframework.stereotype.Controller;
+
+import javax.inject.Inject;
+import java.util.Arrays;
+
+/**
+ * PasswordResetAction
+ *
+ * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
+ * @version $Id$
+ */
+@Controller( "redback-password-reset" )
+@Scope( "prototype" )
+public class PasswordResetAction
+ extends AbstractSecurityAction
+ implements CancellableAction
+{
+ // ------------------------------------------------------------------
+ // Component Requirements
+ // ------------------------------------------------------------------
+
+ /**
+ *
+ */
+ @Inject
+ private Mailer mailer;
+
+ /**
+ *
+ */
+ @Inject
+ private SecuritySystem securitySystem;
+
+ private String username;
+
+ // ------------------------------------------------------------------
+ // Action Entry Points - (aka Names)
+ // ------------------------------------------------------------------
+
+ public String show()
+ {
+ return INPUT;
+ }
+
+ public String reset()
+ {
+ if ( StringUtils.isEmpty( username ) )
+ {
+ addFieldError( "username", getText( "username.cannot.be.empty" ) );
+ return INPUT;
+ }
+
+ UserManager userManager = securitySystem.getUserManager();
+ KeyManager keyManager = securitySystem.getKeyManager();
+ UserSecurityPolicy policy = securitySystem.getPolicy();
+
+ try
+ {
+ User user = userManager.findUser( username );
+
+ AuthenticationKey authkey = keyManager.createKey( username, "Password Reset Request",
+ policy.getUserValidationSettings().getEmailValidationTimeout() );
+
+ mailer.sendPasswordResetEmail( Arrays.asList( user.getEmail() ), authkey, getBaseUrl() );
+
+ AuditEvent event = new AuditEvent( getText( "log.password.reset.request" ) );
+ event.setAffectedUser( username );
+ event.log();
+
+ addActionMessage( getText( "password.reset.success" ) );
+ }
+ catch ( UserNotFoundException e )
+ {
+ // By default, the success and failure messages are the same.
+ // This is done to prevent a malicious user from attempting to ascertain the
+ // validity of usernames.
+ addActionMessage( getText( "password.reset.failure" ) );
+
+ log.info( "Password Reset on non-existant user [{}].", username );
+ }
+ catch ( KeyManagerException e )
+ {
+ addActionError( getText( "password.reset.email.generation.failure" ) );
+ log.info( "Unable to issue password reset.", e );
+ }
+
+ return INPUT;
+ }
+
+ // ------------------------------------------------------------------
+ // Security Specification
+ // ------------------------------------------------------------------
+
+ public SecureActionBundle initSecureActionBundle()
+ throws SecureActionException
+ {
+ return SecureActionBundle.OPEN;
+ }
+
+ public String cancel()
+ {
+ return NONE;
+ }
+
+ // ------------------------------------------------------------------
+ // Parameter Accessor Methods
+ // ------------------------------------------------------------------
+
+ public String getUsername()
+ {
+ return username;
+ }
+
+ public void setUsername( String username )
+ {
+ this.username = username;
+ }
+
+}
--- /dev/null
+package org.apache.archiva.redback.struts2.action;
+
+/*
+ * 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 java.util.Map;
+
+import org.apache.struts2.interceptor.SessionAware;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.opensymphony.xwork2.ActionSupport;
+
+/**
+ *
+ * @author <a href="mailto:james@atlassian.com">James William Dumay</a>
+ */
+public abstract class RedbackActionSupport
+ extends ActionSupport
+ implements SessionAware
+{
+ protected Logger log = LoggerFactory.getLogger( this.getClass() );
+
+ protected Map<String,Object> session;
+
+ public void setSession( Map<String, Object > map )
+ {
+ //noinspection AssignmentToCollectionOrArrayFieldFromParameter
+ this.session = map;
+ }
+}
--- /dev/null
+package org.apache.archiva.redback.struts2.action;
+
+/*
+ * 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.keys.AuthenticationKey;
+import org.apache.archiva.redback.policy.UserSecurityPolicy;
+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.keys.KeyManagerException;
+import org.apache.archiva.redback.users.UserManager;
+import org.apache.archiva.redback.users.UserNotFoundException;
+import org.apache.archiva.redback.integration.interceptor.SecureActionBundle;
+import org.apache.archiva.redback.integration.interceptor.SecureActionException;
+import org.apache.archiva.redback.integration.mail.Mailer;
+import org.apache.archiva.redback.integration.model.CreateUserCredentials;
+import org.apache.archiva.redback.integration.security.role.RedbackRoleConstants;
+import org.springframework.context.annotation.Scope;
+import org.springframework.stereotype.Controller;
+
+import javax.inject.Inject;
+import java.util.Arrays;
+
+/**
+ * RegisterAction
+ *
+ * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
+ * @version $Id$
+ */
+@Controller( "redback-register" )
+@Scope( "prototype" )
+public class RegisterAction
+ extends AbstractUserCredentialsAction
+ implements CancellableAction
+{
+ protected static final String REGISTER_SUCCESS = "security-register-success";
+
+ private static final String VALIDATION_NOTE = "validation-note";
+
+ private static final String RESEND_VALIDATION_EMAIL = "security-resend-validation-email";
+
+ // ------------------------------------------------------------------
+ // Component Requirements
+ // ------------------------------------------------------------------
+
+ /**
+ *
+ */
+ @Inject
+ private Mailer mailer;
+
+ /**
+ *
+ */
+ @Inject
+ private RoleManager roleManager;
+
+ private CreateUserCredentials user;
+
+ private boolean emailValidationRequired;
+
+ private String username;
+
+ // ------------------------------------------------------------------
+ // Action Entry Points - (aka Names)
+ // ------------------------------------------------------------------
+
+ public String show()
+ {
+ if ( user == null )
+ {
+ user = new CreateUserCredentials();
+ }
+
+ emailValidationRequired = securitySystem.getPolicy().getUserValidationSettings().isEmailValidationRequired();
+
+ return INPUT;
+ }
+
+ public String register()
+ {
+ if ( user == null )
+ {
+ user = new CreateUserCredentials();
+ addActionError( getText( "invalid.user.credentials" ) );
+ return ERROR;
+ }
+
+ UserSecurityPolicy securityPolicy = securitySystem.getPolicy();
+
+ emailValidationRequired = securityPolicy.getUserValidationSettings().isEmailValidationRequired();
+
+ internalUser = user;
+
+ if ( securityPolicy.getUserValidationSettings().isEmailValidationRequired() )
+ {
+ validateCredentialsLoose();
+ }
+ else
+ {
+ validateCredentialsStrict();
+ }
+
+ // NOTE: Do not perform Password Rules Validation Here.
+ UserManager manager = super.securitySystem.getUserManager();
+
+ if ( manager.userExists( user.getUsername() ) )
+ {
+ // Means that the role name doesn't exist.
+ // We need to fail fast and return to the previous page.
+ addActionError( getText( "user.already.exists", Arrays.asList( (Object) user.getUsername() ) ) );
+ }
+
+ if ( hasActionErrors() || hasFieldErrors() )
+ {
+ return ERROR;
+ }
+
+ User u = manager.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 )
+ {
+ addActionError( getText( "assign.role.failure" ) );
+ log.error( "RoleProfile Error: " + rpe.getMessage(), rpe );
+ return ERROR;
+ }
+
+ if ( securityPolicy.getUserValidationSettings().isEmailValidationRequired() )
+ {
+ 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 );
+ manager.addUser( u );
+
+ return VALIDATION_NOTE;
+ }
+ catch ( KeyManagerException e )
+ {
+ addActionError( getText( "cannot.register.user" ) );
+ log.error( "Unable to register a new user.", e );
+ return ERROR;
+ }
+ finally
+ {
+ securityPolicy.setEnabled( true );
+ }
+ }
+ else
+ {
+ manager.addUser( u );
+ }
+
+ AuditEvent event = new AuditEvent( getText( "log.account.create" ) );
+ event.setAffectedUser( username );
+ event.log();
+
+ return REGISTER_SUCCESS;
+ }
+
+ public String resendRegistrationEmail()
+ {
+ UserSecurityPolicy securityPolicy = securitySystem.getPolicy();
+
+ try
+ {
+ User user = super.securitySystem.getUserManager().findUser( username );
+
+ AuthenticationKey authkey =
+ securitySystem.getKeyManager().createKey( user.getPrincipal().toString(), "New User Email Validation",
+ securityPolicy.getUserValidationSettings().getEmailValidationTimeout() );
+
+ mailer.sendAccountValidationEmail( Arrays.asList( user.getEmail() ), authkey, getBaseUrl() );
+
+ return RESEND_VALIDATION_EMAIL;
+ }
+ catch ( KeyManagerException e )
+ {
+ addActionError( getText( "cannot.register.user" ) );
+ log.error( "Unable to register a new user.", e );
+ return ERROR;
+ }
+ catch ( UserNotFoundException e )
+ {
+ addActionError( getText( "cannot.find.user" ) );
+ log.error( "Unable to find user.", e );
+ return ERROR;
+ }
+ }
+
+ public String cancel()
+ {
+ return CANCEL;
+ }
+
+ // ------------------------------------------------------------------
+ // Parameter Accessor Methods
+ // ------------------------------------------------------------------
+
+ public CreateUserCredentials getUser()
+ {
+ return user;
+ }
+
+ public void setUser( CreateUserCredentials user )
+ {
+ this.user = user;
+ }
+
+ public boolean isEmailValidationRequired()
+ {
+ return emailValidationRequired;
+ }
+
+ public void setEmailValidationRequired( boolean emailValidationRequired )
+ {
+ this.emailValidationRequired = emailValidationRequired;
+ }
+
+ public String getUsername()
+ {
+ return username;
+ }
+
+ public void setUsername( String username )
+ {
+ this.username = username;
+ }
+
+ public SecureActionBundle initSecureActionBundle()
+ throws SecureActionException
+ {
+ return SecureActionBundle.OPEN;
+ }
+}
--- /dev/null
+package org.apache.archiva.redback.struts2.action;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import org.codehaus.plexus.util.StringUtils;
+import org.springframework.context.annotation.Scope;
+import org.springframework.stereotype.Controller;
+
+/**
+ * SecurityRedirectAction
+ *
+ * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
+ * @version $Id$
+ */
+@Controller( "redback-redirect" )
+@Scope( "prototype" )
+public class SecurityRedirectAction
+ extends RedbackActionSupport
+{
+ private String externalResult;
+
+ public String redirect()
+ {
+ if ( StringUtils.isNotEmpty( externalResult ) )
+ {
+ return externalResult;
+ }
+
+ return SUCCESS;
+ }
+
+ public String getExternalResult()
+ {
+ return externalResult;
+ }
+
+ public void setExternalResult( String name )
+ {
+ this.externalResult = name;
+ }
+}
--- /dev/null
+package org.apache.archiva.redback.struts2.action.admin;
+
+/*
+ * 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.struts2.action.AbstractUserCredentialsAction;
+
+/**
+ * AbstractAdminUserCredentialsAction
+ *
+ * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
+ * @version $Id$
+ */
+public abstract class AbstractAdminUserCredentialsAction
+ extends AbstractUserCredentialsAction
+{
+ private String username;
+
+ public String getUsername()
+ {
+ return username;
+ }
+
+ public void setUsername( String username )
+ {
+ this.username = username;
+ }
+}
--- /dev/null
+package org.apache.archiva.redback.struts2.action.admin;
+
+/*
+ * 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.configuration.UserConfiguration;
+import org.apache.archiva.redback.policy.MustChangePasswordException;
+import org.apache.archiva.redback.role.RoleManager;
+import org.apache.archiva.redback.role.RoleManagerException;
+import org.apache.archiva.redback.struts2.action.AuditEvent;
+import org.apache.archiva.redback.users.UserManager;
+import org.apache.struts2.ServletActionContext;
+import org.apache.archiva.redback.authentication.AuthenticationConstants;
+import org.apache.archiva.redback.authentication.AuthenticationDataSource;
+import org.apache.archiva.redback.authentication.AuthenticationResult;
+import org.apache.archiva.redback.authentication.PasswordBasedAuthenticationDataSource;
+import org.apache.archiva.redback.policy.AccountLockedException;
+import org.apache.archiva.redback.system.SecuritySession;
+import org.apache.archiva.redback.users.User;
+import org.apache.archiva.redback.users.UserNotFoundException;
+import org.apache.archiva.redback.integration.interceptor.SecureActionBundle;
+import org.apache.archiva.redback.integration.interceptor.SecureActionException;
+import org.apache.archiva.redback.integration.model.EditUserCredentials;
+import org.apache.archiva.redback.integration.util.AutoLoginCookies;
+import org.springframework.context.annotation.Scope;
+import org.springframework.stereotype.Controller;
+
+import javax.inject.Inject;
+import java.util.Arrays;
+import java.util.Date;
+
+/**
+ * AddAdminUserAction
+ *
+ * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
+ * @version $Id$
+ */
+@Controller( "redback-admin-account" )
+@Scope( "prototype" )
+public class AddAdminUserAction
+ extends AbstractAdminUserCredentialsAction
+{
+ private static final String LOGIN_ERROR = "login-error";
+
+ private static final String LOGIN_SUCCESS = "security-login-success";
+
+ private static final String PASSWORD_CHANGE = "security-must-change-password";
+
+ private static final String ACCOUNT_LOCKED = "security-login-locked";
+
+ @Inject
+ private RoleManager roleManager;
+
+
+ @Inject
+ private UserConfiguration config;
+
+ private EditUserCredentials user;
+
+ @Inject
+ private AutoLoginCookies autologinCookies;
+
+ public String show()
+ {
+ if ( user == null )
+ {
+ user = new EditUserCredentials( config.getString( "redback.default.admin" ) );
+ }
+
+ return INPUT;
+ }
+
+ /**
+ * TODO this must done in a service !!
+ * @return
+ */
+ public String submit()
+ {
+ if ( user == null )
+ {
+ user = new EditUserCredentials( config.getString( "redback.default.admin" ) );
+ addActionError( getText( "invalid.admin.credentials" ) );
+ return ERROR;
+ }
+
+ log.info( "user = {}", user );
+
+ internalUser = user;
+
+ validateCredentialsStrict();
+
+ UserManager userManager = super.securitySystem.getUserManager();
+
+ if ( userManager.userExists( config.getString( "redback.default.admin" ) ) )
+ {
+ // Means that the role name exist already.
+ // We need to fail fast and return to the previous page.
+ addActionError( getText( "admin.user.already.exists" ) );
+ return ERROR;
+ }
+
+ if ( hasActionErrors() || hasFieldErrors() )
+ {
+ return ERROR;
+ }
+
+ User u =
+ userManager.createUser( config.getString( "redback.default.admin" ), user.getFullName(), user.getEmail() );
+ if ( u == null )
+ {
+ addActionError( getText( "cannot.operate.on.null.user" ) );
+ return ERROR;
+ }
+
+ u.setPassword( user.getPassword() );
+ u.setLocked( false );
+ u.setPasswordChangeRequired( false );
+ u.setPermanent( true );
+
+ userManager.addUser( u );
+
+ AuditEvent event = new AuditEvent( getText( "log.account.create" ) );
+ event.setAffectedUser( u.getUsername() );
+ event.log();
+
+ try
+ {
+ roleManager.assignRole( "system-administrator", u.getPrincipal().toString() );
+ event = new AuditEvent( getText( "log.assign.role" ) );
+ event.setAffectedUser( u.getUsername() );
+ event.setRole( "system-administrator" );
+ event.log();
+ }
+ catch ( RoleManagerException rpe )
+ {
+ addActionError( getText( "cannot.assign.admin.role" ) );
+ return ERROR;
+ }
+
+ PasswordBasedAuthenticationDataSource authdatasource = new PasswordBasedAuthenticationDataSource();
+ authdatasource.setPrincipal( user.getUsername() );
+ authdatasource.setPassword( user.getPassword() );
+
+ return webLogin( authdatasource );
+ }
+
+ public EditUserCredentials getUser()
+ {
+ return user;
+ }
+
+ public void setUser( EditUserCredentials user )
+ {
+ this.user = user;
+ }
+
+ public SecureActionBundle initSecureActionBundle()
+ throws SecureActionException
+ {
+ return SecureActionBundle.OPEN;
+ }
+
+ /**
+ * 1) attempts to authentication based on the passed in data source
+ * 2) if successful sets cookies and returns LOGIN_SUCCESS
+ * 3) if failure then check what kinda failure and return error
+ *
+ * @param authdatasource
+ * @return
+ */
+ private String webLogin( AuthenticationDataSource authdatasource )
+ {
+ // An attempt should log out your authentication tokens first!
+ setAuthTokens( null );
+
+ clearErrorsAndMessages();
+
+ String principal = authdatasource.getPrincipal();
+
+ try
+ {
+ SecuritySession securitySession = securitySystem.authenticate( authdatasource );
+
+ if ( securitySession.getAuthenticationResult().isAuthenticated() )
+ {
+ // Success! Create tokens.
+ setAuthTokens( securitySession );
+
+ setCookies( authdatasource );
+
+ AuditEvent event = new AuditEvent( getText( "log.login.success" ) );
+ event.setAffectedUser( principal );
+ event.log();
+
+ User u = securitySession.getUser();
+ u.setLastLoginDate( new Date() );
+ securitySystem.getUserManager().updateUser( u );
+
+ return LOGIN_SUCCESS;
+ }
+ else
+ {
+ log.debug( "Login Action failed against principal : {}",
+ securitySession.getAuthenticationResult().getPrincipal(),
+ securitySession.getAuthenticationResult().getException() );
+
+ AuthenticationResult result = securitySession.getAuthenticationResult();
+ if ( result.getExceptionsMap() != null && !result.getExceptionsMap().isEmpty() )
+ {
+ if ( result.getExceptionsMap().get( AuthenticationConstants.AUTHN_NO_SUCH_USER ) != null )
+ {
+ addActionError( getText( "incorrect.username.password" ) );
+ }
+ else
+ {
+ addActionError( getText( "authentication.failed" ) );
+ }
+ }
+ else
+ {
+ addActionError( getText( "authentication.failed" ) );
+ }
+
+ AuditEvent event = new AuditEvent( getText( "log.login.fail" ) );
+ event.setAffectedUser( principal );
+ event.log();
+
+ return LOGIN_ERROR;
+ }
+ }
+ catch ( AuthenticationException ae )
+ {
+ addActionError( getText( "authentication.exception", Arrays.asList( (Object) ae.getMessage() ) ) );
+ return LOGIN_ERROR;
+ }
+ catch ( UserNotFoundException ue )
+ {
+ addActionError(
+ getText( "user.not.found.exception", Arrays.asList( (Object) principal, ue.getMessage() ) ) );
+
+ AuditEvent event = new AuditEvent( getText( "log.login.fail" ) );
+ event.setAffectedUser( principal );
+ event.log();
+ return LOGIN_ERROR;
+ }
+ catch ( AccountLockedException e )
+ {
+ addActionError( getText( "account.locked" ) );
+
+ AuditEvent event = new AuditEvent( getText( "log.login.fail.locked" ) );
+ event.setAffectedUser( principal );
+ event.log();
+ return ACCOUNT_LOCKED;
+ }
+ catch ( MustChangePasswordException e )
+ {
+ // TODO: preferably we would not set the cookies for this "partial" login state
+ setCookies( authdatasource );
+
+ AuditEvent event = new AuditEvent( getText( "log.login.fail.locked" ) );
+ event.setAffectedUser( principal );
+ event.log();
+ return PASSWORD_CHANGE;
+ }
+ }
+
+ private void setCookies( AuthenticationDataSource authdatasource )
+ {
+ autologinCookies.setSignonCookie( authdatasource.getPrincipal(), ServletActionContext.getResponse(),
+ ServletActionContext.getRequest() );
+ }
+}
--- /dev/null
+package org.apache.archiva.redback.struts2.action.admin;
+
+/*
+ * 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.Resource;
+import org.apache.archiva.redback.struts2.action.AbstractSecurityAction;
+import org.apache.archiva.redback.integration.interceptor.SecureActionBundle;
+import org.apache.archiva.redback.integration.interceptor.SecureActionException;
+import org.apache.archiva.redback.integration.role.RoleConstants;
+import org.springframework.context.annotation.Scope;
+import org.springframework.stereotype.Controller;
+
+/**
+ * AdminConsoleAction
+ *
+ * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
+ * @version $Id$
+ */
+@Controller("redback-admin-console")
+@Scope("prototype")
+public class AdminConsoleAction
+ extends AbstractSecurityAction
+{
+ public String show()
+ {
+ return INPUT;
+ }
+
+ public SecureActionBundle initSecureActionBundle()
+ throws SecureActionException
+ {
+ SecureActionBundle bundle = new SecureActionBundle();
+ bundle.setRequiresAuthentication( true );
+ bundle.addRequiredAuthorization( RoleConstants.CONFIGURATION_EDIT_OPERATION, Resource.GLOBAL );
+ bundle.addRequiredAuthorization( RoleConstants.USER_MANAGEMENT_RBAC_ADMIN_OPERATION, Resource.GLOBAL );
+ bundle.addRequiredAuthorization( RoleConstants.USER_MANAGEMENT_ROLE_DROP_OPERATION, Resource.GLOBAL );
+ bundle.addRequiredAuthorization( RoleConstants.USER_MANAGEMENT_ROLE_GRANT_OPERATION, Resource.GLOBAL );
+ bundle.addRequiredAuthorization( RoleConstants.USER_MANAGEMENT_USER_CREATE_OPERATION, Resource.GLOBAL );
+ bundle.addRequiredAuthorization( RoleConstants.USER_MANAGEMENT_USER_DELETE_OPERATION, Resource.GLOBAL );
+ bundle.addRequiredAuthorization( RoleConstants.USER_MANAGEMENT_USER_EDIT_OPERATION, Resource.GLOBAL );
+ bundle.addRequiredAuthorization( RoleConstants.USER_MANAGEMENT_USER_LIST_OPERATION, Resource.GLOBAL );
+ return bundle;
+ }
+}
--- /dev/null
+package org.apache.archiva.redback.struts2.action.admin;
+
+/*
+ * 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.Resource;
+import org.apache.archiva.redback.rbac.Role;
+import org.apache.archiva.redback.rbac.UserAssignment;
+import org.apache.archiva.redback.role.RoleManager;
+import org.apache.archiva.redback.struts2.action.AbstractUserCredentialsAction;
+import org.apache.archiva.redback.users.User;
+import org.apache.archiva.redback.users.UserNotFoundException;
+import org.apache.archiva.redback.rbac.RbacManagerException;
+import org.codehaus.plexus.redback.role.model.ModelApplication;
+import org.apache.archiva.redback.struts2.action.AuditEvent;
+import org.apache.archiva.redback.struts2.model.ApplicationRoleDetails;
+import org.apache.archiva.redback.struts2.model.ApplicationRoleDetails.RoleTableCell;
+import org.apache.archiva.redback.users.UserManager;
+import org.codehaus.plexus.util.StringUtils;
+import org.apache.archiva.redback.integration.interceptor.SecureActionBundle;
+import org.apache.archiva.redback.integration.interceptor.SecureActionException;
+import org.apache.archiva.redback.integration.model.AdminEditUserCredentials;
+import org.apache.archiva.redback.integration.role.RoleConstants;
+import org.springframework.context.annotation.Scope;
+import org.springframework.stereotype.Controller;
+
+import javax.inject.Inject;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
+
+/**
+ * AssignmentsAction
+ *
+ * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
+ * @version $Id$
+ */
+@Controller("redback-assignments")
+@Scope("prototype")
+public class AssignmentsAction
+ extends AbstractUserCredentialsAction
+{
+ // ------------------------------------------------------------------
+ // Component Requirements
+ // ------------------------------------------------------------------
+
+ /**
+ * role-hint="default"
+ */
+ @Inject
+ private RoleManager rmanager;
+
+ // ------------------------------------------------------------------
+ // Action Parameters
+ // ------------------------------------------------------------------
+
+ private String principal;
+
+ private AdminEditUserCredentials user;
+
+ /**
+ * A List of {@link Role} objects.
+ */
+ private List<Role> assignedRoles;
+
+ /**
+ * A List of {@link Role} objects.
+ */
+ private List<Role> availableRoles;
+
+ private List<Role> effectivelyAssignedRoles;
+
+ /**
+ * List of names (received from client) of dynamic roles to set/unset
+ */
+ private List<String> addDSelectedRoles;
+
+ /**
+ * List of names (received from client) of nondynamic roles to set/unset
+ */
+ private List<String> addNDSelectedRoles;
+
+ private List<Role> nondynamicroles;
+
+ private List<Role> dynamicroles;
+
+ private List<String> NDRoles;
+
+ private List<String> DRoles;
+
+ private List<ApplicationRoleDetails> applicationRoleDetails = new ArrayList<ApplicationRoleDetails>();
+
+ // ------------------------------------------------------------------
+ // Action Entry Points - (aka Names)
+ // ------------------------------------------------------------------
+
+ public List<ApplicationRoleDetails> getApplicationRoleDetails()
+ {
+ return applicationRoleDetails;
+ }
+
+ /**
+ * Display the edit user panel. <p/> This should consist of the Role details for the specified user. <p/> A table of
+ * currently assigned roles. This table should have a column to remove the role from the user. This table should
+ * also have a column of checkboxes that can be selected and then removed from the user. <p/> A table of roles that
+ * can be assigned. This table should have a set of checkboxes that can be selected and then added to the user. <p/>
+ * Duplicate role assignment needs to be taken care of.
+ *
+ * @throws RbacManagerException
+ * @throws org.apache.archiva.redback.rbac.RbacObjectNotFoundException
+ */
+ @SuppressWarnings( "unchecked" )
+ public String show()
+ throws RbacManagerException
+ {
+ this.addNDSelectedRoles = new ArrayList<String>();
+ this.addDSelectedRoles = new ArrayList<String>();
+
+ if ( StringUtils.isEmpty( principal ) )
+ {
+ addActionError( getText( "rbac.edit.user.empty.principal" ) );
+ return ERROR;
+ }
+
+ UserManager userManager = super.securitySystem.getUserManager();
+
+ if ( !userManager.userExists( principal ) )
+ {
+ addActionError( getText( "user.does.not.exist", new String[]{principal} ) );
+ return ERROR;
+ }
+
+ try
+ {
+ User u = userManager.findUser( principal );
+
+ if ( u == null )
+ {
+ addActionError( getText( "cannot.operate.on.null.user" ) );
+ return ERROR;
+ }
+
+ user = new AdminEditUserCredentials( u );
+ }
+ catch ( UserNotFoundException e )
+ {
+ addActionError( getText( "user.not.found.exception", Arrays.asList( ( Object ) principal, e.getMessage() ) ) );
+ return ERROR;
+ }
+
+ // check first if role assignments for user exist
+ if ( !getManager().userAssignmentExists( principal ) )
+ {
+ UserAssignment assignment = getManager().createUserAssignment( principal );
+ getManager().saveUserAssignment( assignment );
+ }
+
+ List<Role> assignableRoles = getFilteredRolesForCurrentUserAccess();
+ List<ApplicationRoleDetails> appRoleDetails = lookupAppRoleDetails( principal, assignableRoles );
+ applicationRoleDetails.addAll( appRoleDetails );
+
+ return SUCCESS;
+ }
+
+ @SuppressWarnings( "unchecked" )
+ private List<ApplicationRoleDetails> lookupAppRoleDetails( String principal, List<Role> assignableRoles )
+ throws RbacManagerException
+ {
+ List<ApplicationRoleDetails> appRoleDetails = new ArrayList<ApplicationRoleDetails>();
+ for ( Iterator<ModelApplication> i = rmanager.getModel().getApplications().iterator(); i.hasNext(); )
+ {
+ ModelApplication application = i.next();
+ ApplicationRoleDetails details =
+ new ApplicationRoleDetails( application, getManager().getEffectivelyAssignedRoles( principal ),
+ getManager().getAssignedRoles( principal ), assignableRoles );
+ appRoleDetails.add( details );
+ }
+ return appRoleDetails;
+ }
+
+ /**
+ * Applies role additions and removals and then displays the edit user panel.
+ *
+ * @return
+ */
+ public String edituser()
+ {
+ try
+ {
+ Collection<Role> assignedRoles = getManager().getAssignedRoles( principal );
+ List<Role> assignableRoles = getFilteredRolesForCurrentUserAccess();
+
+ // Compute set of roles usable by configured apps, add/del from this set only
+ List<ApplicationRoleDetails> appRoleDetails = lookupAppRoleDetails( principal, assignableRoles );
+ applicationRoleDetails.addAll( appRoleDetails );
+
+ Set<String> availableAppRoleNames = new HashSet<String>();
+ for ( ApplicationRoleDetails appRoleDetail : applicationRoleDetails )
+ {
+ availableAppRoleNames.addAll( appRoleDetail.getAssignedRoles() );
+ availableAppRoleNames.addAll( appRoleDetail.getAvailableRoles() );
+
+ // Add dynamic roles offered on page
+ for ( List<RoleTableCell> row : appRoleDetail.getTable() )
+ {
+ for ( RoleTableCell col : row )
+ {
+ if ( !col.isLabel() )
+ {
+ availableAppRoleNames.add( col.getName() );
+ }
+ }
+ }
+ }
+
+ Set<Role> availableRoles = new HashSet<Role>( assignedRoles );
+ availableRoles.addAll( assignableRoles );
+
+ // Filter the available roles so we only consider configured app roles
+ Iterator<Role> availableRoleIterator = availableRoles.iterator();
+ while ( availableRoleIterator.hasNext() )
+ {
+ Role availableRole = availableRoleIterator.next();
+ if ( !availableAppRoleNames.contains( availableRole.getName() ) )
+ {
+ availableRoleIterator.remove();
+ }
+ }
+
+ List<String> selectedRoleNames = new ArrayList<String>();
+ addSelectedRoles( availableRoles, selectedRoleNames, addNDSelectedRoles );
+ addSelectedRoles( availableRoles, selectedRoleNames, addDSelectedRoles );
+
+ List<String> newRoles = new ArrayList<String>( selectedRoleNames );
+ String currentUser = getCurrentUser();
+ for ( Role assignedRole : assignedRoles )
+ {
+ if ( !selectedRoleNames.contains( assignedRole.getName() ) )
+ {
+ // removing a currently assigned role, check if we have permission
+ if ( !availableRoles.contains( assignedRole )
+ || !checkRoleName( assignableRoles, assignedRole.getName() ) )
+ {
+ // it may have not been on the page. Leave it assigned.
+ selectedRoleNames.add( assignedRole.getName() );
+ }
+ else
+ {
+ String role = assignedRole.getName();
+ AuditEvent event = new AuditEvent( getText( "log.revoke.role" ) );
+ event.setAffectedUser( principal );
+ event.setRole( role );
+ event.setCurrentUser( currentUser );
+ event.log();
+ }
+ }
+ else
+ {
+ newRoles.remove( assignedRole.getName() );
+ }
+ }
+ for ( String r : newRoles )
+ {
+ AuditEvent event = new AuditEvent( getText( "log.assign.role" ) );
+ event.setAffectedUser( principal );
+ event.setRole( r );
+ event.setCurrentUser( currentUser );
+ event.log();
+ }
+
+ UserAssignment assignment;
+
+ if ( getManager().userAssignmentExists( principal ) )
+ {
+ assignment = getManager().getUserAssignment( principal );
+ }
+ else
+ {
+ assignment = getManager().createUserAssignment( principal );
+ }
+
+ assignment.setRoleNames( selectedRoleNames );
+
+ assignment = getManager().saveUserAssignment( assignment );
+ }
+ catch ( RbacManagerException ne )
+ {
+ addActionError( getText( "error.removing.selected.roles", Arrays.asList( ( Object ) ne.getMessage() ) ) );
+ return ERROR;
+ }
+ return SUCCESS;
+ }
+
+ private void addSelectedRoles( Collection<Role> assignableRoles, List<String> roles, List<String> selectedRoles )
+ {
+ if ( selectedRoles != null )
+ {
+ for ( String r : selectedRoles )
+ {
+ if ( checkRoleName( assignableRoles, r ) )
+ {
+ roles.add( r );
+ }
+ }
+ }
+ }
+
+ private boolean checkRoleName( Collection<Role> assignableRoles, String r )
+ {
+ for ( Role role : assignableRoles )
+ {
+ if ( role.getName().equals( r ) )
+ {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ // ------------------------------------------------------------------
+ // Parameter Accessor Methods
+ // ------------------------------------------------------------------
+
+ public List<Role> getAssignedRoles()
+ {
+ return assignedRoles;
+ }
+
+ public void setAssignedRoles( List<Role> assignedRoles )
+ {
+ this.assignedRoles = assignedRoles;
+ }
+
+ public List<Role> getAvailableRoles()
+ {
+ return availableRoles;
+ }
+
+ public void setAvailableRoles( List<Role> availableRoles )
+ {
+ this.availableRoles = availableRoles;
+ }
+
+ public List<Role> getEffectivelyAssignedRoles()
+ {
+ return effectivelyAssignedRoles;
+ }
+
+ public void setEffectivelyAssignedRoles( List<Role> effectivelyAssignedRoles )
+ {
+ this.effectivelyAssignedRoles = effectivelyAssignedRoles;
+ }
+
+ public String getPrincipal()
+ {
+ return principal;
+ }
+
+ public void setPrincipal( String principal )
+ {
+ this.principal = principal;
+ }
+
+ public void setUsername( String username )
+ {
+ this.principal = username;
+ }
+
+ public AdminEditUserCredentials getUser()
+ {
+ return user;
+ }
+
+ public SecureActionBundle initSecureActionBundle()
+ throws SecureActionException
+ {
+ SecureActionBundle bundle = new SecureActionBundle();
+ bundle.setRequiresAuthentication( true );
+ bundle.addRequiredAuthorization( RoleConstants.USER_MANAGEMENT_USER_EDIT_OPERATION, Resource.GLOBAL );
+ bundle.addRequiredAuthorization( RoleConstants.USER_MANAGEMENT_RBAC_ADMIN_OPERATION, Resource.GLOBAL );
+ bundle.addRequiredAuthorization( RoleConstants.USER_MANAGEMENT_ROLE_GRANT_OPERATION, Resource.GLOBAL );
+ bundle.addRequiredAuthorization( RoleConstants.USER_MANAGEMENT_ROLE_DROP_OPERATION, Resource.GLOBAL );
+ bundle.addRequiredAuthorization( RoleConstants.USER_MANAGEMENT_USER_ROLE_OPERATION, Resource.GLOBAL );
+
+ return bundle;
+ }
+
+ public List<Role> getNondynamicroles()
+ {
+ return nondynamicroles;
+ }
+
+ public void setNondynamicroles( List<Role> nondynamicroles )
+ {
+ this.nondynamicroles = nondynamicroles;
+ }
+
+ public List<Role> getDynamicroles()
+ {
+ return dynamicroles;
+ }
+
+ public void setDynamicroles( List<Role> dynamicroles )
+ {
+ this.dynamicroles = dynamicroles;
+ }
+
+ public List<String> getNDRoles()
+ {
+ return NDRoles;
+ }
+
+ public void setNDRoles( List<String> roles )
+ {
+ NDRoles = roles;
+ }
+
+ public List<String> getDRoles()
+ {
+ return DRoles;
+ }
+
+ public void setDRoles( List<String> roles )
+ {
+ DRoles = roles;
+ }
+
+ public List<String> getAddDSelectedRoles()
+ {
+ return addDSelectedRoles;
+ }
+
+ public void setAddDSelectedRoles( List<String> addDSelectedRoles )
+ {
+ this.addDSelectedRoles = addDSelectedRoles;
+ }
+
+ public List<String> getAddNDSelectedRoles()
+ {
+ return addNDSelectedRoles;
+ }
+
+ public void setAddNDSelectedRoles( List<String> addNDSelectedRoles )
+ {
+ this.addNDSelectedRoles = addNDSelectedRoles;
+ }
+}
--- /dev/null
+package org.apache.archiva.redback.struts2.action.admin;
+
+/*
+ * 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 java.io.File;
+import java.util.Date;
+
+/**
+ * A record of a backup directory for displaying the backup/restore page.
+ */
+public class BackupRecord
+ implements Comparable<BackupRecord>
+{
+ private final File directory;
+
+ private final Date date;
+
+ private final boolean userDatabase;
+
+ public BackupRecord( File directory )
+ {
+ this.directory = directory;
+
+ this.date = new Date( directory.lastModified() );
+
+ this.userDatabase = new File( directory, "users.xml" ).exists();
+ }
+
+ public File getDirectory()
+ {
+ return directory;
+ }
+
+ public Date getDate()
+ {
+ return date;
+ }
+
+ public boolean isUserDatabase()
+ {
+ return userDatabase;
+ }
+
+ public boolean isValidBackup()
+ {
+ return userDatabase;
+ }
+
+ public int compareTo( BackupRecord record )
+ {
+ return record.date.compareTo( this.date );
+ }
+}
--- /dev/null
+package org.apache.archiva.redback.struts2.action.admin;
+
+/*
+ * 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 com.opensymphony.xwork2.Preparable;
+import org.apache.archiva.redback.rbac.RBACManager;
+import org.apache.archiva.redback.rbac.Resource;
+import org.apache.archiva.redback.struts2.action.AbstractSecurityAction;
+import org.apache.commons.lang.StringUtils;
+import org.apache.archiva.redback.keys.KeyManager;
+import org.apache.archiva.redback.management.DataManagementTool;
+import org.apache.archiva.redback.users.UserManager;
+import org.apache.archiva.redback.integration.interceptor.SecureAction;
+import org.apache.archiva.redback.integration.interceptor.SecureActionBundle;
+import org.apache.archiva.redback.integration.interceptor.SecureActionException;
+import org.apache.archiva.redback.integration.role.RoleConstants;
+import org.springframework.context.annotation.Scope;
+import org.springframework.stereotype.Controller;
+
+import javax.inject.Inject;
+import javax.inject.Named;
+import java.io.File;
+import java.io.IOException;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Date;
+import java.util.List;
+import java.util.Locale;
+
+
+/**
+ * BackupRestoreAction
+ */
+@Controller( "backup-restore" )
+@Scope( "prototype" )
+public class BackupRestoreAction
+ extends AbstractSecurityAction
+ implements SecureAction, Preparable
+{
+ public final static String CUSTOM_ERROR = "custom_error";
+
+ /**
+ *
+ */
+ private File applicationHome = new File( "data" );
+
+ /**
+ * role-hint="jdo"
+ */
+ @Inject
+ private DataManagementTool dataManagementTool;
+
+ /**
+ * role-hint="jdo"
+ */
+ @Inject
+ @Named( value = "rBACManager#jdo" )
+ private RBACManager rbacManager;
+
+ /**
+ * role-hint="jdo"
+ */
+ @Inject
+ @Named( value = "userManager#jdo" )
+ private UserManager userManager;
+
+ /**
+ * role-hint="jdo"
+ */
+ @Inject
+ @Named( value = "keyManager#jdo" )
+ private KeyManager keyManager;
+
+ private File backupDirectory;
+
+ private String restoreDirectory;
+
+ private List<BackupRecord> previousBackups;
+
+ private boolean confirmed;
+
+ public static final String BACKUP_DIRECTORY = "user-backup-directory";
+
+ public String view()
+ throws Exception
+ {
+
+ retrievePreviousBackups();
+
+ return SUCCESS;
+ }
+
+ public String backup()
+ throws Exception
+ {
+
+ File backupDirectory = getTimestampedBackupDirectory();
+ backupDirectory.mkdirs();
+
+ log.info( "Backing up security database to {}", backupDirectory );
+ this.backupDatabase( backupDirectory );
+
+ log.info( "Done backing up security database" );
+
+ return SUCCESS;
+ }
+
+ public String restore()
+ throws Exception
+ {
+ if ( StringUtils.isEmpty( restoreDirectory ) )
+ {
+ addActionError( getText( "backupRestore.backup.empty.error" ) );
+ return CUSTOM_ERROR;
+ }
+
+ File restoreDirectory = new File( this.restoreDirectory );
+
+ boolean fileExists = restoreDirectory.exists() && restoreDirectory.isDirectory();
+ boolean isValidBackup = false;
+
+ if ( fileExists )
+ {
+ BackupRecord record = new BackupRecord( restoreDirectory );
+ isValidBackup = record.isValidBackup();
+ }
+
+ if ( !fileExists )
+ {
+ log.warn( "Backup: " + this.restoreDirectory + " not found." );
+ addActionError( getText( "backupRestore.backup.error" ) );
+ retrievePreviousBackups();
+ return CUSTOM_ERROR;
+ }
+ else if ( !isValidBackup )
+ {
+ log.warn( "Backup: " + this.restoreDirectory + " is not a valid backup directory." );
+ addActionError( getText( "backupRestore.backup.error" ) );
+ retrievePreviousBackups();
+ return CUSTOM_ERROR;
+ }
+
+ log.info( "Restoring security database from {}", this.restoreDirectory );
+ this.eraseDatabase();
+ this.restoreDatabase( restoreDirectory );
+ log.info( "Done restoring security database" );
+
+ return SUCCESS;
+ }
+
+
+ private void backupDatabase( File backupDirectory )
+ throws Exception
+ {
+
+ dataManagementTool.backupKeyDatabase( keyManager, backupDirectory );
+ dataManagementTool.backupRBACDatabase( rbacManager, backupDirectory );
+ dataManagementTool.backupUserDatabase( userManager, backupDirectory );
+ }
+
+ private void eraseDatabase()
+ {
+ dataManagementTool.eraseKeysDatabase( keyManager );
+ dataManagementTool.eraseRBACDatabase( rbacManager );
+ dataManagementTool.eraseUsersDatabase( userManager );
+ }
+
+ private void restoreDatabase( File backupDirectory )
+ throws Exception
+ {
+
+ dataManagementTool.restoreKeysDatabase( keyManager, backupDirectory );
+ dataManagementTool.restoreRBACDatabase( rbacManager, backupDirectory );
+ dataManagementTool.restoreUsersDatabase( userManager, backupDirectory );
+ }
+
+ public String getRestoreDirectory()
+ {
+ return restoreDirectory;
+ }
+
+ public void setRestoreDirectory( String restoreDirectory )
+ {
+ this.restoreDirectory = restoreDirectory;
+ }
+
+ private File getTimestampedBackupDirectory()
+ {
+ SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyyMMdd.HHmmss", Locale.US );
+ return new File( this.backupDirectory, dateFormat.format( new Date() ) );
+ }
+
+ public File getBackupDirectory()
+ {
+ return backupDirectory;
+ }
+
+ public List<BackupRecord> getPreviousBackups()
+ {
+ return previousBackups;
+ }
+
+ public void prepare()
+ {
+ backupDirectory = this.getFile( BACKUP_DIRECTORY );
+ retrievePreviousBackups();
+ }
+
+ private void retrievePreviousBackups()
+ {
+ previousBackups = new ArrayList<BackupRecord>();
+ File[] files = backupDirectory.listFiles();
+ if ( files != null )
+ {
+ for ( int i = 0; i < files.length; i++ )
+ {
+ File f = files[i];
+
+ if ( f.isDirectory() && !f.getName().startsWith( "." ) )
+ {
+ BackupRecord record = new BackupRecord( f );
+
+ if ( record.isValidBackup() )
+ {
+ previousBackups.add( record );
+ }
+ }
+ }
+ }
+ Collections.sort( previousBackups );
+ }
+
+ public boolean isConfirmed()
+ {
+ return confirmed;
+ }
+
+ public void setConfirmed( boolean confirmed )
+ {
+ this.confirmed = confirmed;
+ }
+
+ @Override
+ public SecureActionBundle initSecureActionBundle()
+ throws SecureActionException
+ {
+ SecureActionBundle bundle = new SecureActionBundle();
+ bundle.setRequiresAuthentication( true );
+ bundle.addRequiredAuthorization( RoleConstants.USER_MANAGEMENT_MANAGE_DATA, Resource.GLOBAL );
+ return bundle;
+ }
+
+ public File getFile( String filename )
+ {
+ if ( filename == null )
+ {
+ return null;
+ }
+
+ File f = null;
+
+ if ( filename != null && filename.length() != 0 )
+ {
+ f = new File( filename );
+
+ if ( !f.isAbsolute() )
+ {
+ f = new File( applicationHome, filename );
+ }
+ }
+
+ try
+ {
+ return f.getCanonicalFile();
+ }
+ catch ( IOException e )
+ {
+ return f;
+ }
+ }
+}
--- /dev/null
+package org.apache.archiva.redback.struts2.action.admin;
+
+/*
+ * 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.RbacManagerException;
+import org.apache.archiva.redback.rbac.Resource;
+import org.apache.archiva.redback.rbac.Role;
+import org.apache.archiva.redback.rbac.UserAssignment;
+import org.apache.archiva.redback.users.User;
+import org.apache.commons.lang.StringEscapeUtils;
+import org.apache.archiva.redback.struts2.action.AbstractUserCredentialsAction;
+import org.apache.archiva.redback.struts2.action.AuditEvent;
+import org.apache.archiva.redback.users.UserManager;
+import org.apache.archiva.redback.users.UserNotFoundException;
+import org.codehaus.plexus.util.StringUtils;
+import org.apache.archiva.redback.integration.interceptor.SecureActionBundle;
+import org.apache.archiva.redback.integration.interceptor.SecureActionException;
+import org.apache.archiva.redback.integration.security.role.RedbackRoleConstants;
+import org.springframework.context.annotation.Scope;
+import org.springframework.stereotype.Controller;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * EditRoleAction
+ *
+ * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
+ * @version $Id$
+ */
+@Controller( "redback-role-edit" )
+@Scope( "prototype" )
+public class EditRoleAction
+ extends AbstractUserCredentialsAction
+{
+ // ------------------------------------------------------------------
+ // Action Parameters
+ // ------------------------------------------------------------------
+
+ private String name;
+
+ private String description;
+
+ private String newDescription;
+
+ private List<String> childRoleNames = new ArrayList<String>();
+
+ private List<String> parentRoleNames = new ArrayList<String>();
+
+ private List<Permission> permissions = new ArrayList<Permission>();
+
+ private List<User> users = new ArrayList<User>();
+
+ private List<User> parentUsers = new ArrayList<User>();
+
+ private List<User> allUsers = new ArrayList<User>();
+
+ private List<String> usersList = new ArrayList<String>();
+
+ private List<String> availableUsers = new ArrayList<String>();
+
+ private List<String> currentUsers = new ArrayList<String>();
+
+ // ------------------------------------------------------------------
+ // Action Entry Points - (aka Names)
+ // ------------------------------------------------------------------
+
+ public String input()
+ {
+ if ( name == null )
+ {
+ addActionError( getText( "cannot.edit.null.role" ) );
+ return ERROR;
+ }
+
+ if ( StringUtils.isEmpty( name ) )
+ {
+ addActionError( getText( "cannot.edit.empty.role" ) );
+ return ERROR;
+ }
+
+ name = StringEscapeUtils.escapeXml( name );
+
+ if ( !getManager().roleExists( name ) )
+ {
+ // Means that the role name doesn't exist.
+ // We should exit early and not attempt to look up the role information.
+ return INPUT;
+ }
+
+ try
+ {
+ if ( !isAuthorized() )
+ {
+ log.warn( getCurrentUser() + " isn't authorized to access to the role '" + name + "'" );
+ addActionError( getText( "alert.message" ) );
+ return ERROR;
+ }
+
+ Role role = getManager().getRole( name );
+ if ( role == null )
+ {
+ addActionError( getText( "cannot.operate.null.role" ) );
+ return ERROR;
+ }
+
+ description = role.getDescription();
+ childRoleNames = role.getChildRoleNames();
+ Map<String, Role> parentRoles = getManager().getParentRoles( role );
+ for ( String roleName : parentRoles.keySet() )
+ {
+ parentRoleNames.add( roleName );
+ }
+ permissions = role.getPermissions();
+
+ //Get users of the current role
+ List<String> roles = new ArrayList<String>();
+ roles.add( name );
+ List<UserAssignment> userAssignments = getManager().getUserAssignmentsForRoles( roles );
+ users = new ArrayList<User>();
+ if ( userAssignments != null )
+ {
+ for ( UserAssignment userAssignment : userAssignments )
+ {
+ try
+ {
+ User user = getUserManager().findUser( userAssignment.getPrincipal() );
+ users.add( user );
+ }
+ catch ( UserNotFoundException e )
+ {
+ log.warn( "User '" + userAssignment.getPrincipal() + "' doesn't exist.", e );
+ }
+ }
+ }
+
+ //Get users of the parent roles
+ parentUsers = new ArrayList<User>();
+ if ( !parentRoles.isEmpty() )
+ {
+ List<UserAssignment> userParentAssignments =
+ getManager().getUserAssignmentsForRoles( parentRoles.keySet() );
+ if ( userParentAssignments != null )
+ {
+ for ( UserAssignment userAssignment : userParentAssignments )
+ {
+ try
+ {
+ User user = getUserManager().findUser( userAssignment.getPrincipal() );
+ parentUsers.add( user );
+ }
+ catch ( UserNotFoundException e )
+ {
+ log.warn( "User '" + userAssignment.getPrincipal() + "' doesn't exist.", e );
+ }
+ }
+ }
+ }
+ }
+ catch ( RbacManagerException e )
+ {
+ List<Object> list = new ArrayList<Object>();
+ list.add( name );
+ list.add( e.getMessage() );
+ addActionError( getText( "cannot.get.role", list ) );
+ return ERROR;
+ }
+
+ return INPUT;
+ }
+
+ private boolean isAuthorized()
+ throws RbacManagerException
+ {
+ List<Role> assignableRoles = getFilteredRolesForCurrentUserAccess();
+ boolean updatableRole = false;
+ for ( Role r : assignableRoles )
+ {
+ if ( r.getName().equalsIgnoreCase( name ) )
+ {
+ updatableRole = true;
+ }
+ }
+
+ return updatableRole;
+ }
+
+ public String edit()
+ {
+ String result = input();
+ if ( ERROR.equals( result ) )
+ {
+ return result;
+ }
+
+ newDescription = description;
+
+ //TODO: Remove all users defined in parent roles too
+ allUsers = getUserManager().getUsers();
+
+ for ( User user : users )
+ {
+ if ( allUsers.contains( user ) )
+ {
+ allUsers.remove( user );
+ }
+ }
+
+ for ( User user : parentUsers )
+ {
+ if ( allUsers.contains( user ) )
+ {
+ allUsers.remove( user );
+ }
+ }
+
+ return result;
+ }
+
+ public String save()
+ {
+ String result = input();
+ if ( ERROR.equals( result ) )
+ {
+ return result;
+ }
+
+ if ( name == null )
+ {
+ addActionError( getText( "cannot.edit.null.role" ) );
+ return ERROR;
+ }
+
+ if ( StringUtils.isEmpty( name ) )
+ {
+ addActionError( getText( "cannot.edit.empty.role" ) );
+ return ERROR;
+ }
+
+ try
+ {
+ Role role;
+ if ( getManager().roleExists( name ) )
+ {
+ role = getManager().getRole( name );
+ }
+ else
+ {
+ role = getManager().createRole( name );
+ }
+
+ //TODO: allow to modify childRoleNames and permissions
+ role.setDescription( newDescription );
+ //role.setChildRoleNames( childRoleNames );
+ //role.setPermissions( permissions );
+
+ getManager().saveRole( role );
+
+ List<Object> list = new ArrayList<Object>();
+ list.add( name );
+ String currentUser = getCurrentUser();
+ AuditEvent event = new AuditEvent( getText( "log.role.edit" ) );
+ event.setRole( name );
+ event.setCurrentUser( currentUser );
+ event.log();
+ addActionMessage( getText( "save.role.success", list ) );
+ }
+ catch ( RbacManagerException e )
+ {
+ List<Object> list = new ArrayList<Object>();
+ list.add( name );
+ list.add( e.getMessage() );
+ addActionError( getText( "cannot.get.role", list ) );
+ return ERROR;
+ }
+
+ return SUCCESS;
+ }
+
+ public String addUsers()
+ {
+ if ( availableUsers == null || availableUsers.isEmpty() )
+ {
+ return INPUT;
+ }
+
+ for ( String principal : availableUsers )
+ {
+ if ( !getUserManager().userExists( principal ) )
+ {
+ // Means that the role name doesn't exist.
+ // We need to fail fast and return to the previous page.
+ List<Object> list = new ArrayList<Object>();
+ list.add( principal );
+ addActionError( getText( "user.does.not.exist", list ) );
+ return ERROR;
+ }
+
+ try
+ {
+ UserAssignment assignment;
+
+ if ( getManager().userAssignmentExists( principal ) )
+ {
+ assignment = getManager().getUserAssignment( principal );
+ }
+ else
+ {
+ assignment = getManager().createUserAssignment( principal );
+ }
+
+ assignment.addRoleName( name );
+ assignment = getManager().saveUserAssignment( assignment );
+ log.info( "{} role assigned to {}", name, principal );
+ }
+ catch ( RbacManagerException e )
+ {
+ List<Object> list = new ArrayList<Object>();
+ list.add( principal );
+ list.add( e.getMessage() );
+ addActionError( getText( "cannot.assign.role", list ) );
+ return ERROR;
+ }
+ }
+
+ edit();
+ return SUCCESS;
+ }
+
+ public String removeUsers()
+ {
+ if ( currentUsers == null || currentUsers.isEmpty() )
+ {
+ return INPUT;
+ }
+
+ for ( String principal : currentUsers )
+ {
+ if ( !getUserManager().userExists( principal ) )
+ {
+ // Means that the role name doesn't exist.
+ // We need to fail fast and return to the previous page.
+ List<Object> list = new ArrayList<Object>();
+ list.add( principal );
+ addActionError( getText( "user.does.not.exist", list ) );
+ return ERROR;
+ }
+
+ try
+ {
+ UserAssignment assignment;
+
+ if ( getManager().userAssignmentExists( principal ) )
+ {
+ assignment = getManager().getUserAssignment( principal );
+ }
+ else
+ {
+ assignment = getManager().createUserAssignment( principal );
+ }
+
+ assignment.removeRoleName( name );
+ assignment = getManager().saveUserAssignment( assignment );
+ log.info( "{} role unassigned to {}", name, principal );
+ }
+ catch ( RbacManagerException e )
+ {
+ List<Object> list = new ArrayList<Object>();
+ list.add( principal );
+ list.add( e.getMessage() );
+ addActionError( getText( "cannot.assign.role", list ) );
+ return ERROR;
+ }
+ }
+
+ edit();
+ return SUCCESS;
+ }
+
+ private UserManager getUserManager()
+ {
+ return securitySystem.getUserManager();
+ }
+
+ // ------------------------------------------------------------------
+ // Parameter Accessor Methods
+ // ------------------------------------------------------------------
+
+ public String getName()
+ {
+ return name;
+ }
+
+ public void setName( String roleName )
+ {
+ this.name = roleName;
+ }
+
+ public List<String> getChildRoleNames()
+ {
+ return childRoleNames;
+ }
+
+ public void setChildRoleNames( List<String> childRoleNames )
+ {
+ this.childRoleNames = childRoleNames;
+ }
+
+ public String getDescription()
+ {
+ return description;
+ }
+
+ public void setDescription( String description )
+ {
+ this.description = description;
+ }
+
+ public String getNewDescription()
+ {
+ return newDescription;
+ }
+
+ public void setNewDescription( String newDescription )
+ {
+ this.newDescription = newDescription;
+ }
+
+ public List<Permission> getPermissions()
+ {
+ return permissions;
+ }
+
+ public void setPermissions( List<Permission> permissions )
+ {
+ this.permissions = permissions;
+ }
+
+ public List<User> getUsers()
+ {
+ return users;
+ }
+
+ public void setUsers( List<User> users )
+ {
+ this.users = users;
+ }
+
+ public List<User> getAllUsers()
+ {
+ return allUsers;
+ }
+
+ public void setAllUsers( List<User> allUsers )
+ {
+ this.allUsers = allUsers;
+ }
+
+ public List<String> getUsersList()
+ {
+ return usersList;
+ }
+
+ public void setUsersList( List<String> usersList )
+ {
+ this.usersList = usersList;
+ }
+
+ public List<String> getAvailableUsers()
+ {
+ return availableUsers;
+ }
+
+ public void setAvailableUsers( List<String> availableUsers )
+ {
+ this.availableUsers = availableUsers;
+ }
+
+ public List<String> getCurrentUsers()
+ {
+ return currentUsers;
+ }
+
+ public void setCurrentUsers( List<String> currentUsers )
+ {
+ this.currentUsers = currentUsers;
+ }
+
+ public List<String> getParentRoleNames()
+ {
+ return parentRoleNames;
+ }
+
+ public void setParentRoleNames( List<String> parentRoleNames )
+ {
+ this.parentRoleNames = parentRoleNames;
+ }
+
+ public List<User> getParentUsers()
+ {
+ return parentUsers;
+ }
+
+ public void setParentUsers( List<User> parentUsers )
+ {
+ this.parentUsers = parentUsers;
+ }
+
+ // ------------------------------------------------------------------
+ // Internal Support Methods
+ // ------------------------------------------------------------------
+
+ public SecureActionBundle initSecureActionBundle()
+ throws SecureActionException
+ {
+ SecureActionBundle bundle = new SecureActionBundle();
+ bundle.setRequiresAuthentication( true );
+ bundle.addRequiredAuthorization( RedbackRoleConstants.USER_MANAGEMENT_USER_EDIT_OPERATION, Resource.GLOBAL );
+ bundle.addRequiredAuthorization( RedbackRoleConstants.USER_MANAGEMENT_RBAC_ADMIN_OPERATION, Resource.GLOBAL );
+ bundle.addRequiredAuthorization( RedbackRoleConstants.USER_MANAGEMENT_ROLE_GRANT_OPERATION, Resource.GLOBAL );
+ bundle.addRequiredAuthorization( RedbackRoleConstants.USER_MANAGEMENT_ROLE_DROP_OPERATION, Resource.GLOBAL );
+ bundle.addRequiredAuthorization( RedbackRoleConstants.USER_MANAGEMENT_USER_ROLE_OPERATION, Resource.GLOBAL );
+ return bundle;
+ }
+}
--- /dev/null
+package org.apache.archiva.redback.struts2.action.admin;
+
+/*
+ * 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.Operation;
+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.struts2.action.RedbackActionSupport;
+import org.apache.archiva.redback.integration.interceptor.SecureActionBundle;
+import org.apache.archiva.redback.integration.interceptor.SecureActionException;
+import org.apache.archiva.redback.integration.role.RoleConstants;
+import org.apache.archiva.redback.integration.util.OperationSorter;
+import org.springframework.context.annotation.Scope;
+import org.springframework.stereotype.Controller;
+
+import javax.inject.Inject;
+import javax.inject.Named;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+/**
+ * OperationsAction:
+ *
+ * @author Jesse McConnell <jmcconnell@apache.org>
+ * @version $Id$
+ */
+@Controller( "redback-operations" )
+@Scope( "prototype" )
+public class OperationsAction
+ extends RedbackActionSupport
+{
+ private static final String LIST = "list";
+
+ /**
+ * role-hint="cached"
+ */
+ @Inject
+ @Named( value = "rBACManager#cached" )
+ private RBACManager manager;
+
+ private String operationName;
+
+ private String description;
+
+ private List<Operation> allOperations;
+
+ public String list()
+ {
+ try
+ {
+ allOperations = manager.getAllOperations();
+
+ if ( allOperations == null )
+ {
+ allOperations = Collections.emptyList();
+ }
+
+ Collections.sort( allOperations, new OperationSorter() );
+ }
+ catch ( RbacManagerException e )
+ {
+ addActionError( getText( "cannot.list.all.operations", Arrays.asList( (Object) e.getMessage() ) ) );
+ log.error( "System error:", e );
+ allOperations = Collections.emptyList();
+ }
+
+ return LIST;
+ }
+
+ public String save()
+ {
+ try
+ {
+ Operation temp = manager.createOperation( operationName );
+
+ temp.setDescription( description );
+
+ manager.saveOperation( temp );
+ }
+ catch ( RbacManagerException e )
+ {
+ addActionError( getText( "cannot.save.operation", Arrays.asList( (Object) operationName ) ) );
+ log.error( "System error:", e );
+ allOperations = Collections.emptyList();
+ }
+
+ return LIST;
+ }
+
+ public String remove()
+ {
+ try
+ {
+ manager.removeOperation( manager.getOperation( operationName ) );
+ }
+ catch ( RbacManagerException ne )
+ {
+ addActionError( getText( "cannot.remove.operation", Arrays.asList( (Object) operationName ) ) );
+ return ERROR;
+ }
+ return LIST;
+ }
+
+ public List<Operation> getAllOperations()
+ {
+ return allOperations;
+ }
+
+ public void setAllOperations( List<Operation> allOperations )
+ {
+ this.allOperations = allOperations;
+ }
+
+ public String getDescription()
+ {
+ return description;
+ }
+
+ public void setDescription( String description )
+ {
+ this.description = description;
+ }
+
+ public String getOperationName()
+ {
+ return operationName;
+ }
+
+ public void setOperationName( String operationName )
+ {
+ this.operationName = operationName;
+ }
+
+ public SecureActionBundle initSecureActionBundle()
+ throws SecureActionException
+ {
+ SecureActionBundle bundle = new SecureActionBundle();
+ bundle.setRequiresAuthentication( true );
+ bundle.addRequiredAuthorization( RoleConstants.USER_MANAGEMENT_RBAC_ADMIN_OPERATION, Resource.GLOBAL );
+ return bundle;
+ }
+}
--- /dev/null
+package org.apache.archiva.redback.struts2.action.admin;
+
+/*
+ * 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.Operation;
+import org.apache.archiva.redback.rbac.Permission;
+import org.apache.archiva.redback.rbac.RBACManager;
+import org.apache.archiva.redback.rbac.Resource;
+import org.apache.archiva.redback.rbac.RbacManagerException;
+import org.apache.archiva.redback.struts2.action.RedbackActionSupport;
+import org.codehaus.plexus.util.StringUtils;
+import org.apache.archiva.redback.integration.interceptor.SecureActionBundle;
+import org.apache.archiva.redback.integration.interceptor.SecureActionException;
+import org.apache.archiva.redback.integration.role.RoleConstants;
+import org.apache.archiva.redback.integration.util.PermissionSorter;
+import org.springframework.context.annotation.Scope;
+import org.springframework.stereotype.Controller;
+
+import javax.inject.Inject;
+import javax.inject.Named;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+/**
+ * PermissionsAction
+ *
+ * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
+ * @version $Id$
+ */
+@Controller( "redback-permissions" )
+@Scope( "prototype" )
+public class PermissionsAction
+ extends RedbackActionSupport
+{
+ private static final String LIST = "list";
+
+ // ------------------------------------------------------------------
+ // Plexus Component Requirements
+ // ------------------------------------------------------------------
+
+ /**
+ * role-hint="cached"
+ */
+ @Inject
+ @Named( value = "rBACManager#cached" )
+ private RBACManager manager;
+
+ // ------------------------------------------------------------------
+ // Action Parameters
+ // ------------------------------------------------------------------
+
+ private String name;
+
+ private String description;
+
+ private String operationName;
+
+ private String operationDescription;
+
+ private String resourceIdentifier;
+
+ private List<Permission> allPermissions;
+
+ // ------------------------------------------------------------------
+ // Action Entry Points - (aka Names)
+ // ------------------------------------------------------------------
+
+ public String list()
+ {
+ try
+ {
+ allPermissions = manager.getAllPermissions();
+
+ if ( allPermissions == null )
+ {
+ allPermissions = Collections.emptyList();
+ }
+
+ Collections.sort( allPermissions, new PermissionSorter() );
+ }
+ catch ( RbacManagerException e )
+ {
+ addActionError( getText( "cannot.list.all.permissions", Arrays.asList( (Object) e.getMessage() ) ) );
+ log.error( "System error:", e );
+ allPermissions = Collections.emptyList();
+ }
+
+ return LIST;
+ }
+
+ public String input()
+ {
+ if ( name == null )
+ {
+ addActionError( getText( "cannot.edit.null.permission" ) );
+ return ERROR;
+ }
+
+ if ( StringUtils.isEmpty( name ) )
+ {
+ addActionError( getText( "cannot.edit.empty.permission" ) );
+ return ERROR;
+ }
+
+ if ( !manager.permissionExists( name ) )
+ {
+ // Means that the permission name doesn't exist.
+ // We should exit early and not attempt to look up the permission information.
+ return LIST;
+ }
+
+ try
+ {
+ Permission permission = manager.getPermission( name );
+ if ( permission == null )
+ {
+ addActionError( getText( "cannot.operate.null.permission" ) );
+ return ERROR;
+ }
+
+ description = permission.getDescription();
+ Operation operation = permission.getOperation();
+ if ( operation != null )
+ {
+ operationName = operation.getName();
+ operationDescription = operation.getDescription();
+ }
+
+ Resource resource = permission.getResource();
+ if ( resource != null )
+ {
+ resourceIdentifier = resource.getIdentifier();
+ }
+ }
+ catch ( RbacManagerException e )
+ {
+ addActionError( getText( "cannot.get.permission", Arrays.asList( (Object) name, e.getMessage() ) ) );
+ return ERROR;
+ }
+
+ return LIST;
+ }
+
+ public String submit()
+ {
+ if ( name == null )
+ {
+ addActionError( getText( "cannot.edit.null.permission" ) );
+ return ERROR;
+ }
+
+ if ( StringUtils.isEmpty( name ) )
+ {
+ addActionError( getText( "cannot.edit.empty.permission" ) );
+ return ERROR;
+ }
+
+ try
+ {
+ Permission permission;
+ if ( manager.permissionExists( name ) )
+ {
+ permission = manager.getPermission( name );
+ }
+ else
+ {
+ permission = manager.createPermission( name );
+ }
+
+ permission.setDescription( description );
+
+ Operation operation = manager.createOperation( operationName );
+ if ( StringUtils.isNotEmpty( operationDescription ) )
+ {
+ operation.setDescription( operationDescription );
+ }
+ permission.setOperation( manager.saveOperation( operation ) );
+
+ Resource resource = manager.createResource( resourceIdentifier );
+ permission.setResource( manager.saveResource( resource ) );
+
+ manager.savePermission( permission );
+
+ addActionMessage( getText( "save.permission.success", Arrays.asList( (Object) name ) ) );
+ }
+ catch ( RbacManagerException e )
+ {
+ addActionError( getText( "cannot.get.permission", Arrays.asList( (Object) name, e.getMessage() ) ) );
+ return ERROR;
+ }
+
+ return LIST;
+ }
+
+ // ------------------------------------------------------------------
+ // Parameter Accessor Methods
+ // ------------------------------------------------------------------
+
+ public String getDescription()
+ {
+ return description;
+ }
+
+ public void setDescription( String description )
+ {
+ this.description = description;
+ }
+
+ public String getName()
+ {
+ return name;
+ }
+
+ public void setName( String name )
+ {
+ this.name = name;
+ }
+
+ public String getOperationDescription()
+ {
+ return operationDescription;
+ }
+
+ public void setOperationDescription( String operationDescription )
+ {
+ this.operationDescription = operationDescription;
+ }
+
+ public String getOperationName()
+ {
+ return operationName;
+ }
+
+ public void setOperationName( String operationName )
+ {
+ this.operationName = operationName;
+ }
+
+ public String getResourceIdentifier()
+ {
+ return resourceIdentifier;
+ }
+
+ public void setResourceIdentifier( String resourceIdentifier )
+ {
+ this.resourceIdentifier = resourceIdentifier;
+ }
+
+ public List<Permission> getAllPermissions()
+ {
+ return allPermissions;
+ }
+
+ public void setAllPermissions( List<Permission> allPermissions )
+ {
+ this.allPermissions = allPermissions;
+ }
+
+ public SecureActionBundle initSecureActionBundle()
+ throws SecureActionException
+ {
+ SecureActionBundle bundle = new SecureActionBundle();
+ bundle.setRequiresAuthentication( true );
+ bundle.addRequiredAuthorization( RoleConstants.USER_MANAGEMENT_RBAC_ADMIN_OPERATION, Resource.GLOBAL );
+ return bundle;
+ }
+}
--- /dev/null
+package org.apache.archiva.redback.struts2.action.admin;
+
+/*
+ * 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 java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.util.Arrays;
+
+import javax.inject.Inject;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.struts2.ServletActionContext;
+import org.apache.archiva.redback.rbac.Resource;
+import org.apache.archiva.redback.struts2.action.AbstractSecurityAction;
+import org.apache.archiva.redback.integration.interceptor.SecureActionBundle;
+import org.apache.archiva.redback.integration.interceptor.SecureActionException;
+import org.apache.archiva.redback.integration.reports.Report;
+import org.apache.archiva.redback.integration.reports.ReportException;
+import org.apache.archiva.redback.integration.reports.ReportManager;
+import org.apache.archiva.redback.integration.role.RoleConstants;
+
+import com.opensymphony.module.sitemesh.filter.PageResponseWrapper;
+import org.springframework.context.annotation.Scope;
+import org.springframework.stereotype.Controller;
+
+/**
+ * ReportAction
+ *
+ * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
+ * @version $Id$
+ */
+@Controller("redback-report")
+@Scope("prototype")
+public class ReportAction
+ extends AbstractSecurityAction
+{
+ /**
+ *
+ */
+ @Inject
+ private ReportManager reportManager;
+
+ private String reportId;
+
+ private String reportType;
+
+ public String generate()
+ {
+ Report report;
+ try
+ {
+ report = reportManager.findReport( reportId, reportType );
+ }
+ catch ( ReportException e )
+ {
+ addActionError( getText( "cannot.get.report", Arrays.asList( ( Object ) e.getMessage() ) ) );
+ return ERROR;
+ }
+
+ HttpServletResponse response = ServletActionContext.getResponse();
+
+ // HACK: Unwrap sitemesh response. (effectively disables sitemesh)
+ if ( response instanceof PageResponseWrapper )
+ {
+ response = (HttpServletResponse) ( (PageResponseWrapper) response ).getResponse();
+ }
+
+ try
+ {
+ ByteArrayOutputStream os = new ByteArrayOutputStream();
+ report.writeReport( os );
+
+ response.reset();
+ response.setContentType( report.getMimeType() );
+ response.addHeader( "Content-Disposition",
+ "attachment; filename=" + report.getId() + "." + report.getType() );
+ byte bytes[] = os.toByteArray();
+ response.setContentLength( bytes.length );
+ response.getOutputStream().write( bytes, 0, bytes.length );
+ response.getOutputStream().flush();
+ response.getOutputStream().close();
+
+ // Don't return a result.
+ return null;
+ }
+ catch ( ReportException e )
+ {
+ String emsg = getText( "cannot.generate.report" );
+ addActionError( emsg );
+ log.error( emsg, e );
+ return ERROR;
+ }
+ catch ( IOException e )
+ {
+ String emsg = getText( "cannot.generate.report" );
+ addActionError( emsg );
+ log.error( emsg, e );
+ return ERROR;
+ }
+ }
+
+ public SecureActionBundle initSecureActionBundle()
+ throws SecureActionException
+ {
+ SecureActionBundle bundle = new SecureActionBundle();
+ bundle.setRequiresAuthentication( true );
+ bundle.addRequiredAuthorization( RoleConstants.USER_MANAGEMENT_USER_LIST_OPERATION, Resource.GLOBAL );
+ return bundle;
+ }
+
+ public String getReportId()
+ {
+ return reportId;
+ }
+
+ public void setReportId( String reportId )
+ {
+ this.reportId = reportId;
+ }
+
+ public String getReportType()
+ {
+ return reportType;
+ }
+
+ public void setReportType( String reportType )
+ {
+ this.reportType = reportType;
+ }
+}
--- /dev/null
+package org.apache.archiva.redback.struts2.action.admin;
+
+/*
+ * 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.rbac.Resource;
+import org.apache.archiva.redback.rbac.RbacManagerException;
+import org.apache.archiva.redback.struts2.action.AbstractSecurityAction;
+import org.apache.archiva.redback.integration.interceptor.SecureActionBundle;
+import org.apache.archiva.redback.integration.interceptor.SecureActionException;
+import org.apache.archiva.redback.integration.role.RoleConstants;
+import org.apache.archiva.redback.integration.util.ResourceSorter;
+import org.springframework.context.annotation.Scope;
+import org.springframework.stereotype.Controller;
+
+import javax.inject.Inject;
+import javax.inject.Named;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+/**
+ * OperationsAction:
+ *
+ * @author Jesse McConnell <jmcconnell@apache.org>
+ * @version $Id$
+ */
+@Controller( "redback-resources" )
+@Scope( "prototype" )
+public class ResourcesAction
+ extends AbstractSecurityAction
+{
+ private static final String LIST = "list";
+
+ /**
+ * role-hint="cached"
+ */
+ @Inject
+ @Named( value = "rBACManager#cached" )
+ private RBACManager manager;
+
+ private String resourceIdentifier;
+
+ private boolean isPattern;
+
+ private List<Resource> allResources;
+
+ public String list()
+ {
+ try
+ {
+ allResources = manager.getAllResources();
+
+ if ( allResources == null )
+ {
+ allResources = Collections.emptyList();
+ }
+
+ Collections.sort( allResources, new ResourceSorter() );
+ }
+ catch ( RbacManagerException e )
+ {
+ addActionError( getText( "cannot.list.all.resources", Arrays.asList( (Object) e.getMessage() ) ) );
+ log.error( "System error:", e );
+ allResources = Collections.emptyList();
+ }
+
+ return LIST;
+ }
+
+ public String save()
+ {
+ try
+ {
+ Resource temp = manager.createResource( resourceIdentifier );
+
+ temp.setIdentifier( resourceIdentifier );
+ temp.setPattern( isPattern );
+
+ manager.saveResource( temp );
+ }
+ catch ( RbacManagerException e )
+ {
+ addActionError( getText( "cannot.save.resource", Arrays.asList( (Object) e.getMessage() ) ) );
+ log.error( "System error:", e );
+ allResources = Collections.emptyList();
+ }
+
+ return LIST;
+ }
+
+ public String remove()
+ {
+ try
+ {
+ manager.removeResource( manager.getResource( resourceIdentifier ) );
+ }
+ catch ( RbacManagerException ne )
+ {
+ addActionError( getText( "cannot.remove.resource", Arrays.asList( (Object) resourceIdentifier ) ) );
+ return ERROR;
+ }
+ return LIST;
+ }
+
+ public List<Resource> getAllResources()
+ {
+ return allResources;
+ }
+
+ public void setAllResources( List<Resource> allResources )
+ {
+ this.allResources = allResources;
+ }
+
+ public String getResourceIdentifier()
+ {
+ return resourceIdentifier;
+ }
+
+ public void setResourceIdentifier( String resourceIdentifier )
+ {
+ this.resourceIdentifier = resourceIdentifier;
+ }
+
+ public boolean isPattern()
+ {
+ return isPattern;
+ }
+
+ public void setPattern( boolean isPattern )
+ {
+ this.isPattern = isPattern;
+ }
+
+ public SecureActionBundle initSecureActionBundle()
+ throws SecureActionException
+ {
+ SecureActionBundle bundle = new SecureActionBundle();
+ bundle.setRequiresAuthentication( true );
+ bundle.addRequiredAuthorization( RoleConstants.USER_MANAGEMENT_RBAC_ADMIN_OPERATION, Resource.GLOBAL );
+ return bundle;
+ }
+}
--- /dev/null
+package org.apache.archiva.redback.struts2.action.admin;
+
+/*
+ * 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.RbacManagerException;
+import org.apache.archiva.redback.rbac.Resource;
+import org.apache.archiva.redback.rbac.Role;
+import org.apache.archiva.redback.rbac.RBACManager;
+import org.apache.archiva.redback.struts2.action.AuditEvent;
+import org.apache.archiva.redback.struts2.action.AbstractSecurityAction;
+import org.codehaus.plexus.util.StringUtils;
+import org.apache.archiva.redback.integration.interceptor.SecureActionBundle;
+import org.apache.archiva.redback.integration.interceptor.SecureActionException;
+import org.apache.archiva.redback.integration.model.SimplePermission;
+import org.apache.archiva.redback.integration.role.RoleConstants;
+import org.springframework.context.annotation.Scope;
+import org.springframework.stereotype.Controller;
+
+import javax.inject.Inject;
+import javax.inject.Named;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+/**
+ * RoleCreateAction
+ *
+ * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
+ * @version $Id$
+ */
+@Controller( "redback-role-create" )
+@Scope( "prototype" )
+public class RoleCreateAction
+ extends AbstractSecurityAction
+{
+ // ------------------------------------------------------------------
+ // Component Requirements
+ // ------------------------------------------------------------------
+
+ /**
+ * role-hint="cached"
+ */
+ @Inject
+ @Named( value = "rBACManager#cached" )
+ private RBACManager manager;
+
+ // ------------------------------------------------------------------
+ // Action Parameters
+ // ------------------------------------------------------------------
+
+ private String principal;
+
+ private String roleName;
+
+ private String description;
+
+ private List<SimplePermission> permissions;
+
+ private List<String> childRoles;
+
+ private SimplePermission addpermission;
+
+ private String submitMode;
+
+ protected static final String VALID_ROLENAME_CHARS = "[a-zA-Z_0-9\\-\\s.,]*";
+
+ // ------------------------------------------------------------------
+ // Action Entry Points - (aka Names)
+ // ------------------------------------------------------------------
+
+ public String show()
+ {
+ if ( permissions == null )
+ {
+ permissions = new ArrayList<SimplePermission>();
+ }
+
+ if ( childRoles == null )
+ {
+ childRoles = new ArrayList<String>();
+ }
+
+ if ( addpermission == null )
+ {
+ addpermission = new SimplePermission();
+ }
+
+ return INPUT;
+ }
+
+ public String addpermission()
+ {
+ if ( addpermission == null )
+ {
+ addActionError( getText( "cannot.add.null.permission" ) );
+ return ERROR;
+ }
+
+ if ( permissions == null )
+ {
+ permissions = new ArrayList<SimplePermission>();
+ }
+
+ permissions.add( addpermission );
+
+ addpermission = new SimplePermission();
+
+ return INPUT;
+ }
+
+ public String submit()
+ {
+ if ( StringUtils.equals( getSubmitMode(), "addPermission" ) )
+ {
+ return addpermission();
+ }
+
+ if ( StringUtils.isEmpty( roleName ) )
+ {
+ addActionError( getText( "cannot.add.empty.role" ) );
+ return ERROR;
+ }
+ if ( !roleName.matches( VALID_ROLENAME_CHARS ) )
+ {
+ addActionError( getText( "roleName.invalid.characters" ) );
+ return ERROR;
+ }
+
+ try
+ {
+ Role _role;
+ if ( manager.roleExists( roleName ) )
+ {
+ _role = manager.getRole( roleName );
+ }
+ else
+ {
+ _role = manager.createRole( roleName );
+ }
+
+ _role.setDescription( description );
+ _role.setChildRoleNames( childRoles );
+
+ List<Permission> _permissionList = new ArrayList<Permission>();
+ for ( SimplePermission perm : permissions )
+ {
+ _permissionList.add(
+ manager.createPermission( perm.getName(), perm.getOperationName(), perm.getResourceIdentifier() ) );
+ }
+
+ _role.setPermissions( _permissionList );
+
+ manager.saveRole( _role );
+
+ addActionMessage( getText( "save.role.success", Arrays.asList( (Object) roleName ) ) );
+ String currentUser = getCurrentUser();
+ AuditEvent event = new AuditEvent( getText( "log.role.create" ) );
+ event.setRole( roleName );
+ event.setCurrentUser( currentUser );
+ event.log();
+ }
+ catch ( RbacManagerException e )
+ {
+ addActionError( getText( "cannot.get.role", Arrays.asList( (Object) roleName, e.getMessage() ) ) );
+ return ERROR;
+ }
+
+ return SUCCESS;
+ }
+
+ // ------------------------------------------------------------------
+ // Parameter Accessor Methods
+ // ------------------------------------------------------------------
+
+ public String getPrincipal()
+ {
+ return principal;
+ }
+
+ public void setPrincipal( String principal )
+ {
+ this.principal = principal;
+ }
+
+ public SimplePermission getAddpermission()
+ {
+ return addpermission;
+ }
+
+ public void setAddpermission( SimplePermission addpermission )
+ {
+ this.addpermission = addpermission;
+ }
+
+ public String getSubmitMode()
+ {
+ return submitMode;
+ }
+
+ public void setSubmitMode( String submitMode )
+ {
+ this.submitMode = submitMode;
+ }
+
+ public SecureActionBundle initSecureActionBundle()
+ throws SecureActionException
+ {
+ SecureActionBundle bundle = new SecureActionBundle();
+ bundle.setRequiresAuthentication( true );
+ bundle.addRequiredAuthorization( RoleConstants.USER_MANAGEMENT_RBAC_ADMIN_OPERATION, Resource.GLOBAL );
+ return bundle;
+ }
+
+}
--- /dev/null
+package org.apache.archiva.redback.struts2.action.admin;
+
+/*
+ * 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.Resource;
+import org.apache.archiva.redback.role.RoleManager;
+import org.apache.archiva.redback.struts2.action.AbstractSecurityAction;
+import org.codehaus.plexus.redback.role.model.RedbackRoleModel;
+import org.apache.archiva.redback.integration.interceptor.SecureActionBundle;
+import org.apache.archiva.redback.integration.interceptor.SecureActionException;
+import org.apache.archiva.redback.integration.role.RoleConstants;
+import org.springframework.context.annotation.Scope;
+import org.springframework.stereotype.Controller;
+
+import javax.inject.Inject;
+
+/**
+ * RolesAction
+ *
+ * @author <a href="mailto:jmcconnell@apache.org">Jesse McConnell</a>
+ * @version $Id$
+ */
+@Controller( "redback-role-model" )
+@Scope( "prototype" )
+public class RoleModelAction
+ extends AbstractSecurityAction
+{
+ /**
+ * role-hint="default"
+ */
+ @Inject
+ private RoleManager manager;
+
+ private RedbackRoleModel model;
+
+ public String view()
+ {
+ model = manager.getModel();
+
+ return SUCCESS;
+ }
+
+ public RedbackRoleModel getModel()
+ {
+ return model;
+ }
+
+ public void setModel( RedbackRoleModel model )
+ {
+ this.model = model;
+ }
+
+ public SecureActionBundle initSecureActionBundle()
+ throws SecureActionException
+ {
+ SecureActionBundle bundle = new SecureActionBundle();
+ bundle.setRequiresAuthentication( true );
+ bundle.addRequiredAuthorization( RoleConstants.USER_MANAGEMENT_RBAC_ADMIN_OPERATION, Resource.GLOBAL );
+ return bundle;
+ }
+}
--- /dev/null
+package org.apache.archiva.redback.struts2.action.admin;
+
+/*
+ * 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.Resource;
+import org.apache.archiva.redback.rbac.Role;
+import org.apache.archiva.redback.rbac.RbacManagerException;
+import org.apache.archiva.redback.struts2.action.AbstractUserCredentialsAction;
+import org.apache.archiva.redback.integration.interceptor.SecureActionBundle;
+import org.apache.archiva.redback.integration.interceptor.SecureActionException;
+import org.apache.archiva.redback.integration.role.RoleConstants;
+import org.springframework.context.annotation.Scope;
+import org.springframework.stereotype.Controller;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+/**
+ * RolesAction
+ *
+ * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
+ * @version $Id$
+ */
+@Controller( "redback-roles" )
+@Scope( "prototype" )
+public class RolesAction
+ extends AbstractUserCredentialsAction
+{
+ private static final String LIST = "list";
+
+ private List<Role> allRoles;
+
+ public String list()
+ {
+ try
+ {
+ allRoles = getFilteredRolesForCurrentUserAccess();
+ }
+ catch ( RbacManagerException e )
+ {
+ List<Object> list = new ArrayList<Object>();
+ list.add( e.getMessage() );
+ addActionError( getText( "cannot.list.all.roles", list ) );
+ log.error( "System error:", e );
+ allRoles = Collections.emptyList();
+ }
+
+ return LIST;
+ }
+
+ public List<Role> getAllRoles()
+ {
+ return allRoles;
+ }
+
+ public void setAllRoles( List<Role> allRoles )
+ {
+ this.allRoles = allRoles;
+ }
+
+ public SecureActionBundle initSecureActionBundle()
+ throws SecureActionException
+ {
+ SecureActionBundle bundle = new SecureActionBundle();
+ bundle.setRequiresAuthentication( true );
+ bundle.addRequiredAuthorization( RoleConstants.USER_MANAGEMENT_USER_EDIT_OPERATION, Resource.GLOBAL );
+ bundle.addRequiredAuthorization( RoleConstants.USER_MANAGEMENT_RBAC_ADMIN_OPERATION, Resource.GLOBAL );
+ bundle.addRequiredAuthorization( RoleConstants.USER_MANAGEMENT_ROLE_GRANT_OPERATION, Resource.GLOBAL );
+ bundle.addRequiredAuthorization( RoleConstants.USER_MANAGEMENT_ROLE_DROP_OPERATION, Resource.GLOBAL );
+ bundle.addRequiredAuthorization( RoleConstants.USER_MANAGEMENT_USER_ROLE_OPERATION, Resource.GLOBAL );
+ return bundle;
+ }
+}
--- /dev/null
+package org.apache.archiva.redback.struts2.action.admin;
+
+/*
+ * 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.rbac.Resource;
+import org.apache.commons.beanutils.PropertyUtils;
+import org.apache.commons.lang.StringEscapeUtils;
+import org.apache.commons.lang.StringUtils;
+import org.apache.archiva.redback.struts2.action.AbstractSecurityAction;
+import org.apache.archiva.redback.system.SecuritySystem;
+import org.codehaus.plexus.registry.Registry;
+import org.apache.archiva.redback.integration.interceptor.SecureActionBundle;
+import org.apache.archiva.redback.integration.interceptor.SecureActionException;
+import org.apache.archiva.redback.integration.role.RoleConstants;
+import org.springframework.context.annotation.Scope;
+import org.springframework.stereotype.Controller;
+
+import javax.inject.Inject;
+import javax.inject.Named;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * SystemInfoAction
+ *
+ * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
+ * @version $Id$
+ */
+@Controller( "redback-sysinfo" )
+@Scope( "prototype" )
+public class SystemInfoAction
+ extends AbstractSecurityAction
+{
+ // ------------------------------------------------------------------
+ // Component Requirements
+ // ------------------------------------------------------------------
+
+ /**
+ *
+ */
+ @Inject
+ private SecuritySystem securitySystem;
+
+ /**
+ * role-hint="commons-configuration"
+ */
+ @Inject
+ @Named( value = "commons-configuration" )
+ private Registry registry;
+
+ /**
+ * role-hint="cached"
+ */
+ @Inject
+ @Named( value = "rBACManager#cached" )
+ private RBACManager rbacManager;
+
+ // Class.getClass() and some JPOX classes
+ private static final List<String> ignoredReaders = Arrays.asList( "class", "copy" );
+
+ private static final String NULL = "<null>";
+
+ private static final char LN = Character.LINE_SEPARATOR;
+
+ private static final String INDENT = " ";
+
+ private static final int MAXDEPTH = 10;
+
+ // ------------------------------------------------------------------
+ // Action Parameters
+ // ------------------------------------------------------------------
+
+ private StringBuilder details;
+
+ // ------------------------------------------------------------------
+ // Action Entry Points - (aka Names)
+ // ------------------------------------------------------------------
+
+ public String show()
+ {
+ details = new StringBuilder();
+
+ details.append( "Configuration: " );
+ dumpObject( details, registry, INDENT );
+ details.append( registry.dump() );
+ details.append( LN );
+
+ details.append( LN ).append( "<hr/>" ).append( LN );
+ details.append( "RBAC Manager: " );
+ dumpObject( details, rbacManager, INDENT );
+
+ details.append( LN ).append( "<hr/>" ).append( LN );
+ details.append( "SecuritySystem: " );
+ dumpObject( details, securitySystem, INDENT );
+
+ return SUCCESS;
+ }
+
+ private void dumpObject( StringBuilder sb, Object obj, String indent )
+ {
+ dumpObjectSwitchboard( new ArrayList<Object>(), sb, obj, indent, 0 );
+ }
+
+ /**
+ * The recursive object dumping switchboard.
+ *
+ * @param seenObjects objects already seen (to prevent cycles)
+ * @param sb the stringbuffer to populate
+ * @param obj the object to dump
+ * @param indent the current indent string.
+ * @param depth the depth in the tree.
+ */
+ private void dumpObjectSwitchboard( List<Object> seenObjects, StringBuilder sb, Object obj, String indent,
+ int depth )
+ {
+ if ( obj == null )
+ {
+ sb.append( NULL ).append( LN );
+ return;
+ }
+
+ if ( depth > MAXDEPTH )
+ {
+ sb.append( StringEscapeUtils.escapeHtml( "<MAX DEPTH>" ) );
+ sb.append( LN );
+ return;
+ }
+
+ depth++;
+
+ String className = obj.getClass().getName();
+
+ sb.append( '(' ).append( className ).append( ") " );
+
+ if ( obj instanceof List )
+ {
+ dumpIterator( seenObjects, sb, ( (List<?>) obj ).iterator(), indent, depth );
+ }
+ else if ( obj instanceof Set )
+ {
+ dumpIterator( seenObjects, sb, ( (Set<?>) obj ).iterator(), indent, depth );
+ }
+ else if ( obj instanceof Map )
+ {
+ dumpIterator( seenObjects, sb, ( (Map<?, ?>) obj ).entrySet().iterator(), indent, depth );
+ }
+ else if ( obj instanceof Iterator )
+ {
+ dumpIterator( seenObjects, sb, (Iterator<?>) obj, indent, depth );
+ }
+ else
+ {
+ // Filter classes that start with java or javax
+ if ( className.startsWith( "java." ) || className.startsWith( "javax." ) )
+ {
+ sb.append( StringEscapeUtils.escapeHtml( obj.toString() ) ).append( LN );
+ return;
+ }
+
+ // prevent cycles
+ if ( seenObjects.contains( obj ) )
+ {
+ // No need to dump.
+ sb.append( StringEscapeUtils.escapeHtml( "<seen already preventing cycle in dump> " ) );
+ sb.append( LN );
+ return;
+ }
+
+ // Adding object to seen list (to prevent cycles)
+ seenObjects.add( obj );
+
+ dumpObjectReaders( seenObjects, sb, obj, indent, depth );
+ }
+ depth--;
+ }
+
+ @SuppressWarnings( "unchecked" )
+ private void dumpObjectReaders( List<Object> seenObjects, StringBuilder sb, Object obj, String indent, int depth )
+ {
+ sb.append( obj.toString() ).append( LN );
+ String name = null;
+
+ try
+ {
+ Map<String, Object> readers = PropertyUtils.describe( obj );
+ for ( Map.Entry<String, Object> readerEntry : readers.entrySet() )
+ {
+ name = (String) readerEntry.getKey();
+
+ if ( ignoredReaders.contains( name ) )
+ {
+ // skip this reader.
+ continue;
+ }
+
+ sb.append( indent );
+ sb.append( name ).append( ':' );
+
+ Object value = readerEntry.getValue();
+ if ( value == null )
+ {
+ sb.append( NULL ).append( LN );
+ }
+ else
+ {
+ dumpObjectSwitchboard( seenObjects, sb, value, INDENT + indent, depth );
+ }
+ }
+ }
+ catch ( Throwable e )
+ {
+ sb.append( LN ).append( indent );
+ sb.append( "Unable to read bean [" ).append( obj.getClass().getName() );
+ if ( StringUtils.isNotBlank( name ) )
+ {
+ sb.append( ".get" ).append( StringUtils.capitalize( name ) ).append( "()" );
+ }
+ sb.append( "]: " ).append( '(' ).append( e.getClass().getName() ).append( ") " );
+ sb.append( e.getMessage() ).append( LN );
+ }
+ }
+
+ private void dumpIterator( List<Object> seenObjects, StringBuilder sb, Iterator<?> iterator, String indent,
+ int depth )
+ {
+ sb.append( LN );
+ while ( iterator.hasNext() )
+ {
+ Object entry = iterator.next();
+ sb.append( indent );
+ dumpObjectSwitchboard( seenObjects, sb, entry, indent + " | ", depth );
+ }
+ }
+
+ // ------------------------------------------------------------------
+ // Parameter Accessor Methods
+ // ------------------------------------------------------------------
+
+ public String getDetails()
+ {
+ return details.toString();
+ }
+
+ public SecureActionBundle initSecureActionBundle()
+ throws SecureActionException
+ {
+ SecureActionBundle bundle = new SecureActionBundle();
+ bundle.setRequiresAuthentication( true );
+ bundle.addRequiredAuthorization( RoleConstants.CONFIGURATION_EDIT_OPERATION, Resource.GLOBAL );
+ return bundle;
+ }
+}
--- /dev/null
+package org.apache.archiva.redback.struts2.action.admin;
+
+/*
+ * 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 java.util.Arrays;
+
+import org.apache.archiva.redback.policy.UserSecurityPolicy;
+import org.apache.archiva.redback.rbac.Resource;
+import org.apache.archiva.redback.struts2.action.AbstractUserCredentialsAction;
+import org.apache.archiva.redback.struts2.action.AuditEvent;
+import org.apache.archiva.redback.users.User;
+import org.apache.archiva.redback.users.UserManager;
+import org.apache.archiva.redback.integration.interceptor.SecureActionBundle;
+import org.apache.archiva.redback.integration.interceptor.SecureActionException;
+import org.apache.archiva.redback.integration.model.CreateUserCredentials;
+import org.apache.archiva.redback.integration.role.RoleConstants;
+import org.springframework.context.annotation.Scope;
+import org.springframework.stereotype.Controller;
+
+/**
+ * UserCreateAction
+ *
+ * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
+ * @version $Id$
+ */
+@Controller("redback-admin-user-create")
+@Scope("prototype")
+public class UserCreateAction
+ extends AbstractUserCredentialsAction
+{
+ // ------------------------------------------------------------------
+ // Action Parameters
+ // ------------------------------------------------------------------
+
+ private CreateUserCredentials user;
+
+ // ------------------------------------------------------------------
+ // Action Entry Points - (aka Names)
+ // ------------------------------------------------------------------
+
+ public String show()
+ {
+ if ( user == null )
+ {
+ user = new CreateUserCredentials();
+ }
+
+ return INPUT;
+ }
+
+ public String submit()
+ {
+ if ( user == null )
+ {
+ user = new CreateUserCredentials();
+ addActionError( getText( "invalid.user.credentials" ) );
+ return ERROR;
+ }
+
+ internalUser = user;
+
+ validateCredentialsLoose();
+
+ // NOTE: Do not perform Password Rules Validation Here.
+
+ UserManager manager = super.securitySystem.getUserManager();
+
+ if ( manager.userExists( user.getUsername() ) )
+ {
+ // Means that the role name doesn't exist.
+ // We need to fail fast and return to the previous page.
+ addActionError( getText( "user.already.exists", Arrays.asList( ( Object ) user.getUsername() ) ) );
+ }
+
+ if ( hasActionErrors() || hasFieldErrors() )
+ {
+ return ERROR;
+ }
+
+ User u = manager.createUser( user.getUsername(), user.getFullName(), user.getEmail() );
+ u.setPassword( user.getPassword() );
+
+ // force the user to change their password when they log in next
+ u.setPasswordChangeRequired( true );
+
+ // Disable Password Rules for this creation.
+ UserSecurityPolicy securityPolicy = securitySystem.getPolicy();
+ try
+ {
+ // REDBACK-156
+ securityPolicy.setEnabled( false );
+ u.setValidated( true );
+ manager.addUser( u );
+ String currentUser = getCurrentUser();
+ AuditEvent event = new AuditEvent( getText( "log.account.create" ) );
+ event.setAffectedUser( u.getUsername() );
+ event.setCurrentUser( currentUser );
+ event.log();
+ }
+ finally
+ {
+ securityPolicy.setEnabled( true );
+ }
+
+ return SUCCESS;
+ }
+
+ // ------------------------------------------------------------------
+ // Parameter Accessor Methods
+ // ------------------------------------------------------------------
+
+ public CreateUserCredentials getUser()
+ {
+ return user;
+ }
+
+ public void setUser( CreateUserCredentials user )
+ {
+ this.user = user;
+ }
+
+ public SecureActionBundle initSecureActionBundle()
+ throws SecureActionException
+ {
+ SecureActionBundle bundle = new SecureActionBundle();
+ bundle.setRequiresAuthentication( true );
+ bundle.addRequiredAuthorization( RoleConstants.USER_MANAGEMENT_USER_CREATE_OPERATION, Resource.GLOBAL );
+ return bundle;
+ }
+
+}
--- /dev/null
+package org.apache.archiva.redback.struts2.action.admin;
+
+/*
+ * 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.rbac.RbacObjectInvalidException;
+import org.apache.archiva.redback.rbac.Resource;
+import org.apache.archiva.redback.struts2.action.AbstractSecurityAction;
+import org.apache.archiva.redback.users.User;
+import org.apache.archiva.redback.users.UserManager;
+import org.apache.archiva.redback.rbac.RbacManagerException;
+import org.apache.archiva.redback.rbac.RbacObjectNotFoundException;
+import org.apache.archiva.redback.struts2.action.AuditEvent;
+import org.apache.archiva.redback.struts2.action.CancellableAction;
+import org.apache.archiva.redback.users.UserNotFoundException;
+import org.codehaus.plexus.util.StringUtils;
+import org.apache.archiva.redback.integration.interceptor.SecureActionBundle;
+import org.apache.archiva.redback.integration.interceptor.SecureActionException;
+import org.apache.archiva.redback.integration.role.RoleConstants;
+import org.springframework.context.annotation.Scope;
+import org.springframework.stereotype.Controller;
+
+import javax.inject.Inject;
+import javax.inject.Named;
+import java.util.Arrays;
+
+/**
+ * UserDeleteAction
+ *
+ * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
+ * @version $Id$
+ */
+@Controller( "redback-admin-user-delete" )
+@Scope( "prototype" )
+public class UserDeleteAction
+ extends AbstractSecurityAction
+ implements CancellableAction
+{
+ // ------------------------------------------------------------------
+ // Component Requirements
+ // ------------------------------------------------------------------
+
+ /**
+ * role-hint="configurable"
+ */
+ @Inject
+ @Named( value = "userManager#configurable" )
+ private UserManager userManager;
+
+ /**
+ * role-hint="cached"
+ */
+ @Inject
+ @Named( value = "rBACManager#cached" )
+ private RBACManager rbacManager;
+
+ // ------------------------------------------------------------------
+ // Action Parameters
+ // ------------------------------------------------------------------
+
+ private String username;
+
+ private User user;
+
+ // ------------------------------------------------------------------
+ // Action Entry Points - (aka Names)
+ // ------------------------------------------------------------------
+
+ public String confirm()
+ {
+ if ( username == null )
+ {
+ addActionError( getText( "cannot.remove.user.null.username" ) );
+ return SUCCESS;
+ }
+
+ try
+ {
+ user = userManager.findUser( username );
+ }
+ catch ( UserNotFoundException e )
+ {
+ addActionError( getText( "cannot.remove.user.not.found", Arrays.asList( (Object) username ) ) );
+ return SUCCESS;
+ }
+
+ return INPUT;
+ }
+
+ public String submit()
+ {
+ if ( username == null )
+ {
+ addActionError( getText( "invalid.user.credentials" ) );
+ return SUCCESS;
+ }
+
+ if ( StringUtils.isEmpty( username ) )
+ {
+ addActionError( getText( "cannot.remove.user.empty.username" ) );
+ return SUCCESS;
+ }
+
+ try
+ {
+ rbacManager.removeUserAssignment( username );
+ }
+ catch ( RbacObjectNotFoundException e )
+ {
+ // ignore, this is possible since the user may never have had roles assigned
+ }
+ catch ( RbacObjectInvalidException e )
+ {
+ addActionError( getText( "cannot.remove.user.role", Arrays.asList( (Object) username, e.getMessage() ) ) );
+ }
+ catch ( RbacManagerException e )
+ {
+ addActionError( getText( "cannot.remove.user.role", Arrays.asList( (Object) username, e.getMessage() ) ) );
+ }
+
+ if ( getActionErrors().isEmpty() )
+ {
+ try
+ {
+ userManager.deleteUser( username );
+ }
+ catch ( UserNotFoundException e )
+ {
+ addActionError( getText( "cannot.remove.user.non.existent", Arrays.asList( (Object) username ) ) );
+ }
+ }
+ String currentUser = getCurrentUser();
+
+ AuditEvent event = new AuditEvent( getText( "log.account.delete" ) );
+ event.setAffectedUser( username );
+ event.setCurrentUser( currentUser );
+ event.log();
+
+ return SUCCESS;
+ }
+
+ /**
+ * Returns the cancel result. <p/> A basic implementation would simply be to return CANCEL.
+ *
+ * @return
+ */
+ public String cancel()
+ {
+ return CANCEL;
+ }
+
+ // ------------------------------------------------------------------
+ // Parameter Accessor Methods
+ // ------------------------------------------------------------------
+
+ public String getUsername()
+ {
+ return username;
+ }
+
+ public void setUsername( String username )
+ {
+ this.username = username;
+ }
+
+ public User getUser()
+ {
+ return user;
+ }
+
+ public void setUser( User user )
+ {
+ this.user = user;
+ }
+
+ public SecureActionBundle initSecureActionBundle()
+ throws SecureActionException
+ {
+ SecureActionBundle bundle = new SecureActionBundle();
+ bundle.setRequiresAuthentication( true );
+ bundle.addRequiredAuthorization( RoleConstants.USER_MANAGEMENT_USER_DELETE_OPERATION, Resource.GLOBAL );
+ return bundle;
+ }
+
+}
--- /dev/null
+package org.apache.archiva.redback.struts2.action.admin;
+
+/*
+ * 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.rbac.RBACManager;
+import org.apache.archiva.redback.rbac.Resource;
+import org.apache.archiva.redback.struts2.action.AuditEvent;
+import org.apache.archiva.redback.struts2.action.CancellableAction;
+import org.apache.archiva.redback.users.User;
+import org.apache.archiva.redback.users.UserNotFoundException;
+import org.apache.commons.lang.StringEscapeUtils;
+import org.apache.archiva.redback.policy.PasswordRuleViolationException;
+import org.apache.archiva.redback.rbac.RbacManagerException;
+import org.apache.archiva.redback.rbac.Role;
+import org.apache.archiva.redback.system.DefaultSecuritySession;
+import org.apache.archiva.redback.system.SecuritySession;
+import org.apache.archiva.redback.system.SecuritySystemConstants;
+import org.apache.archiva.redback.users.UserManager;
+import org.codehaus.plexus.util.StringUtils;
+import org.apache.archiva.redback.integration.interceptor.SecureActionBundle;
+import org.apache.archiva.redback.integration.interceptor.SecureActionException;
+import org.apache.archiva.redback.integration.model.AdminEditUserCredentials;
+import org.apache.archiva.redback.integration.role.RoleConstants;
+import org.springframework.context.annotation.Scope;
+import org.springframework.stereotype.Controller;
+
+import javax.inject.Inject;
+import javax.inject.Named;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+
+/**
+ * UserEditAction
+ *
+ * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
+ * @version $Id$
+ */
+@Controller( "redback-admin-user-edit" )
+@Scope( "prototype" )
+public class UserEditAction
+ extends AbstractAdminUserCredentialsAction
+ implements CancellableAction
+{
+ /**
+ * role-hint="cached"
+ */
+ @Inject
+ @Named( value = "rBACManager#cached" )
+ private RBACManager rbacManager;
+
+ /**
+ * A List of {@link org.apache.archiva.redback.rbac.Role} objects.
+ */
+ private List<Role> effectivelyAssignedRoles;
+
+ // ------------------------------------------------------------------
+ // Action Parameters
+ // ------------------------------------------------------------------
+
+ private AdminEditUserCredentials user;
+
+ private String updateButton;
+
+ private boolean emailValidationRequired;
+
+ private boolean hasHiddenRoles;
+
+ private String oldPassword;
+
+ private String userAdminPassword;
+
+ private boolean self;
+
+ public static String CONFIRM = "confirm";
+
+ public static String CONFIRM_ERROR = "confirmError";
+
+ // ------------------------------------------------------------------
+ // Action Entry Points - (aka Names)
+ // ------------------------------------------------------------------
+
+ public String edit()
+ {
+ oldPassword = "";
+
+ emailValidationRequired = securitySystem.getPolicy().getUserValidationSettings().isEmailValidationRequired();
+
+ if ( getUsername() == null )
+ {
+ addActionError( getText( "cannot.edit.user.null.username" ) );
+ return ERROR;
+ }
+
+ if ( StringUtils.isEmpty( getUsername() ) )
+ {
+ addActionError( getText( "cannot.edit.user.empty.username" ) );
+ return ERROR;
+ }
+
+ UserManager manager = super.securitySystem.getUserManager();
+
+ String escapedUsername = StringEscapeUtils.escapeXml( getUsername() );
+
+ if ( !manager.userExists( escapedUsername ) )
+ {
+ // Means that the role name doesn't exist.
+ // We need to fail fast and return to the previous page.
+ addActionError( getText( "user.does.not.exist", Collections.singletonList( (Object) escapedUsername ) ) );
+ return ERROR;
+ }
+
+ try
+ {
+ User u = manager.findUser( escapedUsername );
+
+ if ( u == null )
+ {
+ addActionError( getText( "cannot.operate.on.null.user" ) );
+ return ERROR;
+ }
+
+ user = new AdminEditUserCredentials( u );
+
+ // require user admin to provide his/her password if editing account of others
+ if ( getUsername().equals( getCurrentUser() ) )
+ {
+ self = true;
+ }
+
+ try
+ {
+ String principal = u.getPrincipal().toString();
+ List<Role> roles = filterAssignableRoles( rbacManager.getEffectivelyAssignedRoles( principal ) );
+ effectivelyAssignedRoles = filterRolesForCurrentUserAccess( roles );
+ hasHiddenRoles = ( roles.size() > effectivelyAssignedRoles.size() );
+ }
+ catch ( RbacManagerException rme )
+ {
+ // ignore, this can happen when the user has no roles assigned
+ }
+ }
+ catch ( UserNotFoundException e )
+ {
+ addActionError( getText( "cannot.get.user", Arrays.asList( (Object) getUsername(), e.getMessage() ) ) );
+ return ERROR;
+ }
+
+ return INPUT;
+ }
+
+ private List<Role> filterAssignableRoles( Collection<Role> roles )
+ {
+ List<Role> assignableRoles = new ArrayList<Role>( roles.size() );
+ for ( Role r : roles )
+ {
+ if ( r.isAssignable() )
+ {
+ assignableRoles.add( r );
+ }
+ }
+ return assignableRoles;
+ }
+
+ public String submit()
+ {
+ if ( getUsername() == null )
+ {
+ addActionError( getText( "cannot.edit.user.null.username" ) );
+ return ERROR;
+ }
+
+ if ( StringUtils.isEmpty( getUsername() ) )
+ {
+ addActionError( getText( "cannot.edit.user.empty.username" ) );
+ return ERROR;
+ }
+
+ if ( user == null )
+ {
+ addActionError( getText( "cannot.edit.user.null.credentials" ) );
+ return ERROR;
+ }
+
+ internalUser = user;
+
+ validateCredentialsLoose();
+
+ // if form errors, return with them before continuing
+ if ( hasActionErrors() || hasFieldErrors() )
+ {
+ return ERROR;
+ }
+
+ if ( !getUsername().equals( getCurrentUser() ) )
+ {
+ return CONFIRM;
+ }
+ else
+ {
+ return save( true );
+ }
+ }
+
+ // confirm user admin's password before allowing to proceed with the operation
+ public String confirmAdminPassword()
+ {
+ UserManager manager = super.securitySystem.getUserManager();
+
+ if ( StringUtils.isEmpty( userAdminPassword ) )
+ {
+ addActionError( getText( "user.admin.password.required" ) );
+ return CONFIRM_ERROR;
+ }
+
+ try
+ {
+ User currentUser = manager.findUser( getCurrentUser() );
+
+ // check if user admin provided correct password!
+ PasswordEncoder encoder = securitySystem.getPolicy().getPasswordEncoder();
+ if ( !encoder.isPasswordValid( currentUser.getEncodedPassword(), userAdminPassword ) )
+ {
+ addActionError( getText( "user.admin.password.does.not.match.existing" ) );
+ return CONFIRM_ERROR;
+ }
+ }
+ catch ( UserNotFoundException e )
+ {
+ addActionError( getText( "cannot.find.user", Arrays.asList( (Object) getCurrentUser(), e.getMessage() ) ) );
+ return CONFIRM_ERROR;
+ }
+
+ return save( false );
+ }
+
+ public String cancel()
+ {
+ return CANCEL;
+ }
+
+ private String save( boolean validateOldPassword )
+ {
+ UserManager manager = super.securitySystem.getUserManager();
+
+ if ( !manager.userExists( getUsername() ) )
+ {
+ // Means that the role name doesn't exist.
+ // We need to fail fast and return to the previous page.
+ addActionError( getText( "user.does.not.exist", Collections.singletonList( (Object) getUsername() ) ) );
+ return ERROR;
+ }
+
+ try
+ {
+ User u = manager.findUser( getUsername() );
+ if ( u == null )
+ {
+ addActionError( getText( "cannot.operate.on.null.user" ) );
+ return ERROR;
+ }
+
+ if ( validateOldPassword )
+ {
+ PasswordEncoder encoder = securitySystem.getPolicy().getPasswordEncoder();
+
+ if ( StringUtils.isEmpty( oldPassword ) )
+ {
+ self = true;
+ addFieldError( "oldPassword", getText( "old.password.required" ) );
+ return ERROR;
+ }
+
+ if ( !encoder.isPasswordValid( u.getEncodedPassword(), oldPassword ) )
+ {
+ self = true;
+ addFieldError( "oldPassword", getText( "password.provided.does.not.match.existing" ) );
+ return ERROR;
+ }
+ }
+
+ u.setFullName( user.getFullName() );
+ u.setEmail( user.getEmail() );
+ u.setPassword( user.getPassword() );
+ u.setLocked( user.isLocked() );
+ u.setPasswordChangeRequired( user.isPasswordChangeRequired() );
+
+ manager.updateUser( u, user.isPasswordChangeRequired() );
+
+ //check if current user then update the session
+ if ( getSecuritySession().getUser().getUsername().equals( u.getUsername() ) )
+ {
+ SecuritySession securitySession =
+ new DefaultSecuritySession( getSecuritySession().getAuthenticationResult(), u );
+
+ session.put( SecuritySystemConstants.SECURITY_SESSION_KEY, securitySession );
+
+ setSession( session );
+ }
+ }
+ catch ( UserNotFoundException e )
+ {
+ addActionError( getText( "cannot.find.user", Arrays.asList( (Object) getUsername(), e.getMessage() ) ) );
+ return ERROR;
+ }
+ catch ( PasswordRuleViolationException pe )
+ {
+ processPasswordRuleViolations( pe );
+ return ERROR;
+ }
+ String currentUser = getCurrentUser();
+
+ AuditEvent event = new AuditEvent( getText( "log.account.edit" ) );
+ event.setAffectedUser( getUsername() );
+ event.setCurrentUser( currentUser );
+ event.log();
+
+ return SUCCESS;
+ }
+
+ // ------------------------------------------------------------------
+ // Parameter Accessor Methods
+ // ------------------------------------------------------------------
+
+
+ public String getUpdateButton()
+ {
+ return updateButton;
+ }
+
+ public void setUpdateButton( String updateButton )
+ {
+ this.updateButton = updateButton;
+ }
+
+ public AdminEditUserCredentials getUser()
+ {
+ return user;
+ }
+
+ public void setUser( AdminEditUserCredentials user )
+ {
+ this.user = user;
+ }
+
+ public SecureActionBundle initSecureActionBundle()
+ throws SecureActionException
+ {
+ SecureActionBundle bundle = new SecureActionBundle();
+ bundle.setRequiresAuthentication( true );
+ bundle.addRequiredAuthorization( RoleConstants.USER_MANAGEMENT_USER_EDIT_OPERATION, Resource.GLOBAL );
+ bundle.addRequiredAuthorization( RoleConstants.USER_MANAGEMENT_USER_EDIT_OPERATION, getUsername() );
+ bundle.addRequiredAuthorization( RoleConstants.USER_MANAGEMENT_USER_ROLE_OPERATION, Resource.GLOBAL );
+ return bundle;
+ }
+
+ public List<Role> getEffectivelyAssignedRoles()
+ {
+ return effectivelyAssignedRoles;
+ }
+
+ public boolean isEmailValidationRequired()
+ {
+ return emailValidationRequired;
+ }
+
+ public boolean isHasHiddenRoles()
+ {
+ return hasHiddenRoles;
+ }
+
+ public void setHasHiddenRoles( boolean hasHiddenRoles )
+ {
+ this.hasHiddenRoles = hasHiddenRoles;
+ }
+
+ public void setOldPassword( String oldPassword )
+ {
+ this.oldPassword = oldPassword;
+ }
+
+ public void setUserAdminPassword( String userAdminPassword )
+ {
+ this.userAdminPassword = userAdminPassword;
+ }
+
+ public boolean isSelf()
+ {
+ return self;
+ }
+}
--- /dev/null
+package org.apache.archiva.redback.struts2.action.admin;
+
+/*
+ * 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.RbacManagerException;
+import org.apache.archiva.redback.rbac.RbacObjectNotFoundException;
+import org.apache.archiva.redback.rbac.Resource;
+import org.apache.archiva.redback.rbac.Role;
+import org.apache.archiva.redback.rbac.UserAssignment;
+import org.apache.archiva.redback.struts2.action.AbstractSecurityAction;
+import org.apache.archiva.redback.users.User;
+import org.apache.commons.lang.StringEscapeUtils;
+import org.apache.struts2.ServletActionContext;
+import org.apache.archiva.redback.rbac.RBACManager;
+import org.apache.archiva.redback.system.SecuritySystem;
+import org.apache.archiva.redback.users.UserManager;
+import org.apache.archiva.redback.users.UserQuery;
+import org.codehaus.plexus.util.StringUtils;
+import org.apache.archiva.redback.integration.interceptor.SecureActionBundle;
+import org.apache.archiva.redback.integration.interceptor.SecureActionException;
+import org.apache.archiva.redback.integration.reports.Report;
+import org.apache.archiva.redback.integration.reports.ReportManager;
+import org.apache.archiva.redback.integration.role.RoleConstants;
+import org.extremecomponents.table.context.Context;
+import org.extremecomponents.table.context.HttpServletRequestContext;
+import org.extremecomponents.table.limit.FilterSet;
+import org.extremecomponents.table.limit.Limit;
+import org.extremecomponents.table.limit.LimitFactory;
+import org.extremecomponents.table.limit.TableLimit;
+import org.extremecomponents.table.limit.TableLimitFactory;
+import org.springframework.context.annotation.Scope;
+import org.springframework.stereotype.Controller;
+
+import javax.inject.Inject;
+import javax.inject.Named;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * UserListAction
+ *
+ * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
+ * @version $Id$
+ */
+@Controller( "redback-admin-user-list" )
+@Scope( "prototype" )
+public class UserListAction
+ extends AbstractSecurityAction
+{
+ // ------------------------------------------------------------------
+ // Component Requirements
+ // ------------------------------------------------------------------
+
+ /**
+ *
+ */
+ @Inject
+ private SecuritySystem securitySystem;
+
+ /**
+ * role-hint="cached"
+ */
+ @Inject
+ @Named( value = "rBACManager#cached" )
+ private RBACManager rbac;
+
+ /**
+ *
+ */
+ @Inject
+ private ReportManager reportManager;
+
+ // ------------------------------------------------------------------
+ // Action Parameters
+ // ------------------------------------------------------------------
+
+ private List<User> users;
+
+ private List<Role> roles;
+
+ private String roleName;
+
+ // ------------------------------------------------------------------
+ // Action Entry Points - (aka Names)
+ // ------------------------------------------------------------------
+
+ public String show()
+ {
+ try
+ {
+ roles = rbac.getAllRoles();
+ }
+ catch ( RbacManagerException e )
+ {
+ roles = Collections.emptyList();
+ }
+
+ if ( StringUtils.isEmpty( roleName ) )
+ {
+ users = findUsersWithFilter();
+ }
+ else
+ {
+ roleName = StringEscapeUtils.escapeXml( roleName );
+
+ try
+ {
+ Role target = rbac.getRole( roleName );
+ Set<String> targetRoleNames = new HashSet<String>();
+
+ for ( int i = 0; i < roles.size(); i++ )
+ {
+ Role r = roles.get( i );
+ if ( rbac.getEffectiveRoles( r ).contains( target ) )
+ {
+ targetRoleNames.add( r.getName() );
+ }
+ }
+
+ users = findUsers( targetRoleNames );
+ }
+ catch ( RbacObjectNotFoundException e )
+ {
+ users = Collections.emptyList();
+ }
+ catch ( RbacManagerException e )
+ {
+ users = Collections.emptyList();
+ }
+ }
+
+ if ( users == null )
+ {
+ users = Collections.emptyList();
+ }
+
+ return INPUT;
+ }
+
+ public SecureActionBundle initSecureActionBundle()
+ throws SecureActionException
+ {
+ SecureActionBundle bundle = new SecureActionBundle();
+ bundle.setRequiresAuthentication( true );
+ bundle.addRequiredAuthorization( RoleConstants.USER_MANAGEMENT_USER_LIST_OPERATION, Resource.GLOBAL );
+ bundle.addRequiredAuthorization( RoleConstants.USER_MANAGEMENT_USER_ROLE_OPERATION, Resource.GLOBAL );
+ return bundle;
+ }
+
+ private List<User> findUsers( Collection<String> roleNames )
+ {
+ List<String> usernames = getUsernamesForRoles( roleNames );
+ List<User> filteredUsers = new ArrayList<User>();
+
+ for ( User user : findUsersWithFilter() )
+ {
+ if ( usernames.contains( user.getUsername() ) )
+ {
+ filteredUsers.add( user );
+ }
+ }
+
+ return filteredUsers;
+ }
+
+ private List<User> findUsersWithFilter()
+ {
+ Context context = new HttpServletRequestContext( ServletActionContext.getRequest() );
+ LimitFactory limitFactory = new TableLimitFactory( context );
+ Limit limit = new TableLimit( limitFactory );
+ FilterSet filterSet = limit.getFilterSet();
+
+ UserQuery query = getUserManager().createUserQuery();
+ if ( filterSet.getFilter( "username" ) != null )
+ {
+ query.setUsername( filterSet.getFilter( "username" ).getValue() );
+ }
+ if ( filterSet.getFilter( "fullName" ) != null )
+ {
+ query.setFullName( filterSet.getFilter( "fullName" ).getValue() );
+ }
+ if ( filterSet.getFilter( "email" ) != null )
+ {
+ query.setEmail( filterSet.getFilter( "email" ).getValue() );
+ }
+ return getUserManager().findUsersByQuery( query );
+ }
+
+ private List<String> getUsernamesForRoles( Collection<String> roleNames )
+ {
+ Set<String> usernames = new HashSet<String>();
+
+ try
+ {
+ List<UserAssignment> userAssignments = rbac.getUserAssignmentsForRoles( roleNames );
+
+ if ( userAssignments != null )
+ {
+ for ( UserAssignment a : userAssignments )
+ {
+ usernames.add( a.getPrincipal() );
+ }
+ }
+ }
+ catch ( RbacManagerException e )
+ {
+ log.warn( "Unable to get user assignments for roles " + roleNames, e );
+ }
+
+ return new ArrayList<String>( usernames );
+ }
+
+ private UserManager getUserManager()
+ {
+ return securitySystem.getUserManager();
+ }
+
+ // ------------------------------------------------------------------
+ // Parameter Accessor Methods
+ // ------------------------------------------------------------------
+
+ public List<User> getUsers()
+ {
+ return users;
+ }
+
+ public void setUsers( List<User> users )
+ {
+ this.users = users;
+ }
+
+ public String getRoleName()
+ {
+ if ( StringUtils.isEmpty( roleName ) )
+ {
+ return "Any";
+ }
+ return roleName;
+ }
+
+ public void setRoleName( String roleName )
+ {
+ this.roleName = roleName;
+ }
+
+ public List<Role> getRoles()
+ {
+ return roles;
+ }
+
+ public Map<String, Map<String, Report>> getReportMap()
+ {
+ return reportManager.getReportMap();
+ }
+}
--- /dev/null
+package org.apache.archiva.redback.struts2.checks;
+
+/*
+ * 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 java.util.List;
+import java.util.Map;
+
+import org.codehaus.plexus.util.StringUtils;
+import org.apache.archiva.redback.integration.checks.xwork.XworkActionConfig;
+import org.apache.archiva.redback.integration.checks.xwork.XworkPackageConfig;
+
+import com.opensymphony.xwork2.config.Configuration;
+import com.opensymphony.xwork2.config.entities.ActionConfig;
+import com.opensymphony.xwork2.config.entities.PackageConfig;
+
+/**
+ * AbstractXworkConfigurationCheck
+ *
+ * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
+ * @version $Id$
+ */
+public class AbstractXworkConfigurationCheck
+{
+
+ protected void checkAction( List<String> violations, XworkPackageConfig expectedPackage, XworkActionConfig expectedAction,
+ Map<?, ?> xwActionMap )
+ {
+ ActionConfig xwActionConfig = (ActionConfig) xwActionMap.get( expectedAction.name );
+ if ( xwActionConfig != null )
+ {
+ if ( StringUtils.isNotEmpty( expectedAction.clazz ) )
+ {
+ if ( !StringUtils.equals( expectedAction.clazz, xwActionConfig.getClassName() ) )
+ {
+ violations.add( "xwork.xml - Expected class attribute value of " + quote( expectedAction.clazz ) +
+ " but got " + quote( xwActionConfig.getClassName() ) + " instead, on action " +
+ quote( expectedAction.name ) + " in package " + quote( expectedPackage.name ) + "." );
+ }
+ }
+
+ if ( StringUtils.isNotEmpty( expectedAction.method ) )
+ {
+ if ( !StringUtils.equals( expectedAction.method, xwActionConfig.getMethodName() ) )
+ {
+ violations.add( "xwork.xml - Expected method attribute value of " + quote( expectedAction.method ) +
+ " but got " + quote( xwActionConfig.getMethodName() ) + " instead, on action " +
+ quote( expectedAction.name ) + " in package " + quote( expectedPackage.name ) + "." );
+ }
+ }
+
+ Map<?, ?> xwResultMap = xwActionConfig.getResults();
+
+ if ( expectedAction.results.isEmpty() )
+ {
+ // Check for single default result.
+ if ( xwResultMap.size() < 1 )
+ {
+ violations.add( "xwork.xml - Missing default result on action name " +
+ quote( expectedAction.name ) + " in package " + quote( expectedPackage.name ) + "." );
+ }
+ }
+ else
+ {
+ // Check for named result names.
+ for ( String resultName : expectedAction.results )
+ {
+ if ( xwResultMap.get( resultName ) == null )
+ {
+ violations.add( "xwork.xml - Missing named result " + quote( resultName ) + " in action " +
+ quote( expectedAction.name ) + " in package " + quote( expectedPackage.name ) + "." );
+ }
+ }
+ }
+ }
+ else
+ {
+ violations.add( "xwork.xml - Missing action named " + quote( expectedAction.name ) + " in package " +
+ quote( expectedPackage.name ) + "." );
+ }
+ }
+
+ protected void checkPackage( List<String> violations, XworkPackageConfig expectedPackage, Configuration xwConfig )
+ {
+ PackageConfig xwPackageConfig = findPackageNamespace( xwConfig, expectedPackage.name );
+
+ if ( xwPackageConfig != null )
+ {
+ Map<?, ?> xwActionMap = xwPackageConfig.getActionConfigs();
+
+ for ( XworkActionConfig expectedAction : expectedPackage.actions )
+ {
+ checkAction( violations, expectedPackage, expectedAction, xwActionMap );
+ }
+ }
+ else
+ {
+ violations.add( "Missing " + quote( expectedPackage.name ) + " package namespace in xwork.xml" );
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ protected PackageConfig findPackageNamespace( Configuration xwConfig, String name )
+ {
+ Map<?,PackageConfig> xwPackageConfigMap = xwConfig.getPackageConfigs();
+
+ for ( PackageConfig xwPackageConfig : xwPackageConfigMap.values() )
+ {
+ if ( StringUtils.equals( name, xwPackageConfig.getNamespace() ) )
+ {
+ return xwPackageConfig;
+ }
+ }
+
+ return null;
+ }
+
+ protected String quote( Object o )
+ {
+ if ( o == null )
+ {
+ return "<null>";
+ }
+ return "\"" + o.toString() + "\"";
+ }
+
+}
--- /dev/null
+package org.apache.archiva.redback.struts2.checks;
+
+/*
+ * 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 java.util.List;
+
+import org.apache.archiva.redback.system.check.EnvironmentCheck;
+
+/**
+ * ExpectedXworkActions
+ *
+ * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
+ */
+public class ExpectedXworkActions
+ implements EnvironmentCheck
+{
+ public void validateEnvironment( List<String> violations )
+ {
+ String classNames[] = new String[]{"org.apache.archiva.redback.struts2.action.admin.UserCreateAction",
+ "org.apache.archiva.redback.struts2.action.admin.UserDeleteAction",
+ "org.apache.archiva.redback.struts2.action.admin.UserEditAction",
+ "org.apache.archiva.redback.struts2.action.admin.UserListAction",
+ "org.apache.archiva.redback.struts2.action.AccountAction",
+ "org.apache.archiva.redback.struts2.action.LoginAction",
+ "org.apache.archiva.redback.struts2.action.LogoutAction",
+ "org.apache.archiva.redback.struts2.action.PasswordAction",
+ "org.apache.archiva.redback.struts2.action.RegisterAction",
+ "org.apache.archiva.redback.struts2.action.admin.AdminConsoleAction",
+ "org.apache.archiva.redback.struts2.action.admin.SystemInfoAction"};
+
+ int count = 0;
+
+ for ( int i = 0; i >= classNames.length; i++ )
+ {
+ if ( !classExists( violations, classNames[i] ) )
+ {
+ count++;
+ }
+ }
+
+ if ( count > 0 )
+ {
+ violations.add( "Missing [" + count + "] xwork Actions." );
+ }
+ }
+
+ private boolean classExists( List<String> violations, String className )
+ {
+ try
+ {
+ Class.forName( className );
+
+ // TODO: check that class is an instance of Action?
+ }
+ catch ( ClassNotFoundException e )
+ {
+ violations.add( "Missing xwork Action class " + quote( className ) + "." );
+ return false;
+ }
+ return true;
+ }
+
+ private String quote( Object o )
+ {
+ if ( o == null )
+ {
+ return "<null>";
+ }
+ return "\"" + o.toString() + "\"";
+ }
+}
--- /dev/null
+package org.apache.archiva.redback.struts2.checks;
+
+/*
+ * 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 java.util.ArrayList;
+import java.util.List;
+
+import org.apache.archiva.redback.system.check.EnvironmentCheck;
+import org.apache.archiva.redback.integration.checks.xwork.XworkPackageConfig;
+
+import com.opensymphony.xwork2.config.Configuration;
+import com.opensymphony.xwork2.config.ConfigurationManager;
+
+/**
+ * <p/>
+ * ExpectedXworkConfiguration reason for existence is to validate that the executing
+ * environment has everything needed for a proper execution of
+ * Plexus Security :: UI Web components and javascript and jsps.
+ * </p>
+ * <p/>
+ * <p/>
+ * It is quite possible for the environment overlay to have not been done.
+ * Such as when using <code>"mvn jetty:run"</code>, but forgetting to run
+ * <code>"mvn war:inplace"</code> first.
+ * </p>
+ *
+ * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
+ * @version $Id$
+ *
+ * TODO: Address comment below and add back in the component declaration
+ *
+ */
+public class ExpectedXworkConfiguration
+ extends AbstractXworkConfigurationCheck
+ implements EnvironmentCheck
+{
+ public void validateEnvironment( List<String> violations )
+ {
+ // Get the configuration.
+
+ Configuration xworkConfig = new ConfigurationManager().getConfiguration();
+
+ if ( xworkConfig != null )
+ {
+ List<String> internalViolations = new ArrayList<String>();
+
+ /* PLXREDBACK-67
+ * TODO: this currently throws a violation since the standard practice is
+ * to include the xwork-security namespace in from the war overlay. Otherwise
+ * all actions in the security namespace are also addressable from the
+ * root default action lookup since by extending the security package thats how
+ * webwork/xwork deals with the actions
+ */
+ XworkPackageConfig expectedPackage = new XworkPackageConfig( "/security" );
+
+ expectedPackage.addAction( "account", "redback-account", "show" ).addResult( "input" ).addResult(
+ "error" ).addResult( "success" );
+
+ expectedPackage.addAction( "login", "redback-login", "show" ).addResult( "input" ).addResult(
+ "error" ).addResult( "success" );
+
+ expectedPackage.addAction( "logout", "redback-logout", "show" ).addResult( "input" ).addResult(
+ "error" ).addResult( "success" );
+
+ expectedPackage.addAction( "register", "redback-register", "show" ).addResult( "input" ).addResult(
+ "error" ).addResult( "success" );
+
+ expectedPackage.addAction( "password", "redback-password", "show" ).addResult( "input" ).addResult(
+ "error" ).addResult( "success" );
+
+ // -----------------------------------------------------------------
+ // Security Admin Tests
+
+ expectedPackage.addAction( "systeminfo", "redback-sysinfo", "show" );
+ expectedPackage.addAction( "adminConsole", "redback-admin-console", "show" );
+
+ expectedPackage.addAction( "userlist", "redback-admin-user-list", "show" ).addResult( "input" ).addResult(
+ "success" );
+
+ expectedPackage.addAction( "useredit", "redback-admin-user-edit", "edit" ).addResult( "input" ).addResult(
+ "error" ).addResult( "success" );
+
+ expectedPackage.addAction( "usercreate", "redback-admin-user-create", "edit" ).addResult( "input" ).addResult(
+ "error" ).addResult( "success" );
+
+ expectedPackage.addAction( "userdelete", "redback-admin-user-delete", "confirm" ).addResult(
+ "input" ).addResult( "error" ).addResult( "success" );
+
+ expectedPackage.addAction( "assignments", "redback-assignments", "show" ).addResult( "input" ).addResult(
+ "error" ).addResult( "success" );
+
+ expectedPackage.addAction( "roles", "redback-roles", "show" ).addResult( "input" ).addResult(
+ "error" ).addResult( "success" );
+
+ expectedPackage.addAction( "permissions", "redback-permissions", "show" ).addResult( "input" ).addResult(
+ "error" ).addResult( "success" );
+
+ checkPackage( internalViolations, expectedPackage, xworkConfig );
+
+ if ( internalViolations.size() > 0 )
+ {
+ violations.addAll( internalViolations );
+ violations.add( "Missing [" + internalViolations.size() + "] xwork.xml configuration elements." );
+ }
+ }
+ else
+ {
+ violations.add( "Missing xwork.xml configuration." );
+ }
+ }
+
+}
--- /dev/null
+package org.apache.archiva.redback.struts2.interceptor;
+
+/*
+ * 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 com.opensymphony.xwork2.ActionContext;
+import com.opensymphony.xwork2.ActionInvocation;
+import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
+import org.apache.struts2.StrutsException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.context.ApplicationContext;
+import org.springframework.web.context.WebApplicationContext;
+
+import java.util.Map;
+
+public abstract class AbstractHttpRequestTrackerInterceptor
+ extends AbstractInterceptor
+{
+ public static final String TRACKER_NAME = ActionInvocationTracker.class.getName( )+ ":name";
+
+ protected Logger logger = LoggerFactory.getLogger( getClass() );
+
+ protected abstract String getTrackerName();
+
+ @Override
+ public void init()
+ {
+ super.init();
+ logger.info( "{} initialized!", this.getClass().getName() );
+ }
+
+ @SuppressWarnings( "unchecked" )
+ protected synchronized ActionInvocationTracker addActionInvocation( ActionInvocation invocation )
+ {
+ Map<String, Object> sessionMap = invocation.getInvocationContext().getSession();
+
+ ApplicationContext applicationContext = (ApplicationContext) ActionContext.getContext().getApplication().get(
+ WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE );
+ if ( applicationContext == null )
+ {
+ throw new StrutsException( "Could not locate ApplicationContext" );
+ }
+
+ ActionInvocationTracker tracker = (ActionInvocationTracker) sessionMap.get( ActionInvocationTracker.class.getName() );
+
+ if ( tracker == null )
+ {
+ //noinspection deprecation
+ tracker = applicationContext.getBean( getTrackerName(), ActionInvocationTracker.class );
+ sessionMap.put( ActionInvocationTracker.class.getName(), tracker );
+ }
+
+ tracker.addActionInvocation( invocation );
+
+ return tracker;
+ }
+}
--- /dev/null
+package org.apache.archiva.redback.struts2.interceptor;
+
+/*
+ * 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 com.opensymphony.xwork2.ActionInvocation;
+
+public interface ActionInvocationTracker
+{
+
+ static final String SESSION_KEY = ActionInvocationTracker.class.getName();
+
+ void setHistorySize( int size );
+
+ int getHistorySize();
+
+ int getHistoryCount();
+
+ SavedActionInvocation getPrevious();
+
+ SavedActionInvocation getCurrent();
+
+ SavedActionInvocation getActionInvocationAt( int index );
+
+ void addActionInvocation( ActionInvocation invocation );
+
+ void setBackTrack();
+
+ void unsetBackTrack();
+
+ boolean isBackTracked();
+}
--- /dev/null
+package org.apache.archiva.redback.struts2.interceptor;
+
+/*
+ * 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 com.opensymphony.xwork2.ActionContext;
+import com.opensymphony.xwork2.ActionInvocation;
+import com.opensymphony.xwork2.interceptor.Interceptor;
+import org.apache.archiva.redback.keys.AuthenticationKey;
+import org.apache.archiva.redback.policy.AccountLockedException;
+import org.apache.archiva.redback.policy.MustChangePasswordException;
+import org.apache.struts2.ServletActionContext;
+import org.apache.archiva.redback.authentication.AuthenticationException;
+import org.apache.archiva.redback.authentication.AuthenticationResult;
+import org.apache.archiva.redback.authentication.TokenBasedAuthenticationDataSource;
+import org.apache.archiva.redback.system.SecuritySession;
+import org.apache.archiva.redback.system.SecuritySystem;
+import org.apache.archiva.redback.system.SecuritySystemConstants;
+import org.apache.archiva.redback.users.UserNotFoundException;
+import org.apache.archiva.redback.integration.util.AutoLoginCookies;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.context.annotation.Scope;
+import org.springframework.stereotype.Controller;
+
+import javax.inject.Inject;
+import javax.servlet.http.HttpSession;
+
+/**
+ * AutoLoginInterceptor
+ *
+ * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
+ */
+@Controller( "redbackAutoLoginInterceptor" )
+@Scope( "prototype" )
+public class AutoLoginInterceptor
+ implements Interceptor
+{
+ private Logger log = LoggerFactory.getLogger( AutoLoginInterceptor.class );
+
+ static final String PASSWORD_CHANGE = "security-must-change-password";
+
+ static final String ACCOUNT_LOCKED = "security-login-locked";
+
+ /**
+ *
+ */
+ @Inject
+ private SecuritySystem securitySystem;
+
+ /**
+ *
+ */
+ @Inject
+ private AutoLoginCookies autologinCookies;
+
+ public void destroy()
+ {
+ // Ignore
+ }
+
+ public void init()
+ {
+ // Ignore
+ }
+
+ /**
+ * @noinspection ProhibitedExceptionDeclared
+ */
+ public String intercept( ActionInvocation invocation )
+ throws Exception
+ {
+ SecuritySession securitySession = getSecuritySession();
+
+ if ( securitySession != null && securitySession.isAuthenticated() )
+ {
+ // User already authenticated.
+ log.debug( "User already authenticated." );
+
+ if ( !checkCookieConsistency( securitySession ) )
+ {
+ // update single sign on cookie
+ autologinCookies.setSignonCookie( securitySession.getUser().getUsername(),
+ ServletActionContext.getResponse(),
+ ServletActionContext.getRequest() );
+ }
+ }
+ else
+ {
+ AuthenticationKey authkey =
+ autologinCookies.getSignonKey( ServletActionContext.getResponse(), ServletActionContext.getRequest() );
+
+ if ( authkey != null )
+ {
+ try
+ {
+ securitySession = checkAuthentication( authkey, invocation.getInvocationContext().getName().equals(
+ PASSWORD_CHANGE ) );
+
+ if ( securitySession != null && securitySession.isAuthenticated() )
+ {
+ ActionContext.getContext().getSession().put( SecuritySystemConstants.SECURITY_SESSION_KEY,
+ securitySession );
+ checkCookieConsistency( securitySession );
+ }
+ else
+ {
+ autologinCookies.removeSignonCookie( ServletActionContext.getResponse(),
+ ServletActionContext.getRequest() );
+ autologinCookies.removeRememberMeCookie( ServletActionContext.getResponse(),
+ ServletActionContext.getRequest() );
+ }
+ }
+ catch ( AccountLockedException e )
+ {
+ log.info( "Account Locked : Username [{}]", e.getUser().getUsername(), e );
+ autologinCookies.removeSignonCookie( ServletActionContext.getResponse(),
+ ServletActionContext.getRequest() );
+ autologinCookies.removeRememberMeCookie( ServletActionContext.getResponse(),
+ ServletActionContext.getRequest() );
+ return ACCOUNT_LOCKED;
+ }
+ catch ( MustChangePasswordException e )
+ {
+ return PASSWORD_CHANGE;
+ }
+ }
+ else if ( autologinCookies.isRememberMeEnabled() )
+ {
+ authkey = autologinCookies.getRememberMeKey( ServletActionContext.getResponse(),
+ ServletActionContext.getRequest() );
+
+ if ( authkey != null )
+ {
+ try
+ {
+ securitySession = checkAuthentication( authkey, false );
+
+ if ( securitySession == null || !securitySession.isAuthenticated() )
+ {
+ autologinCookies.removeRememberMeCookie( ServletActionContext.getResponse(),
+ ServletActionContext.getRequest() );
+ }
+ }
+ catch ( AccountLockedException e )
+ {
+ log.info( "Account Locked : Username [{}]", e.getUser().getUsername(), e );
+ autologinCookies.removeRememberMeCookie( ServletActionContext.getResponse(),
+ ServletActionContext.getRequest() );
+ return ACCOUNT_LOCKED;
+ }
+ catch ( MustChangePasswordException e )
+ {
+ return PASSWORD_CHANGE;
+ }
+ }
+ }
+ }
+
+ return invocation.invoke();
+ }
+
+ private boolean checkCookieConsistency( SecuritySession securitySession )
+ {
+ String username = securitySession.getUser().getUsername();
+
+ boolean failed = false;
+
+ AuthenticationKey key =
+ autologinCookies.getRememberMeKey( ServletActionContext.getResponse(), ServletActionContext.getRequest() );
+ if ( key != null )
+ {
+ if ( !key.getForPrincipal().equals( username ) )
+ {
+ log.debug( "Login invalidated: remember me cookie was for{}; but session was for {}",
+ key.getForPrincipal(), username );
+ failed = true;
+ }
+ }
+
+ if ( !failed )
+ {
+ key =
+ autologinCookies.getSignonKey( ServletActionContext.getResponse(), ServletActionContext.getRequest() );
+ if ( key != null )
+ {
+ if ( !key.getForPrincipal().equals( username ) )
+ {
+ log.debug( "Login invalidated: signon cookie was for {}; but session was for {}",
+ key.getForPrincipal(), username );
+ failed = true;
+ }
+ }
+ else
+ {
+ log.debug( "Login invalidated: signon cookie was removed" );
+ failed = true;
+ }
+ }
+
+ if ( failed )
+ {
+ removeCookiesAndSession();
+ }
+
+ return failed;
+ }
+
+ private SecuritySession checkAuthentication( AuthenticationKey authkey, boolean enforcePasswordChange )
+ throws AccountLockedException, MustChangePasswordException
+ {
+ SecuritySession securitySession = null;
+ log.debug( "Logging in with an authentication key: {}", authkey.getForPrincipal() );
+ TokenBasedAuthenticationDataSource authsource = new TokenBasedAuthenticationDataSource();
+ authsource.setPrincipal( authkey.getForPrincipal() );
+ authsource.setToken( authkey.getKey() );
+ authsource.setEnforcePasswordChange( enforcePasswordChange );
+
+ try
+ {
+ securitySession = securitySystem.authenticate( authsource );
+
+ if ( securitySession.isAuthenticated() )
+ {
+ // TODO: this should not happen if there is a password change required - but the password change action needs to log the user in on success to swap them
+ log.debug( "Login success." );
+
+ HttpSession session = ServletActionContext.getRequest().getSession( true );
+ session.setAttribute( SecuritySystemConstants.SECURITY_SESSION_KEY, securitySession );
+ log.debug( "Setting session:{} to {}", SecuritySystemConstants.SECURITY_SESSION_KEY, securitySession );
+
+ autologinCookies.setSignonCookie( authkey.getForPrincipal(), ServletActionContext.getResponse(),
+ ServletActionContext.getRequest() );
+ }
+ else
+ {
+ AuthenticationResult result = securitySession.getAuthenticationResult();
+ log.info( "Login interceptor failed against principal : {}", result.getPrincipal(),
+ result.getException() );
+ }
+
+ }
+ catch ( AuthenticationException e )
+ {
+ log.info( "Authentication Exception.", e );
+ }
+ catch ( UserNotFoundException e )
+ {
+ log.info( "User Not Found: {}", authkey.getForPrincipal(), e );
+ }
+ return securitySession;
+ }
+
+ private void removeCookiesAndSession()
+ {
+ autologinCookies.removeRememberMeCookie( ServletActionContext.getResponse(),
+ ServletActionContext.getRequest() );
+ autologinCookies.removeSignonCookie( ServletActionContext.getResponse(), ServletActionContext.getRequest() );
+
+ HttpSession session = ServletActionContext.getRequest().getSession();
+ if ( session != null )
+ {
+ session.removeAttribute( SecuritySystemConstants.SECURITY_SESSION_KEY );
+ }
+ }
+
+ private SecuritySession getSecuritySession()
+ {
+ HttpSession session = ServletActionContext.getRequest().getSession();
+ if ( session == null )
+ {
+ log.debug( "No HTTP Session exists." );
+ return null;
+ }
+
+ SecuritySession secSession =
+ (SecuritySession) session.getAttribute( SecuritySystemConstants.SECURITY_SESSION_KEY );
+ log.debug( "Returning Security Session: {}", secSession );
+ return secSession;
+ }
+}
--- /dev/null
+package org.apache.archiva.redback.struts2.interceptor;
+
+/*
+ * 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 com.opensymphony.xwork2.ActionInvocation;
+import com.opensymphony.xwork2.interceptor.Interceptor;
+import org.apache.archiva.redback.system.check.EnvironmentCheck;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.context.annotation.Scope;
+import org.springframework.stereotype.Controller;
+
+import javax.annotation.PostConstruct;
+import javax.inject.Inject;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * EnvironmentCheckInterceptor
+ *
+ * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
+ * @version $Id$
+ */
+@Controller( "redbackEnvironmentCheckInterceptor" )
+@Scope( "prototype" )
+public class EnvironmentCheckInterceptor
+ implements Interceptor
+{
+ private static boolean checked = false;
+
+ private Logger log = LoggerFactory.getLogger( EnvironmentCheckInterceptor.class );
+
+
+ /**
+ *
+ */
+ @Inject
+ private List<EnvironmentCheck> checkers;
+
+ public void destroy()
+ {
+ // no-op
+ }
+
+ @PostConstruct
+ public void init()
+ {
+
+ if ( EnvironmentCheckInterceptor.checked )
+ {
+ // No need to check twice.
+ return;
+ }
+
+ if ( checkers != null )
+ {
+ List<String> violations = new ArrayList<String>();
+
+ for ( EnvironmentCheck check : checkers )
+ {
+ check.validateEnvironment( violations );
+ }
+
+ if ( !violations.isEmpty() )
+ {
+ StringBuffer msg = new StringBuffer();
+ 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() );
+ }
+ }
+
+ EnvironmentCheckInterceptor.checked = true;
+ }
+
+ public String intercept( ActionInvocation invocation )
+ throws Exception
+ {
+ // A no-op here. Work for this intereceptor is done in init().
+ return invocation.invoke();
+ }
+}
--- /dev/null
+package org.apache.archiva.redback.struts2.interceptor;
+
+/*
+ * 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 com.opensymphony.xwork2.ActionInvocation;
+import com.opensymphony.xwork2.interceptor.Interceptor;
+import org.apache.archiva.redback.integration.checks.security.AdminAutoCreateCheck;
+import org.apache.archiva.redback.users.User;
+import org.apache.archiva.redback.users.UserNotFoundException;
+import org.apache.commons.lang.StringUtils;
+import org.apache.struts2.ServletActionContext;
+import org.apache.archiva.redback.authentication.PasswordBasedAuthenticationDataSource;
+import org.apache.archiva.redback.configuration.UserConfiguration;
+import org.apache.archiva.redback.role.RoleManager;
+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.SecuritySystemConstants;
+import org.apache.archiva.redback.users.UserManager;
+import org.apache.archiva.redback.integration.util.AutoLoginCookies;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.context.annotation.Scope;
+import org.springframework.stereotype.Controller;
+
+import javax.inject.Inject;
+import javax.inject.Named;
+import java.io.File;
+import java.io.FileInputStream;
+import java.util.Date;
+import java.util.Map;
+import java.util.Properties;
+
+/**
+ * EnvironmentCheckInterceptor
+ *
+ * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
+ * @version $Id$
+ */
+@Controller( "redbackForceAdminUserInterceptor" )
+@Scope( "prototype" )
+public class ForceAdminUserInterceptor
+ implements Interceptor
+{
+ private Logger log = LoggerFactory.getLogger( getClass() );
+
+ private static final String SECURITY_ADMIN_USER_NEEDED = "security-admin-user-needed";
+
+ private static boolean checked = false;
+
+ /**
+ * role-hint="configurable"
+ */
+ @Inject
+ @Named( value = "userManager#configurable" )
+ private UserManager userManager;
+
+ /**
+ * role-hint="default"
+ */
+ @Inject
+ private RoleManager roleManager;
+
+ /**
+ * role-hint="default"
+ */
+ @Inject
+ private UserConfiguration config;
+
+ @Inject
+ protected SecuritySystem securitySystem;
+
+ @Inject
+ private AutoLoginCookies autologinCookies;
+
+ protected Map<String, Object> session;
+
+ public void destroy()
+ {
+ // no-op
+ }
+
+ public void init()
+ {
+
+ }
+
+ public String intercept( ActionInvocation invocation )
+ throws Exception
+ {
+ if ( checked )
+ {
+ return invocation.invoke();
+ }
+
+ try
+ {
+ User user = userManager.findUser( getAdminUid() );
+ if ( user == null )
+ {
+ user = useForceAdminFile();
+ if ( user == null )
+ {
+ log.info( "No admin user configured - forwarding to admin user creation page." );
+ return SECURITY_ADMIN_USER_NEEDED;
+ }
+ }
+
+ assignAdminRole( user );
+
+ checked = true;
+ log.info( "Admin user found. No need to configure admin user." );
+
+ }
+ catch ( UserNotFoundException e )
+ {
+ User user = useForceAdminFile();
+ if ( user != null )
+ {
+ assignAdminRole( user );
+
+ checked = true;
+ }
+ else
+ {
+ log.info( "No admin user found - forwarding to admin user creation page." );
+ return SECURITY_ADMIN_USER_NEEDED;
+ }
+ }
+
+ return invocation.invoke();
+ }
+
+ private User useForceAdminFile()
+ {
+ try
+ {
+ String forceAdminFilePath = System.getProperty( AdminAutoCreateCheck.FORCE_ADMIN_FILE_PATH );
+ if ( StringUtils.isBlank( forceAdminFilePath ) )
+ {
+ log.info( AdminAutoCreateCheck.FORCE_ADMIN_FILE_PATH + " system props is empty don't use an auto creation admin " );
+ return null;
+ }
+ File file = new File( forceAdminFilePath );
+ if ( !file.exists() )
+ {
+ log.warn( "file set in sysprops " + AdminAutoCreateCheck.FORCE_ADMIN_FILE_PATH + " not exists skip admin auto creation" );
+ return null;
+ }
+ Properties properties = new Properties();
+ FileInputStream fis = null;
+ try
+ {
+ properties.load( new FileInputStream( file ) );
+ }
+ catch ( Exception e )
+ {
+ log.warn( "error loading properties from file " + forceAdminFilePath + " skip admin auto creation" );
+ return null;
+ }
+
+ // ensure we have all properties
+ String password = properties.getProperty( AdminAutoCreateCheck.ADMIN_PASSWORD_KEY );
+ String email = properties.getProperty( AdminAutoCreateCheck.ADMIN_EMAIL_KEY );
+ String fullName = properties.getProperty( AdminAutoCreateCheck.ADMIN_FULL_NAME_KEY );
+
+ if ( StringUtils.isBlank( password ) )
+ {
+ log.warn( "property " + AdminAutoCreateCheck.ADMIN_PASSWORD_KEY + " not set skip auto admin creation" );
+ return null;
+ }
+
+ if ( StringUtils.isBlank( email ) )
+ {
+ log.warn( "property " + AdminAutoCreateCheck.ADMIN_EMAIL_KEY + " not set skip auto admin creation" );
+ return null;
+ }
+
+ if ( StringUtils.isBlank( fullName ) )
+ {
+ log.warn( "property " + AdminAutoCreateCheck.ADMIN_FULL_NAME_KEY + " not set skip auto admin creation" );
+ return null;
+ }
+
+ User u = userManager.createUser( getAdminUid(), fullName, email );
+
+ u.setPassword( password );
+ u.setLocked( false );
+ u.setPasswordChangeRequired( false );
+ u.setPermanent( true );
+
+ u = userManager.addUser( u );
+ u.setPassword( password );
+
+ PasswordBasedAuthenticationDataSource authdatasource = new PasswordBasedAuthenticationDataSource();
+ authdatasource.setPrincipal( u.getUsername() );
+ authdatasource.setPassword( u.getPassword() );
+ SecuritySession securitySession = securitySystem.authenticate( authdatasource );
+ if ( securitySession.getAuthenticationResult().isAuthenticated() )
+ {
+ // good add various tokens.
+ ServletActionContext.getRequest().getSession( true ).setAttribute(
+ SecuritySystemConstants.SECURITY_SESSION_KEY, securitySession );
+ autologinCookies.setSignonCookie( authdatasource.getPrincipal(), ServletActionContext.getResponse(),
+ ServletActionContext.getRequest() );
+ u = securitySession.getUser();
+ u.setLastLoginDate( new Date() );
+ securitySystem.getUserManager().updateUser( u );
+ }
+
+ return u;
+ }
+ catch ( Exception e )
+ {
+ log.warn( "failed to automatically create an admin account " + e.getMessage(), e );
+ }
+ return null;
+ }
+
+ private String getAdminUid()
+ {
+ return config.getString( "redback.default.admin" );
+ }
+
+ private void assignAdminRole( User user )
+ throws RoleManagerException
+ {
+ roleManager.assignRole( "system-administrator", user.getPrincipal().toString() );
+ }
+}
--- /dev/null
+package org.apache.archiva.redback.struts2.interceptor;
+
+/*
+ * 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 java.util.Calendar;
+import java.util.Map;
+
+import javax.inject.Inject;
+import javax.servlet.http.HttpServletRequest;
+
+import org.apache.archiva.redback.configuration.UserConfiguration;
+import org.apache.archiva.redback.users.UserManager;
+import org.apache.struts2.ServletActionContext;
+import org.apache.archiva.redback.policy.UserSecurityPolicy;
+import org.apache.archiva.redback.system.DefaultSecuritySession;
+import org.apache.archiva.redback.system.SecuritySession;
+import org.apache.archiva.redback.system.SecuritySystem;
+import org.apache.archiva.redback.system.SecuritySystemConstants;
+import org.apache.archiva.redback.users.User;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.opensymphony.xwork2.ActionContext;
+import com.opensymphony.xwork2.ActionInvocation;
+import com.opensymphony.xwork2.interceptor.Interceptor;
+import org.springframework.context.annotation.Scope;
+import org.springframework.stereotype.Controller;
+
+/**
+ * Interceptor to force the user to perform actions, when required.
+ *
+ * @author Edwin Punzalan
+ */
+@Controller( "redbackPolicyEnforcementInterceptor" )
+@Scope( "prototype" )
+public class PolicyEnforcementInterceptor
+ implements Interceptor
+{
+ private Logger log = LoggerFactory.getLogger( PolicyEnforcementInterceptor.class );
+
+ private static final String SECURITY_USER_MUST_CHANGE_PASSWORD = "security-must-change-password";
+
+ /**
+ *
+ */
+ @Inject
+ private UserConfiguration config;
+
+ /**
+ *
+ */
+ @Inject
+ protected SecuritySystem securitySystem;
+
+ public void destroy()
+ {
+ //ignore
+ }
+
+ public void init()
+ {
+ //ignore
+ }
+
+ /**
+ * 1) validate that the user doesn't have to change their password, if they do then re-route accordingly
+ *
+ * @param actionInvocation
+ * @return
+ * @throws Exception
+ */
+ @SuppressWarnings("unchecked")
+ public String intercept( ActionInvocation actionInvocation )
+ throws Exception
+ {
+
+ if ( config.getBoolean( "security.policy.strict.enforcement.enabled" ) )
+ {
+ log.debug( "Enforcement: enforcing per click security policies." );
+
+
+ ActionContext context = ActionContext.getContext();
+
+ SecuritySession securitySession = null;
+
+ try
+ {
+ securitySession = (SecuritySession) context.getSession().get( SecuritySystemConstants.SECURITY_SESSION_KEY );
+ }
+ catch (IllegalStateException e)
+ {
+ log.debug("Could not get security session as the session was invalid", e);
+ }
+
+ UserSecurityPolicy policy = securitySystem.getPolicy();
+
+ if ( securitySession != null )
+ {
+ UserManager userManager = securitySystem.getUserManager();
+ User user = userManager.findUser( securitySession.getUser().getPrincipal() );
+ securitySession = new DefaultSecuritySession( securitySession.getAuthenticationResult(), user );
+ context.getSession().put( SecuritySystemConstants.SECURITY_SESSION_KEY, securitySession );
+ }
+ else
+ {
+ log.debug( "Enforcement: no user security session detected, skipping enforcement" );
+ return actionInvocation.invoke();
+ }
+
+ if ( checkForcePasswordChange( securitySession, actionInvocation ) )
+ {
+ Map<String, Object> session = ServletActionContext.getContext().getSession();
+ HttpServletRequest request = ServletActionContext.getRequest();
+
+ String queryString = request.getQueryString();
+ String targetUrl = request.getRequestURL() + ( queryString==null ? "" : "?" + queryString );
+
+ session.put( "targetUrl", targetUrl );
+
+ log.info( "storing targetUrl : {}", targetUrl );
+
+ return SECURITY_USER_MUST_CHANGE_PASSWORD;
+ }
+
+ if ( config.getBoolean( "security.policy.password.expiration.enabled" ) )
+ {
+ log.debug( "checking password expiration notification" );
+
+ UserManager userManager = securitySystem.getUserManager();
+ User user = userManager.findUser( securitySession.getUser().getPrincipal() );
+
+ Calendar expirationNotifyDate = Calendar.getInstance();
+ expirationNotifyDate.setTime( user.getLastPasswordChange() );
+ // add on the total days to expire minus the notification days
+ expirationNotifyDate.add( Calendar.DAY_OF_MONTH, policy.getPasswordExpirationDays() - config.getInt( "security.policy.password.expiration.notify.days" ) );
+
+ Calendar now = Calendar.getInstance();
+
+ if ( now.after( expirationNotifyDate ) )
+ {
+ log.debug( "setting password expiration notification" );
+
+ Calendar expirationDate = Calendar.getInstance();
+ expirationDate.setTime( user.getLastPasswordChange() );
+ expirationDate.add( Calendar.DAY_OF_MONTH, policy.getPasswordExpirationDays() );
+ Map<String, Object> session = ServletActionContext.getContext().getSession();
+ session.put( "passwordExpirationNotification", expirationDate.getTime().toString() );
+ }
+ }
+
+ return actionInvocation.invoke();
+ }
+ else
+ {
+ log.debug( "Enforcement: not processing per click security policies." );
+ return actionInvocation.invoke();
+ }
+ }
+
+ private boolean checkForcePasswordChange( SecuritySession securitySession, ActionInvocation actionInvocation )
+ {
+ /*
+ * FIXME: something less 'hackish'
+ *
+ * these two classes should not be subject to this enforcement policy and this
+ * ideally should be governed by the interceptor stacks but that just didn't work
+ * when I was trying to solve the problem that way, psquad32 recommended I just
+ * find a way to get around this interceptor in the particular case I needed to and use
+ * "One stack to rule them all
+ */
+ if ( "org.apache.archiva.redback.struts2.action.PasswordAction".equals( actionInvocation.getAction().getClass().getName() ) )
+ {
+ log.debug( "Enforcement: skipping force password check on password action" );
+ return false;
+ }
+
+ if ( "org.apache.archiva.redback.struts2.action.LoginAction".equals( actionInvocation.getAction().getClass().getName() ) )
+ {
+ log.debug( "Enforcement: skipping force password check on login action" );
+ return false;
+ }
+
+ if ( "org.apache.archiva.redback.struts2.action.LogoutAction".equals( actionInvocation.getAction().getClass().getName() ) )
+ {
+ log.debug( "Enforcement: skipping force password check on logout action" );
+ return false;
+ }
+
+ if ( config.getBoolean( "security.policy.strict.force.password.change.enabled" ) )
+ {
+ log.debug( "Enforcement: checking active user password change enabled" );
+
+ if ( securitySession.getUser().isPasswordChangeRequired() )
+ {
+ log.info( "Enforcement: User must change password - forwarding to change password page." );
+
+ return true;
+ }
+ else
+ {
+ log.debug( "Enforcement: User doesn't need to change password." );
+ }
+ }
+ return false;
+ }
+
+}
--- /dev/null
+package org.apache.archiva.redback.struts2.interceptor;
+
+/*
+ * 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 com.opensymphony.xwork2.ActionInvocation;
+
+import java.util.HashMap;
+import java.util.Map;
+
+public class SavedActionInvocation
+{
+ private String namespace;
+
+ private String actionName;
+
+ private Map<String, Object> parameterMap;
+
+ private String methodName;
+
+ @SuppressWarnings("unchecked")
+ public SavedActionInvocation( ActionInvocation invocation )
+ {
+ namespace = invocation.getProxy().getNamespace();
+ actionName = invocation.getProxy().getActionName();
+ methodName = invocation.getProxy().getMethod();
+
+ parameterMap = new HashMap<String, Object>();
+
+ parameterMap.putAll( invocation.getInvocationContext().getParameters() );
+ }
+
+ public String getNamespace()
+ {
+ return namespace;
+ }
+
+ public String getActionName()
+ {
+ return actionName;
+ }
+
+ public Map<String,Object> getParametersMap()
+ {
+ return parameterMap;
+ }
+
+ public String getMethodName()
+ {
+ return methodName;
+ }
+}
--- /dev/null
+package org.apache.archiva.redback.struts2.interceptor;
+
+/*
+ * 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 com.google.common.collect.Lists;
+import com.opensymphony.xwork2.Action;
+import com.opensymphony.xwork2.ActionContext;
+import com.opensymphony.xwork2.ActionInvocation;
+import org.apache.commons.lang.StringUtils;
+import org.apache.commons.lang.SystemUtils;
+import org.apache.struts2.ServletActionContext;
+import org.apache.archiva.redback.authorization.AuthorizationResult;
+import org.apache.archiva.redback.system.SecuritySession;
+import org.apache.archiva.redback.system.SecuritySystem;
+import org.apache.archiva.redback.system.SecuritySystemConstants;
+import org.apache.archiva.redback.integration.interceptor.SecureAction;
+import org.apache.archiva.redback.integration.interceptor.SecureActionBundle;
+import org.apache.archiva.redback.integration.interceptor.SecureActionException;
+import org.springframework.context.annotation.Scope;
+import org.springframework.stereotype.Controller;
+
+import javax.inject.Inject;
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpSession;
+import java.util.List;
+
+/**
+ * SecureActionInterceptor: Interceptor that will detect webwork actions that implement the SecureAction
+ * interface and providing they do verify that the current user is authorized to execute the action
+ *
+ * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
+ * @author Jesse McConnell <jesse@codehaus.org>
+ * @version $Id$
+ */
+@Controller( "redbackSecureActionInterceptor" )
+@Scope( "prototype" )
+public class SecureActionInterceptor
+ extends AbstractHttpRequestTrackerInterceptor
+{
+ private static final String REQUIRES_AUTHORIZATION = "requires-authorization";
+
+ private static final String REQUIRES_AUTHENTICATION = "requires-authentication";
+
+ private static final String HTTP_HEADER_REFERER = "Referer";
+
+ /**
+ *
+ */
+ @Inject
+ private SecuritySystem securitySystem;
+
+ /**
+ *
+ */
+ private String trackerName = "simple";
+
+ private String enableReferrerCheck;
+
+ @Override
+ public void destroy()
+ {
+ // noop
+ }
+
+
+ /**
+ * process the action to determine if it implements SecureAction and then act
+ * accordingly
+ *
+ * @param invocation
+ * @return
+ * @throws Exception
+ */
+ @Override
+ public String intercept( ActionInvocation invocation )
+ throws Exception
+ {
+ ActionContext context = ActionContext.getContext();
+
+ Action action = (Action) context.getActionInvocation().getAction();
+
+ logger.debug( "SecureActionInterceptor: processing {}", action.getClass().getName() );
+
+ if ( Boolean.valueOf( enableReferrerCheck ) )
+ {
+ logger.debug( "Referrer security check enabled." );
+ executeReferrerSecurityCheck();
+ }
+
+ try
+ {
+ if ( action instanceof SecureAction )
+ {
+ SecureAction secureAction = (SecureAction) action;
+ SecureActionBundle bundle = secureAction.getSecureActionBundle();
+
+ if ( bundle == null )
+ {
+ logger.error( "Null bundle detected." );
+
+ // TODO: send them somewhere else?
+ return invocation.invoke();
+ }
+
+ if ( bundle == SecureActionBundle.OPEN )
+ {
+ logger.debug( "Bundle.OPEN detected." );
+
+ return invocation.invoke();
+ }
+
+ SecuritySession session =
+ (SecuritySession) context.getSession().get( SecuritySystemConstants.SECURITY_SESSION_KEY );
+
+ // check the authentication requirements
+ if ( bundle.requiresAuthentication() )
+ {
+ if ( session == null || !session.isAuthenticated() )
+ {
+ logger.debug( "not authenticated, need to authenticate for this action" );
+ return processRequiresAuthentication( invocation );
+ }
+ }
+
+ List<SecureActionBundle.AuthorizationTuple> authzTuples = bundle.getAuthorizationTuples();
+
+ // if operations are returned we need to perform authorization checks
+ if ( authzTuples != null && authzTuples.size() > 0 )
+ {
+ // authn adds a session, if there is no session they are not authorized and authn is required for
+ // authz, even if it is just a guest user
+ if ( session == null )
+ {
+ logger.debug( "session required for authorization to run" );
+ return processRequiresAuthentication( invocation );
+ }
+
+ for ( SecureActionBundle.AuthorizationTuple tuple : authzTuples )
+ {
+ logger.debug( "checking authz for {}", tuple.toString() );
+
+ AuthorizationResult authzResult =
+ securitySystem.authorize( session, tuple.getOperation(), tuple.getResource() );
+
+ logger.debug( "checking the interceptor authz {} for {}", authzResult.isAuthorized(),
+ tuple.toString() );
+
+ if ( authzResult.isAuthorized() )
+ {
+ if ( logger.isDebugEnabled() )
+ {
+ logger.debug( "{} is authorized for action {} by {}",
+ Lists.<Object>newArrayList( session.getUser().getPrincipal(),
+ secureAction.getClass().getName(),
+ tuple.toString() ) );
+ }
+ return invocation.invoke();
+ }
+ }
+
+ return processRequiresAuthorization( invocation );
+ }
+ }
+ else
+ {
+ logger.debug( "SecureActionInterceptor: {} not a secure action", action.getClass().getName() );
+ }
+ }
+ catch ( SecureActionException se )
+ {
+ logger.error( "can't generate the SecureActionBundle, deny access: " + se.getMessage() );
+ return processRequiresAuthentication( invocation );
+ }
+
+ logger.debug( "not a secure action {}", action.getClass().getName() );
+ String result = invocation.invoke();
+ logger.debug( "Passing invocation up, result is [{}] on call {}", result,
+ invocation.getAction().getClass().getName() );
+ return result;
+ }
+
+ private void executeReferrerSecurityCheck()
+ {
+ String referrer = ServletActionContext.getRequest().getHeader( HTTP_HEADER_REFERER );
+
+ logger.debug( "HTTP Referer header: {}", referrer );
+
+ String[] tokens = StringUtils.splitPreserveAllTokens( referrer, "/", 3 );
+
+ if ( tokens != null )
+ {
+ String path;
+ if ( tokens.length < 3 )
+ {
+ path = referrer;
+ }
+ else
+ {
+ path = tokens[tokens.length - 1];
+ }
+
+ logger.debug( "Calculated virtual path: {}", path );
+
+ ServletContext servletContext = ServletActionContext.getServletContext();
+
+ String realPath = servletContext.getRealPath( path );
+
+ if ( StringUtils.isNotEmpty( realPath ) )
+ {
+ // on windows realPath can return full path c:\\bla\\bla\....
+ // so transforming \\ to /
+ if ( SystemUtils.IS_OS_WINDOWS )
+ {
+ realPath = StringUtils.replace( realPath, "\\", "/" );
+ }
+ if ( !realPath.endsWith( path ) )
+ {
+ String errorMsg = "Failed referrer security check: Request did not come from the same server. "
+ + "Detected HTTP Referer header is '" + referrer + "'.";
+ logger.error( errorMsg );
+ throw new RuntimeException( errorMsg );
+ }
+ else
+ {
+ logger.debug( "HTTP Referer header path found in server." );
+ }
+ }
+ }
+ else
+ {
+ logger.warn( "HTTP Referer header is null." );
+ }
+ }
+
+ protected String processRequiresAuthorization( ActionInvocation invocation )
+ {
+ addActionInvocation( invocation ).setBackTrack();
+ return REQUIRES_AUTHORIZATION;
+ }
+
+ protected String processRequiresAuthentication( ActionInvocation invocation )
+ {
+ HttpSession session = ServletActionContext.getRequest().getSession();
+
+ if ( session != null )
+ {
+ session.removeAttribute( SecuritySystemConstants.SECURITY_SESSION_KEY );
+ }
+
+ addActionInvocation( invocation ).setBackTrack();
+ return REQUIRES_AUTHENTICATION;
+ }
+
+ public SecuritySystem getSecuritySystem()
+ {
+ return securitySystem;
+ }
+
+ public void setSecuritySystem( SecuritySystem securitySystem )
+ {
+ this.securitySystem = securitySystem;
+ }
+
+ protected String getTrackerName()
+ {
+ return trackerName;
+ }
+
+ public String getEnableReferrerCheck()
+ {
+ return enableReferrerCheck;
+ }
+
+ public void setEnableReferrerCheck( String enableReferrerCheck )
+ {
+ this.enableReferrerCheck = enableReferrerCheck;
+ }
+
+ public void setTrackerName( String trackerName )
+ {
+ this.trackerName = trackerName;
+ }
+}
--- /dev/null
+package org.apache.archiva.redback.struts2.interceptor;
+
+/*
+ * 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 com.opensymphony.xwork2.ActionInvocation;
+import org.springframework.context.annotation.Scope;
+import org.springframework.stereotype.Controller;
+
+import java.util.Stack;
+
+/**
+ *
+ */
+@Controller( "simple" )
+@Scope( "prototype" )
+public class SimpleActionInvocationTracker
+ implements ActionInvocationTracker
+{
+ /**
+ *
+ */
+ private int historySize = 5;
+
+ private boolean backTrack;
+
+ private Stack<SavedActionInvocation> actionInvocationStack = new Stack<SavedActionInvocation>();
+
+ public void setHistorySize( int size )
+ {
+ this.historySize = size;
+ }
+
+ public int getHistorySize()
+ {
+ return this.historySize;
+ }
+
+ public int getHistoryCount()
+ {
+ return actionInvocationStack.size();
+ }
+
+ /**
+ * returns the previous actioninvocation and dropping the current one
+ */
+ public SavedActionInvocation getPrevious()
+ {
+ if ( actionInvocationStack.size() > 1 )
+ {
+ // drop the current SavedActionInvocation
+ actionInvocationStack.pop();
+ return (SavedActionInvocation) actionInvocationStack.pop();
+ }
+
+ return null;
+ }
+
+ /**
+ * return the current action invocation
+ */
+ public SavedActionInvocation getCurrent()
+ {
+ if ( actionInvocationStack.size() > 0 )
+ {
+ return (SavedActionInvocation) actionInvocationStack.pop();
+ }
+
+ return null;
+ }
+
+ /**
+ * returns the actioninvocation at the specified index, preserving
+ * the actioninvocation list
+ */
+ public SavedActionInvocation getActionInvocationAt( int index )
+ {
+ if ( actionInvocationStack.size() >= index )
+ {
+ return (SavedActionInvocation) actionInvocationStack.get( index );
+ }
+
+ return null;
+ }
+
+ public void addActionInvocation( ActionInvocation invocation )
+ {
+ actionInvocationStack.push( new SavedActionInvocation( invocation ) );
+
+ // remove oldest action invocation
+ if ( actionInvocationStack.size() > historySize )
+ {
+ actionInvocationStack.remove( 0 );
+ }
+ }
+
+ public void setBackTrack()
+ {
+ backTrack = true;
+ }
+
+ public void unsetBackTrack()
+ {
+ backTrack = false;
+ }
+
+ public boolean isBackTracked()
+ {
+ return backTrack;
+ }
+}
--- /dev/null
+package org.apache.archiva.redback.struts2.model;
+
+/*
+ * 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.Role;
+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 java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Set;
+
+/**
+ * @todo incredibly ugly population of the table, needs to be more concise
+ */
+public class ApplicationRoleDetails
+{
+ private String name;
+
+ private String description;
+
+ private List<String> assignedRoles;
+
+ private List<String> availableRoles;
+
+ private List<ModelTemplate> tableHeader;
+
+ private List<List<RoleTableCell>> table;
+
+ @SuppressWarnings("unchecked")
+ public ApplicationRoleDetails( ModelApplication application, Collection<Role> effectivelyAssignedRoles,
+ Collection<Role> allAssignedRoles, List<Role> assignableRoles )
+ {
+ name = application.getId();
+ description = application.getDescription();
+
+ List<ModelTemplate> templates = application.getTemplates();
+ List<ModelRole> roles = application.getRoles();
+
+ tableHeader = new LinkedList<ModelTemplate>( templates );
+
+ computeRoles( roles, assignableRoles, effectivelyAssignedRoles, allAssignedRoles );
+
+ computeTable( gatherResources( templates, assignableRoles ), effectivelyAssignedRoles, allAssignedRoles );
+ }
+
+ public String getName()
+ {
+ return name;
+ }
+
+ public String getDescription()
+ {
+ return description;
+ }
+
+ public List<String> getAssignedRoles()
+ {
+ return assignedRoles;
+ }
+
+ public List<String> getAvailableRoles()
+ {
+ return availableRoles;
+ }
+
+ public List<ModelTemplate> getTableHeader()
+ {
+ return tableHeader;
+ }
+
+ public List<List<RoleTableCell>> getTable()
+ {
+ return table;
+ }
+
+ private void computeRoles( Collection<ModelRole> applicationRoles, Collection<Role> assignableRoles,
+ Collection<Role> effectivelyAssignedRoles, Collection<Role> allAssignedRoles )
+ {
+ assignedRoles = new ArrayList<String>();
+ availableRoles = new ArrayList<String>();
+ for ( Iterator<ModelRole> i = applicationRoles.iterator(); i.hasNext(); )
+ {
+ ModelRole role = i.next();
+
+ if ( isInList( role.getName(), allAssignedRoles ) )
+ {
+ if ( role.isAssignable() )
+ {
+ assignedRoles.add( role.getName() );
+ }
+ }
+ else if ( isInList( role.getName(), effectivelyAssignedRoles ) )
+ {
+ // nothing
+ }
+ else if ( isInList( role.getName(), assignableRoles ) )
+ {
+ if ( role.isAssignable() )
+ {
+ availableRoles.add( role.getName() );
+ }
+ }
+ }
+
+ Collections.sort( assignedRoles, String.CASE_INSENSITIVE_ORDER );
+ Collections.sort( availableRoles, String.CASE_INSENSITIVE_ORDER );
+ }
+
+ private Set<String> gatherResources( List<ModelTemplate> applicationTemplates, List<Role> roles )
+ {
+ Set<String> resources = new HashSet<String>();
+ for ( ModelTemplate modelTemplate : applicationTemplates )
+ {
+ for ( 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;
+ }
+
+ private void computeTable( Collection<String> resources, Collection<Role> effectivelyAssignedRoles,
+ Collection<Role> allAssignedRoles )
+ {
+ table = new LinkedList<List<RoleTableCell>>();
+
+ List<String> resourcesList = new ArrayList<String>( resources );
+ Collections.sort( resourcesList, String.CASE_INSENSITIVE_ORDER );
+
+ for ( String resource : resourcesList )
+ {
+ LinkedList<RoleTableCell> tableRow = new LinkedList<RoleTableCell>();
+
+ RoleTableCell resourceCell = new RoleTableCell();
+ resourceCell.setName( resource );
+ resourceCell.setLabel( true );
+ tableRow.add( resourceCell );
+
+ for ( ModelTemplate modelTemplate : tableHeader )
+ {
+ RoleTableCell cell = new RoleTableCell();
+
+ cell.setName( modelTemplate.getNamePrefix() + modelTemplate.getDelimiter() + resource );
+ cell.setEffectivelyAssigned( isInList( cell.getName(), effectivelyAssignedRoles ) );
+ cell.setAssigned( isInList( cell.getName(), allAssignedRoles ) );
+ cell.setLabel( false );
+
+ tableRow.add( cell );
+ }
+
+ table.add( tableRow );
+ }
+ }
+
+ private boolean isInList( String roleName, Collection<Role> effectivelyAssignedRoles )
+ {
+ for ( Role role : effectivelyAssignedRoles )
+ {
+ if ( roleName.equals( role.getName() ) )
+ {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ public class RoleTableCell
+ {
+ private String name;
+
+ private boolean effectivelyAssigned;
+
+ private boolean assigned;
+
+ private boolean label;
+
+ public String getName()
+ {
+ return name;
+ }
+
+ public void setName( String name )
+ {
+ this.name = name;
+ }
+
+ public boolean isEffectivelyAssigned()
+ {
+ return effectivelyAssigned;
+ }
+
+ public void setEffectivelyAssigned( boolean effectivelyAssigned )
+ {
+ this.effectivelyAssigned = effectivelyAssigned;
+ }
+
+ public boolean isAssigned()
+ {
+ return assigned;
+ }
+
+ public void setAssigned( boolean assigned )
+ {
+ this.assigned = assigned;
+ }
+
+ public boolean isLabel()
+ {
+ return label;
+ }
+
+ public void setLabel( boolean label )
+ {
+ this.label = label;
+ }
+ }
+}
--- /dev/null
+package org.apache.archiva.redback.struts2.result;
+
+/*
+ * 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 java.util.Map;
+import java.util.Set;
+
+import org.apache.archiva.redback.struts2.interceptor.SavedActionInvocation;
+import org.apache.struts2.dispatcher.ServletActionRedirectResult;
+import org.apache.archiva.redback.struts2.interceptor.ActionInvocationTracker;
+import com.opensymphony.xwork2.ActionInvocation;
+
+@SuppressWarnings("serial")
+public class AbstractBackTrackingResult
+ extends ServletActionRedirectResult
+{
+ public static final int PREVIOUS = 1;
+
+ public static final int CURRENT = 2;
+
+ protected boolean setupBackTrackPrevious( ActionInvocation invocation )
+ {
+ return setupBackTrack( invocation, PREVIOUS );
+ }
+
+ protected boolean setupBackTrackCurrent( ActionInvocation invocation )
+ {
+ return setupBackTrack( invocation, CURRENT );
+ }
+
+ @SuppressWarnings("unchecked")
+ protected boolean setupBackTrack( ActionInvocation invocation, int order )
+ {
+ Map session = invocation.getInvocationContext().getSession();
+ ActionInvocationTracker tracker = (ActionInvocationTracker) session.get( ActionInvocationTracker.SESSION_KEY );
+
+ if ( tracker != null && tracker.isBackTracked() )
+ {
+ SavedActionInvocation savedInvocation;
+
+ if ( order == PREVIOUS )
+ {
+ savedInvocation = tracker.getPrevious();
+ }
+ else
+ {
+ savedInvocation = tracker.getCurrent();
+ }
+
+ if ( savedInvocation != null )
+ {
+ setNamespace( savedInvocation.getNamespace() );
+ setActionName( savedInvocation.getActionName() );
+ setMethod( savedInvocation.getMethodName() );
+
+ invocation.getInvocationContext().getParameters().clear();
+ invocation.getInvocationContext().getParameters().putAll( savedInvocation.getParametersMap() );
+
+ // hack for REDBACK-188
+ String resultCode = invocation.getResultCode();
+
+ if( resultCode != null )
+ {
+ // hack for REDBACK-262
+ // set this to null so the ResultConfig parameters won't be added in the ServletActionRedirectResult
+ // because we can't clear the parameters of ResultConfig since it's read-only
+ invocation.setResultCode( null );
+
+ Set<String> keys = savedInvocation.getParametersMap().keySet();
+
+ for( String key : keys )
+ {
+ if ( !getProhibitedResultParams().contains( key ) )
+ {
+ String value = ( (String[]) savedInvocation.getParametersMap().get( key ) )[0];
+ if ( value != null && value.length() > 0 )
+ {
+ addParameter( key, conditionalParse( value, invocation ) );
+ }
+ }
+ }
+ }
+
+ tracker.unsetBackTrack();
+ }
+
+ return true;
+ }
+
+ return false;
+ }
+}
--- /dev/null
+package org.apache.archiva.redback.struts2.result;
+
+/*
+ * 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 com.opensymphony.xwork2.ActionInvocation;
+import org.springframework.context.annotation.Scope;
+import org.springframework.stereotype.Controller;
+
+
+/**
+ * SecurityExternalResult
+ *
+ * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
+ * @version $Id$
+ */
+@SuppressWarnings( "serial" )
+@Controller( "securityExternalResult" )
+@Scope( "prototype" )
+public class SecurityExternalResult
+ extends AbstractBackTrackingResult
+{
+ /**
+ *
+ */
+ private String externalActionName = "redbackRedirect";
+
+ private String externalResult;
+
+ @Override
+ public void execute( ActionInvocation invocation )
+ throws Exception
+ {
+ // the login redirection is not captured by the http request
+ // tracker, so we backtrack to the current request
+ if ( !setupBackTrackCurrent( invocation ) )
+ {
+ setNamespace( "/" );
+ setActionName( externalActionName );
+ }
+
+ super.execute( invocation );
+ }
+
+ public String getExternalResult()
+ {
+ return externalResult;
+ }
+
+ public void setExternalResult( String externalResult )
+ {
+ this.externalResult = externalResult;
+ }
+
+}
+++ /dev/null
-package org.codehaus.plexus.redback.struts2.action;
-
-/*
- * 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.servlet.http.HttpServletRequest;
-
-import org.apache.struts2.ServletActionContext;
-import org.apache.archiva.redback.policy.PasswordRuleViolationException;
-import org.apache.archiva.redback.policy.PasswordRuleViolations;
-import org.apache.archiva.redback.system.SecuritySession;
-import org.apache.archiva.redback.system.SecuritySystemConstants;
-import org.apache.archiva.redback.integration.interceptor.SecureAction;
-import org.apache.archiva.redback.integration.interceptor.SecureActionBundle;
-import org.apache.archiva.redback.integration.interceptor.SecureActionException;
-
-/**
- * AbstractSecurityAction
- *
- * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
- * @version $Id$
- */
-public abstract class AbstractSecurityAction
- extends RedbackActionSupport
- implements SecureAction
-{
- protected static final String REQUIRES_AUTHENTICATION = "requires-authentication";
-
- private SecureActionBundle securityBundle;
-
- public SecureActionBundle getSecureActionBundle()
- throws SecureActionException
- {
- if ( securityBundle == null )
- {
- securityBundle = initSecureActionBundle();
- }
-
- return securityBundle;
- }
-
- public abstract SecureActionBundle initSecureActionBundle()
- throws SecureActionException;
-
- protected void setAuthTokens( SecuritySession securitySession )
- {
- session.put( SecuritySystemConstants.SECURITY_SESSION_KEY, securitySession );
- this.setSession( session );
- }
-
- protected SecuritySession getSecuritySession()
- {
- return (SecuritySession) session.get( SecuritySystemConstants.SECURITY_SESSION_KEY );
- }
-
- // ------------------------------------------------------------------
- // Internal Support Methods
- // ------------------------------------------------------------------
- protected void processPasswordRuleViolations( PasswordRuleViolationException e )
- {
- processPasswordRuleViolations( e, "user.password" );
- }
-
- protected void processPasswordRuleViolations( PasswordRuleViolationException e, String field )
- {
- PasswordRuleViolations violations = e.getViolations();
-
- if ( violations != null )
- {
- for ( String violation : violations.getLocalizedViolations() )
- {
- addFieldError( field, violation );
- }
- }
- }
-
- protected String getBaseUrl()
- {
- HttpServletRequest req = ServletActionContext.getRequest();
- return req.getScheme() + "://" + req.getServerName()
- + ( req.getServerPort() == 80 ? "" : ":" + req.getServerPort() ) + req.getContextPath();
- }
-
- protected String getCurrentUser()
- {
- SecuritySession securitySession = getSecuritySession();
- if ( securitySession != null && securitySession.getUser() != null )
- {
- return securitySession.getUser().getPrincipal().toString();
- }
- else
- {
- return null;
- }
- }
-}
+++ /dev/null
-package org.codehaus.plexus.redback.struts2.action;
-
-/*
- * 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.Resource;
-import org.apache.archiva.redback.rbac.Role;
-import org.apache.archiva.redback.users.User;
-import org.apache.archiva.redback.policy.PasswordRuleViolationException;
-import org.apache.archiva.redback.rbac.RbacManagerException;
-import org.apache.archiva.redback.system.SecuritySystem;
-import org.codehaus.plexus.util.StringUtils;
-import org.apache.archiva.redback.integration.model.UserCredentials;
-import org.apache.archiva.redback.integration.security.role.RedbackRoleConstants;
-import org.apache.archiva.redback.integration.util.RoleSorter;
-
-import javax.inject.Inject;
-import javax.inject.Named;
-import javax.mail.internet.AddressException;
-import javax.mail.internet.InternetAddress;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-
-/**
- * AbstractUserCredentialsAction
- *
- * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
- * @version $Id$
- */
-public abstract class AbstractUserCredentialsAction
- extends AbstractSecurityAction
-{
- // ------------------------------------------------------------------
- // Component Requirements
- // ------------------------------------------------------------------
-
- /**
- *
- */
- @Inject
- @Named( value = "rBACManager#cached" )
- private RBACManager manager;
-
- /**
- *
- */
- @Inject
- protected SecuritySystem securitySystem;
-
- // ------------------------------------------------------------------
- // Action Parameters
- // ------------------------------------------------------------------
-
- protected UserCredentials internalUser;
-
- protected final String VALID_USERNAME_CHARS = "[a-zA-Z_0-9\\-.@]*";
-
- public RBACManager getManager()
- {
- return manager;
- }
-
- public void setManager( RBACManager manager )
- {
- this.manager = manager;
- }
-
- public SecuritySystem getSecuritySystem()
- {
- return securitySystem;
- }
-
- public void setSecuritySystem( SecuritySystem securitySystem )
- {
- this.securitySystem = securitySystem;
- }
-
- // ------------------------------------------------------------------
- // Action Entry Points - (aka Names)
- // ------------------------------------------------------------------
-
- public void validateCredentialsLoose()
- {
- if ( StringUtils.isEmpty( internalUser.getUsername() ) )
- {
- addFieldError( "user.username", getText( "username.required" ) );
- }
- else
- {
- if ( !internalUser.getUsername().matches( VALID_USERNAME_CHARS ) )
- {
- addFieldError( "user.username", getText( "username.invalid.characters" ) );
- }
- }
-
- if ( StringUtils.isEmpty( internalUser.getFullName() ) )
- {
- addFieldError( "user.fullName", getText( "fullName.required" ) );
- }
-
- if ( StringUtils.isEmpty( internalUser.getEmail() ) )
- {
- addFieldError( "user.email", getText( "email.required" ) );
- }
-
- if ( !StringUtils.equals( internalUser.getPassword(), internalUser.getConfirmPassword() ) )
- {
- addFieldError( "user.confirmPassword", getText( "passwords.does.not.match" ) );
- }
-
- try
- {
- if ( !StringUtils.isEmpty( internalUser.getEmail() ) )
- {
- new InternetAddress( internalUser.getEmail(), true );
- }
- }
- catch ( AddressException e )
- {
- addFieldError( "user.email", getText( "email.invalid" ) );
- }
- }
-
- public void validateCredentialsStrict()
- {
- validateCredentialsLoose();
-
- User tmpuser = internalUser.createUser( securitySystem.getUserManager() );
-
- try
- {
- securitySystem.getPolicy().validatePassword( tmpuser );
- }
- catch ( PasswordRuleViolationException e )
- {
- processPasswordRuleViolations( e );
- }
-
- if ( ( StringUtils.isEmpty( internalUser.getPassword() ) ) )
- {
- addFieldError( "user.password", getText( "password.required" ) );
- }
- }
-
- /**
- * 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<Role> filterRolesForCurrentUserAccess( List<Role> roleList )
- throws RbacManagerException
- {
- String currentUser = getCurrentUser();
-
- List<Role> filteredRoleList = new ArrayList<Role>();
-
- Map<String, List<Permission>> assignedPermissionMap = manager.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 ( 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 );
- }
- }
- }
- }
-
- Collections.sort( filteredRoleList, new RoleSorter() );
- return filteredRoleList;
- }
-
- protected List<Role> getFilteredRolesForCurrentUserAccess()
- throws RbacManagerException
- {
- List<Role> roles = manager.getAllRoles();
-
- if ( roles == null )
- {
- return Collections.emptyList();
- }
-
- return filterRolesForCurrentUserAccess( roles );
- }
-}
+++ /dev/null
-package org.codehaus.plexus.redback.struts2.action;
-
-/*
- * 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 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.DefaultSecuritySession;
-import org.apache.archiva.redback.system.SecuritySession;
-import org.apache.archiva.redback.system.SecuritySystemConstants;
-import org.apache.archiva.redback.users.UserManager;
-import org.codehaus.plexus.util.StringUtils;
-import org.apache.archiva.redback.integration.interceptor.SecureActionBundle;
-import org.apache.archiva.redback.integration.interceptor.SecureActionException;
-import org.apache.archiva.redback.integration.model.EditUserCredentials;
-import org.springframework.context.annotation.Scope;
-import org.springframework.stereotype.Controller;
-
-import java.util.Arrays;
-
-/**
- * AccountAction
- *
- * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
- * @version $Id$
- */
-@Controller( "redback-account" )
-@Scope( "prototype" )
-public class AccountAction
- extends AbstractUserCredentialsAction
- implements CancellableAction
-{
- private static final String ACCOUNT_SUCCESS = "security-account-success";
-
- // ------------------------------------------------------------------
- // Action Parameters
- // ------------------------------------------------------------------
-
- private EditUserCredentials user;
-
- private String oldPassword;
-
- // ------------------------------------------------------------------
- // Action Entry Points - (aka Names)
- // ------------------------------------------------------------------
-
- public String show()
- {
- SecuritySession session = getSecuritySession();
-
- if ( !session.isAuthenticated() )
- {
- addActionError( getText( "cannot.show.account.login.required" ) );
- return REQUIRES_AUTHENTICATION;
- }
-
- String username = session.getUser().getUsername();
-
- if ( username == null )
- {
- addActionError( getText( "cannot.edit.user.null.username" ) );
- return ERROR;
- }
-
- if ( StringUtils.isEmpty( username ) )
- {
- addActionError( getText( "cannot.edit.user.empty.username" ) );
- return ERROR;
- }
-
- UserManager manager = super.securitySystem.getUserManager();
-
- if ( !manager.userExists( username ) )
- {
- // Means that the role name doesn't exist.
- // We need to fail fast and return to the previous page.
- addActionError( getText( "user.does.not.exist", Arrays.asList( (Object) username ) ) );
- return ERROR;
- }
-
- internalUser = user;
-
- try
- {
- User u = manager.findUser( username );
- if ( u == null )
- {
- addActionError( getText( "cannot.operate.on.null.user" ) );
- return ERROR;
- }
-
- user = new EditUserCredentials( u );
- }
- catch ( UserNotFoundException e )
- {
- addActionError( getText( "cannot.get.user", Arrays.asList( (Object) username, e.getMessage() ) ) );
- return ERROR;
- }
-
- return INPUT;
- }
-
- public String submit()
- {
- SecuritySession session = getSecuritySession();
-
- if ( !session.isAuthenticated() )
- {
- addActionError( getText( "cannot.show.account.login.required" ) );
- return REQUIRES_AUTHENTICATION;
- }
-
- String username = session.getUser().getUsername();
-
- if ( username == null )
- {
- addActionError( getText( "cannot.edit.user.null.username" ) );
- return ERROR;
- }
-
- if ( StringUtils.isEmpty( username ) )
- {
- addActionError( getText( "cannot.edit.user.empty.username" ) );
- return ERROR;
- }
-
- if ( user == null )
- {
- addActionError( getText( "cannot.edit.user.null.credentials" ) );
- return ERROR;
- }
-
- if ( !user.getPassword().equals( user.getConfirmPassword() ) )
- {
- addFieldError( "user.confirmPassword", getText( "password.confimation.failed" ) );
- return ERROR;
- }
-
- UserManager manager = super.securitySystem.getUserManager();
-
- if ( !manager.userExists( username ) )
- {
- // Means that the role name doesn't exist.
- // We need to fail fast and return to the previous page.
- addActionError( getText( "user.does.not.exist", Arrays.asList( (Object) username ) ) );
- return ERROR;
- }
-
- internalUser = user;
-
- try
- {
- User u = manager.findUser( username );
- if ( u == null )
- {
- addActionError( getText( "cannot.operate.on.null.user" ) );
- return ERROR;
- }
-
- if ( StringUtils.isNotEmpty( user.getPassword() ) )
- {
- PasswordEncoder encoder = securitySystem.getPolicy().getPasswordEncoder();
-
- if ( !encoder.isPasswordValid( u.getEncodedPassword(), oldPassword ) )
- {
- addFieldError( "oldPassword", getText( "password.provided.does.not.match.existing" ) );
- return ERROR;
- }
-
- u.setPassword( user.getPassword() );
- }
-
- u.setFullName( user.getFullName() );
- u.setEmail( user.getEmail() );
- u.setPassword( user.getPassword() );
-
- manager.updateUser( u );
-
- //check if current user then update the session
- if ( getSecuritySession().getUser().getUsername().equals( u.getUsername() ) )
- {
- SecuritySession securitySession =
- new DefaultSecuritySession( getSecuritySession().getAuthenticationResult(), u );
-
- this.session.put( SecuritySystemConstants.SECURITY_SESSION_KEY, securitySession );
-
- setSession( this.session );
- }
- }
- catch ( UserNotFoundException e )
- {
- addActionError( getText( "cannot.get.user", Arrays.asList( (Object) username, e.getMessage() ) ) );
- return ERROR;
- }
- catch ( PasswordRuleViolationException e )
- {
- processPasswordRuleViolations( e );
- return ERROR;
- }
-
- return ACCOUNT_SUCCESS;
- }
-
- public String cancel()
- {
- return CANCEL;
- }
-
- // ------------------------------------------------------------------
- // Parameter Accessor Methods
- // ------------------------------------------------------------------
-
- public EditUserCredentials getUser()
- {
- return user;
- }
-
- public void setUser( EditUserCredentials user )
- {
- this.user = user;
- }
-
- public SecureActionBundle initSecureActionBundle()
- throws SecureActionException
- {
- SecureActionBundle bundle = new SecureActionBundle();
- bundle.setRequiresAuthentication( true );
- return bundle;
- }
-
- public void setOldPassword( String oldPassword )
- {
- this.oldPassword = oldPassword;
- }
-
- public boolean isSelf()
- {
- return true;
- }
-}
+++ /dev/null
-package org.codehaus.plexus.redback.struts2.action;
-
-/*
- * 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.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.slf4j.MDC;
-
-public class AuditEvent
-{
- private Logger logger = LoggerFactory.getLogger( AuditEvent.class.getName() );
-
- private final String action;
-
- private String affectedUser;
-
- private String role;
-
- private String currentUser;
-
- public AuditEvent( String action )
- {
- this.action = action;
- }
-
- public void setRole( String role )
- {
- this.role = role;
- }
-
- public String getRole()
- {
- return role;
- }
-
- public void setAffectedUser( String affectedUser )
- {
- this.affectedUser = affectedUser;
- }
-
- public String getAffectedUser()
- {
- return affectedUser;
- }
-
- public void setCurrentUser( String currentUser )
- {
- this.currentUser = currentUser;
- }
-
- public String getCurrentUser()
- {
- return currentUser;
- }
-
- public void log()
- {
- // TODO: it would be better to push this into the login interceptor so it is always set consistently
- // (same for IP address)
- if ( currentUser != null )
- {
- MDC.put( "redback.currentUser", currentUser );
- }
-
- if ( affectedUser != null )
- {
- if ( role != null )
- {
- logger.info( action, affectedUser, role );
- }
- else
- {
- logger.info( action, affectedUser );
-
- }
- }
- }
-}
+++ /dev/null
-package org.codehaus.plexus.redback.struts2.action;
-
-/*
- * 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.
- */
-
-public interface CancellableAction
-{
- public static final String CANCEL = "cancel";
-
- /**
- * Returns the cancel result.
- *
- * A basic implementation would simply be to return CANCEL.
- * @return
- */
- String cancel();
-}
+++ /dev/null
-package org.codehaus.plexus.redback.struts2.action;
-
-/*
- * 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.keys.AuthenticationKey;
-import org.apache.archiva.redback.policy.AccountLockedException;
-import org.apache.archiva.redback.users.User;
-import org.apache.struts2.ServletActionContext;
-import org.apache.archiva.redback.authentication.AuthenticationConstants;
-import org.apache.archiva.redback.authentication.AuthenticationDataSource;
-import org.apache.archiva.redback.authentication.AuthenticationException;
-import org.apache.archiva.redback.authentication.AuthenticationResult;
-import org.apache.archiva.redback.authentication.PasswordBasedAuthenticationDataSource;
-import org.apache.archiva.redback.authentication.TokenBasedAuthenticationDataSource;
-import org.apache.archiva.redback.configuration.UserConfiguration;
-import org.apache.archiva.redback.keys.KeyManagerException;
-import org.apache.archiva.redback.keys.KeyNotFoundException;
-import org.apache.archiva.redback.policy.MustChangePasswordException;
-import org.apache.archiva.redback.system.SecuritySession;
-import org.apache.archiva.redback.system.SecuritySystem;
-import org.apache.archiva.redback.users.UserNotFoundException;
-import org.codehaus.plexus.util.StringUtils;
-import org.apache.archiva.redback.integration.interceptor.SecureActionBundle;
-import org.apache.archiva.redback.integration.interceptor.SecureActionException;
-import org.apache.archiva.redback.integration.util.AutoLoginCookies;
-import org.springframework.context.annotation.Scope;
-import org.springframework.stereotype.Controller;
-
-import javax.inject.Inject;
-import java.util.Arrays;
-import java.util.Date;
-
-/**
- * LoginAction
- *
- * @author Jesse McConnell <jmcconnell@apache.org>
- * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
- * @version $Id$
- */
-@Controller( "redback-login" )
-@Scope( "prototype" )
-public class LoginAction
- extends AbstractSecurityAction
- implements CancellableAction
-{
- private static final String LOGIN_SUCCESS = "security-login-success";
-
- private static final String PASSWORD_CHANGE = "security-must-change-password";
-
- private static final String ACCOUNT_LOCKED = "security-login-locked";
-
- // ------------------------------------------------------------------
- // Component Requirements
- // ------------------------------------------------------------------
-
- /**
- *
- */
- @Inject
- protected SecuritySystem securitySystem;
-
- private String username;
-
- private String password;
-
- private String validateMe;
-
- private String resetPassword;
-
- private boolean rememberMe;
-
- /**
- *
- */
- @Inject
- private AutoLoginCookies autologinCookies;
-
- /**
- *
- */
- @Inject
- private UserConfiguration config;
-
- // ------------------------------------------------------------------
- // Action Entry Points - (aka Names)
- // ------------------------------------------------------------------
-
- public String show()
- {
- return INPUT;
- }
-
- /**
- * 1) check if this is a validation authentication action
- * 2) check if this is a reset password authentication action
- * 3) sets up a password based authentication and passes on to webLogin()
- *
- * @return
- */
- public String login()
- {
- if ( StringUtils.isNotEmpty( validateMe ) )
- {
- // Process a login / validate request.
- return validated();
- }
-
- if ( StringUtils.isNotEmpty( resetPassword ) )
- {
- // Process a login / reset password request.
- return resetPassword();
- }
-
- if ( StringUtils.isEmpty( username ) )
- {
- addFieldError( "username", getText( "username.required" ) );
- return ERROR;
- }
-
- PasswordBasedAuthenticationDataSource authdatasource = new PasswordBasedAuthenticationDataSource();
- authdatasource.setPrincipal( username );
- authdatasource.setPassword( password );
-
- return webLogin( authdatasource, rememberMe );
- }
-
- /**
- * 1) sets up a token based authentication
- * 2) forces a password change requirement to the user
- * 3) passes on to webLogin()
- *
- * @return
- */
- public String resetPassword()
- {
- if ( StringUtils.isEmpty( resetPassword ) )
- {
- addActionError( getText( "reset.password.missing" ) );
- return ERROR;
- }
-
- try
- {
- AuthenticationKey authkey = securitySystem.getKeyManager().findKey( resetPassword );
-
- User user = securitySystem.getUserManager().findUser( authkey.getForPrincipal() );
-
- user.setPasswordChangeRequired( true );
- user.setEncodedPassword( "" );
-
- TokenBasedAuthenticationDataSource authsource = new TokenBasedAuthenticationDataSource();
- authsource.setPrincipal( user.getPrincipal().toString() );
- authsource.setToken( authkey.getKey() );
- authsource.setEnforcePasswordChange( false );
-
- securitySystem.getUserManager().updateUser( user );
-
- AuditEvent event = new AuditEvent( getText( "log.password.change" ) );
- event.setAffectedUser( username );
- event.log();
-
- return webLogin( authsource, false );
- }
- catch ( KeyNotFoundException e )
- {
- log.info( "Invalid key requested: {}", resetPassword );
- addActionError( getText( "cannot.find.key" ) );
- return ERROR;
- }
- catch ( KeyManagerException e )
- {
- addActionError( getText( "cannot.find.key.at.the.moment" ) );
- log.warn( "Key Manager error: ", e );
- return ERROR;
- }
- catch ( UserNotFoundException e )
- {
- addActionError( getText( "cannot.find.user" ) );
- return ERROR;
- }
- }
-
- /**
- * 1) sets up a token based authentication
- * 2) forces a password change requirement to the user
- * 3) passes on to webLogin()
- *
- * @return
- */
- public String validated()
- {
- if ( StringUtils.isEmpty( validateMe ) )
- {
- addActionError( getText( "validation.failure.key.missing" ) );
- return ERROR;
- }
-
- try
- {
- AuthenticationKey authkey = securitySystem.getKeyManager().findKey( validateMe );
-
- User user = securitySystem.getUserManager().findUser( authkey.getForPrincipal() );
-
- user.setValidated( true );
- user.setLocked( false );
- user.setPasswordChangeRequired( true );
- user.setEncodedPassword( "" );
-
- TokenBasedAuthenticationDataSource authsource = new TokenBasedAuthenticationDataSource();
- authsource.setPrincipal( user.getPrincipal().toString() );
- authsource.setToken( authkey.getKey() );
- authsource.setEnforcePasswordChange( false );
-
- securitySystem.getUserManager().updateUser( user );
- String currentUser = getCurrentUser();
-
- AuditEvent event = new AuditEvent( getText( "log.account.validation" ) );
- event.setAffectedUser( username );
- event.setCurrentUser( currentUser );
- event.log();
-
- return webLogin( authsource, false );
- }
- catch ( KeyNotFoundException e )
- {
- log.info( "Invalid key requested: {}", validateMe );
- addActionError( getText( "cannot.find.key" ) );
- return ERROR;
- }
- catch ( KeyManagerException e )
- {
- addActionError( getText( "cannot.find.key.at.the.momment" ) );
- return ERROR;
- }
- catch ( UserNotFoundException e )
- {
- addActionError( getText( "cannot.find.user" ) );
- return ERROR;
- }
- }
-
- public String cancel()
- {
- return CANCEL;
- }
-
- public String getUsername()
- {
- return username;
- }
-
- public void setUsername( String username )
- {
- this.username = username;
- }
-
- public String getPassword()
- {
- return password;
- }
-
- public void setPassword( String password )
- {
- this.password = password;
- }
-
- public String getValidateMe()
- {
- return validateMe;
- }
-
- public void setValidateMe( String validateMe )
- {
- this.validateMe = validateMe;
- }
-
- public SecureActionBundle initSecureActionBundle()
- throws SecureActionException
- {
- return SecureActionBundle.OPEN;
- }
-
- public String getResetPassword()
- {
- return resetPassword;
- }
-
- public void setResetPassword( String resetPassword )
- {
- this.resetPassword = resetPassword;
- }
-
- public boolean isRememberMe()
- {
- return rememberMe;
- }
-
- public void setRememberMe( boolean rememberMe )
- {
- this.rememberMe = rememberMe;
- }
-
-
- /**
- * 1) attempts to authentication based on the passed in data source
- * 2) if successful sets cookies and returns LOGIN_SUCCESS
- * 3) if failure then check what kinda failure and return error
- *
- * @param authdatasource
- * @param rememberMe
- * @return
- */
- private String webLogin( AuthenticationDataSource authdatasource, boolean rememberMe )
- {
- // An attempt should log out your authentication tokens first!
- setAuthTokens( null );
-
- clearErrorsAndMessages();
-
- // TODO: share this section with AutoLoginInterceptor
- try
- {
- SecuritySession securitySession = securitySystem.authenticate( authdatasource );
-
- if ( securitySession.isAuthenticated() )
- {
- // Success! Create tokens.
- setAuthTokens( securitySession );
-
- if ( securitySystem.getPolicy().getUserValidationSettings().isEmailValidationRequired() )
- {
- if ( !securitySession.getUser().getUsername().equals(
- config.getString( "redback.default.admin" ) ) )
- {
- if ( !securitySession.getUser().isValidated() )
- {
- setAuthTokens( null );
- // NOTE: this text is the same as incorrect.username.password to avoid exposing actual account existence
- addActionError( getText( "account.validation.required" ) );
- return ERROR;
- }
- }
- }
-
- setCookies( authdatasource, rememberMe );
-
- AuditEvent event = new AuditEvent( getText( "log.login.success" ) );
- event.setAffectedUser( username );
- event.log();
-
- User user = securitySession.getUser();
- user.setLastLoginDate( new Date() );
- securitySystem.getUserManager().updateUser( user );
-
- if ( StringUtils.isNotEmpty( validateMe ) )
- {
- try
- {
- //REDBACK-146: delete key after validating so user won't be able to use it the second time around
- securitySystem.getKeyManager().deleteKey( validateMe );
- }
- catch ( KeyManagerException e )
- {
- addActionError( getText( "cannot.find.key.at.the.momment" ) );
- return ERROR;
- }
- }
-
- return LOGIN_SUCCESS;
- }
- else
- {
- log.debug( "Login Action failed against principal : {}",
- securitySession.getAuthenticationResult().getPrincipal(),
- securitySession.getAuthenticationResult().getException() );
-
- AuthenticationResult result = securitySession.getAuthenticationResult();
- if ( result.getExceptionsMap() != null && !result.getExceptionsMap().isEmpty() )
- {
- if ( result.getExceptionsMap().get( AuthenticationConstants.AUTHN_NO_SUCH_USER ) != null )
- {
- addActionError( getText( "incorrect.username.password" ) );
- }
- else
- {
- addActionError( getText( "authentication.failed" ) );
- }
- }
- else
- {
- addActionError( getText( "authentication.failed" ) );
- }
-
- AuditEvent event = new AuditEvent( getText( "log.login.fail" ) );
- event.setAffectedUser( username );
- event.log();
-
- return ERROR;
- }
- }
- catch ( AuthenticationException ae )
- {
- addActionError( getText( "authentication.exception", Arrays.asList( (Object) ae.getMessage() ) ) );
- return ERROR;
- }
- catch ( UserNotFoundException ue )
- {
- addActionError(
- getText( "user.not.found.exception", Arrays.asList( (Object) username, ue.getMessage() ) ) );
-
- AuditEvent event = new AuditEvent( getText( "log.login.fail" ) );
- event.setAffectedUser( username );
- event.log();
- return ERROR;
- }
- catch ( AccountLockedException e )
- {
- addActionError( getText( "account.locked" ) );
-
- AuditEvent event = new AuditEvent( getText( "log.login.fail.locked" ) );
- event.setAffectedUser( username );
- event.log();
- return ACCOUNT_LOCKED;
- }
- catch ( MustChangePasswordException e )
- {
- // TODO: preferably we would not set the cookies for this "partial" login state
- setCookies( authdatasource, rememberMe );
-
- AuditEvent event = new AuditEvent( getText( "log.login.fail.locked" ) );
- event.setAffectedUser( username );
- event.log();
- return PASSWORD_CHANGE;
- }
- }
-
- private void setCookies( AuthenticationDataSource authdatasource, boolean rememberMe )
- {
- if ( rememberMe )
- {
- autologinCookies.setRememberMeCookie( authdatasource.getPrincipal(), ServletActionContext.getResponse(),
- ServletActionContext.getRequest() );
- }
- autologinCookies.setSignonCookie( authdatasource.getPrincipal(), ServletActionContext.getResponse(),
- ServletActionContext.getRequest() );
- }
-}
+++ /dev/null
-package org.codehaus.plexus.redback.struts2.action;
-
-/*
- * 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.struts2.ServletActionContext;
-import org.apache.struts2.dispatcher.SessionMap;
-import org.codehaus.plexus.cache.Cache;
-import org.apache.archiva.redback.integration.interceptor.SecureActionBundle;
-import org.apache.archiva.redback.integration.interceptor.SecureActionException;
-import org.apache.archiva.redback.integration.util.AutoLoginCookies;
-import org.springframework.context.annotation.Scope;
-import org.springframework.stereotype.Controller;
-
-import javax.inject.Inject;
-import javax.inject.Named;
-
-/**
- * LogoutAction
- *
- * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
- * @version $Id$
- */
-@Controller( "redback-logout" )
-@Scope( "prototype" )
-public class LogoutAction
- extends AbstractSecurityAction
-{
- // Result Names.
- private static final String LOGOUT = "security-logout";
-
- /**
- * cache used for user assignments
- *
- * role-hint="userAssignments"
- */
- @Inject
- @Named( value = "cache#userAssignments" )
- private Cache userAssignmentsCache;
-
- /**
- * cache used for user permissions
- *
- * role-hint="userPermissions"
- */
- @Inject
- @Named( value = "cache#userPermissions" )
- private Cache userPermissionsCache;
-
- /**
- * Cache used for users
- *
- * role-hint="users"
- */
- @Inject
- @Named( value = "cache#users" )
- private Cache usersCache;
-
- /**
- *
- */
- @Inject
- private AutoLoginCookies autologinCookies;
-
- public String logout()
- {
- if ( getSecuritySession().getUser() == null )
- {
- return LOGOUT;
- }
-
- String currentUser = (String) getSecuritySession().getUser().getPrincipal();
-
- if ( getSecuritySession() != null )
- {
- // [PLXREDBACK-65] this is a bit of a hack around the cached managers since they don't have the ability to
- // purge their caches through the API. Instead try and bring them in here and invalidate
- // the keys directly. This will not be required once we move to a different model for pre-calculated
- // permission sets since that will not have the overhead that required these caches in the first place.
- Object principal = (String) getSecuritySession().getUser().getPrincipal();
- if ( userAssignmentsCache != null )
- {
- userAssignmentsCache.remove( principal );
- }
- if ( userPermissionsCache != null )
- {
- userPermissionsCache.remove( principal );
- }
- if ( usersCache != null )
- {
- usersCache.remove( principal );
- }
- }
-
- autologinCookies.removeRememberMeCookie( ServletActionContext.getResponse(),
- ServletActionContext.getRequest() );
- autologinCookies.removeSignonCookie( ServletActionContext.getResponse(), ServletActionContext.getRequest() );
-
- setAuthTokens( null );
-
- if ( session != null )
- {
- ( (SessionMap) session ).invalidate();
- }
-
- AuditEvent event = new AuditEvent( getText( "log.logout.success" ) );
- event.setAffectedUser( currentUser );
- event.log();
-
- return LOGOUT;
- }
-
- public SecureActionBundle initSecureActionBundle()
- throws SecureActionException
- {
- return SecureActionBundle.OPEN;
- }
-}
+++ /dev/null
-package org.codehaus.plexus.redback.struts2.action;
-
-/*
- * 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.PasswordRuleViolations;
-import org.apache.archiva.redback.users.User;
-import org.apache.archiva.redback.policy.PasswordRuleViolationException;
-import org.apache.archiva.redback.system.SecuritySession;
-import org.apache.archiva.redback.system.SecuritySystem;
-import org.apache.archiva.redback.users.UserNotFoundException;
-import org.codehaus.plexus.util.StringUtils;
-import org.apache.archiva.redback.integration.interceptor.SecureActionBundle;
-import org.apache.archiva.redback.integration.interceptor.SecureActionException;
-import org.springframework.context.annotation.Scope;
-import org.springframework.stereotype.Controller;
-
-import javax.inject.Inject;
-import java.util.Arrays;
-import java.util.Map;
-
-/**
- * PasswordAction
- *
- * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
- * @version $Id$
- */
-@Controller( "redback-password" )
-@Scope( "prototype" )
-public class PasswordAction
- extends AbstractSecurityAction
- implements CancellableAction
-{
- // ------------------------------------------------------------------
- // Plexus Component Requirements
- // ------------------------------------------------------------------
-
- protected static final String CHANGE_PASSWORD_SUCCESS = "security-change-password-success";
-
- /**
- *
- */
- @Inject
- protected SecuritySystem securitySystem;
-
- // ------------------------------------------------------------------
- // Action Parameters
- // ------------------------------------------------------------------
-
- private String existingPassword;
-
- private String newPassword;
-
- private String newPasswordConfirm;
-
- private String targetUrl;
-
- private boolean provideExisting;
-
- public String show()
- {
- provideExisting = StringUtils.isNotEmpty( getSecuritySession().getUser().getEncodedPassword() );
- return INPUT;
- }
-
- public String submit()
- {
- final SecuritySession securitySession = getSecuritySession();
-
- provideExisting = StringUtils.isNotEmpty( securitySession.getUser().getEncodedPassword() );
-
- if ( StringUtils.isEmpty( newPassword ) )
- {
- addFieldError( "newPassword", getText( "newPassword.cannot.be.empty" ) );
- }
-
- if ( !StringUtils.equals( newPassword, newPasswordConfirm ) )
- {
- addFieldError( "newPassword", getText( "password.confimation.failed" ) );
- }
-
- User user = securitySession.getUser();
-
- // Test existing Password.
- PasswordEncoder encoder = securitySystem.getPolicy().getPasswordEncoder();
-
- if ( provideExisting )
- {
- if ( !encoder.isPasswordValid( user.getEncodedPassword(), existingPassword ) )
- {
- addFieldError( "existingPassword", getText( "password.provided.does.not.match.existing" ) );
- }
- }
-
- // Validate the Password.
- try
- {
- User tempUser = securitySystem.getUserManager().createUser( "temp", "temp", "temp" );
- tempUser.setPassword( newPassword );
- securitySystem.getPolicy().validatePassword( tempUser );
- }
- catch ( PasswordRuleViolationException e )
- {
- PasswordRuleViolations violations = e.getViolations();
-
- if ( violations != null )
- {
- for ( String violation : violations.getLocalizedViolations() )
- {
- addFieldError( "newPassword", violation );
- }
- }
- }
-
- // Toss error (if any exists)
- if ( hasActionErrors() || hasFieldErrors() || hasActionMessages() )
- {
- newPassword = "";
- newPasswordConfirm = "";
- existingPassword = "";
- return ERROR;
- }
-
- // We can save the new password.
- try
- {
- String encodedPassword = encoder.encodePassword( newPassword );
- user.setEncodedPassword( encodedPassword );
- user.setPassword( newPassword );
- // TODO: (address this) check once more for password policy, some policies may require additional information
- // only available in the actual user object, perhaps the thing to do is add a deep cloning mechanism
- // to user so we can validate this with a test user. Its ok to just set and test it here before
- // setting the updateUser, but logically its better to maintain a clear separation here
- securitySystem.getPolicy().validatePassword( user );
- securitySystem.getUserManager().updateUser( user );
- }
- catch ( UserNotFoundException e )
- {
- addActionError( getText( "cannot.update.user.not.found", Arrays.asList( (Object) user.getUsername() ) ) );
- addActionError( getText( "admin.deleted.account" ) );
-
- return ERROR;
- }
- catch ( PasswordRuleViolationException e )
- {
- PasswordRuleViolations violations = e.getViolations();
-
- if ( violations != null )
- {
- for ( String violation : violations.getLocalizedViolations() )
- {
- addFieldError( "newPassword", violation );
- }
- }
- // [REDBACK-30] when the password is one of the previous 6, it throws exception here, but since the user
- // object is in the session we need to clear out the encodedPassword otherwise the flow will change and think
- // it needs to have existingPassword which isn't set on some reset password checks
- if ( !provideExisting )
- {
- user.setEncodedPassword( "" );
- user.setPassword( "" );
- }
-
- return ERROR;
- }
-
- log.info( "Password Change Request Success." );
- String currentUser = getCurrentUser();
- AuditEvent event = new AuditEvent( getText( "log.password.change" ) );
- event.setAffectedUser( user.getUsername() );
- event.setCurrentUser( currentUser );
- event.log();
-
- if ( !securitySession.isAuthenticated() )
- {
- log.debug( "User is not authenticated." );
- return REQUIRES_AUTHENTICATION;
- }
-
- /*
- * If provide existing is true, then this was a normal password change flow, if it is
- * false then it is changing the password from the registration flow in which case direct to
- * external link
- */
- if ( !provideExisting )
- {
- return CHANGE_PASSWORD_SUCCESS;
- }
- else
- {
-
- if ( super.session != null )
- {
-
- Map<String, Object> map = (Map<String, Object>) super.session;
- String url = "";
- if ( map.containsKey( "targetUrl" ) )
- {
- url = map.remove( "targetUrl" ).toString();
- log.info( "targetUrl is retrieved and removed from the session: {}", url );
- }
- else
- {
- log.info( "targetUrl is empty, redirect to change password success page" );
- return CHANGE_PASSWORD_SUCCESS;
- }
- setTargetUrl( url );
- }
- return SUCCESS;
- }
- }
-
- public String cancel()
- {
- return CANCEL;
- }
-
- // ------------------------------------------------------------------
- // Parameter Accessor Methods
- // ------------------------------------------------------------------
-
- public String getExistingPassword()
- {
- return existingPassword;
- }
-
- public void setExistingPassword( String existingPassword )
- {
- this.existingPassword = existingPassword;
- }
-
- public String getNewPassword()
- {
- return newPassword;
- }
-
- public void setNewPassword( String newPassword )
- {
- this.newPassword = newPassword;
- }
-
- public String getNewPasswordConfirm()
- {
- return newPasswordConfirm;
- }
-
- public void setNewPasswordConfirm( String newPasswordConfirm )
- {
- this.newPasswordConfirm = newPasswordConfirm;
- }
-
- public boolean isProvideExisting()
- {
- return provideExisting;
- }
-
- public void setProvideExisting( boolean provideExisting )
- {
- // Do nothing.
- }
-
- public SecureActionBundle initSecureActionBundle()
- throws SecureActionException
- {
- return SecureActionBundle.AUTHONLY;
- }
-
- public String getTargetUrl()
- {
- return targetUrl;
- }
-
- public void setTargetUrl( String targetUrl )
- {
- this.targetUrl = targetUrl;
- }
-}
+++ /dev/null
-package org.codehaus.plexus.redback.struts2.action;
-
-/*
- * 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.keys.KeyManager;
-import org.apache.archiva.redback.policy.UserSecurityPolicy;
-import org.apache.archiva.redback.users.UserManager;
-import org.apache.archiva.redback.users.UserNotFoundException;
-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.User;
-import org.codehaus.plexus.util.StringUtils;
-import org.apache.archiva.redback.integration.interceptor.SecureActionBundle;
-import org.apache.archiva.redback.integration.interceptor.SecureActionException;
-import org.apache.archiva.redback.integration.mail.Mailer;
-import org.springframework.context.annotation.Scope;
-import org.springframework.stereotype.Controller;
-
-import javax.inject.Inject;
-import java.util.Arrays;
-
-/**
- * PasswordResetAction
- *
- * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
- * @version $Id$
- */
-@Controller( "redback-password-reset" )
-@Scope( "prototype" )
-public class PasswordResetAction
- extends AbstractSecurityAction
- implements CancellableAction
-{
- // ------------------------------------------------------------------
- // Component Requirements
- // ------------------------------------------------------------------
-
- /**
- *
- */
- @Inject
- private Mailer mailer;
-
- /**
- *
- */
- @Inject
- private SecuritySystem securitySystem;
-
- private String username;
-
- // ------------------------------------------------------------------
- // Action Entry Points - (aka Names)
- // ------------------------------------------------------------------
-
- public String show()
- {
- return INPUT;
- }
-
- public String reset()
- {
- if ( StringUtils.isEmpty( username ) )
- {
- addFieldError( "username", getText( "username.cannot.be.empty" ) );
- return INPUT;
- }
-
- UserManager userManager = securitySystem.getUserManager();
- KeyManager keyManager = securitySystem.getKeyManager();
- UserSecurityPolicy policy = securitySystem.getPolicy();
-
- try
- {
- User user = userManager.findUser( username );
-
- AuthenticationKey authkey = keyManager.createKey( username, "Password Reset Request",
- policy.getUserValidationSettings().getEmailValidationTimeout() );
-
- mailer.sendPasswordResetEmail( Arrays.asList( user.getEmail() ), authkey, getBaseUrl() );
-
- AuditEvent event = new AuditEvent( getText( "log.password.reset.request" ) );
- event.setAffectedUser( username );
- event.log();
-
- addActionMessage( getText( "password.reset.success" ) );
- }
- catch ( UserNotFoundException e )
- {
- // By default, the success and failure messages are the same.
- // This is done to prevent a malicious user from attempting to ascertain the
- // validity of usernames.
- addActionMessage( getText( "password.reset.failure" ) );
-
- log.info( "Password Reset on non-existant user [{}].", username );
- }
- catch ( KeyManagerException e )
- {
- addActionError( getText( "password.reset.email.generation.failure" ) );
- log.info( "Unable to issue password reset.", e );
- }
-
- return INPUT;
- }
-
- // ------------------------------------------------------------------
- // Security Specification
- // ------------------------------------------------------------------
-
- public SecureActionBundle initSecureActionBundle()
- throws SecureActionException
- {
- return SecureActionBundle.OPEN;
- }
-
- public String cancel()
- {
- return NONE;
- }
-
- // ------------------------------------------------------------------
- // Parameter Accessor Methods
- // ------------------------------------------------------------------
-
- public String getUsername()
- {
- return username;
- }
-
- public void setUsername( String username )
- {
- this.username = username;
- }
-
-}
+++ /dev/null
-package org.codehaus.plexus.redback.struts2.action;
-
-/*
- * 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 java.util.Map;
-
-import org.apache.struts2.interceptor.SessionAware;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.opensymphony.xwork2.ActionSupport;
-
-/**
- *
- * @author <a href="mailto:james@atlassian.com">James William Dumay</a>
- */
-public abstract class RedbackActionSupport
- extends ActionSupport
- implements SessionAware
-{
- protected Logger log = LoggerFactory.getLogger( this.getClass() );
-
- protected Map<String,Object> session;
-
- public void setSession( Map<String, Object > map )
- {
- //noinspection AssignmentToCollectionOrArrayFieldFromParameter
- this.session = map;
- }
-}
+++ /dev/null
-package org.codehaus.plexus.redback.struts2.action;
-
-/*
- * 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.keys.AuthenticationKey;
-import org.apache.archiva.redback.policy.UserSecurityPolicy;
-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.keys.KeyManagerException;
-import org.apache.archiva.redback.users.UserManager;
-import org.apache.archiva.redback.users.UserNotFoundException;
-import org.apache.archiva.redback.integration.interceptor.SecureActionBundle;
-import org.apache.archiva.redback.integration.interceptor.SecureActionException;
-import org.apache.archiva.redback.integration.mail.Mailer;
-import org.apache.archiva.redback.integration.model.CreateUserCredentials;
-import org.apache.archiva.redback.integration.security.role.RedbackRoleConstants;
-import org.springframework.context.annotation.Scope;
-import org.springframework.stereotype.Controller;
-
-import javax.inject.Inject;
-import java.util.Arrays;
-
-/**
- * RegisterAction
- *
- * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
- * @version $Id$
- */
-@Controller( "redback-register" )
-@Scope( "prototype" )
-public class RegisterAction
- extends AbstractUserCredentialsAction
- implements CancellableAction
-{
- protected static final String REGISTER_SUCCESS = "security-register-success";
-
- private static final String VALIDATION_NOTE = "validation-note";
-
- private static final String RESEND_VALIDATION_EMAIL = "security-resend-validation-email";
-
- // ------------------------------------------------------------------
- // Component Requirements
- // ------------------------------------------------------------------
-
- /**
- *
- */
- @Inject
- private Mailer mailer;
-
- /**
- *
- */
- @Inject
- private RoleManager roleManager;
-
- private CreateUserCredentials user;
-
- private boolean emailValidationRequired;
-
- private String username;
-
- // ------------------------------------------------------------------
- // Action Entry Points - (aka Names)
- // ------------------------------------------------------------------
-
- public String show()
- {
- if ( user == null )
- {
- user = new CreateUserCredentials();
- }
-
- emailValidationRequired = securitySystem.getPolicy().getUserValidationSettings().isEmailValidationRequired();
-
- return INPUT;
- }
-
- public String register()
- {
- if ( user == null )
- {
- user = new CreateUserCredentials();
- addActionError( getText( "invalid.user.credentials" ) );
- return ERROR;
- }
-
- UserSecurityPolicy securityPolicy = securitySystem.getPolicy();
-
- emailValidationRequired = securityPolicy.getUserValidationSettings().isEmailValidationRequired();
-
- internalUser = user;
-
- if ( securityPolicy.getUserValidationSettings().isEmailValidationRequired() )
- {
- validateCredentialsLoose();
- }
- else
- {
- validateCredentialsStrict();
- }
-
- // NOTE: Do not perform Password Rules Validation Here.
- UserManager manager = super.securitySystem.getUserManager();
-
- if ( manager.userExists( user.getUsername() ) )
- {
- // Means that the role name doesn't exist.
- // We need to fail fast and return to the previous page.
- addActionError( getText( "user.already.exists", Arrays.asList( (Object) user.getUsername() ) ) );
- }
-
- if ( hasActionErrors() || hasFieldErrors() )
- {
- return ERROR;
- }
-
- User u = manager.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 )
- {
- addActionError( getText( "assign.role.failure" ) );
- log.error( "RoleProfile Error: " + rpe.getMessage(), rpe );
- return ERROR;
- }
-
- if ( securityPolicy.getUserValidationSettings().isEmailValidationRequired() )
- {
- 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 );
- manager.addUser( u );
-
- return VALIDATION_NOTE;
- }
- catch ( KeyManagerException e )
- {
- addActionError( getText( "cannot.register.user" ) );
- log.error( "Unable to register a new user.", e );
- return ERROR;
- }
- finally
- {
- securityPolicy.setEnabled( true );
- }
- }
- else
- {
- manager.addUser( u );
- }
-
- AuditEvent event = new AuditEvent( getText( "log.account.create" ) );
- event.setAffectedUser( username );
- event.log();
-
- return REGISTER_SUCCESS;
- }
-
- public String resendRegistrationEmail()
- {
- UserSecurityPolicy securityPolicy = securitySystem.getPolicy();
-
- try
- {
- User user = super.securitySystem.getUserManager().findUser( username );
-
- AuthenticationKey authkey =
- securitySystem.getKeyManager().createKey( user.getPrincipal().toString(), "New User Email Validation",
- securityPolicy.getUserValidationSettings().getEmailValidationTimeout() );
-
- mailer.sendAccountValidationEmail( Arrays.asList( user.getEmail() ), authkey, getBaseUrl() );
-
- return RESEND_VALIDATION_EMAIL;
- }
- catch ( KeyManagerException e )
- {
- addActionError( getText( "cannot.register.user" ) );
- log.error( "Unable to register a new user.", e );
- return ERROR;
- }
- catch ( UserNotFoundException e )
- {
- addActionError( getText( "cannot.find.user" ) );
- log.error( "Unable to find user.", e );
- return ERROR;
- }
- }
-
- public String cancel()
- {
- return CANCEL;
- }
-
- // ------------------------------------------------------------------
- // Parameter Accessor Methods
- // ------------------------------------------------------------------
-
- public CreateUserCredentials getUser()
- {
- return user;
- }
-
- public void setUser( CreateUserCredentials user )
- {
- this.user = user;
- }
-
- public boolean isEmailValidationRequired()
- {
- return emailValidationRequired;
- }
-
- public void setEmailValidationRequired( boolean emailValidationRequired )
- {
- this.emailValidationRequired = emailValidationRequired;
- }
-
- public String getUsername()
- {
- return username;
- }
-
- public void setUsername( String username )
- {
- this.username = username;
- }
-
- public SecureActionBundle initSecureActionBundle()
- throws SecureActionException
- {
- return SecureActionBundle.OPEN;
- }
-}
+++ /dev/null
-package org.codehaus.plexus.redback.struts2.action;
-
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-import org.codehaus.plexus.util.StringUtils;
-import org.springframework.context.annotation.Scope;
-import org.springframework.stereotype.Controller;
-
-/**
- * SecurityRedirectAction
- *
- * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
- * @version $Id$
- */
-@Controller( "redback-redirect" )
-@Scope( "prototype" )
-public class SecurityRedirectAction
- extends RedbackActionSupport
-{
- private String externalResult;
-
- public String redirect()
- {
- if ( StringUtils.isNotEmpty( externalResult ) )
- {
- return externalResult;
- }
-
- return SUCCESS;
- }
-
- public String getExternalResult()
- {
- return externalResult;
- }
-
- public void setExternalResult( String name )
- {
- this.externalResult = name;
- }
-}
+++ /dev/null
-package org.codehaus.plexus.redback.struts2.action.admin;
-
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-import org.codehaus.plexus.redback.struts2.action.AbstractUserCredentialsAction;
-
-/**
- * AbstractAdminUserCredentialsAction
- *
- * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
- * @version $Id$
- */
-public abstract class AbstractAdminUserCredentialsAction
- extends AbstractUserCredentialsAction
-{
- private String username;
-
- public String getUsername()
- {
- return username;
- }
-
- public void setUsername( String username )
- {
- this.username = username;
- }
-}
+++ /dev/null
-package org.codehaus.plexus.redback.struts2.action.admin;
-
-/*
- * 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.configuration.UserConfiguration;
-import org.apache.archiva.redback.policy.MustChangePasswordException;
-import org.apache.archiva.redback.role.RoleManager;
-import org.apache.archiva.redback.role.RoleManagerException;
-import org.apache.archiva.redback.users.UserManager;
-import org.apache.struts2.ServletActionContext;
-import org.apache.archiva.redback.authentication.AuthenticationConstants;
-import org.apache.archiva.redback.authentication.AuthenticationDataSource;
-import org.apache.archiva.redback.authentication.AuthenticationResult;
-import org.apache.archiva.redback.authentication.PasswordBasedAuthenticationDataSource;
-import org.apache.archiva.redback.policy.AccountLockedException;
-import org.codehaus.plexus.redback.struts2.action.AuditEvent;
-import org.apache.archiva.redback.system.SecuritySession;
-import org.apache.archiva.redback.users.User;
-import org.apache.archiva.redback.users.UserNotFoundException;
-import org.apache.archiva.redback.integration.interceptor.SecureActionBundle;
-import org.apache.archiva.redback.integration.interceptor.SecureActionException;
-import org.apache.archiva.redback.integration.model.EditUserCredentials;
-import org.apache.archiva.redback.integration.util.AutoLoginCookies;
-import org.springframework.context.annotation.Scope;
-import org.springframework.stereotype.Controller;
-
-import javax.inject.Inject;
-import java.util.Arrays;
-import java.util.Date;
-
-/**
- * AddAdminUserAction
- *
- * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
- * @version $Id$
- */
-@Controller( "redback-admin-account" )
-@Scope( "prototype" )
-public class AddAdminUserAction
- extends AbstractAdminUserCredentialsAction
-{
- private static final String LOGIN_ERROR = "login-error";
-
- private static final String LOGIN_SUCCESS = "security-login-success";
-
- private static final String PASSWORD_CHANGE = "security-must-change-password";
-
- private static final String ACCOUNT_LOCKED = "security-login-locked";
-
- @Inject
- private RoleManager roleManager;
-
-
- @Inject
- private UserConfiguration config;
-
- private EditUserCredentials user;
-
- @Inject
- private AutoLoginCookies autologinCookies;
-
- public String show()
- {
- if ( user == null )
- {
- user = new EditUserCredentials( config.getString( "redback.default.admin" ) );
- }
-
- return INPUT;
- }
-
- /**
- * TODO this must done in a service !!
- * @return
- */
- public String submit()
- {
- if ( user == null )
- {
- user = new EditUserCredentials( config.getString( "redback.default.admin" ) );
- addActionError( getText( "invalid.admin.credentials" ) );
- return ERROR;
- }
-
- log.info( "user = {}", user );
-
- internalUser = user;
-
- validateCredentialsStrict();
-
- UserManager userManager = super.securitySystem.getUserManager();
-
- if ( userManager.userExists( config.getString( "redback.default.admin" ) ) )
- {
- // Means that the role name exist already.
- // We need to fail fast and return to the previous page.
- addActionError( getText( "admin.user.already.exists" ) );
- return ERROR;
- }
-
- if ( hasActionErrors() || hasFieldErrors() )
- {
- return ERROR;
- }
-
- User u =
- userManager.createUser( config.getString( "redback.default.admin" ), user.getFullName(), user.getEmail() );
- if ( u == null )
- {
- addActionError( getText( "cannot.operate.on.null.user" ) );
- return ERROR;
- }
-
- u.setPassword( user.getPassword() );
- u.setLocked( false );
- u.setPasswordChangeRequired( false );
- u.setPermanent( true );
-
- userManager.addUser( u );
-
- AuditEvent event = new AuditEvent( getText( "log.account.create" ) );
- event.setAffectedUser( u.getUsername() );
- event.log();
-
- try
- {
- roleManager.assignRole( "system-administrator", u.getPrincipal().toString() );
- event = new AuditEvent( getText( "log.assign.role" ) );
- event.setAffectedUser( u.getUsername() );
- event.setRole( "system-administrator" );
- event.log();
- }
- catch ( RoleManagerException rpe )
- {
- addActionError( getText( "cannot.assign.admin.role" ) );
- return ERROR;
- }
-
- PasswordBasedAuthenticationDataSource authdatasource = new PasswordBasedAuthenticationDataSource();
- authdatasource.setPrincipal( user.getUsername() );
- authdatasource.setPassword( user.getPassword() );
-
- return webLogin( authdatasource );
- }
-
- public EditUserCredentials getUser()
- {
- return user;
- }
-
- public void setUser( EditUserCredentials user )
- {
- this.user = user;
- }
-
- public SecureActionBundle initSecureActionBundle()
- throws SecureActionException
- {
- return SecureActionBundle.OPEN;
- }
-
- /**
- * 1) attempts to authentication based on the passed in data source
- * 2) if successful sets cookies and returns LOGIN_SUCCESS
- * 3) if failure then check what kinda failure and return error
- *
- * @param authdatasource
- * @return
- */
- private String webLogin( AuthenticationDataSource authdatasource )
- {
- // An attempt should log out your authentication tokens first!
- setAuthTokens( null );
-
- clearErrorsAndMessages();
-
- String principal = authdatasource.getPrincipal();
-
- try
- {
- SecuritySession securitySession = securitySystem.authenticate( authdatasource );
-
- if ( securitySession.getAuthenticationResult().isAuthenticated() )
- {
- // Success! Create tokens.
- setAuthTokens( securitySession );
-
- setCookies( authdatasource );
-
- AuditEvent event = new AuditEvent( getText( "log.login.success" ) );
- event.setAffectedUser( principal );
- event.log();
-
- User u = securitySession.getUser();
- u.setLastLoginDate( new Date() );
- securitySystem.getUserManager().updateUser( u );
-
- return LOGIN_SUCCESS;
- }
- else
- {
- log.debug( "Login Action failed against principal : {}",
- securitySession.getAuthenticationResult().getPrincipal(),
- securitySession.getAuthenticationResult().getException() );
-
- AuthenticationResult result = securitySession.getAuthenticationResult();
- if ( result.getExceptionsMap() != null && !result.getExceptionsMap().isEmpty() )
- {
- if ( result.getExceptionsMap().get( AuthenticationConstants.AUTHN_NO_SUCH_USER ) != null )
- {
- addActionError( getText( "incorrect.username.password" ) );
- }
- else
- {
- addActionError( getText( "authentication.failed" ) );
- }
- }
- else
- {
- addActionError( getText( "authentication.failed" ) );
- }
-
- AuditEvent event = new AuditEvent( getText( "log.login.fail" ) );
- event.setAffectedUser( principal );
- event.log();
-
- return LOGIN_ERROR;
- }
- }
- catch ( AuthenticationException ae )
- {
- addActionError( getText( "authentication.exception", Arrays.asList( (Object) ae.getMessage() ) ) );
- return LOGIN_ERROR;
- }
- catch ( UserNotFoundException ue )
- {
- addActionError(
- getText( "user.not.found.exception", Arrays.asList( (Object) principal, ue.getMessage() ) ) );
-
- AuditEvent event = new AuditEvent( getText( "log.login.fail" ) );
- event.setAffectedUser( principal );
- event.log();
- return LOGIN_ERROR;
- }
- catch ( AccountLockedException e )
- {
- addActionError( getText( "account.locked" ) );
-
- AuditEvent event = new AuditEvent( getText( "log.login.fail.locked" ) );
- event.setAffectedUser( principal );
- event.log();
- return ACCOUNT_LOCKED;
- }
- catch ( MustChangePasswordException e )
- {
- // TODO: preferably we would not set the cookies for this "partial" login state
- setCookies( authdatasource );
-
- AuditEvent event = new AuditEvent( getText( "log.login.fail.locked" ) );
- event.setAffectedUser( principal );
- event.log();
- return PASSWORD_CHANGE;
- }
- }
-
- private void setCookies( AuthenticationDataSource authdatasource )
- {
- autologinCookies.setSignonCookie( authdatasource.getPrincipal(), ServletActionContext.getResponse(),
- ServletActionContext.getRequest() );
- }
-}
+++ /dev/null
-package org.codehaus.plexus.redback.struts2.action.admin;
-
-/*
- * 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.Resource;
-import org.codehaus.plexus.redback.struts2.action.AbstractSecurityAction;
-import org.apache.archiva.redback.integration.interceptor.SecureActionBundle;
-import org.apache.archiva.redback.integration.interceptor.SecureActionException;
-import org.apache.archiva.redback.integration.role.RoleConstants;
-import org.springframework.context.annotation.Scope;
-import org.springframework.stereotype.Controller;
-
-/**
- * AdminConsoleAction
- *
- * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
- * @version $Id$
- */
-@Controller("redback-admin-console")
-@Scope("prototype")
-public class AdminConsoleAction
- extends AbstractSecurityAction
-{
- public String show()
- {
- return INPUT;
- }
-
- public SecureActionBundle initSecureActionBundle()
- throws SecureActionException
- {
- SecureActionBundle bundle = new SecureActionBundle();
- bundle.setRequiresAuthentication( true );
- bundle.addRequiredAuthorization( RoleConstants.CONFIGURATION_EDIT_OPERATION, Resource.GLOBAL );
- bundle.addRequiredAuthorization( RoleConstants.USER_MANAGEMENT_RBAC_ADMIN_OPERATION, Resource.GLOBAL );
- bundle.addRequiredAuthorization( RoleConstants.USER_MANAGEMENT_ROLE_DROP_OPERATION, Resource.GLOBAL );
- bundle.addRequiredAuthorization( RoleConstants.USER_MANAGEMENT_ROLE_GRANT_OPERATION, Resource.GLOBAL );
- bundle.addRequiredAuthorization( RoleConstants.USER_MANAGEMENT_USER_CREATE_OPERATION, Resource.GLOBAL );
- bundle.addRequiredAuthorization( RoleConstants.USER_MANAGEMENT_USER_DELETE_OPERATION, Resource.GLOBAL );
- bundle.addRequiredAuthorization( RoleConstants.USER_MANAGEMENT_USER_EDIT_OPERATION, Resource.GLOBAL );
- bundle.addRequiredAuthorization( RoleConstants.USER_MANAGEMENT_USER_LIST_OPERATION, Resource.GLOBAL );
- return bundle;
- }
-}
+++ /dev/null
-package org.codehaus.plexus.redback.struts2.action.admin;
-
-/*
- * 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.Resource;
-import org.apache.archiva.redback.rbac.Role;
-import org.apache.archiva.redback.rbac.UserAssignment;
-import org.apache.archiva.redback.role.RoleManager;
-import org.apache.archiva.redback.users.User;
-import org.apache.archiva.redback.users.UserNotFoundException;
-import org.apache.archiva.redback.rbac.RbacManagerException;
-import org.codehaus.plexus.redback.role.model.ModelApplication;
-import org.codehaus.plexus.redback.struts2.action.AbstractUserCredentialsAction;
-import org.codehaus.plexus.redback.struts2.action.AuditEvent;
-import org.codehaus.plexus.redback.struts2.model.ApplicationRoleDetails;
-import org.codehaus.plexus.redback.struts2.model.ApplicationRoleDetails.RoleTableCell;
-import org.apache.archiva.redback.users.UserManager;
-import org.codehaus.plexus.util.StringUtils;
-import org.apache.archiva.redback.integration.interceptor.SecureActionBundle;
-import org.apache.archiva.redback.integration.interceptor.SecureActionException;
-import org.apache.archiva.redback.integration.model.AdminEditUserCredentials;
-import org.apache.archiva.redback.integration.role.RoleConstants;
-import org.springframework.context.annotation.Scope;
-import org.springframework.stereotype.Controller;
-
-import javax.inject.Inject;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Set;
-
-/**
- * AssignmentsAction
- *
- * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
- * @version $Id$
- */
-@Controller("redback-assignments")
-@Scope("prototype")
-public class AssignmentsAction
- extends AbstractUserCredentialsAction
-{
- // ------------------------------------------------------------------
- // Component Requirements
- // ------------------------------------------------------------------
-
- /**
- * role-hint="default"
- */
- @Inject
- private RoleManager rmanager;
-
- // ------------------------------------------------------------------
- // Action Parameters
- // ------------------------------------------------------------------
-
- private String principal;
-
- private AdminEditUserCredentials user;
-
- /**
- * A List of {@link Role} objects.
- */
- private List<Role> assignedRoles;
-
- /**
- * A List of {@link Role} objects.
- */
- private List<Role> availableRoles;
-
- private List<Role> effectivelyAssignedRoles;
-
- /**
- * List of names (received from client) of dynamic roles to set/unset
- */
- private List<String> addDSelectedRoles;
-
- /**
- * List of names (received from client) of nondynamic roles to set/unset
- */
- private List<String> addNDSelectedRoles;
-
- private List<Role> nondynamicroles;
-
- private List<Role> dynamicroles;
-
- private List<String> NDRoles;
-
- private List<String> DRoles;
-
- private List<ApplicationRoleDetails> applicationRoleDetails = new ArrayList<ApplicationRoleDetails>();
-
- // ------------------------------------------------------------------
- // Action Entry Points - (aka Names)
- // ------------------------------------------------------------------
-
- public List<ApplicationRoleDetails> getApplicationRoleDetails()
- {
- return applicationRoleDetails;
- }
-
- /**
- * Display the edit user panel. <p/> This should consist of the Role details for the specified user. <p/> A table of
- * currently assigned roles. This table should have a column to remove the role from the user. This table should
- * also have a column of checkboxes that can be selected and then removed from the user. <p/> A table of roles that
- * can be assigned. This table should have a set of checkboxes that can be selected and then added to the user. <p/>
- * Duplicate role assignment needs to be taken care of.
- *
- * @throws RbacManagerException
- * @throws org.apache.archiva.redback.rbac.RbacObjectNotFoundException
- */
- @SuppressWarnings( "unchecked" )
- public String show()
- throws RbacManagerException
- {
- this.addNDSelectedRoles = new ArrayList<String>();
- this.addDSelectedRoles = new ArrayList<String>();
-
- if ( StringUtils.isEmpty( principal ) )
- {
- addActionError( getText( "rbac.edit.user.empty.principal" ) );
- return ERROR;
- }
-
- UserManager userManager = super.securitySystem.getUserManager();
-
- if ( !userManager.userExists( principal ) )
- {
- addActionError( getText( "user.does.not.exist", new String[]{principal} ) );
- return ERROR;
- }
-
- try
- {
- User u = userManager.findUser( principal );
-
- if ( u == null )
- {
- addActionError( getText( "cannot.operate.on.null.user" ) );
- return ERROR;
- }
-
- user = new AdminEditUserCredentials( u );
- }
- catch ( UserNotFoundException e )
- {
- addActionError( getText( "user.not.found.exception", Arrays.asList( ( Object ) principal, e.getMessage() ) ) );
- return ERROR;
- }
-
- // check first if role assignments for user exist
- if ( !getManager().userAssignmentExists( principal ) )
- {
- UserAssignment assignment = getManager().createUserAssignment( principal );
- getManager().saveUserAssignment( assignment );
- }
-
- List<Role> assignableRoles = getFilteredRolesForCurrentUserAccess();
- List<ApplicationRoleDetails> appRoleDetails = lookupAppRoleDetails( principal, assignableRoles );
- applicationRoleDetails.addAll( appRoleDetails );
-
- return SUCCESS;
- }
-
- @SuppressWarnings( "unchecked" )
- private List<ApplicationRoleDetails> lookupAppRoleDetails( String principal, List<Role> assignableRoles )
- throws RbacManagerException
- {
- List<ApplicationRoleDetails> appRoleDetails = new ArrayList<ApplicationRoleDetails>();
- for ( Iterator<ModelApplication> i = rmanager.getModel().getApplications().iterator(); i.hasNext(); )
- {
- ModelApplication application = i.next();
- ApplicationRoleDetails details =
- new ApplicationRoleDetails( application, getManager().getEffectivelyAssignedRoles( principal ),
- getManager().getAssignedRoles( principal ), assignableRoles );
- appRoleDetails.add( details );
- }
- return appRoleDetails;
- }
-
- /**
- * Applies role additions and removals and then displays the edit user panel.
- *
- * @return
- */
- public String edituser()
- {
- try
- {
- Collection<Role> assignedRoles = getManager().getAssignedRoles( principal );
- List<Role> assignableRoles = getFilteredRolesForCurrentUserAccess();
-
- // Compute set of roles usable by configured apps, add/del from this set only
- List<ApplicationRoleDetails> appRoleDetails = lookupAppRoleDetails( principal, assignableRoles );
- applicationRoleDetails.addAll( appRoleDetails );
-
- Set<String> availableAppRoleNames = new HashSet<String>();
- for ( ApplicationRoleDetails appRoleDetail : applicationRoleDetails )
- {
- availableAppRoleNames.addAll( appRoleDetail.getAssignedRoles() );
- availableAppRoleNames.addAll( appRoleDetail.getAvailableRoles() );
-
- // Add dynamic roles offered on page
- for ( List<RoleTableCell> row : appRoleDetail.getTable() )
- {
- for ( RoleTableCell col : row )
- {
- if ( !col.isLabel() )
- {
- availableAppRoleNames.add( col.getName() );
- }
- }
- }
- }
-
- Set<Role> availableRoles = new HashSet<Role>( assignedRoles );
- availableRoles.addAll( assignableRoles );
-
- // Filter the available roles so we only consider configured app roles
- Iterator<Role> availableRoleIterator = availableRoles.iterator();
- while ( availableRoleIterator.hasNext() )
- {
- Role availableRole = availableRoleIterator.next();
- if ( !availableAppRoleNames.contains( availableRole.getName() ) )
- {
- availableRoleIterator.remove();
- }
- }
-
- List<String> selectedRoleNames = new ArrayList<String>();
- addSelectedRoles( availableRoles, selectedRoleNames, addNDSelectedRoles );
- addSelectedRoles( availableRoles, selectedRoleNames, addDSelectedRoles );
-
- List<String> newRoles = new ArrayList<String>( selectedRoleNames );
- String currentUser = getCurrentUser();
- for ( Role assignedRole : assignedRoles )
- {
- if ( !selectedRoleNames.contains( assignedRole.getName() ) )
- {
- // removing a currently assigned role, check if we have permission
- if ( !availableRoles.contains( assignedRole )
- || !checkRoleName( assignableRoles, assignedRole.getName() ) )
- {
- // it may have not been on the page. Leave it assigned.
- selectedRoleNames.add( assignedRole.getName() );
- }
- else
- {
- String role = assignedRole.getName();
- AuditEvent event = new AuditEvent( getText( "log.revoke.role" ) );
- event.setAffectedUser( principal );
- event.setRole( role );
- event.setCurrentUser( currentUser );
- event.log();
- }
- }
- else
- {
- newRoles.remove( assignedRole.getName() );
- }
- }
- for ( String r : newRoles )
- {
- AuditEvent event = new AuditEvent( getText( "log.assign.role" ) );
- event.setAffectedUser( principal );
- event.setRole( r );
- event.setCurrentUser( currentUser );
- event.log();
- }
-
- UserAssignment assignment;
-
- if ( getManager().userAssignmentExists( principal ) )
- {
- assignment = getManager().getUserAssignment( principal );
- }
- else
- {
- assignment = getManager().createUserAssignment( principal );
- }
-
- assignment.setRoleNames( selectedRoleNames );
-
- assignment = getManager().saveUserAssignment( assignment );
- }
- catch ( RbacManagerException ne )
- {
- addActionError( getText( "error.removing.selected.roles", Arrays.asList( ( Object ) ne.getMessage() ) ) );
- return ERROR;
- }
- return SUCCESS;
- }
-
- private void addSelectedRoles( Collection<Role> assignableRoles, List<String> roles, List<String> selectedRoles )
- {
- if ( selectedRoles != null )
- {
- for ( String r : selectedRoles )
- {
- if ( checkRoleName( assignableRoles, r ) )
- {
- roles.add( r );
- }
- }
- }
- }
-
- private boolean checkRoleName( Collection<Role> assignableRoles, String r )
- {
- for ( Role role : assignableRoles )
- {
- if ( role.getName().equals( r ) )
- {
- return true;
- }
- }
- return false;
- }
-
- // ------------------------------------------------------------------
- // Parameter Accessor Methods
- // ------------------------------------------------------------------
-
- public List<Role> getAssignedRoles()
- {
- return assignedRoles;
- }
-
- public void setAssignedRoles( List<Role> assignedRoles )
- {
- this.assignedRoles = assignedRoles;
- }
-
- public List<Role> getAvailableRoles()
- {
- return availableRoles;
- }
-
- public void setAvailableRoles( List<Role> availableRoles )
- {
- this.availableRoles = availableRoles;
- }
-
- public List<Role> getEffectivelyAssignedRoles()
- {
- return effectivelyAssignedRoles;
- }
-
- public void setEffectivelyAssignedRoles( List<Role> effectivelyAssignedRoles )
- {
- this.effectivelyAssignedRoles = effectivelyAssignedRoles;
- }
-
- public String getPrincipal()
- {
- return principal;
- }
-
- public void setPrincipal( String principal )
- {
- this.principal = principal;
- }
-
- public void setUsername( String username )
- {
- this.principal = username;
- }
-
- public AdminEditUserCredentials getUser()
- {
- return user;
- }
-
- public SecureActionBundle initSecureActionBundle()
- throws SecureActionException
- {
- SecureActionBundle bundle = new SecureActionBundle();
- bundle.setRequiresAuthentication( true );
- bundle.addRequiredAuthorization( RoleConstants.USER_MANAGEMENT_USER_EDIT_OPERATION, Resource.GLOBAL );
- bundle.addRequiredAuthorization( RoleConstants.USER_MANAGEMENT_RBAC_ADMIN_OPERATION, Resource.GLOBAL );
- bundle.addRequiredAuthorization( RoleConstants.USER_MANAGEMENT_ROLE_GRANT_OPERATION, Resource.GLOBAL );
- bundle.addRequiredAuthorization( RoleConstants.USER_MANAGEMENT_ROLE_DROP_OPERATION, Resource.GLOBAL );
- bundle.addRequiredAuthorization( RoleConstants.USER_MANAGEMENT_USER_ROLE_OPERATION, Resource.GLOBAL );
-
- return bundle;
- }
-
- public List<Role> getNondynamicroles()
- {
- return nondynamicroles;
- }
-
- public void setNondynamicroles( List<Role> nondynamicroles )
- {
- this.nondynamicroles = nondynamicroles;
- }
-
- public List<Role> getDynamicroles()
- {
- return dynamicroles;
- }
-
- public void setDynamicroles( List<Role> dynamicroles )
- {
- this.dynamicroles = dynamicroles;
- }
-
- public List<String> getNDRoles()
- {
- return NDRoles;
- }
-
- public void setNDRoles( List<String> roles )
- {
- NDRoles = roles;
- }
-
- public List<String> getDRoles()
- {
- return DRoles;
- }
-
- public void setDRoles( List<String> roles )
- {
- DRoles = roles;
- }
-
- public List<String> getAddDSelectedRoles()
- {
- return addDSelectedRoles;
- }
-
- public void setAddDSelectedRoles( List<String> addDSelectedRoles )
- {
- this.addDSelectedRoles = addDSelectedRoles;
- }
-
- public List<String> getAddNDSelectedRoles()
- {
- return addNDSelectedRoles;
- }
-
- public void setAddNDSelectedRoles( List<String> addNDSelectedRoles )
- {
- this.addNDSelectedRoles = addNDSelectedRoles;
- }
-}
+++ /dev/null
-package org.codehaus.plexus.redback.struts2.action.admin;
-
-/*
- * 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 java.io.File;
-import java.util.Date;
-
-/**
- * A record of a backup directory for displaying the backup/restore page.
- */
-public class BackupRecord
- implements Comparable<BackupRecord>
-{
- private final File directory;
-
- private final Date date;
-
- private final boolean userDatabase;
-
- public BackupRecord( File directory )
- {
- this.directory = directory;
-
- this.date = new Date( directory.lastModified() );
-
- this.userDatabase = new File( directory, "users.xml" ).exists();
- }
-
- public File getDirectory()
- {
- return directory;
- }
-
- public Date getDate()
- {
- return date;
- }
-
- public boolean isUserDatabase()
- {
- return userDatabase;
- }
-
- public boolean isValidBackup()
- {
- return userDatabase;
- }
-
- public int compareTo( BackupRecord record )
- {
- return record.date.compareTo( this.date );
- }
-}
+++ /dev/null
-package org.codehaus.plexus.redback.struts2.action.admin;
-
-/*
- * 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 com.opensymphony.xwork2.Preparable;
-import org.apache.archiva.redback.rbac.RBACManager;
-import org.apache.archiva.redback.rbac.Resource;
-import org.apache.commons.lang.StringUtils;
-import org.apache.archiva.redback.keys.KeyManager;
-import org.apache.archiva.redback.management.DataManagementTool;
-import org.codehaus.plexus.redback.struts2.action.AbstractSecurityAction;
-import org.apache.archiva.redback.users.UserManager;
-import org.apache.archiva.redback.integration.interceptor.SecureAction;
-import org.apache.archiva.redback.integration.interceptor.SecureActionBundle;
-import org.apache.archiva.redback.integration.interceptor.SecureActionException;
-import org.apache.archiva.redback.integration.role.RoleConstants;
-import org.springframework.context.annotation.Scope;
-import org.springframework.stereotype.Controller;
-
-import javax.inject.Inject;
-import javax.inject.Named;
-import java.io.File;
-import java.io.IOException;
-import java.text.SimpleDateFormat;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Date;
-import java.util.List;
-import java.util.Locale;
-
-
-/**
- * BackupRestoreAction
- */
-@Controller( "backup-restore" )
-@Scope( "prototype" )
-public class BackupRestoreAction
- extends AbstractSecurityAction
- implements SecureAction, Preparable
-{
- public final static String CUSTOM_ERROR = "custom_error";
-
- /**
- *
- */
- private File applicationHome = new File( "data" );
-
- /**
- * role-hint="jdo"
- */
- @Inject
- private DataManagementTool dataManagementTool;
-
- /**
- * role-hint="jdo"
- */
- @Inject
- @Named( value = "rBACManager#jdo" )
- private RBACManager rbacManager;
-
- /**
- * role-hint="jdo"
- */
- @Inject
- @Named( value = "userManager#jdo" )
- private UserManager userManager;
-
- /**
- * role-hint="jdo"
- */
- @Inject
- @Named( value = "keyManager#jdo" )
- private KeyManager keyManager;
-
- private File backupDirectory;
-
- private String restoreDirectory;
-
- private List<BackupRecord> previousBackups;
-
- private boolean confirmed;
-
- public static final String BACKUP_DIRECTORY = "user-backup-directory";
-
- public String view()
- throws Exception
- {
-
- retrievePreviousBackups();
-
- return SUCCESS;
- }
-
- public String backup()
- throws Exception
- {
-
- File backupDirectory = getTimestampedBackupDirectory();
- backupDirectory.mkdirs();
-
- log.info( "Backing up security database to {}", backupDirectory );
- this.backupDatabase( backupDirectory );
-
- log.info( "Done backing up security database" );
-
- return SUCCESS;
- }
-
- public String restore()
- throws Exception
- {
- if ( StringUtils.isEmpty( restoreDirectory ) )
- {
- addActionError( getText( "backupRestore.backup.empty.error" ) );
- return CUSTOM_ERROR;
- }
-
- File restoreDirectory = new File( this.restoreDirectory );
-
- boolean fileExists = restoreDirectory.exists() && restoreDirectory.isDirectory();
- boolean isValidBackup = false;
-
- if ( fileExists )
- {
- BackupRecord record = new BackupRecord( restoreDirectory );
- isValidBackup = record.isValidBackup();
- }
-
- if ( !fileExists )
- {
- log.warn( "Backup: " + this.restoreDirectory + " not found." );
- addActionError( getText( "backupRestore.backup.error" ) );
- retrievePreviousBackups();
- return CUSTOM_ERROR;
- }
- else if ( !isValidBackup )
- {
- log.warn( "Backup: " + this.restoreDirectory + " is not a valid backup directory." );
- addActionError( getText( "backupRestore.backup.error" ) );
- retrievePreviousBackups();
- return CUSTOM_ERROR;
- }
-
- log.info( "Restoring security database from {}", this.restoreDirectory );
- this.eraseDatabase();
- this.restoreDatabase( restoreDirectory );
- log.info( "Done restoring security database" );
-
- return SUCCESS;
- }
-
-
- private void backupDatabase( File backupDirectory )
- throws Exception
- {
-
- dataManagementTool.backupKeyDatabase( keyManager, backupDirectory );
- dataManagementTool.backupRBACDatabase( rbacManager, backupDirectory );
- dataManagementTool.backupUserDatabase( userManager, backupDirectory );
- }
-
- private void eraseDatabase()
- {
- dataManagementTool.eraseKeysDatabase( keyManager );
- dataManagementTool.eraseRBACDatabase( rbacManager );
- dataManagementTool.eraseUsersDatabase( userManager );
- }
-
- private void restoreDatabase( File backupDirectory )
- throws Exception
- {
-
- dataManagementTool.restoreKeysDatabase( keyManager, backupDirectory );
- dataManagementTool.restoreRBACDatabase( rbacManager, backupDirectory );
- dataManagementTool.restoreUsersDatabase( userManager, backupDirectory );
- }
-
- public String getRestoreDirectory()
- {
- return restoreDirectory;
- }
-
- public void setRestoreDirectory( String restoreDirectory )
- {
- this.restoreDirectory = restoreDirectory;
- }
-
- private File getTimestampedBackupDirectory()
- {
- SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyyMMdd.HHmmss", Locale.US );
- return new File( this.backupDirectory, dateFormat.format( new Date() ) );
- }
-
- public File getBackupDirectory()
- {
- return backupDirectory;
- }
-
- public List<BackupRecord> getPreviousBackups()
- {
- return previousBackups;
- }
-
- public void prepare()
- {
- backupDirectory = this.getFile( BACKUP_DIRECTORY );
- retrievePreviousBackups();
- }
-
- private void retrievePreviousBackups()
- {
- previousBackups = new ArrayList<BackupRecord>();
- File[] files = backupDirectory.listFiles();
- if ( files != null )
- {
- for ( int i = 0; i < files.length; i++ )
- {
- File f = files[i];
-
- if ( f.isDirectory() && !f.getName().startsWith( "." ) )
- {
- BackupRecord record = new BackupRecord( f );
-
- if ( record.isValidBackup() )
- {
- previousBackups.add( record );
- }
- }
- }
- }
- Collections.sort( previousBackups );
- }
-
- public boolean isConfirmed()
- {
- return confirmed;
- }
-
- public void setConfirmed( boolean confirmed )
- {
- this.confirmed = confirmed;
- }
-
- @Override
- public SecureActionBundle initSecureActionBundle()
- throws SecureActionException
- {
- SecureActionBundle bundle = new SecureActionBundle();
- bundle.setRequiresAuthentication( true );
- bundle.addRequiredAuthorization( RoleConstants.USER_MANAGEMENT_MANAGE_DATA, Resource.GLOBAL );
- return bundle;
- }
-
- public File getFile( String filename )
- {
- if ( filename == null )
- {
- return null;
- }
-
- File f = null;
-
- if ( filename != null && filename.length() != 0 )
- {
- f = new File( filename );
-
- if ( !f.isAbsolute() )
- {
- f = new File( applicationHome, filename );
- }
- }
-
- try
- {
- return f.getCanonicalFile();
- }
- catch ( IOException e )
- {
- return f;
- }
- }
-}
+++ /dev/null
-package org.codehaus.plexus.redback.struts2.action.admin;
-
-/*
- * 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.RbacManagerException;
-import org.apache.archiva.redback.rbac.Resource;
-import org.apache.archiva.redback.rbac.Role;
-import org.apache.archiva.redback.rbac.UserAssignment;
-import org.apache.archiva.redback.users.User;
-import org.apache.commons.lang.StringEscapeUtils;
-import org.codehaus.plexus.redback.struts2.action.AbstractUserCredentialsAction;
-import org.codehaus.plexus.redback.struts2.action.AuditEvent;
-import org.apache.archiva.redback.users.UserManager;
-import org.apache.archiva.redback.users.UserNotFoundException;
-import org.codehaus.plexus.util.StringUtils;
-import org.apache.archiva.redback.integration.interceptor.SecureActionBundle;
-import org.apache.archiva.redback.integration.interceptor.SecureActionException;
-import org.apache.archiva.redback.integration.security.role.RedbackRoleConstants;
-import org.springframework.context.annotation.Scope;
-import org.springframework.stereotype.Controller;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-
-/**
- * EditRoleAction
- *
- * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
- * @version $Id$
- */
-@Controller( "redback-role-edit" )
-@Scope( "prototype" )
-public class EditRoleAction
- extends AbstractUserCredentialsAction
-{
- // ------------------------------------------------------------------
- // Action Parameters
- // ------------------------------------------------------------------
-
- private String name;
-
- private String description;
-
- private String newDescription;
-
- private List<String> childRoleNames = new ArrayList<String>();
-
- private List<String> parentRoleNames = new ArrayList<String>();
-
- private List<Permission> permissions = new ArrayList<Permission>();
-
- private List<User> users = new ArrayList<User>();
-
- private List<User> parentUsers = new ArrayList<User>();
-
- private List<User> allUsers = new ArrayList<User>();
-
- private List<String> usersList = new ArrayList<String>();
-
- private List<String> availableUsers = new ArrayList<String>();
-
- private List<String> currentUsers = new ArrayList<String>();
-
- // ------------------------------------------------------------------
- // Action Entry Points - (aka Names)
- // ------------------------------------------------------------------
-
- public String input()
- {
- if ( name == null )
- {
- addActionError( getText( "cannot.edit.null.role" ) );
- return ERROR;
- }
-
- if ( StringUtils.isEmpty( name ) )
- {
- addActionError( getText( "cannot.edit.empty.role" ) );
- return ERROR;
- }
-
- name = StringEscapeUtils.escapeXml( name );
-
- if ( !getManager().roleExists( name ) )
- {
- // Means that the role name doesn't exist.
- // We should exit early and not attempt to look up the role information.
- return INPUT;
- }
-
- try
- {
- if ( !isAuthorized() )
- {
- log.warn( getCurrentUser() + " isn't authorized to access to the role '" + name + "'" );
- addActionError( getText( "alert.message" ) );
- return ERROR;
- }
-
- Role role = getManager().getRole( name );
- if ( role == null )
- {
- addActionError( getText( "cannot.operate.null.role" ) );
- return ERROR;
- }
-
- description = role.getDescription();
- childRoleNames = role.getChildRoleNames();
- Map<String, Role> parentRoles = getManager().getParentRoles( role );
- for ( String roleName : parentRoles.keySet() )
- {
- parentRoleNames.add( roleName );
- }
- permissions = role.getPermissions();
-
- //Get users of the current role
- List<String> roles = new ArrayList<String>();
- roles.add( name );
- List<UserAssignment> userAssignments = getManager().getUserAssignmentsForRoles( roles );
- users = new ArrayList<User>();
- if ( userAssignments != null )
- {
- for ( UserAssignment userAssignment : userAssignments )
- {
- try
- {
- User user = getUserManager().findUser( userAssignment.getPrincipal() );
- users.add( user );
- }
- catch ( UserNotFoundException e )
- {
- log.warn( "User '" + userAssignment.getPrincipal() + "' doesn't exist.", e );
- }
- }
- }
-
- //Get users of the parent roles
- parentUsers = new ArrayList<User>();
- if ( !parentRoles.isEmpty() )
- {
- List<UserAssignment> userParentAssignments =
- getManager().getUserAssignmentsForRoles( parentRoles.keySet() );
- if ( userParentAssignments != null )
- {
- for ( UserAssignment userAssignment : userParentAssignments )
- {
- try
- {
- User user = getUserManager().findUser( userAssignment.getPrincipal() );
- parentUsers.add( user );
- }
- catch ( UserNotFoundException e )
- {
- log.warn( "User '" + userAssignment.getPrincipal() + "' doesn't exist.", e );
- }
- }
- }
- }
- }
- catch ( RbacManagerException e )
- {
- List<Object> list = new ArrayList<Object>();
- list.add( name );
- list.add( e.getMessage() );
- addActionError( getText( "cannot.get.role", list ) );
- return ERROR;
- }
-
- return INPUT;
- }
-
- private boolean isAuthorized()
- throws RbacManagerException
- {
- List<Role> assignableRoles = getFilteredRolesForCurrentUserAccess();
- boolean updatableRole = false;
- for ( Role r : assignableRoles )
- {
- if ( r.getName().equalsIgnoreCase( name ) )
- {
- updatableRole = true;
- }
- }
-
- return updatableRole;
- }
-
- public String edit()
- {
- String result = input();
- if ( ERROR.equals( result ) )
- {
- return result;
- }
-
- newDescription = description;
-
- //TODO: Remove all users defined in parent roles too
- allUsers = getUserManager().getUsers();
-
- for ( User user : users )
- {
- if ( allUsers.contains( user ) )
- {
- allUsers.remove( user );
- }
- }
-
- for ( User user : parentUsers )
- {
- if ( allUsers.contains( user ) )
- {
- allUsers.remove( user );
- }
- }
-
- return result;
- }
-
- public String save()
- {
- String result = input();
- if ( ERROR.equals( result ) )
- {
- return result;
- }
-
- if ( name == null )
- {
- addActionError( getText( "cannot.edit.null.role" ) );
- return ERROR;
- }
-
- if ( StringUtils.isEmpty( name ) )
- {
- addActionError( getText( "cannot.edit.empty.role" ) );
- return ERROR;
- }
-
- try
- {
- Role role;
- if ( getManager().roleExists( name ) )
- {
- role = getManager().getRole( name );
- }
- else
- {
- role = getManager().createRole( name );
- }
-
- //TODO: allow to modify childRoleNames and permissions
- role.setDescription( newDescription );
- //role.setChildRoleNames( childRoleNames );
- //role.setPermissions( permissions );
-
- getManager().saveRole( role );
-
- List<Object> list = new ArrayList<Object>();
- list.add( name );
- String currentUser = getCurrentUser();
- AuditEvent event = new AuditEvent( getText( "log.role.edit" ) );
- event.setRole( name );
- event.setCurrentUser( currentUser );
- event.log();
- addActionMessage( getText( "save.role.success", list ) );
- }
- catch ( RbacManagerException e )
- {
- List<Object> list = new ArrayList<Object>();
- list.add( name );
- list.add( e.getMessage() );
- addActionError( getText( "cannot.get.role", list ) );
- return ERROR;
- }
-
- return SUCCESS;
- }
-
- public String addUsers()
- {
- if ( availableUsers == null || availableUsers.isEmpty() )
- {
- return INPUT;
- }
-
- for ( String principal : availableUsers )
- {
- if ( !getUserManager().userExists( principal ) )
- {
- // Means that the role name doesn't exist.
- // We need to fail fast and return to the previous page.
- List<Object> list = new ArrayList<Object>();
- list.add( principal );
- addActionError( getText( "user.does.not.exist", list ) );
- return ERROR;
- }
-
- try
- {
- UserAssignment assignment;
-
- if ( getManager().userAssignmentExists( principal ) )
- {
- assignment = getManager().getUserAssignment( principal );
- }
- else
- {
- assignment = getManager().createUserAssignment( principal );
- }
-
- assignment.addRoleName( name );
- assignment = getManager().saveUserAssignment( assignment );
- log.info( "{} role assigned to {}", name, principal );
- }
- catch ( RbacManagerException e )
- {
- List<Object> list = new ArrayList<Object>();
- list.add( principal );
- list.add( e.getMessage() );
- addActionError( getText( "cannot.assign.role", list ) );
- return ERROR;
- }
- }
-
- edit();
- return SUCCESS;
- }
-
- public String removeUsers()
- {
- if ( currentUsers == null || currentUsers.isEmpty() )
- {
- return INPUT;
- }
-
- for ( String principal : currentUsers )
- {
- if ( !getUserManager().userExists( principal ) )
- {
- // Means that the role name doesn't exist.
- // We need to fail fast and return to the previous page.
- List<Object> list = new ArrayList<Object>();
- list.add( principal );
- addActionError( getText( "user.does.not.exist", list ) );
- return ERROR;
- }
-
- try
- {
- UserAssignment assignment;
-
- if ( getManager().userAssignmentExists( principal ) )
- {
- assignment = getManager().getUserAssignment( principal );
- }
- else
- {
- assignment = getManager().createUserAssignment( principal );
- }
-
- assignment.removeRoleName( name );
- assignment = getManager().saveUserAssignment( assignment );
- log.info( "{} role unassigned to {}", name, principal );
- }
- catch ( RbacManagerException e )
- {
- List<Object> list = new ArrayList<Object>();
- list.add( principal );
- list.add( e.getMessage() );
- addActionError( getText( "cannot.assign.role", list ) );
- return ERROR;
- }
- }
-
- edit();
- return SUCCESS;
- }
-
- private UserManager getUserManager()
- {
- return securitySystem.getUserManager();
- }
-
- // ------------------------------------------------------------------
- // Parameter Accessor Methods
- // ------------------------------------------------------------------
-
- public String getName()
- {
- return name;
- }
-
- public void setName( String roleName )
- {
- this.name = roleName;
- }
-
- public List<String> getChildRoleNames()
- {
- return childRoleNames;
- }
-
- public void setChildRoleNames( List<String> childRoleNames )
- {
- this.childRoleNames = childRoleNames;
- }
-
- public String getDescription()
- {
- return description;
- }
-
- public void setDescription( String description )
- {
- this.description = description;
- }
-
- public String getNewDescription()
- {
- return newDescription;
- }
-
- public void setNewDescription( String newDescription )
- {
- this.newDescription = newDescription;
- }
-
- public List<Permission> getPermissions()
- {
- return permissions;
- }
-
- public void setPermissions( List<Permission> permissions )
- {
- this.permissions = permissions;
- }
-
- public List<User> getUsers()
- {
- return users;
- }
-
- public void setUsers( List<User> users )
- {
- this.users = users;
- }
-
- public List<User> getAllUsers()
- {
- return allUsers;
- }
-
- public void setAllUsers( List<User> allUsers )
- {
- this.allUsers = allUsers;
- }
-
- public List<String> getUsersList()
- {
- return usersList;
- }
-
- public void setUsersList( List<String> usersList )
- {
- this.usersList = usersList;
- }
-
- public List<String> getAvailableUsers()
- {
- return availableUsers;
- }
-
- public void setAvailableUsers( List<String> availableUsers )
- {
- this.availableUsers = availableUsers;
- }
-
- public List<String> getCurrentUsers()
- {
- return currentUsers;
- }
-
- public void setCurrentUsers( List<String> currentUsers )
- {
- this.currentUsers = currentUsers;
- }
-
- public List<String> getParentRoleNames()
- {
- return parentRoleNames;
- }
-
- public void setParentRoleNames( List<String> parentRoleNames )
- {
- this.parentRoleNames = parentRoleNames;
- }
-
- public List<User> getParentUsers()
- {
- return parentUsers;
- }
-
- public void setParentUsers( List<User> parentUsers )
- {
- this.parentUsers = parentUsers;
- }
-
- // ------------------------------------------------------------------
- // Internal Support Methods
- // ------------------------------------------------------------------
-
- public SecureActionBundle initSecureActionBundle()
- throws SecureActionException
- {
- SecureActionBundle bundle = new SecureActionBundle();
- bundle.setRequiresAuthentication( true );
- bundle.addRequiredAuthorization( RedbackRoleConstants.USER_MANAGEMENT_USER_EDIT_OPERATION, Resource.GLOBAL );
- bundle.addRequiredAuthorization( RedbackRoleConstants.USER_MANAGEMENT_RBAC_ADMIN_OPERATION, Resource.GLOBAL );
- bundle.addRequiredAuthorization( RedbackRoleConstants.USER_MANAGEMENT_ROLE_GRANT_OPERATION, Resource.GLOBAL );
- bundle.addRequiredAuthorization( RedbackRoleConstants.USER_MANAGEMENT_ROLE_DROP_OPERATION, Resource.GLOBAL );
- bundle.addRequiredAuthorization( RedbackRoleConstants.USER_MANAGEMENT_USER_ROLE_OPERATION, Resource.GLOBAL );
- return bundle;
- }
-}
+++ /dev/null
-package org.codehaus.plexus.redback.struts2.action.admin;
-
-/*
- * 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.Operation;
-import org.apache.archiva.redback.rbac.RBACManager;
-import org.apache.archiva.redback.rbac.RbacManagerException;
-import org.apache.archiva.redback.rbac.Resource;
-import org.codehaus.plexus.redback.struts2.action.RedbackActionSupport;
-import org.apache.archiva.redback.integration.interceptor.SecureActionBundle;
-import org.apache.archiva.redback.integration.interceptor.SecureActionException;
-import org.apache.archiva.redback.integration.role.RoleConstants;
-import org.apache.archiva.redback.integration.util.OperationSorter;
-import org.springframework.context.annotation.Scope;
-import org.springframework.stereotype.Controller;
-
-import javax.inject.Inject;
-import javax.inject.Named;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-
-/**
- * OperationsAction:
- *
- * @author Jesse McConnell <jmcconnell@apache.org>
- * @version $Id$
- */
-@Controller( "redback-operations" )
-@Scope( "prototype" )
-public class OperationsAction
- extends RedbackActionSupport
-{
- private static final String LIST = "list";
-
- /**
- * role-hint="cached"
- */
- @Inject
- @Named( value = "rBACManager#cached" )
- private RBACManager manager;
-
- private String operationName;
-
- private String description;
-
- private List<Operation> allOperations;
-
- public String list()
- {
- try
- {
- allOperations = manager.getAllOperations();
-
- if ( allOperations == null )
- {
- allOperations = Collections.emptyList();
- }
-
- Collections.sort( allOperations, new OperationSorter() );
- }
- catch ( RbacManagerException e )
- {
- addActionError( getText( "cannot.list.all.operations", Arrays.asList( (Object) e.getMessage() ) ) );
- log.error( "System error:", e );
- allOperations = Collections.emptyList();
- }
-
- return LIST;
- }
-
- public String save()
- {
- try
- {
- Operation temp = manager.createOperation( operationName );
-
- temp.setDescription( description );
-
- manager.saveOperation( temp );
- }
- catch ( RbacManagerException e )
- {
- addActionError( getText( "cannot.save.operation", Arrays.asList( (Object) operationName ) ) );
- log.error( "System error:", e );
- allOperations = Collections.emptyList();
- }
-
- return LIST;
- }
-
- public String remove()
- {
- try
- {
- manager.removeOperation( manager.getOperation( operationName ) );
- }
- catch ( RbacManagerException ne )
- {
- addActionError( getText( "cannot.remove.operation", Arrays.asList( (Object) operationName ) ) );
- return ERROR;
- }
- return LIST;
- }
-
- public List<Operation> getAllOperations()
- {
- return allOperations;
- }
-
- public void setAllOperations( List<Operation> allOperations )
- {
- this.allOperations = allOperations;
- }
-
- public String getDescription()
- {
- return description;
- }
-
- public void setDescription( String description )
- {
- this.description = description;
- }
-
- public String getOperationName()
- {
- return operationName;
- }
-
- public void setOperationName( String operationName )
- {
- this.operationName = operationName;
- }
-
- public SecureActionBundle initSecureActionBundle()
- throws SecureActionException
- {
- SecureActionBundle bundle = new SecureActionBundle();
- bundle.setRequiresAuthentication( true );
- bundle.addRequiredAuthorization( RoleConstants.USER_MANAGEMENT_RBAC_ADMIN_OPERATION, Resource.GLOBAL );
- return bundle;
- }
-}
+++ /dev/null
-package org.codehaus.plexus.redback.struts2.action.admin;
-
-/*
- * 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.Operation;
-import org.apache.archiva.redback.rbac.Permission;
-import org.apache.archiva.redback.rbac.RBACManager;
-import org.apache.archiva.redback.rbac.Resource;
-import org.apache.archiva.redback.rbac.RbacManagerException;
-import org.codehaus.plexus.redback.struts2.action.RedbackActionSupport;
-import org.codehaus.plexus.util.StringUtils;
-import org.apache.archiva.redback.integration.interceptor.SecureActionBundle;
-import org.apache.archiva.redback.integration.interceptor.SecureActionException;
-import org.apache.archiva.redback.integration.role.RoleConstants;
-import org.apache.archiva.redback.integration.util.PermissionSorter;
-import org.springframework.context.annotation.Scope;
-import org.springframework.stereotype.Controller;
-
-import javax.inject.Inject;
-import javax.inject.Named;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-
-/**
- * PermissionsAction
- *
- * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
- * @version $Id$
- */
-@Controller( "redback-permissions" )
-@Scope( "prototype" )
-public class PermissionsAction
- extends RedbackActionSupport
-{
- private static final String LIST = "list";
-
- // ------------------------------------------------------------------
- // Plexus Component Requirements
- // ------------------------------------------------------------------
-
- /**
- * role-hint="cached"
- */
- @Inject
- @Named( value = "rBACManager#cached" )
- private RBACManager manager;
-
- // ------------------------------------------------------------------
- // Action Parameters
- // ------------------------------------------------------------------
-
- private String name;
-
- private String description;
-
- private String operationName;
-
- private String operationDescription;
-
- private String resourceIdentifier;
-
- private List<Permission> allPermissions;
-
- // ------------------------------------------------------------------
- // Action Entry Points - (aka Names)
- // ------------------------------------------------------------------
-
- public String list()
- {
- try
- {
- allPermissions = manager.getAllPermissions();
-
- if ( allPermissions == null )
- {
- allPermissions = Collections.emptyList();
- }
-
- Collections.sort( allPermissions, new PermissionSorter() );
- }
- catch ( RbacManagerException e )
- {
- addActionError( getText( "cannot.list.all.permissions", Arrays.asList( (Object) e.getMessage() ) ) );
- log.error( "System error:", e );
- allPermissions = Collections.emptyList();
- }
-
- return LIST;
- }
-
- public String input()
- {
- if ( name == null )
- {
- addActionError( getText( "cannot.edit.null.permission" ) );
- return ERROR;
- }
-
- if ( StringUtils.isEmpty( name ) )
- {
- addActionError( getText( "cannot.edit.empty.permission" ) );
- return ERROR;
- }
-
- if ( !manager.permissionExists( name ) )
- {
- // Means that the permission name doesn't exist.
- // We should exit early and not attempt to look up the permission information.
- return LIST;
- }
-
- try
- {
- Permission permission = manager.getPermission( name );
- if ( permission == null )
- {
- addActionError( getText( "cannot.operate.null.permission" ) );
- return ERROR;
- }
-
- description = permission.getDescription();
- Operation operation = permission.getOperation();
- if ( operation != null )
- {
- operationName = operation.getName();
- operationDescription = operation.getDescription();
- }
-
- Resource resource = permission.getResource();
- if ( resource != null )
- {
- resourceIdentifier = resource.getIdentifier();
- }
- }
- catch ( RbacManagerException e )
- {
- addActionError( getText( "cannot.get.permission", Arrays.asList( (Object) name, e.getMessage() ) ) );
- return ERROR;
- }
-
- return LIST;
- }
-
- public String submit()
- {
- if ( name == null )
- {
- addActionError( getText( "cannot.edit.null.permission" ) );
- return ERROR;
- }
-
- if ( StringUtils.isEmpty( name ) )
- {
- addActionError( getText( "cannot.edit.empty.permission" ) );
- return ERROR;
- }
-
- try
- {
- Permission permission;
- if ( manager.permissionExists( name ) )
- {
- permission = manager.getPermission( name );
- }
- else
- {
- permission = manager.createPermission( name );
- }
-
- permission.setDescription( description );
-
- Operation operation = manager.createOperation( operationName );
- if ( StringUtils.isNotEmpty( operationDescription ) )
- {
- operation.setDescription( operationDescription );
- }
- permission.setOperation( manager.saveOperation( operation ) );
-
- Resource resource = manager.createResource( resourceIdentifier );
- permission.setResource( manager.saveResource( resource ) );
-
- manager.savePermission( permission );
-
- addActionMessage( getText( "save.permission.success", Arrays.asList( (Object) name ) ) );
- }
- catch ( RbacManagerException e )
- {
- addActionError( getText( "cannot.get.permission", Arrays.asList( (Object) name, e.getMessage() ) ) );
- return ERROR;
- }
-
- return LIST;
- }
-
- // ------------------------------------------------------------------
- // Parameter Accessor Methods
- // ------------------------------------------------------------------
-
- public String getDescription()
- {
- return description;
- }
-
- public void setDescription( String description )
- {
- this.description = description;
- }
-
- public String getName()
- {
- return name;
- }
-
- public void setName( String name )
- {
- this.name = name;
- }
-
- public String getOperationDescription()
- {
- return operationDescription;
- }
-
- public void setOperationDescription( String operationDescription )
- {
- this.operationDescription = operationDescription;
- }
-
- public String getOperationName()
- {
- return operationName;
- }
-
- public void setOperationName( String operationName )
- {
- this.operationName = operationName;
- }
-
- public String getResourceIdentifier()
- {
- return resourceIdentifier;
- }
-
- public void setResourceIdentifier( String resourceIdentifier )
- {
- this.resourceIdentifier = resourceIdentifier;
- }
-
- public List<Permission> getAllPermissions()
- {
- return allPermissions;
- }
-
- public void setAllPermissions( List<Permission> allPermissions )
- {
- this.allPermissions = allPermissions;
- }
-
- public SecureActionBundle initSecureActionBundle()
- throws SecureActionException
- {
- SecureActionBundle bundle = new SecureActionBundle();
- bundle.setRequiresAuthentication( true );
- bundle.addRequiredAuthorization( RoleConstants.USER_MANAGEMENT_RBAC_ADMIN_OPERATION, Resource.GLOBAL );
- return bundle;
- }
-}
+++ /dev/null
-package org.codehaus.plexus.redback.struts2.action.admin;
-
-/*
- * 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 java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.util.Arrays;
-
-import javax.inject.Inject;
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.struts2.ServletActionContext;
-import org.apache.archiva.redback.rbac.Resource;
-import org.codehaus.plexus.redback.struts2.action.AbstractSecurityAction;
-import org.apache.archiva.redback.integration.interceptor.SecureActionBundle;
-import org.apache.archiva.redback.integration.interceptor.SecureActionException;
-import org.apache.archiva.redback.integration.reports.Report;
-import org.apache.archiva.redback.integration.reports.ReportException;
-import org.apache.archiva.redback.integration.reports.ReportManager;
-import org.apache.archiva.redback.integration.role.RoleConstants;
-
-import com.opensymphony.module.sitemesh.filter.PageResponseWrapper;
-import org.springframework.context.annotation.Scope;
-import org.springframework.stereotype.Controller;
-
-/**
- * ReportAction
- *
- * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
- * @version $Id$
- */
-@Controller("redback-report")
-@Scope("prototype")
-public class ReportAction
- extends AbstractSecurityAction
-{
- /**
- *
- */
- @Inject
- private ReportManager reportManager;
-
- private String reportId;
-
- private String reportType;
-
- public String generate()
- {
- Report report;
- try
- {
- report = reportManager.findReport( reportId, reportType );
- }
- catch ( ReportException e )
- {
- addActionError( getText( "cannot.get.report", Arrays.asList( ( Object ) e.getMessage() ) ) );
- return ERROR;
- }
-
- HttpServletResponse response = ServletActionContext.getResponse();
-
- // HACK: Unwrap sitemesh response. (effectively disables sitemesh)
- if ( response instanceof PageResponseWrapper )
- {
- response = (HttpServletResponse) ( (PageResponseWrapper) response ).getResponse();
- }
-
- try
- {
- ByteArrayOutputStream os = new ByteArrayOutputStream();
- report.writeReport( os );
-
- response.reset();
- response.setContentType( report.getMimeType() );
- response.addHeader( "Content-Disposition",
- "attachment; filename=" + report.getId() + "." + report.getType() );
- byte bytes[] = os.toByteArray();
- response.setContentLength( bytes.length );
- response.getOutputStream().write( bytes, 0, bytes.length );
- response.getOutputStream().flush();
- response.getOutputStream().close();
-
- // Don't return a result.
- return null;
- }
- catch ( ReportException e )
- {
- String emsg = getText( "cannot.generate.report" );
- addActionError( emsg );
- log.error( emsg, e );
- return ERROR;
- }
- catch ( IOException e )
- {
- String emsg = getText( "cannot.generate.report" );
- addActionError( emsg );
- log.error( emsg, e );
- return ERROR;
- }
- }
-
- public SecureActionBundle initSecureActionBundle()
- throws SecureActionException
- {
- SecureActionBundle bundle = new SecureActionBundle();
- bundle.setRequiresAuthentication( true );
- bundle.addRequiredAuthorization( RoleConstants.USER_MANAGEMENT_USER_LIST_OPERATION, Resource.GLOBAL );
- return bundle;
- }
-
- public String getReportId()
- {
- return reportId;
- }
-
- public void setReportId( String reportId )
- {
- this.reportId = reportId;
- }
-
- public String getReportType()
- {
- return reportType;
- }
-
- public void setReportType( String reportType )
- {
- this.reportType = reportType;
- }
-}
+++ /dev/null
-package org.codehaus.plexus.redback.struts2.action.admin;
-
-/*
- * 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.rbac.Resource;
-import org.apache.archiva.redback.rbac.RbacManagerException;
-import org.codehaus.plexus.redback.struts2.action.AbstractSecurityAction;
-import org.apache.archiva.redback.integration.interceptor.SecureActionBundle;
-import org.apache.archiva.redback.integration.interceptor.SecureActionException;
-import org.apache.archiva.redback.integration.role.RoleConstants;
-import org.apache.archiva.redback.integration.util.ResourceSorter;
-import org.springframework.context.annotation.Scope;
-import org.springframework.stereotype.Controller;
-
-import javax.inject.Inject;
-import javax.inject.Named;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-
-/**
- * OperationsAction:
- *
- * @author Jesse McConnell <jmcconnell@apache.org>
- * @version $Id$
- */
-@Controller( "redback-resources" )
-@Scope( "prototype" )
-public class ResourcesAction
- extends AbstractSecurityAction
-{
- private static final String LIST = "list";
-
- /**
- * role-hint="cached"
- */
- @Inject
- @Named( value = "rBACManager#cached" )
- private RBACManager manager;
-
- private String resourceIdentifier;
-
- private boolean isPattern;
-
- private List<Resource> allResources;
-
- public String list()
- {
- try
- {
- allResources = manager.getAllResources();
-
- if ( allResources == null )
- {
- allResources = Collections.emptyList();
- }
-
- Collections.sort( allResources, new ResourceSorter() );
- }
- catch ( RbacManagerException e )
- {
- addActionError( getText( "cannot.list.all.resources", Arrays.asList( (Object) e.getMessage() ) ) );
- log.error( "System error:", e );
- allResources = Collections.emptyList();
- }
-
- return LIST;
- }
-
- public String save()
- {
- try
- {
- Resource temp = manager.createResource( resourceIdentifier );
-
- temp.setIdentifier( resourceIdentifier );
- temp.setPattern( isPattern );
-
- manager.saveResource( temp );
- }
- catch ( RbacManagerException e )
- {
- addActionError( getText( "cannot.save.resource", Arrays.asList( (Object) e.getMessage() ) ) );
- log.error( "System error:", e );
- allResources = Collections.emptyList();
- }
-
- return LIST;
- }
-
- public String remove()
- {
- try
- {
- manager.removeResource( manager.getResource( resourceIdentifier ) );
- }
- catch ( RbacManagerException ne )
- {
- addActionError( getText( "cannot.remove.resource", Arrays.asList( (Object) resourceIdentifier ) ) );
- return ERROR;
- }
- return LIST;
- }
-
- public List<Resource> getAllResources()
- {
- return allResources;
- }
-
- public void setAllResources( List<Resource> allResources )
- {
- this.allResources = allResources;
- }
-
- public String getResourceIdentifier()
- {
- return resourceIdentifier;
- }
-
- public void setResourceIdentifier( String resourceIdentifier )
- {
- this.resourceIdentifier = resourceIdentifier;
- }
-
- public boolean isPattern()
- {
- return isPattern;
- }
-
- public void setPattern( boolean isPattern )
- {
- this.isPattern = isPattern;
- }
-
- public SecureActionBundle initSecureActionBundle()
- throws SecureActionException
- {
- SecureActionBundle bundle = new SecureActionBundle();
- bundle.setRequiresAuthentication( true );
- bundle.addRequiredAuthorization( RoleConstants.USER_MANAGEMENT_RBAC_ADMIN_OPERATION, Resource.GLOBAL );
- return bundle;
- }
-}
+++ /dev/null
-package org.codehaus.plexus.redback.struts2.action.admin;
-
-/*
- * 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.RbacManagerException;
-import org.apache.archiva.redback.rbac.Resource;
-import org.apache.archiva.redback.rbac.Role;
-import org.apache.archiva.redback.rbac.RBACManager;
-import org.codehaus.plexus.redback.struts2.action.AbstractSecurityAction;
-import org.codehaus.plexus.redback.struts2.action.AuditEvent;
-import org.codehaus.plexus.util.StringUtils;
-import org.apache.archiva.redback.integration.interceptor.SecureActionBundle;
-import org.apache.archiva.redback.integration.interceptor.SecureActionException;
-import org.apache.archiva.redback.integration.model.SimplePermission;
-import org.apache.archiva.redback.integration.role.RoleConstants;
-import org.springframework.context.annotation.Scope;
-import org.springframework.stereotype.Controller;
-
-import javax.inject.Inject;
-import javax.inject.Named;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-/**
- * RoleCreateAction
- *
- * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
- * @version $Id$
- */
-@Controller( "redback-role-create" )
-@Scope( "prototype" )
-public class RoleCreateAction
- extends AbstractSecurityAction
-{
- // ------------------------------------------------------------------
- // Component Requirements
- // ------------------------------------------------------------------
-
- /**
- * role-hint="cached"
- */
- @Inject
- @Named( value = "rBACManager#cached" )
- private RBACManager manager;
-
- // ------------------------------------------------------------------
- // Action Parameters
- // ------------------------------------------------------------------
-
- private String principal;
-
- private String roleName;
-
- private String description;
-
- private List<SimplePermission> permissions;
-
- private List<String> childRoles;
-
- private SimplePermission addpermission;
-
- private String submitMode;
-
- protected static final String VALID_ROLENAME_CHARS = "[a-zA-Z_0-9\\-\\s.,]*";
-
- // ------------------------------------------------------------------
- // Action Entry Points - (aka Names)
- // ------------------------------------------------------------------
-
- public String show()
- {
- if ( permissions == null )
- {
- permissions = new ArrayList<SimplePermission>();
- }
-
- if ( childRoles == null )
- {
- childRoles = new ArrayList<String>();
- }
-
- if ( addpermission == null )
- {
- addpermission = new SimplePermission();
- }
-
- return INPUT;
- }
-
- public String addpermission()
- {
- if ( addpermission == null )
- {
- addActionError( getText( "cannot.add.null.permission" ) );
- return ERROR;
- }
-
- if ( permissions == null )
- {
- permissions = new ArrayList<SimplePermission>();
- }
-
- permissions.add( addpermission );
-
- addpermission = new SimplePermission();
-
- return INPUT;
- }
-
- public String submit()
- {
- if ( StringUtils.equals( getSubmitMode(), "addPermission" ) )
- {
- return addpermission();
- }
-
- if ( StringUtils.isEmpty( roleName ) )
- {
- addActionError( getText( "cannot.add.empty.role" ) );
- return ERROR;
- }
- if ( !roleName.matches( VALID_ROLENAME_CHARS ) )
- {
- addActionError( getText( "roleName.invalid.characters" ) );
- return ERROR;
- }
-
- try
- {
- Role _role;
- if ( manager.roleExists( roleName ) )
- {
- _role = manager.getRole( roleName );
- }
- else
- {
- _role = manager.createRole( roleName );
- }
-
- _role.setDescription( description );
- _role.setChildRoleNames( childRoles );
-
- List<Permission> _permissionList = new ArrayList<Permission>();
- for ( SimplePermission perm : permissions )
- {
- _permissionList.add(
- manager.createPermission( perm.getName(), perm.getOperationName(), perm.getResourceIdentifier() ) );
- }
-
- _role.setPermissions( _permissionList );
-
- manager.saveRole( _role );
-
- addActionMessage( getText( "save.role.success", Arrays.asList( (Object) roleName ) ) );
- String currentUser = getCurrentUser();
- AuditEvent event = new AuditEvent( getText( "log.role.create" ) );
- event.setRole( roleName );
- event.setCurrentUser( currentUser );
- event.log();
- }
- catch ( RbacManagerException e )
- {
- addActionError( getText( "cannot.get.role", Arrays.asList( (Object) roleName, e.getMessage() ) ) );
- return ERROR;
- }
-
- return SUCCESS;
- }
-
- // ------------------------------------------------------------------
- // Parameter Accessor Methods
- // ------------------------------------------------------------------
-
- public String getPrincipal()
- {
- return principal;
- }
-
- public void setPrincipal( String principal )
- {
- this.principal = principal;
- }
-
- public SimplePermission getAddpermission()
- {
- return addpermission;
- }
-
- public void setAddpermission( SimplePermission addpermission )
- {
- this.addpermission = addpermission;
- }
-
- public String getSubmitMode()
- {
- return submitMode;
- }
-
- public void setSubmitMode( String submitMode )
- {
- this.submitMode = submitMode;
- }
-
- public SecureActionBundle initSecureActionBundle()
- throws SecureActionException
- {
- SecureActionBundle bundle = new SecureActionBundle();
- bundle.setRequiresAuthentication( true );
- bundle.addRequiredAuthorization( RoleConstants.USER_MANAGEMENT_RBAC_ADMIN_OPERATION, Resource.GLOBAL );
- return bundle;
- }
-
-}
+++ /dev/null
-package org.codehaus.plexus.redback.struts2.action.admin;
-
-/*
- * 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.Resource;
-import org.apache.archiva.redback.role.RoleManager;
-import org.codehaus.plexus.redback.role.model.RedbackRoleModel;
-import org.codehaus.plexus.redback.struts2.action.AbstractSecurityAction;
-import org.apache.archiva.redback.integration.interceptor.SecureActionBundle;
-import org.apache.archiva.redback.integration.interceptor.SecureActionException;
-import org.apache.archiva.redback.integration.role.RoleConstants;
-import org.springframework.context.annotation.Scope;
-import org.springframework.stereotype.Controller;
-
-import javax.inject.Inject;
-
-/**
- * RolesAction
- *
- * @author <a href="mailto:jmcconnell@apache.org">Jesse McConnell</a>
- * @version $Id$
- */
-@Controller( "redback-role-model" )
-@Scope( "prototype" )
-public class RoleModelAction
- extends AbstractSecurityAction
-{
- /**
- * role-hint="default"
- */
- @Inject
- private RoleManager manager;
-
- private RedbackRoleModel model;
-
- public String view()
- {
- model = manager.getModel();
-
- return SUCCESS;
- }
-
- public RedbackRoleModel getModel()
- {
- return model;
- }
-
- public void setModel( RedbackRoleModel model )
- {
- this.model = model;
- }
-
- public SecureActionBundle initSecureActionBundle()
- throws SecureActionException
- {
- SecureActionBundle bundle = new SecureActionBundle();
- bundle.setRequiresAuthentication( true );
- bundle.addRequiredAuthorization( RoleConstants.USER_MANAGEMENT_RBAC_ADMIN_OPERATION, Resource.GLOBAL );
- return bundle;
- }
-}
+++ /dev/null
-package org.codehaus.plexus.redback.struts2.action.admin;
-
-/*
- * 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.Resource;
-import org.apache.archiva.redback.rbac.Role;
-import org.apache.archiva.redback.rbac.RbacManagerException;
-import org.codehaus.plexus.redback.struts2.action.AbstractUserCredentialsAction;
-import org.apache.archiva.redback.integration.interceptor.SecureActionBundle;
-import org.apache.archiva.redback.integration.interceptor.SecureActionException;
-import org.apache.archiva.redback.integration.role.RoleConstants;
-import org.springframework.context.annotation.Scope;
-import org.springframework.stereotype.Controller;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-
-/**
- * RolesAction
- *
- * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
- * @version $Id$
- */
-@Controller( "redback-roles" )
-@Scope( "prototype" )
-public class RolesAction
- extends AbstractUserCredentialsAction
-{
- private static final String LIST = "list";
-
- private List<Role> allRoles;
-
- public String list()
- {
- try
- {
- allRoles = getFilteredRolesForCurrentUserAccess();
- }
- catch ( RbacManagerException e )
- {
- List<Object> list = new ArrayList<Object>();
- list.add( e.getMessage() );
- addActionError( getText( "cannot.list.all.roles", list ) );
- log.error( "System error:", e );
- allRoles = Collections.emptyList();
- }
-
- return LIST;
- }
-
- public List<Role> getAllRoles()
- {
- return allRoles;
- }
-
- public void setAllRoles( List<Role> allRoles )
- {
- this.allRoles = allRoles;
- }
-
- public SecureActionBundle initSecureActionBundle()
- throws SecureActionException
- {
- SecureActionBundle bundle = new SecureActionBundle();
- bundle.setRequiresAuthentication( true );
- bundle.addRequiredAuthorization( RoleConstants.USER_MANAGEMENT_USER_EDIT_OPERATION, Resource.GLOBAL );
- bundle.addRequiredAuthorization( RoleConstants.USER_MANAGEMENT_RBAC_ADMIN_OPERATION, Resource.GLOBAL );
- bundle.addRequiredAuthorization( RoleConstants.USER_MANAGEMENT_ROLE_GRANT_OPERATION, Resource.GLOBAL );
- bundle.addRequiredAuthorization( RoleConstants.USER_MANAGEMENT_ROLE_DROP_OPERATION, Resource.GLOBAL );
- bundle.addRequiredAuthorization( RoleConstants.USER_MANAGEMENT_USER_ROLE_OPERATION, Resource.GLOBAL );
- return bundle;
- }
-}
+++ /dev/null
-package org.codehaus.plexus.redback.struts2.action.admin;
-
-/*
- * 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.rbac.Resource;
-import org.apache.commons.beanutils.PropertyUtils;
-import org.apache.commons.lang.StringEscapeUtils;
-import org.apache.commons.lang.StringUtils;
-import org.codehaus.plexus.redback.struts2.action.AbstractSecurityAction;
-import org.apache.archiva.redback.system.SecuritySystem;
-import org.codehaus.plexus.registry.Registry;
-import org.apache.archiva.redback.integration.interceptor.SecureActionBundle;
-import org.apache.archiva.redback.integration.interceptor.SecureActionException;
-import org.apache.archiva.redback.integration.role.RoleConstants;
-import org.springframework.context.annotation.Scope;
-import org.springframework.stereotype.Controller;
-
-import javax.inject.Inject;
-import javax.inject.Named;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-/**
- * SystemInfoAction
- *
- * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
- * @version $Id$
- */
-@Controller( "redback-sysinfo" )
-@Scope( "prototype" )
-public class SystemInfoAction
- extends AbstractSecurityAction
-{
- // ------------------------------------------------------------------
- // Component Requirements
- // ------------------------------------------------------------------
-
- /**
- *
- */
- @Inject
- private SecuritySystem securitySystem;
-
- /**
- * role-hint="commons-configuration"
- */
- @Inject
- @Named( value = "commons-configuration" )
- private Registry registry;
-
- /**
- * role-hint="cached"
- */
- @Inject
- @Named( value = "rBACManager#cached" )
- private RBACManager rbacManager;
-
- // Class.getClass() and some JPOX classes
- private static final List<String> ignoredReaders = Arrays.asList( "class", "copy" );
-
- private static final String NULL = "<null>";
-
- private static final char LN = Character.LINE_SEPARATOR;
-
- private static final String INDENT = " ";
-
- private static final int MAXDEPTH = 10;
-
- // ------------------------------------------------------------------
- // Action Parameters
- // ------------------------------------------------------------------
-
- private StringBuilder details;
-
- // ------------------------------------------------------------------
- // Action Entry Points - (aka Names)
- // ------------------------------------------------------------------
-
- public String show()
- {
- details = new StringBuilder();
-
- details.append( "Configuration: " );
- dumpObject( details, registry, INDENT );
- details.append( registry.dump() );
- details.append( LN );
-
- details.append( LN ).append( "<hr/>" ).append( LN );
- details.append( "RBAC Manager: " );
- dumpObject( details, rbacManager, INDENT );
-
- details.append( LN ).append( "<hr/>" ).append( LN );
- details.append( "SecuritySystem: " );
- dumpObject( details, securitySystem, INDENT );
-
- return SUCCESS;
- }
-
- private void dumpObject( StringBuilder sb, Object obj, String indent )
- {
- dumpObjectSwitchboard( new ArrayList<Object>(), sb, obj, indent, 0 );
- }
-
- /**
- * The recursive object dumping switchboard.
- *
- * @param seenObjects objects already seen (to prevent cycles)
- * @param sb the stringbuffer to populate
- * @param obj the object to dump
- * @param indent the current indent string.
- * @param depth the depth in the tree.
- */
- private void dumpObjectSwitchboard( List<Object> seenObjects, StringBuilder sb, Object obj, String indent,
- int depth )
- {
- if ( obj == null )
- {
- sb.append( NULL ).append( LN );
- return;
- }
-
- if ( depth > MAXDEPTH )
- {
- sb.append( StringEscapeUtils.escapeHtml( "<MAX DEPTH>" ) );
- sb.append( LN );
- return;
- }
-
- depth++;
-
- String className = obj.getClass().getName();
-
- sb.append( '(' ).append( className ).append( ") " );
-
- if ( obj instanceof List )
- {
- dumpIterator( seenObjects, sb, ( (List<?>) obj ).iterator(), indent, depth );
- }
- else if ( obj instanceof Set )
- {
- dumpIterator( seenObjects, sb, ( (Set<?>) obj ).iterator(), indent, depth );
- }
- else if ( obj instanceof Map )
- {
- dumpIterator( seenObjects, sb, ( (Map<?, ?>) obj ).entrySet().iterator(), indent, depth );
- }
- else if ( obj instanceof Iterator )
- {
- dumpIterator( seenObjects, sb, (Iterator<?>) obj, indent, depth );
- }
- else
- {
- // Filter classes that start with java or javax
- if ( className.startsWith( "java." ) || className.startsWith( "javax." ) )
- {
- sb.append( StringEscapeUtils.escapeHtml( obj.toString() ) ).append( LN );
- return;
- }
-
- // prevent cycles
- if ( seenObjects.contains( obj ) )
- {
- // No need to dump.
- sb.append( StringEscapeUtils.escapeHtml( "<seen already preventing cycle in dump> " ) );
- sb.append( LN );
- return;
- }
-
- // Adding object to seen list (to prevent cycles)
- seenObjects.add( obj );
-
- dumpObjectReaders( seenObjects, sb, obj, indent, depth );
- }
- depth--;
- }
-
- @SuppressWarnings( "unchecked" )
- private void dumpObjectReaders( List<Object> seenObjects, StringBuilder sb, Object obj, String indent, int depth )
- {
- sb.append( obj.toString() ).append( LN );
- String name = null;
-
- try
- {
- Map<String, Object> readers = PropertyUtils.describe( obj );
- for ( Map.Entry<String, Object> readerEntry : readers.entrySet() )
- {
- name = (String) readerEntry.getKey();
-
- if ( ignoredReaders.contains( name ) )
- {
- // skip this reader.
- continue;
- }
-
- sb.append( indent );
- sb.append( name ).append( ':' );
-
- Object value = readerEntry.getValue();
- if ( value == null )
- {
- sb.append( NULL ).append( LN );
- }
- else
- {
- dumpObjectSwitchboard( seenObjects, sb, value, INDENT + indent, depth );
- }
- }
- }
- catch ( Throwable e )
- {
- sb.append( LN ).append( indent );
- sb.append( "Unable to read bean [" ).append( obj.getClass().getName() );
- if ( StringUtils.isNotBlank( name ) )
- {
- sb.append( ".get" ).append( StringUtils.capitalize( name ) ).append( "()" );
- }
- sb.append( "]: " ).append( '(' ).append( e.getClass().getName() ).append( ") " );
- sb.append( e.getMessage() ).append( LN );
- }
- }
-
- private void dumpIterator( List<Object> seenObjects, StringBuilder sb, Iterator<?> iterator, String indent,
- int depth )
- {
- sb.append( LN );
- while ( iterator.hasNext() )
- {
- Object entry = iterator.next();
- sb.append( indent );
- dumpObjectSwitchboard( seenObjects, sb, entry, indent + " | ", depth );
- }
- }
-
- // ------------------------------------------------------------------
- // Parameter Accessor Methods
- // ------------------------------------------------------------------
-
- public String getDetails()
- {
- return details.toString();
- }
-
- public SecureActionBundle initSecureActionBundle()
- throws SecureActionException
- {
- SecureActionBundle bundle = new SecureActionBundle();
- bundle.setRequiresAuthentication( true );
- bundle.addRequiredAuthorization( RoleConstants.CONFIGURATION_EDIT_OPERATION, Resource.GLOBAL );
- return bundle;
- }
-}
+++ /dev/null
-package org.codehaus.plexus.redback.struts2.action.admin;
-
-/*
- * 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 java.util.Arrays;
-
-import org.apache.archiva.redback.policy.UserSecurityPolicy;
-import org.apache.archiva.redback.rbac.Resource;
-import org.codehaus.plexus.redback.struts2.action.AbstractUserCredentialsAction;
-import org.codehaus.plexus.redback.struts2.action.AuditEvent;
-import org.apache.archiva.redback.users.User;
-import org.apache.archiva.redback.users.UserManager;
-import org.apache.archiva.redback.integration.interceptor.SecureActionBundle;
-import org.apache.archiva.redback.integration.interceptor.SecureActionException;
-import org.apache.archiva.redback.integration.model.CreateUserCredentials;
-import org.apache.archiva.redback.integration.role.RoleConstants;
-import org.springframework.context.annotation.Scope;
-import org.springframework.stereotype.Controller;
-
-/**
- * UserCreateAction
- *
- * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
- * @version $Id$
- */
-@Controller("redback-admin-user-create")
-@Scope("prototype")
-public class UserCreateAction
- extends AbstractUserCredentialsAction
-{
- // ------------------------------------------------------------------
- // Action Parameters
- // ------------------------------------------------------------------
-
- private CreateUserCredentials user;
-
- // ------------------------------------------------------------------
- // Action Entry Points - (aka Names)
- // ------------------------------------------------------------------
-
- public String show()
- {
- if ( user == null )
- {
- user = new CreateUserCredentials();
- }
-
- return INPUT;
- }
-
- public String submit()
- {
- if ( user == null )
- {
- user = new CreateUserCredentials();
- addActionError( getText( "invalid.user.credentials" ) );
- return ERROR;
- }
-
- internalUser = user;
-
- validateCredentialsLoose();
-
- // NOTE: Do not perform Password Rules Validation Here.
-
- UserManager manager = super.securitySystem.getUserManager();
-
- if ( manager.userExists( user.getUsername() ) )
- {
- // Means that the role name doesn't exist.
- // We need to fail fast and return to the previous page.
- addActionError( getText( "user.already.exists", Arrays.asList( ( Object ) user.getUsername() ) ) );
- }
-
- if ( hasActionErrors() || hasFieldErrors() )
- {
- return ERROR;
- }
-
- User u = manager.createUser( user.getUsername(), user.getFullName(), user.getEmail() );
- u.setPassword( user.getPassword() );
-
- // force the user to change their password when they log in next
- u.setPasswordChangeRequired( true );
-
- // Disable Password Rules for this creation.
- UserSecurityPolicy securityPolicy = securitySystem.getPolicy();
- try
- {
- // REDBACK-156
- securityPolicy.setEnabled( false );
- u.setValidated( true );
- manager.addUser( u );
- String currentUser = getCurrentUser();
- AuditEvent event = new AuditEvent( getText( "log.account.create" ) );
- event.setAffectedUser( u.getUsername() );
- event.setCurrentUser( currentUser );
- event.log();
- }
- finally
- {
- securityPolicy.setEnabled( true );
- }
-
- return SUCCESS;
- }
-
- // ------------------------------------------------------------------
- // Parameter Accessor Methods
- // ------------------------------------------------------------------
-
- public CreateUserCredentials getUser()
- {
- return user;
- }
-
- public void setUser( CreateUserCredentials user )
- {
- this.user = user;
- }
-
- public SecureActionBundle initSecureActionBundle()
- throws SecureActionException
- {
- SecureActionBundle bundle = new SecureActionBundle();
- bundle.setRequiresAuthentication( true );
- bundle.addRequiredAuthorization( RoleConstants.USER_MANAGEMENT_USER_CREATE_OPERATION, Resource.GLOBAL );
- return bundle;
- }
-
-}
+++ /dev/null
-package org.codehaus.plexus.redback.struts2.action.admin;
-
-/*
- * 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.rbac.RbacObjectInvalidException;
-import org.apache.archiva.redback.rbac.Resource;
-import org.apache.archiva.redback.users.User;
-import org.apache.archiva.redback.users.UserManager;
-import org.apache.archiva.redback.rbac.RbacManagerException;
-import org.apache.archiva.redback.rbac.RbacObjectNotFoundException;
-import org.codehaus.plexus.redback.struts2.action.AbstractSecurityAction;
-import org.codehaus.plexus.redback.struts2.action.AuditEvent;
-import org.codehaus.plexus.redback.struts2.action.CancellableAction;
-import org.apache.archiva.redback.users.UserNotFoundException;
-import org.codehaus.plexus.util.StringUtils;
-import org.apache.archiva.redback.integration.interceptor.SecureActionBundle;
-import org.apache.archiva.redback.integration.interceptor.SecureActionException;
-import org.apache.archiva.redback.integration.role.RoleConstants;
-import org.springframework.context.annotation.Scope;
-import org.springframework.stereotype.Controller;
-
-import javax.inject.Inject;
-import javax.inject.Named;
-import java.util.Arrays;
-
-/**
- * UserDeleteAction
- *
- * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
- * @version $Id$
- */
-@Controller( "redback-admin-user-delete" )
-@Scope( "prototype" )
-public class UserDeleteAction
- extends AbstractSecurityAction
- implements CancellableAction
-{
- // ------------------------------------------------------------------
- // Component Requirements
- // ------------------------------------------------------------------
-
- /**
- * role-hint="configurable"
- */
- @Inject
- @Named( value = "userManager#configurable" )
- private UserManager userManager;
-
- /**
- * role-hint="cached"
- */
- @Inject
- @Named( value = "rBACManager#cached" )
- private RBACManager rbacManager;
-
- // ------------------------------------------------------------------
- // Action Parameters
- // ------------------------------------------------------------------
-
- private String username;
-
- private User user;
-
- // ------------------------------------------------------------------
- // Action Entry Points - (aka Names)
- // ------------------------------------------------------------------
-
- public String confirm()
- {
- if ( username == null )
- {
- addActionError( getText( "cannot.remove.user.null.username" ) );
- return SUCCESS;
- }
-
- try
- {
- user = userManager.findUser( username );
- }
- catch ( UserNotFoundException e )
- {
- addActionError( getText( "cannot.remove.user.not.found", Arrays.asList( (Object) username ) ) );
- return SUCCESS;
- }
-
- return INPUT;
- }
-
- public String submit()
- {
- if ( username == null )
- {
- addActionError( getText( "invalid.user.credentials" ) );
- return SUCCESS;
- }
-
- if ( StringUtils.isEmpty( username ) )
- {
- addActionError( getText( "cannot.remove.user.empty.username" ) );
- return SUCCESS;
- }
-
- try
- {
- rbacManager.removeUserAssignment( username );
- }
- catch ( RbacObjectNotFoundException e )
- {
- // ignore, this is possible since the user may never have had roles assigned
- }
- catch ( RbacObjectInvalidException e )
- {
- addActionError( getText( "cannot.remove.user.role", Arrays.asList( (Object) username, e.getMessage() ) ) );
- }
- catch ( RbacManagerException e )
- {
- addActionError( getText( "cannot.remove.user.role", Arrays.asList( (Object) username, e.getMessage() ) ) );
- }
-
- if ( getActionErrors().isEmpty() )
- {
- try
- {
- userManager.deleteUser( username );
- }
- catch ( UserNotFoundException e )
- {
- addActionError( getText( "cannot.remove.user.non.existent", Arrays.asList( (Object) username ) ) );
- }
- }
- String currentUser = getCurrentUser();
-
- AuditEvent event = new AuditEvent( getText( "log.account.delete" ) );
- event.setAffectedUser( username );
- event.setCurrentUser( currentUser );
- event.log();
-
- return SUCCESS;
- }
-
- /**
- * Returns the cancel result. <p/> A basic implementation would simply be to return CANCEL.
- *
- * @return
- */
- public String cancel()
- {
- return CANCEL;
- }
-
- // ------------------------------------------------------------------
- // Parameter Accessor Methods
- // ------------------------------------------------------------------
-
- public String getUsername()
- {
- return username;
- }
-
- public void setUsername( String username )
- {
- this.username = username;
- }
-
- public User getUser()
- {
- return user;
- }
-
- public void setUser( User user )
- {
- this.user = user;
- }
-
- public SecureActionBundle initSecureActionBundle()
- throws SecureActionException
- {
- SecureActionBundle bundle = new SecureActionBundle();
- bundle.setRequiresAuthentication( true );
- bundle.addRequiredAuthorization( RoleConstants.USER_MANAGEMENT_USER_DELETE_OPERATION, Resource.GLOBAL );
- return bundle;
- }
-
-}
+++ /dev/null
-package org.codehaus.plexus.redback.struts2.action.admin;
-
-/*
- * 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.rbac.RBACManager;
-import org.apache.archiva.redback.rbac.Resource;
-import org.apache.archiva.redback.users.User;
-import org.apache.archiva.redback.users.UserNotFoundException;
-import org.apache.commons.lang.StringEscapeUtils;
-import org.apache.archiva.redback.policy.PasswordRuleViolationException;
-import org.apache.archiva.redback.rbac.RbacManagerException;
-import org.apache.archiva.redback.rbac.Role;
-import org.codehaus.plexus.redback.struts2.action.AuditEvent;
-import org.codehaus.plexus.redback.struts2.action.CancellableAction;
-import org.apache.archiva.redback.system.DefaultSecuritySession;
-import org.apache.archiva.redback.system.SecuritySession;
-import org.apache.archiva.redback.system.SecuritySystemConstants;
-import org.apache.archiva.redback.users.UserManager;
-import org.codehaus.plexus.util.StringUtils;
-import org.apache.archiva.redback.integration.interceptor.SecureActionBundle;
-import org.apache.archiva.redback.integration.interceptor.SecureActionException;
-import org.apache.archiva.redback.integration.model.AdminEditUserCredentials;
-import org.apache.archiva.redback.integration.role.RoleConstants;
-import org.springframework.context.annotation.Scope;
-import org.springframework.stereotype.Controller;
-
-import javax.inject.Inject;
-import javax.inject.Named;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.List;
-
-/**
- * UserEditAction
- *
- * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
- * @version $Id$
- */
-@Controller( "redback-admin-user-edit" )
-@Scope( "prototype" )
-public class UserEditAction
- extends AbstractAdminUserCredentialsAction
- implements CancellableAction
-{
- /**
- * role-hint="cached"
- */
- @Inject
- @Named( value = "rBACManager#cached" )
- private RBACManager rbacManager;
-
- /**
- * A List of {@link org.apache.archiva.redback.rbac.Role} objects.
- */
- private List<Role> effectivelyAssignedRoles;
-
- // ------------------------------------------------------------------
- // Action Parameters
- // ------------------------------------------------------------------
-
- private AdminEditUserCredentials user;
-
- private String updateButton;
-
- private boolean emailValidationRequired;
-
- private boolean hasHiddenRoles;
-
- private String oldPassword;
-
- private String userAdminPassword;
-
- private boolean self;
-
- public static String CONFIRM = "confirm";
-
- public static String CONFIRM_ERROR = "confirmError";
-
- // ------------------------------------------------------------------
- // Action Entry Points - (aka Names)
- // ------------------------------------------------------------------
-
- public String edit()
- {
- oldPassword = "";
-
- emailValidationRequired = securitySystem.getPolicy().getUserValidationSettings().isEmailValidationRequired();
-
- if ( getUsername() == null )
- {
- addActionError( getText( "cannot.edit.user.null.username" ) );
- return ERROR;
- }
-
- if ( StringUtils.isEmpty( getUsername() ) )
- {
- addActionError( getText( "cannot.edit.user.empty.username" ) );
- return ERROR;
- }
-
- UserManager manager = super.securitySystem.getUserManager();
-
- String escapedUsername = StringEscapeUtils.escapeXml( getUsername() );
-
- if ( !manager.userExists( escapedUsername ) )
- {
- // Means that the role name doesn't exist.
- // We need to fail fast and return to the previous page.
- addActionError( getText( "user.does.not.exist", Collections.singletonList( (Object) escapedUsername ) ) );
- return ERROR;
- }
-
- try
- {
- User u = manager.findUser( escapedUsername );
-
- if ( u == null )
- {
- addActionError( getText( "cannot.operate.on.null.user" ) );
- return ERROR;
- }
-
- user = new AdminEditUserCredentials( u );
-
- // require user admin to provide his/her password if editing account of others
- if ( getUsername().equals( getCurrentUser() ) )
- {
- self = true;
- }
-
- try
- {
- String principal = u.getPrincipal().toString();
- List<Role> roles = filterAssignableRoles( rbacManager.getEffectivelyAssignedRoles( principal ) );
- effectivelyAssignedRoles = filterRolesForCurrentUserAccess( roles );
- hasHiddenRoles = ( roles.size() > effectivelyAssignedRoles.size() );
- }
- catch ( RbacManagerException rme )
- {
- // ignore, this can happen when the user has no roles assigned
- }
- }
- catch ( UserNotFoundException e )
- {
- addActionError( getText( "cannot.get.user", Arrays.asList( (Object) getUsername(), e.getMessage() ) ) );
- return ERROR;
- }
-
- return INPUT;
- }
-
- private List<Role> filterAssignableRoles( Collection<Role> roles )
- {
- List<Role> assignableRoles = new ArrayList<Role>( roles.size() );
- for ( Role r : roles )
- {
- if ( r.isAssignable() )
- {
- assignableRoles.add( r );
- }
- }
- return assignableRoles;
- }
-
- public String submit()
- {
- if ( getUsername() == null )
- {
- addActionError( getText( "cannot.edit.user.null.username" ) );
- return ERROR;
- }
-
- if ( StringUtils.isEmpty( getUsername() ) )
- {
- addActionError( getText( "cannot.edit.user.empty.username" ) );
- return ERROR;
- }
-
- if ( user == null )
- {
- addActionError( getText( "cannot.edit.user.null.credentials" ) );
- return ERROR;
- }
-
- internalUser = user;
-
- validateCredentialsLoose();
-
- // if form errors, return with them before continuing
- if ( hasActionErrors() || hasFieldErrors() )
- {
- return ERROR;
- }
-
- if ( !getUsername().equals( getCurrentUser() ) )
- {
- return CONFIRM;
- }
- else
- {
- return save( true );
- }
- }
-
- // confirm user admin's password before allowing to proceed with the operation
- public String confirmAdminPassword()
- {
- UserManager manager = super.securitySystem.getUserManager();
-
- if ( StringUtils.isEmpty( userAdminPassword ) )
- {
- addActionError( getText( "user.admin.password.required" ) );
- return CONFIRM_ERROR;
- }
-
- try
- {
- User currentUser = manager.findUser( getCurrentUser() );
-
- // check if user admin provided correct password!
- PasswordEncoder encoder = securitySystem.getPolicy().getPasswordEncoder();
- if ( !encoder.isPasswordValid( currentUser.getEncodedPassword(), userAdminPassword ) )
- {
- addActionError( getText( "user.admin.password.does.not.match.existing" ) );
- return CONFIRM_ERROR;
- }
- }
- catch ( UserNotFoundException e )
- {
- addActionError( getText( "cannot.find.user", Arrays.asList( (Object) getCurrentUser(), e.getMessage() ) ) );
- return CONFIRM_ERROR;
- }
-
- return save( false );
- }
-
- public String cancel()
- {
- return CANCEL;
- }
-
- private String save( boolean validateOldPassword )
- {
- UserManager manager = super.securitySystem.getUserManager();
-
- if ( !manager.userExists( getUsername() ) )
- {
- // Means that the role name doesn't exist.
- // We need to fail fast and return to the previous page.
- addActionError( getText( "user.does.not.exist", Collections.singletonList( (Object) getUsername() ) ) );
- return ERROR;
- }
-
- try
- {
- User u = manager.findUser( getUsername() );
- if ( u == null )
- {
- addActionError( getText( "cannot.operate.on.null.user" ) );
- return ERROR;
- }
-
- if ( validateOldPassword )
- {
- PasswordEncoder encoder = securitySystem.getPolicy().getPasswordEncoder();
-
- if ( StringUtils.isEmpty( oldPassword ) )
- {
- self = true;
- addFieldError( "oldPassword", getText( "old.password.required" ) );
- return ERROR;
- }
-
- if ( !encoder.isPasswordValid( u.getEncodedPassword(), oldPassword ) )
- {
- self = true;
- addFieldError( "oldPassword", getText( "password.provided.does.not.match.existing" ) );
- return ERROR;
- }
- }
-
- u.setFullName( user.getFullName() );
- u.setEmail( user.getEmail() );
- u.setPassword( user.getPassword() );
- u.setLocked( user.isLocked() );
- u.setPasswordChangeRequired( user.isPasswordChangeRequired() );
-
- manager.updateUser( u, user.isPasswordChangeRequired() );
-
- //check if current user then update the session
- if ( getSecuritySession().getUser().getUsername().equals( u.getUsername() ) )
- {
- SecuritySession securitySession =
- new DefaultSecuritySession( getSecuritySession().getAuthenticationResult(), u );
-
- session.put( SecuritySystemConstants.SECURITY_SESSION_KEY, securitySession );
-
- setSession( session );
- }
- }
- catch ( UserNotFoundException e )
- {
- addActionError( getText( "cannot.find.user", Arrays.asList( (Object) getUsername(), e.getMessage() ) ) );
- return ERROR;
- }
- catch ( PasswordRuleViolationException pe )
- {
- processPasswordRuleViolations( pe );
- return ERROR;
- }
- String currentUser = getCurrentUser();
-
- AuditEvent event = new AuditEvent( getText( "log.account.edit" ) );
- event.setAffectedUser( getUsername() );
- event.setCurrentUser( currentUser );
- event.log();
-
- return SUCCESS;
- }
-
- // ------------------------------------------------------------------
- // Parameter Accessor Methods
- // ------------------------------------------------------------------
-
-
- public String getUpdateButton()
- {
- return updateButton;
- }
-
- public void setUpdateButton( String updateButton )
- {
- this.updateButton = updateButton;
- }
-
- public AdminEditUserCredentials getUser()
- {
- return user;
- }
-
- public void setUser( AdminEditUserCredentials user )
- {
- this.user = user;
- }
-
- public SecureActionBundle initSecureActionBundle()
- throws SecureActionException
- {
- SecureActionBundle bundle = new SecureActionBundle();
- bundle.setRequiresAuthentication( true );
- bundle.addRequiredAuthorization( RoleConstants.USER_MANAGEMENT_USER_EDIT_OPERATION, Resource.GLOBAL );
- bundle.addRequiredAuthorization( RoleConstants.USER_MANAGEMENT_USER_EDIT_OPERATION, getUsername() );
- bundle.addRequiredAuthorization( RoleConstants.USER_MANAGEMENT_USER_ROLE_OPERATION, Resource.GLOBAL );
- return bundle;
- }
-
- public List<Role> getEffectivelyAssignedRoles()
- {
- return effectivelyAssignedRoles;
- }
-
- public boolean isEmailValidationRequired()
- {
- return emailValidationRequired;
- }
-
- public boolean isHasHiddenRoles()
- {
- return hasHiddenRoles;
- }
-
- public void setHasHiddenRoles( boolean hasHiddenRoles )
- {
- this.hasHiddenRoles = hasHiddenRoles;
- }
-
- public void setOldPassword( String oldPassword )
- {
- this.oldPassword = oldPassword;
- }
-
- public void setUserAdminPassword( String userAdminPassword )
- {
- this.userAdminPassword = userAdminPassword;
- }
-
- public boolean isSelf()
- {
- return self;
- }
-}
+++ /dev/null
-package org.codehaus.plexus.redback.struts2.action.admin;
-
-/*
- * 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.RbacManagerException;
-import org.apache.archiva.redback.rbac.RbacObjectNotFoundException;
-import org.apache.archiva.redback.rbac.Resource;
-import org.apache.archiva.redback.rbac.Role;
-import org.apache.archiva.redback.rbac.UserAssignment;
-import org.apache.archiva.redback.users.User;
-import org.apache.commons.lang.StringEscapeUtils;
-import org.apache.struts2.ServletActionContext;
-import org.apache.archiva.redback.rbac.RBACManager;
-import org.codehaus.plexus.redback.struts2.action.AbstractSecurityAction;
-import org.apache.archiva.redback.system.SecuritySystem;
-import org.apache.archiva.redback.users.UserManager;
-import org.apache.archiva.redback.users.UserQuery;
-import org.codehaus.plexus.util.StringUtils;
-import org.apache.archiva.redback.integration.interceptor.SecureActionBundle;
-import org.apache.archiva.redback.integration.interceptor.SecureActionException;
-import org.apache.archiva.redback.integration.reports.Report;
-import org.apache.archiva.redback.integration.reports.ReportManager;
-import org.apache.archiva.redback.integration.role.RoleConstants;
-import org.extremecomponents.table.context.Context;
-import org.extremecomponents.table.context.HttpServletRequestContext;
-import org.extremecomponents.table.limit.FilterSet;
-import org.extremecomponents.table.limit.Limit;
-import org.extremecomponents.table.limit.LimitFactory;
-import org.extremecomponents.table.limit.TableLimit;
-import org.extremecomponents.table.limit.TableLimitFactory;
-import org.springframework.context.annotation.Scope;
-import org.springframework.stereotype.Controller;
-
-import javax.inject.Inject;
-import javax.inject.Named;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-/**
- * UserListAction
- *
- * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
- * @version $Id$
- */
-@Controller( "redback-admin-user-list" )
-@Scope( "prototype" )
-public class UserListAction
- extends AbstractSecurityAction
-{
- // ------------------------------------------------------------------
- // Component Requirements
- // ------------------------------------------------------------------
-
- /**
- *
- */
- @Inject
- private SecuritySystem securitySystem;
-
- /**
- * role-hint="cached"
- */
- @Inject
- @Named( value = "rBACManager#cached" )
- private RBACManager rbac;
-
- /**
- *
- */
- @Inject
- private ReportManager reportManager;
-
- // ------------------------------------------------------------------
- // Action Parameters
- // ------------------------------------------------------------------
-
- private List<User> users;
-
- private List<Role> roles;
-
- private String roleName;
-
- // ------------------------------------------------------------------
- // Action Entry Points - (aka Names)
- // ------------------------------------------------------------------
-
- public String show()
- {
- try
- {
- roles = rbac.getAllRoles();
- }
- catch ( RbacManagerException e )
- {
- roles = Collections.emptyList();
- }
-
- if ( StringUtils.isEmpty( roleName ) )
- {
- users = findUsersWithFilter();
- }
- else
- {
- roleName = StringEscapeUtils.escapeXml( roleName );
-
- try
- {
- Role target = rbac.getRole( roleName );
- Set<String> targetRoleNames = new HashSet<String>();
-
- for ( int i = 0; i < roles.size(); i++ )
- {
- Role r = roles.get( i );
- if ( rbac.getEffectiveRoles( r ).contains( target ) )
- {
- targetRoleNames.add( r.getName() );
- }
- }
-
- users = findUsers( targetRoleNames );
- }
- catch ( RbacObjectNotFoundException e )
- {
- users = Collections.emptyList();
- }
- catch ( RbacManagerException e )
- {
- users = Collections.emptyList();
- }
- }
-
- if ( users == null )
- {
- users = Collections.emptyList();
- }
-
- return INPUT;
- }
-
- public SecureActionBundle initSecureActionBundle()
- throws SecureActionException
- {
- SecureActionBundle bundle = new SecureActionBundle();
- bundle.setRequiresAuthentication( true );
- bundle.addRequiredAuthorization( RoleConstants.USER_MANAGEMENT_USER_LIST_OPERATION, Resource.GLOBAL );
- bundle.addRequiredAuthorization( RoleConstants.USER_MANAGEMENT_USER_ROLE_OPERATION, Resource.GLOBAL );
- return bundle;
- }
-
- private List<User> findUsers( Collection<String> roleNames )
- {
- List<String> usernames = getUsernamesForRoles( roleNames );
- List<User> filteredUsers = new ArrayList<User>();
-
- for ( User user : findUsersWithFilter() )
- {
- if ( usernames.contains( user.getUsername() ) )
- {
- filteredUsers.add( user );
- }
- }
-
- return filteredUsers;
- }
-
- private List<User> findUsersWithFilter()
- {
- Context context = new HttpServletRequestContext( ServletActionContext.getRequest() );
- LimitFactory limitFactory = new TableLimitFactory( context );
- Limit limit = new TableLimit( limitFactory );
- FilterSet filterSet = limit.getFilterSet();
-
- UserQuery query = getUserManager().createUserQuery();
- if ( filterSet.getFilter( "username" ) != null )
- {
- query.setUsername( filterSet.getFilter( "username" ).getValue() );
- }
- if ( filterSet.getFilter( "fullName" ) != null )
- {
- query.setFullName( filterSet.getFilter( "fullName" ).getValue() );
- }
- if ( filterSet.getFilter( "email" ) != null )
- {
- query.setEmail( filterSet.getFilter( "email" ).getValue() );
- }
- return getUserManager().findUsersByQuery( query );
- }
-
- private List<String> getUsernamesForRoles( Collection<String> roleNames )
- {
- Set<String> usernames = new HashSet<String>();
-
- try
- {
- List<UserAssignment> userAssignments = rbac.getUserAssignmentsForRoles( roleNames );
-
- if ( userAssignments != null )
- {
- for ( UserAssignment a : userAssignments )
- {
- usernames.add( a.getPrincipal() );
- }
- }
- }
- catch ( RbacManagerException e )
- {
- log.warn( "Unable to get user assignments for roles " + roleNames, e );
- }
-
- return new ArrayList<String>( usernames );
- }
-
- private UserManager getUserManager()
- {
- return securitySystem.getUserManager();
- }
-
- // ------------------------------------------------------------------
- // Parameter Accessor Methods
- // ------------------------------------------------------------------
-
- public List<User> getUsers()
- {
- return users;
- }
-
- public void setUsers( List<User> users )
- {
- this.users = users;
- }
-
- public String getRoleName()
- {
- if ( StringUtils.isEmpty( roleName ) )
- {
- return "Any";
- }
- return roleName;
- }
-
- public void setRoleName( String roleName )
- {
- this.roleName = roleName;
- }
-
- public List<Role> getRoles()
- {
- return roles;
- }
-
- public Map<String, Map<String, Report>> getReportMap()
- {
- return reportManager.getReportMap();
- }
-}
+++ /dev/null
-package org.codehaus.plexus.redback.struts2.checks;
-
-/*
- * 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 java.util.List;
-import java.util.Map;
-
-import org.codehaus.plexus.util.StringUtils;
-import org.apache.archiva.redback.integration.checks.xwork.XworkActionConfig;
-import org.apache.archiva.redback.integration.checks.xwork.XworkPackageConfig;
-
-import com.opensymphony.xwork2.config.Configuration;
-import com.opensymphony.xwork2.config.entities.ActionConfig;
-import com.opensymphony.xwork2.config.entities.PackageConfig;
-
-/**
- * AbstractXworkConfigurationCheck
- *
- * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
- * @version $Id$
- */
-public class AbstractXworkConfigurationCheck
-{
-
- protected void checkAction( List<String> violations, XworkPackageConfig expectedPackage, XworkActionConfig expectedAction,
- Map<?, ?> xwActionMap )
- {
- ActionConfig xwActionConfig = (ActionConfig) xwActionMap.get( expectedAction.name );
- if ( xwActionConfig != null )
- {
- if ( StringUtils.isNotEmpty( expectedAction.clazz ) )
- {
- if ( !StringUtils.equals( expectedAction.clazz, xwActionConfig.getClassName() ) )
- {
- violations.add( "xwork.xml - Expected class attribute value of " + quote( expectedAction.clazz ) +
- " but got " + quote( xwActionConfig.getClassName() ) + " instead, on action " +
- quote( expectedAction.name ) + " in package " + quote( expectedPackage.name ) + "." );
- }
- }
-
- if ( StringUtils.isNotEmpty( expectedAction.method ) )
- {
- if ( !StringUtils.equals( expectedAction.method, xwActionConfig.getMethodName() ) )
- {
- violations.add( "xwork.xml - Expected method attribute value of " + quote( expectedAction.method ) +
- " but got " + quote( xwActionConfig.getMethodName() ) + " instead, on action " +
- quote( expectedAction.name ) + " in package " + quote( expectedPackage.name ) + "." );
- }
- }
-
- Map<?, ?> xwResultMap = xwActionConfig.getResults();
-
- if ( expectedAction.results.isEmpty() )
- {
- // Check for single default result.
- if ( xwResultMap.size() < 1 )
- {
- violations.add( "xwork.xml - Missing default result on action name " +
- quote( expectedAction.name ) + " in package " + quote( expectedPackage.name ) + "." );
- }
- }
- else
- {
- // Check for named result names.
- for ( String resultName : expectedAction.results )
- {
- if ( xwResultMap.get( resultName ) == null )
- {
- violations.add( "xwork.xml - Missing named result " + quote( resultName ) + " in action " +
- quote( expectedAction.name ) + " in package " + quote( expectedPackage.name ) + "." );
- }
- }
- }
- }
- else
- {
- violations.add( "xwork.xml - Missing action named " + quote( expectedAction.name ) + " in package " +
- quote( expectedPackage.name ) + "." );
- }
- }
-
- protected void checkPackage( List<String> violations, XworkPackageConfig expectedPackage, Configuration xwConfig )
- {
- PackageConfig xwPackageConfig = findPackageNamespace( xwConfig, expectedPackage.name );
-
- if ( xwPackageConfig != null )
- {
- Map<?, ?> xwActionMap = xwPackageConfig.getActionConfigs();
-
- for ( XworkActionConfig expectedAction : expectedPackage.actions )
- {
- checkAction( violations, expectedPackage, expectedAction, xwActionMap );
- }
- }
- else
- {
- violations.add( "Missing " + quote( expectedPackage.name ) + " package namespace in xwork.xml" );
- }
- }
-
- @SuppressWarnings("unchecked")
- protected PackageConfig findPackageNamespace( Configuration xwConfig, String name )
- {
- Map<?,PackageConfig> xwPackageConfigMap = xwConfig.getPackageConfigs();
-
- for ( PackageConfig xwPackageConfig : xwPackageConfigMap.values() )
- {
- if ( StringUtils.equals( name, xwPackageConfig.getNamespace() ) )
- {
- return xwPackageConfig;
- }
- }
-
- return null;
- }
-
- protected String quote( Object o )
- {
- if ( o == null )
- {
- return "<null>";
- }
- return "\"" + o.toString() + "\"";
- }
-
-}
+++ /dev/null
-package org.codehaus.plexus.redback.struts2.checks;
-
-/*
- * 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 java.util.List;
-
-import org.apache.archiva.redback.system.check.EnvironmentCheck;
-
-/**
- * ExpectedXworkActions
- *
- * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
- */
-public class ExpectedXworkActions
- implements EnvironmentCheck
-{
- public void validateEnvironment( List<String> violations )
- {
- String classNames[] = new String[]{"org.codehaus.plexus.redback.struts2.action.admin.UserCreateAction",
- "org.codehaus.plexus.redback.struts2.action.admin.UserDeleteAction",
- "org.codehaus.plexus.redback.struts2.action.admin.UserEditAction",
- "org.codehaus.plexus.redback.struts2.action.admin.UserListAction",
- "org.codehaus.plexus.redback.struts2.action.AccountAction",
- "org.codehaus.plexus.redback.struts2.action.LoginAction",
- "org.codehaus.plexus.redback.struts2.action.LogoutAction",
- "org.codehaus.plexus.redback.struts2.action.PasswordAction",
- "org.codehaus.plexus.redback.struts2.action.RegisterAction",
- "org.codehaus.plexus.redback.struts2.action.admin.AdminConsoleAction",
- "org.codehaus.plexus.redback.struts2.action.admin.SystemInfoAction"};
-
- int count = 0;
-
- for ( int i = 0; i >= classNames.length; i++ )
- {
- if ( !classExists( violations, classNames[i] ) )
- {
- count++;
- }
- }
-
- if ( count > 0 )
- {
- violations.add( "Missing [" + count + "] xwork Actions." );
- }
- }
-
- private boolean classExists( List<String> violations, String className )
- {
- try
- {
- Class.forName( className );
-
- // TODO: check that class is an instance of Action?
- }
- catch ( ClassNotFoundException e )
- {
- violations.add( "Missing xwork Action class " + quote( className ) + "." );
- return false;
- }
- return true;
- }
-
- private String quote( Object o )
- {
- if ( o == null )
- {
- return "<null>";
- }
- return "\"" + o.toString() + "\"";
- }
-}
+++ /dev/null
-package org.codehaus.plexus.redback.struts2.checks;
-
-/*
- * 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 java.util.ArrayList;
-import java.util.List;
-
-import org.apache.archiva.redback.system.check.EnvironmentCheck;
-import org.apache.archiva.redback.integration.checks.xwork.XworkPackageConfig;
-
-import com.opensymphony.xwork2.config.Configuration;
-import com.opensymphony.xwork2.config.ConfigurationManager;
-
-/**
- * <p/>
- * ExpectedXworkConfiguration reason for existence is to validate that the executing
- * environment has everything needed for a proper execution of
- * Plexus Security :: UI Web components and javascript and jsps.
- * </p>
- * <p/>
- * <p/>
- * It is quite possible for the environment overlay to have not been done.
- * Such as when using <code>"mvn jetty:run"</code>, but forgetting to run
- * <code>"mvn war:inplace"</code> first.
- * </p>
- *
- * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
- * @version $Id$
- *
- * TODO: Address comment below and add back in the component declaration
- *
- */
-public class ExpectedXworkConfiguration
- extends AbstractXworkConfigurationCheck
- implements EnvironmentCheck
-{
- public void validateEnvironment( List<String> violations )
- {
- // Get the configuration.
-
- Configuration xworkConfig = new ConfigurationManager().getConfiguration();
-
- if ( xworkConfig != null )
- {
- List<String> internalViolations = new ArrayList<String>();
-
- /* PLXREDBACK-67
- * TODO: this currently throws a violation since the standard practice is
- * to include the xwork-security namespace in from the war overlay. Otherwise
- * all actions in the security namespace are also addressable from the
- * root default action lookup since by extending the security package thats how
- * webwork/xwork deals with the actions
- */
- XworkPackageConfig expectedPackage = new XworkPackageConfig( "/security" );
-
- expectedPackage.addAction( "account", "redback-account", "show" ).addResult( "input" ).addResult(
- "error" ).addResult( "success" );
-
- expectedPackage.addAction( "login", "redback-login", "show" ).addResult( "input" ).addResult(
- "error" ).addResult( "success" );
-
- expectedPackage.addAction( "logout", "redback-logout", "show" ).addResult( "input" ).addResult(
- "error" ).addResult( "success" );
-
- expectedPackage.addAction( "register", "redback-register", "show" ).addResult( "input" ).addResult(
- "error" ).addResult( "success" );
-
- expectedPackage.addAction( "password", "redback-password", "show" ).addResult( "input" ).addResult(
- "error" ).addResult( "success" );
-
- // -----------------------------------------------------------------
- // Security Admin Tests
-
- expectedPackage.addAction( "systeminfo", "redback-sysinfo", "show" );
- expectedPackage.addAction( "adminConsole", "redback-admin-console", "show" );
-
- expectedPackage.addAction( "userlist", "redback-admin-user-list", "show" ).addResult( "input" ).addResult(
- "success" );
-
- expectedPackage.addAction( "useredit", "redback-admin-user-edit", "edit" ).addResult( "input" ).addResult(
- "error" ).addResult( "success" );
-
- expectedPackage.addAction( "usercreate", "redback-admin-user-create", "edit" ).addResult( "input" ).addResult(
- "error" ).addResult( "success" );
-
- expectedPackage.addAction( "userdelete", "redback-admin-user-delete", "confirm" ).addResult(
- "input" ).addResult( "error" ).addResult( "success" );
-
- expectedPackage.addAction( "assignments", "redback-assignments", "show" ).addResult( "input" ).addResult(
- "error" ).addResult( "success" );
-
- expectedPackage.addAction( "roles", "redback-roles", "show" ).addResult( "input" ).addResult(
- "error" ).addResult( "success" );
-
- expectedPackage.addAction( "permissions", "redback-permissions", "show" ).addResult( "input" ).addResult(
- "error" ).addResult( "success" );
-
- checkPackage( internalViolations, expectedPackage, xworkConfig );
-
- if ( internalViolations.size() > 0 )
- {
- violations.addAll( internalViolations );
- violations.add( "Missing [" + internalViolations.size() + "] xwork.xml configuration elements." );
- }
- }
- else
- {
- violations.add( "Missing xwork.xml configuration." );
- }
- }
-
-}
+++ /dev/null
-package org.codehaus.plexus.redback.struts2.interceptor;
-
-/*
- * 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 com.opensymphony.xwork2.ActionContext;
-import com.opensymphony.xwork2.ActionInvocation;
-import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
-import org.apache.struts2.StrutsException;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.context.ApplicationContext;
-import org.springframework.web.context.WebApplicationContext;
-
-import java.util.Map;
-
-public abstract class AbstractHttpRequestTrackerInterceptor
- extends AbstractInterceptor
-{
- public static final String TRACKER_NAME = ActionInvocationTracker.class.getName( )+ ":name";
-
- protected Logger logger = LoggerFactory.getLogger( getClass() );
-
- protected abstract String getTrackerName();
-
- @Override
- public void init()
- {
- super.init();
- logger.info( "{} initialized!", this.getClass().getName() );
- }
-
- @SuppressWarnings( "unchecked" )
- protected synchronized ActionInvocationTracker addActionInvocation( ActionInvocation invocation )
- {
- Map<String, Object> sessionMap = invocation.getInvocationContext().getSession();
-
- ApplicationContext applicationContext = (ApplicationContext) ActionContext.getContext().getApplication().get(
- WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE );
- if ( applicationContext == null )
- {
- throw new StrutsException( "Could not locate ApplicationContext" );
- }
-
- ActionInvocationTracker tracker = (ActionInvocationTracker) sessionMap.get( ActionInvocationTracker.class.getName() );
-
- if ( tracker == null )
- {
- //noinspection deprecation
- tracker = applicationContext.getBean( getTrackerName(), ActionInvocationTracker.class );
- sessionMap.put( ActionInvocationTracker.class.getName(), tracker );
- }
-
- tracker.addActionInvocation( invocation );
-
- return tracker;
- }
-}
+++ /dev/null
-package org.codehaus.plexus.redback.struts2.interceptor;
-
-/*
- * 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 com.opensymphony.xwork2.ActionInvocation;
-
-public interface ActionInvocationTracker
-{
-
- static final String SESSION_KEY = ActionInvocationTracker.class.getName();
-
- void setHistorySize( int size );
-
- int getHistorySize();
-
- int getHistoryCount();
-
- SavedActionInvocation getPrevious();
-
- SavedActionInvocation getCurrent();
-
- SavedActionInvocation getActionInvocationAt( int index );
-
- void addActionInvocation( ActionInvocation invocation );
-
- void setBackTrack();
-
- void unsetBackTrack();
-
- boolean isBackTracked();
-}
+++ /dev/null
-package org.codehaus.plexus.redback.struts2.interceptor;
-
-/*
- * 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 com.opensymphony.xwork2.ActionContext;
-import com.opensymphony.xwork2.ActionInvocation;
-import com.opensymphony.xwork2.interceptor.Interceptor;
-import org.apache.archiva.redback.keys.AuthenticationKey;
-import org.apache.archiva.redback.policy.AccountLockedException;
-import org.apache.archiva.redback.policy.MustChangePasswordException;
-import org.apache.struts2.ServletActionContext;
-import org.apache.archiva.redback.authentication.AuthenticationException;
-import org.apache.archiva.redback.authentication.AuthenticationResult;
-import org.apache.archiva.redback.authentication.TokenBasedAuthenticationDataSource;
-import org.apache.archiva.redback.system.SecuritySession;
-import org.apache.archiva.redback.system.SecuritySystem;
-import org.apache.archiva.redback.system.SecuritySystemConstants;
-import org.apache.archiva.redback.users.UserNotFoundException;
-import org.apache.archiva.redback.integration.util.AutoLoginCookies;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.context.annotation.Scope;
-import org.springframework.stereotype.Controller;
-
-import javax.inject.Inject;
-import javax.servlet.http.HttpSession;
-
-/**
- * AutoLoginInterceptor
- *
- * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
- */
-@Controller( "redbackAutoLoginInterceptor" )
-@Scope( "prototype" )
-public class AutoLoginInterceptor
- implements Interceptor
-{
- private Logger log = LoggerFactory.getLogger( AutoLoginInterceptor.class );
-
- static final String PASSWORD_CHANGE = "security-must-change-password";
-
- static final String ACCOUNT_LOCKED = "security-login-locked";
-
- /**
- *
- */
- @Inject
- private SecuritySystem securitySystem;
-
- /**
- *
- */
- @Inject
- private AutoLoginCookies autologinCookies;
-
- public void destroy()
- {
- // Ignore
- }
-
- public void init()
- {
- // Ignore
- }
-
- /**
- * @noinspection ProhibitedExceptionDeclared
- */
- public String intercept( ActionInvocation invocation )
- throws Exception
- {
- SecuritySession securitySession = getSecuritySession();
-
- if ( securitySession != null && securitySession.isAuthenticated() )
- {
- // User already authenticated.
- log.debug( "User already authenticated." );
-
- if ( !checkCookieConsistency( securitySession ) )
- {
- // update single sign on cookie
- autologinCookies.setSignonCookie( securitySession.getUser().getUsername(),
- ServletActionContext.getResponse(),
- ServletActionContext.getRequest() );
- }
- }
- else
- {
- AuthenticationKey authkey =
- autologinCookies.getSignonKey( ServletActionContext.getResponse(), ServletActionContext.getRequest() );
-
- if ( authkey != null )
- {
- try
- {
- securitySession = checkAuthentication( authkey, invocation.getInvocationContext().getName().equals(
- PASSWORD_CHANGE ) );
-
- if ( securitySession != null && securitySession.isAuthenticated() )
- {
- ActionContext.getContext().getSession().put( SecuritySystemConstants.SECURITY_SESSION_KEY,
- securitySession );
- checkCookieConsistency( securitySession );
- }
- else
- {
- autologinCookies.removeSignonCookie( ServletActionContext.getResponse(),
- ServletActionContext.getRequest() );
- autologinCookies.removeRememberMeCookie( ServletActionContext.getResponse(),
- ServletActionContext.getRequest() );
- }
- }
- catch ( AccountLockedException e )
- {
- log.info( "Account Locked : Username [{}]", e.getUser().getUsername(), e );
- autologinCookies.removeSignonCookie( ServletActionContext.getResponse(),
- ServletActionContext.getRequest() );
- autologinCookies.removeRememberMeCookie( ServletActionContext.getResponse(),
- ServletActionContext.getRequest() );
- return ACCOUNT_LOCKED;
- }
- catch ( MustChangePasswordException e )
- {
- return PASSWORD_CHANGE;
- }
- }
- else if ( autologinCookies.isRememberMeEnabled() )
- {
- authkey = autologinCookies.getRememberMeKey( ServletActionContext.getResponse(),
- ServletActionContext.getRequest() );
-
- if ( authkey != null )
- {
- try
- {
- securitySession = checkAuthentication( authkey, false );
-
- if ( securitySession == null || !securitySession.isAuthenticated() )
- {
- autologinCookies.removeRememberMeCookie( ServletActionContext.getResponse(),
- ServletActionContext.getRequest() );
- }
- }
- catch ( AccountLockedException e )
- {
- log.info( "Account Locked : Username [{}]", e.getUser().getUsername(), e );
- autologinCookies.removeRememberMeCookie( ServletActionContext.getResponse(),
- ServletActionContext.getRequest() );
- return ACCOUNT_LOCKED;
- }
- catch ( MustChangePasswordException e )
- {
- return PASSWORD_CHANGE;
- }
- }
- }
- }
-
- return invocation.invoke();
- }
-
- private boolean checkCookieConsistency( SecuritySession securitySession )
- {
- String username = securitySession.getUser().getUsername();
-
- boolean failed = false;
-
- AuthenticationKey key =
- autologinCookies.getRememberMeKey( ServletActionContext.getResponse(), ServletActionContext.getRequest() );
- if ( key != null )
- {
- if ( !key.getForPrincipal().equals( username ) )
- {
- log.debug( "Login invalidated: remember me cookie was for{}; but session was for {}",
- key.getForPrincipal(), username );
- failed = true;
- }
- }
-
- if ( !failed )
- {
- key =
- autologinCookies.getSignonKey( ServletActionContext.getResponse(), ServletActionContext.getRequest() );
- if ( key != null )
- {
- if ( !key.getForPrincipal().equals( username ) )
- {
- log.debug( "Login invalidated: signon cookie was for {}; but session was for {}",
- key.getForPrincipal(), username );
- failed = true;
- }
- }
- else
- {
- log.debug( "Login invalidated: signon cookie was removed" );
- failed = true;
- }
- }
-
- if ( failed )
- {
- removeCookiesAndSession();
- }
-
- return failed;
- }
-
- private SecuritySession checkAuthentication( AuthenticationKey authkey, boolean enforcePasswordChange )
- throws AccountLockedException, MustChangePasswordException
- {
- SecuritySession securitySession = null;
- log.debug( "Logging in with an authentication key: {}", authkey.getForPrincipal() );
- TokenBasedAuthenticationDataSource authsource = new TokenBasedAuthenticationDataSource();
- authsource.setPrincipal( authkey.getForPrincipal() );
- authsource.setToken( authkey.getKey() );
- authsource.setEnforcePasswordChange( enforcePasswordChange );
-
- try
- {
- securitySession = securitySystem.authenticate( authsource );
-
- if ( securitySession.isAuthenticated() )
- {
- // TODO: this should not happen if there is a password change required - but the password change action needs to log the user in on success to swap them
- log.debug( "Login success." );
-
- HttpSession session = ServletActionContext.getRequest().getSession( true );
- session.setAttribute( SecuritySystemConstants.SECURITY_SESSION_KEY, securitySession );
- log.debug( "Setting session:{} to {}", SecuritySystemConstants.SECURITY_SESSION_KEY, securitySession );
-
- autologinCookies.setSignonCookie( authkey.getForPrincipal(), ServletActionContext.getResponse(),
- ServletActionContext.getRequest() );
- }
- else
- {
- AuthenticationResult result = securitySession.getAuthenticationResult();
- log.info( "Login interceptor failed against principal : {}", result.getPrincipal(),
- result.getException() );
- }
-
- }
- catch ( AuthenticationException e )
- {
- log.info( "Authentication Exception.", e );
- }
- catch ( UserNotFoundException e )
- {
- log.info( "User Not Found: {}", authkey.getForPrincipal(), e );
- }
- return securitySession;
- }
-
- private void removeCookiesAndSession()
- {
- autologinCookies.removeRememberMeCookie( ServletActionContext.getResponse(),
- ServletActionContext.getRequest() );
- autologinCookies.removeSignonCookie( ServletActionContext.getResponse(), ServletActionContext.getRequest() );
-
- HttpSession session = ServletActionContext.getRequest().getSession();
- if ( session != null )
- {
- session.removeAttribute( SecuritySystemConstants.SECURITY_SESSION_KEY );
- }
- }
-
- private SecuritySession getSecuritySession()
- {
- HttpSession session = ServletActionContext.getRequest().getSession();
- if ( session == null )
- {
- log.debug( "No HTTP Session exists." );
- return null;
- }
-
- SecuritySession secSession =
- (SecuritySession) session.getAttribute( SecuritySystemConstants.SECURITY_SESSION_KEY );
- log.debug( "Returning Security Session: {}", secSession );
- return secSession;
- }
-}
+++ /dev/null
-package org.codehaus.plexus.redback.struts2.interceptor;
-
-/*
- * 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 com.opensymphony.xwork2.ActionInvocation;
-import com.opensymphony.xwork2.interceptor.Interceptor;
-import org.apache.archiva.redback.system.check.EnvironmentCheck;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.context.annotation.Scope;
-import org.springframework.stereotype.Controller;
-
-import javax.annotation.PostConstruct;
-import javax.inject.Inject;
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * EnvironmentCheckInterceptor
- *
- * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
- * @version $Id$
- */
-@Controller( "redbackEnvironmentCheckInterceptor" )
-@Scope( "prototype" )
-public class EnvironmentCheckInterceptor
- implements Interceptor
-{
- private static boolean checked = false;
-
- private Logger log = LoggerFactory.getLogger( EnvironmentCheckInterceptor.class );
-
-
- /**
- *
- */
- @Inject
- private List<EnvironmentCheck> checkers;
-
- public void destroy()
- {
- // no-op
- }
-
- @PostConstruct
- public void init()
- {
-
- if ( EnvironmentCheckInterceptor.checked )
- {
- // No need to check twice.
- return;
- }
-
- if ( checkers != null )
- {
- List<String> violations = new ArrayList<String>();
-
- for ( EnvironmentCheck check : checkers )
- {
- check.validateEnvironment( violations );
- }
-
- if ( !violations.isEmpty() )
- {
- StringBuffer msg = new StringBuffer();
- 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() );
- }
- }
-
- EnvironmentCheckInterceptor.checked = true;
- }
-
- public String intercept( ActionInvocation invocation )
- throws Exception
- {
- // A no-op here. Work for this intereceptor is done in init().
- return invocation.invoke();
- }
-}
+++ /dev/null
-package org.codehaus.plexus.redback.struts2.interceptor;
-
-/*
- * 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 com.opensymphony.xwork2.ActionInvocation;
-import com.opensymphony.xwork2.interceptor.Interceptor;
-import org.apache.archiva.redback.integration.checks.security.AdminAutoCreateCheck;
-import org.apache.archiva.redback.users.User;
-import org.apache.archiva.redback.users.UserNotFoundException;
-import org.apache.commons.lang.StringUtils;
-import org.apache.struts2.ServletActionContext;
-import org.apache.archiva.redback.authentication.PasswordBasedAuthenticationDataSource;
-import org.apache.archiva.redback.configuration.UserConfiguration;
-import org.apache.archiva.redback.role.RoleManager;
-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.SecuritySystemConstants;
-import org.apache.archiva.redback.users.UserManager;
-import org.apache.archiva.redback.integration.util.AutoLoginCookies;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.context.annotation.Scope;
-import org.springframework.stereotype.Controller;
-
-import javax.inject.Inject;
-import javax.inject.Named;
-import java.io.File;
-import java.io.FileInputStream;
-import java.util.Date;
-import java.util.Map;
-import java.util.Properties;
-
-/**
- * EnvironmentCheckInterceptor
- *
- * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
- * @version $Id$
- */
-@Controller( "redbackForceAdminUserInterceptor" )
-@Scope( "prototype" )
-public class ForceAdminUserInterceptor
- implements Interceptor
-{
- private Logger log = LoggerFactory.getLogger( getClass() );
-
- private static final String SECURITY_ADMIN_USER_NEEDED = "security-admin-user-needed";
-
- private static boolean checked = false;
-
- /**
- * role-hint="configurable"
- */
- @Inject
- @Named( value = "userManager#configurable" )
- private UserManager userManager;
-
- /**
- * role-hint="default"
- */
- @Inject
- private RoleManager roleManager;
-
- /**
- * role-hint="default"
- */
- @Inject
- private UserConfiguration config;
-
- @Inject
- protected SecuritySystem securitySystem;
-
- @Inject
- private AutoLoginCookies autologinCookies;
-
- protected Map<String, Object> session;
-
- public void destroy()
- {
- // no-op
- }
-
- public void init()
- {
-
- }
-
- public String intercept( ActionInvocation invocation )
- throws Exception
- {
- if ( checked )
- {
- return invocation.invoke();
- }
-
- try
- {
- User user = userManager.findUser( getAdminUid() );
- if ( user == null )
- {
- user = useForceAdminFile();
- if ( user == null )
- {
- log.info( "No admin user configured - forwarding to admin user creation page." );
- return SECURITY_ADMIN_USER_NEEDED;
- }
- }
-
- assignAdminRole( user );
-
- checked = true;
- log.info( "Admin user found. No need to configure admin user." );
-
- }
- catch ( UserNotFoundException e )
- {
- User user = useForceAdminFile();
- if ( user != null )
- {
- assignAdminRole( user );
-
- checked = true;
- }
- else
- {
- log.info( "No admin user found - forwarding to admin user creation page." );
- return SECURITY_ADMIN_USER_NEEDED;
- }
- }
-
- return invocation.invoke();
- }
-
- private User useForceAdminFile()
- {
- try
- {
- String forceAdminFilePath = System.getProperty( AdminAutoCreateCheck.FORCE_ADMIN_FILE_PATH );
- if ( StringUtils.isBlank( forceAdminFilePath ) )
- {
- log.info( AdminAutoCreateCheck.FORCE_ADMIN_FILE_PATH + " system props is empty don't use an auto creation admin " );
- return null;
- }
- File file = new File( forceAdminFilePath );
- if ( !file.exists() )
- {
- log.warn( "file set in sysprops " + AdminAutoCreateCheck.FORCE_ADMIN_FILE_PATH + " not exists skip admin auto creation" );
- return null;
- }
- Properties properties = new Properties();
- FileInputStream fis = null;
- try
- {
- properties.load( new FileInputStream( file ) );
- }
- catch ( Exception e )
- {
- log.warn( "error loading properties from file " + forceAdminFilePath + " skip admin auto creation" );
- return null;
- }
-
- // ensure we have all properties
- String password = properties.getProperty( AdminAutoCreateCheck.ADMIN_PASSWORD_KEY );
- String email = properties.getProperty( AdminAutoCreateCheck.ADMIN_EMAIL_KEY );
- String fullName = properties.getProperty( AdminAutoCreateCheck.ADMIN_FULL_NAME_KEY );
-
- if ( StringUtils.isBlank( password ) )
- {
- log.warn( "property " + AdminAutoCreateCheck.ADMIN_PASSWORD_KEY + " not set skip auto admin creation" );
- return null;
- }
-
- if ( StringUtils.isBlank( email ) )
- {
- log.warn( "property " + AdminAutoCreateCheck.ADMIN_EMAIL_KEY + " not set skip auto admin creation" );
- return null;
- }
-
- if ( StringUtils.isBlank( fullName ) )
- {
- log.warn( "property " + AdminAutoCreateCheck.ADMIN_FULL_NAME_KEY + " not set skip auto admin creation" );
- return null;
- }
-
- User u = userManager.createUser( getAdminUid(), fullName, email );
-
- u.setPassword( password );
- u.setLocked( false );
- u.setPasswordChangeRequired( false );
- u.setPermanent( true );
-
- u = userManager.addUser( u );
- u.setPassword( password );
-
- PasswordBasedAuthenticationDataSource authdatasource = new PasswordBasedAuthenticationDataSource();
- authdatasource.setPrincipal( u.getUsername() );
- authdatasource.setPassword( u.getPassword() );
- SecuritySession securitySession = securitySystem.authenticate( authdatasource );
- if ( securitySession.getAuthenticationResult().isAuthenticated() )
- {
- // good add various tokens.
- ServletActionContext.getRequest().getSession( true ).setAttribute(
- SecuritySystemConstants.SECURITY_SESSION_KEY, securitySession );
- autologinCookies.setSignonCookie( authdatasource.getPrincipal(), ServletActionContext.getResponse(),
- ServletActionContext.getRequest() );
- u = securitySession.getUser();
- u.setLastLoginDate( new Date() );
- securitySystem.getUserManager().updateUser( u );
- }
-
- return u;
- }
- catch ( Exception e )
- {
- log.warn( "failed to automatically create an admin account " + e.getMessage(), e );
- }
- return null;
- }
-
- private String getAdminUid()
- {
- return config.getString( "redback.default.admin" );
- }
-
- private void assignAdminRole( User user )
- throws RoleManagerException
- {
- roleManager.assignRole( "system-administrator", user.getPrincipal().toString() );
- }
-}
+++ /dev/null
-package org.codehaus.plexus.redback.struts2.interceptor;
-
-/*
- * 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 java.util.Calendar;
-import java.util.Map;
-
-import javax.inject.Inject;
-import javax.servlet.http.HttpServletRequest;
-
-import org.apache.archiva.redback.configuration.UserConfiguration;
-import org.apache.archiva.redback.users.UserManager;
-import org.apache.struts2.ServletActionContext;
-import org.apache.archiva.redback.policy.UserSecurityPolicy;
-import org.apache.archiva.redback.system.DefaultSecuritySession;
-import org.apache.archiva.redback.system.SecuritySession;
-import org.apache.archiva.redback.system.SecuritySystem;
-import org.apache.archiva.redback.system.SecuritySystemConstants;
-import org.apache.archiva.redback.users.User;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.opensymphony.xwork2.ActionContext;
-import com.opensymphony.xwork2.ActionInvocation;
-import com.opensymphony.xwork2.interceptor.Interceptor;
-import org.springframework.context.annotation.Scope;
-import org.springframework.stereotype.Controller;
-
-/**
- * Interceptor to force the user to perform actions, when required.
- *
- * @author Edwin Punzalan
- */
-@Controller( "redbackPolicyEnforcementInterceptor" )
-@Scope( "prototype" )
-public class PolicyEnforcementInterceptor
- implements Interceptor
-{
- private Logger log = LoggerFactory.getLogger( PolicyEnforcementInterceptor.class );
-
- private static final String SECURITY_USER_MUST_CHANGE_PASSWORD = "security-must-change-password";
-
- /**
- *
- */
- @Inject
- private UserConfiguration config;
-
- /**
- *
- */
- @Inject
- protected SecuritySystem securitySystem;
-
- public void destroy()
- {
- //ignore
- }
-
- public void init()
- {
- //ignore
- }
-
- /**
- * 1) validate that the user doesn't have to change their password, if they do then re-route accordingly
- *
- * @param actionInvocation
- * @return
- * @throws Exception
- */
- @SuppressWarnings("unchecked")
- public String intercept( ActionInvocation actionInvocation )
- throws Exception
- {
-
- if ( config.getBoolean( "security.policy.strict.enforcement.enabled" ) )
- {
- log.debug( "Enforcement: enforcing per click security policies." );
-
-
- ActionContext context = ActionContext.getContext();
-
- SecuritySession securitySession = null;
-
- try
- {
- securitySession = (SecuritySession) context.getSession().get( SecuritySystemConstants.SECURITY_SESSION_KEY );
- }
- catch (IllegalStateException e)
- {
- log.debug("Could not get security session as the session was invalid", e);
- }
-
- UserSecurityPolicy policy = securitySystem.getPolicy();
-
- if ( securitySession != null )
- {
- UserManager userManager = securitySystem.getUserManager();
- User user = userManager.findUser( securitySession.getUser().getPrincipal() );
- securitySession = new DefaultSecuritySession( securitySession.getAuthenticationResult(), user );
- context.getSession().put( SecuritySystemConstants.SECURITY_SESSION_KEY, securitySession );
- }
- else
- {
- log.debug( "Enforcement: no user security session detected, skipping enforcement" );
- return actionInvocation.invoke();
- }
-
- if ( checkForcePasswordChange( securitySession, actionInvocation ) )
- {
- Map<String, Object> session = ServletActionContext.getContext().getSession();
- HttpServletRequest request = ServletActionContext.getRequest();
-
- String queryString = request.getQueryString();
- String targetUrl = request.getRequestURL() + ( queryString==null ? "" : "?" + queryString );
-
- session.put( "targetUrl", targetUrl );
-
- log.info( "storing targetUrl : {}", targetUrl );
-
- return SECURITY_USER_MUST_CHANGE_PASSWORD;
- }
-
- if ( config.getBoolean( "security.policy.password.expiration.enabled" ) )
- {
- log.debug( "checking password expiration notification" );
-
- UserManager userManager = securitySystem.getUserManager();
- User user = userManager.findUser( securitySession.getUser().getPrincipal() );
-
- Calendar expirationNotifyDate = Calendar.getInstance();
- expirationNotifyDate.setTime( user.getLastPasswordChange() );
- // add on the total days to expire minus the notification days
- expirationNotifyDate.add( Calendar.DAY_OF_MONTH, policy.getPasswordExpirationDays() - config.getInt( "security.policy.password.expiration.notify.days" ) );
-
- Calendar now = Calendar.getInstance();
-
- if ( now.after( expirationNotifyDate ) )
- {
- log.debug( "setting password expiration notification" );
-
- Calendar expirationDate = Calendar.getInstance();
- expirationDate.setTime( user.getLastPasswordChange() );
- expirationDate.add( Calendar.DAY_OF_MONTH, policy.getPasswordExpirationDays() );
- Map<String, Object> session = ServletActionContext.getContext().getSession();
- session.put( "passwordExpirationNotification", expirationDate.getTime().toString() );
- }
- }
-
- return actionInvocation.invoke();
- }
- else
- {
- log.debug( "Enforcement: not processing per click security policies." );
- return actionInvocation.invoke();
- }
- }
-
- private boolean checkForcePasswordChange( SecuritySession securitySession, ActionInvocation actionInvocation )
- {
- /*
- * FIXME: something less 'hackish'
- *
- * these two classes should not be subject to this enforcement policy and this
- * ideally should be governed by the interceptor stacks but that just didn't work
- * when I was trying to solve the problem that way, psquad32 recommended I just
- * find a way to get around this interceptor in the particular case I needed to and use
- * "One stack to rule them all
- */
- if ( "org.codehaus.plexus.redback.struts2.action.PasswordAction".equals( actionInvocation.getAction().getClass().getName() ) )
- {
- log.debug( "Enforcement: skipping force password check on password action" );
- return false;
- }
-
- if ( "org.codehaus.plexus.redback.struts2.action.LoginAction".equals( actionInvocation.getAction().getClass().getName() ) )
- {
- log.debug( "Enforcement: skipping force password check on login action" );
- return false;
- }
-
- if ( "org.codehaus.plexus.redback.struts2.action.LogoutAction".equals( actionInvocation.getAction().getClass().getName() ) )
- {
- log.debug( "Enforcement: skipping force password check on logout action" );
- return false;
- }
-
- if ( config.getBoolean( "security.policy.strict.force.password.change.enabled" ) )
- {
- log.debug( "Enforcement: checking active user password change enabled" );
-
- if ( securitySession.getUser().isPasswordChangeRequired() )
- {
- log.info( "Enforcement: User must change password - forwarding to change password page." );
-
- return true;
- }
- else
- {
- log.debug( "Enforcement: User doesn't need to change password." );
- }
- }
- return false;
- }
-
-}
+++ /dev/null
-package org.codehaus.plexus.redback.struts2.interceptor;
-
-/*
- * 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 com.opensymphony.xwork2.ActionInvocation;
-
-import java.util.HashMap;
-import java.util.Map;
-
-public class SavedActionInvocation
-{
- private String namespace;
-
- private String actionName;
-
- private Map<String, Object> parameterMap;
-
- private String methodName;
-
- @SuppressWarnings("unchecked")
- public SavedActionInvocation( ActionInvocation invocation )
- {
- namespace = invocation.getProxy().getNamespace();
- actionName = invocation.getProxy().getActionName();
- methodName = invocation.getProxy().getMethod();
-
- parameterMap = new HashMap<String, Object>();
-
- parameterMap.putAll( invocation.getInvocationContext().getParameters() );
- }
-
- public String getNamespace()
- {
- return namespace;
- }
-
- public String getActionName()
- {
- return actionName;
- }
-
- public Map<String,Object> getParametersMap()
- {
- return parameterMap;
- }
-
- public String getMethodName()
- {
- return methodName;
- }
-}
+++ /dev/null
-package org.codehaus.plexus.redback.struts2.interceptor;
-
-/*
- * 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 com.google.common.collect.Lists;
-import com.opensymphony.xwork2.Action;
-import com.opensymphony.xwork2.ActionContext;
-import com.opensymphony.xwork2.ActionInvocation;
-import org.apache.commons.lang.StringUtils;
-import org.apache.commons.lang.SystemUtils;
-import org.apache.struts2.ServletActionContext;
-import org.apache.archiva.redback.authorization.AuthorizationResult;
-import org.apache.archiva.redback.system.SecuritySession;
-import org.apache.archiva.redback.system.SecuritySystem;
-import org.apache.archiva.redback.system.SecuritySystemConstants;
-import org.apache.archiva.redback.integration.interceptor.SecureAction;
-import org.apache.archiva.redback.integration.interceptor.SecureActionBundle;
-import org.apache.archiva.redback.integration.interceptor.SecureActionException;
-import org.springframework.context.annotation.Scope;
-import org.springframework.stereotype.Controller;
-
-import javax.inject.Inject;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpSession;
-import java.util.List;
-
-/**
- * SecureActionInterceptor: Interceptor that will detect webwork actions that implement the SecureAction
- * interface and providing they do verify that the current user is authorized to execute the action
- *
- * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
- * @author Jesse McConnell <jesse@codehaus.org>
- * @version $Id$
- */
-@Controller( "redbackSecureActionInterceptor" )
-@Scope( "prototype" )
-public class SecureActionInterceptor
- extends AbstractHttpRequestTrackerInterceptor
-{
- private static final String REQUIRES_AUTHORIZATION = "requires-authorization";
-
- private static final String REQUIRES_AUTHENTICATION = "requires-authentication";
-
- private static final String HTTP_HEADER_REFERER = "Referer";
-
- /**
- *
- */
- @Inject
- private SecuritySystem securitySystem;
-
- /**
- *
- */
- private String trackerName = "simple";
-
- private String enableReferrerCheck;
-
- @Override
- public void destroy()
- {
- // noop
- }
-
-
- /**
- * process the action to determine if it implements SecureAction and then act
- * accordingly
- *
- * @param invocation
- * @return
- * @throws Exception
- */
- @Override
- public String intercept( ActionInvocation invocation )
- throws Exception
- {
- ActionContext context = ActionContext.getContext();
-
- Action action = (Action) context.getActionInvocation().getAction();
-
- logger.debug( "SecureActionInterceptor: processing {}", action.getClass().getName() );
-
- if ( Boolean.valueOf( enableReferrerCheck ) )
- {
- logger.debug( "Referrer security check enabled." );
- executeReferrerSecurityCheck();
- }
-
- try
- {
- if ( action instanceof SecureAction )
- {
- SecureAction secureAction = (SecureAction) action;
- SecureActionBundle bundle = secureAction.getSecureActionBundle();
-
- if ( bundle == null )
- {
- logger.error( "Null bundle detected." );
-
- // TODO: send them somewhere else?
- return invocation.invoke();
- }
-
- if ( bundle == SecureActionBundle.OPEN )
- {
- logger.debug( "Bundle.OPEN detected." );
-
- return invocation.invoke();
- }
-
- SecuritySession session =
- (SecuritySession) context.getSession().get( SecuritySystemConstants.SECURITY_SESSION_KEY );
-
- // check the authentication requirements
- if ( bundle.requiresAuthentication() )
- {
- if ( session == null || !session.isAuthenticated() )
- {
- logger.debug( "not authenticated, need to authenticate for this action" );
- return processRequiresAuthentication( invocation );
- }
- }
-
- List<SecureActionBundle.AuthorizationTuple> authzTuples = bundle.getAuthorizationTuples();
-
- // if operations are returned we need to perform authorization checks
- if ( authzTuples != null && authzTuples.size() > 0 )
- {
- // authn adds a session, if there is no session they are not authorized and authn is required for
- // authz, even if it is just a guest user
- if ( session == null )
- {
- logger.debug( "session required for authorization to run" );
- return processRequiresAuthentication( invocation );
- }
-
- for ( SecureActionBundle.AuthorizationTuple tuple : authzTuples )
- {
- logger.debug( "checking authz for {}", tuple.toString() );
-
- AuthorizationResult authzResult =
- securitySystem.authorize( session, tuple.getOperation(), tuple.getResource() );
-
- logger.debug( "checking the interceptor authz {} for {}", authzResult.isAuthorized(),
- tuple.toString() );
-
- if ( authzResult.isAuthorized() )
- {
- if ( logger.isDebugEnabled() )
- {
- logger.debug( "{} is authorized for action {} by {}",
- Lists.<Object>newArrayList( session.getUser().getPrincipal(),
- secureAction.getClass().getName(),
- tuple.toString() ) );
- }
- return invocation.invoke();
- }
- }
-
- return processRequiresAuthorization( invocation );
- }
- }
- else
- {
- logger.debug( "SecureActionInterceptor: {} not a secure action", action.getClass().getName() );
- }
- }
- catch ( SecureActionException se )
- {
- logger.error( "can't generate the SecureActionBundle, deny access: " + se.getMessage() );
- return processRequiresAuthentication( invocation );
- }
-
- logger.debug( "not a secure action {}", action.getClass().getName() );
- String result = invocation.invoke();
- logger.debug( "Passing invocation up, result is [{}] on call {}", result,
- invocation.getAction().getClass().getName() );
- return result;
- }
-
- private void executeReferrerSecurityCheck()
- {
- String referrer = ServletActionContext.getRequest().getHeader( HTTP_HEADER_REFERER );
-
- logger.debug( "HTTP Referer header: {}", referrer );
-
- String[] tokens = StringUtils.splitPreserveAllTokens( referrer, "/", 3 );
-
- if ( tokens != null )
- {
- String path;
- if ( tokens.length < 3 )
- {
- path = referrer;
- }
- else
- {
- path = tokens[tokens.length - 1];
- }
-
- logger.debug( "Calculated virtual path: {}", path );
-
- ServletContext servletContext = ServletActionContext.getServletContext();
-
- String realPath = servletContext.getRealPath( path );
-
- if ( StringUtils.isNotEmpty( realPath ) )
- {
- // on windows realPath can return full path c:\\bla\\bla\....
- // so transforming \\ to /
- if ( SystemUtils.IS_OS_WINDOWS )
- {
- realPath = StringUtils.replace( realPath, "\\", "/" );
- }
- if ( !realPath.endsWith( path ) )
- {
- String errorMsg = "Failed referrer security check: Request did not come from the same server. "
- + "Detected HTTP Referer header is '" + referrer + "'.";
- logger.error( errorMsg );
- throw new RuntimeException( errorMsg );
- }
- else
- {
- logger.debug( "HTTP Referer header path found in server." );
- }
- }
- }
- else
- {
- logger.warn( "HTTP Referer header is null." );
- }
- }
-
- protected String processRequiresAuthorization( ActionInvocation invocation )
- {
- addActionInvocation( invocation ).setBackTrack();
- return REQUIRES_AUTHORIZATION;
- }
-
- protected String processRequiresAuthentication( ActionInvocation invocation )
- {
- HttpSession session = ServletActionContext.getRequest().getSession();
-
- if ( session != null )
- {
- session.removeAttribute( SecuritySystemConstants.SECURITY_SESSION_KEY );
- }
-
- addActionInvocation( invocation ).setBackTrack();
- return REQUIRES_AUTHENTICATION;
- }
-
- public SecuritySystem getSecuritySystem()
- {
- return securitySystem;
- }
-
- public void setSecuritySystem( SecuritySystem securitySystem )
- {
- this.securitySystem = securitySystem;
- }
-
- protected String getTrackerName()
- {
- return trackerName;
- }
-
- public String getEnableReferrerCheck()
- {
- return enableReferrerCheck;
- }
-
- public void setEnableReferrerCheck( String enableReferrerCheck )
- {
- this.enableReferrerCheck = enableReferrerCheck;
- }
-
- public void setTrackerName( String trackerName )
- {
- this.trackerName = trackerName;
- }
-}
+++ /dev/null
-package org.codehaus.plexus.redback.struts2.interceptor;
-
-/*
- * 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 com.opensymphony.xwork2.ActionInvocation;
-import org.springframework.context.annotation.Scope;
-import org.springframework.stereotype.Controller;
-
-import java.util.Stack;
-
-/**
- *
- */
-@Controller( "simple" )
-@Scope( "prototype" )
-public class SimpleActionInvocationTracker
- implements ActionInvocationTracker
-{
- /**
- *
- */
- private int historySize = 5;
-
- private boolean backTrack;
-
- private Stack<SavedActionInvocation> actionInvocationStack = new Stack<SavedActionInvocation>();
-
- public void setHistorySize( int size )
- {
- this.historySize = size;
- }
-
- public int getHistorySize()
- {
- return this.historySize;
- }
-
- public int getHistoryCount()
- {
- return actionInvocationStack.size();
- }
-
- /**
- * returns the previous actioninvocation and dropping the current one
- */
- public SavedActionInvocation getPrevious()
- {
- if ( actionInvocationStack.size() > 1 )
- {
- // drop the current SavedActionInvocation
- actionInvocationStack.pop();
- return (SavedActionInvocation) actionInvocationStack.pop();
- }
-
- return null;
- }
-
- /**
- * return the current action invocation
- */
- public SavedActionInvocation getCurrent()
- {
- if ( actionInvocationStack.size() > 0 )
- {
- return (SavedActionInvocation) actionInvocationStack.pop();
- }
-
- return null;
- }
-
- /**
- * returns the actioninvocation at the specified index, preserving
- * the actioninvocation list
- */
- public SavedActionInvocation getActionInvocationAt( int index )
- {
- if ( actionInvocationStack.size() >= index )
- {
- return (SavedActionInvocation) actionInvocationStack.get( index );
- }
-
- return null;
- }
-
- public void addActionInvocation( ActionInvocation invocation )
- {
- actionInvocationStack.push( new SavedActionInvocation( invocation ) );
-
- // remove oldest action invocation
- if ( actionInvocationStack.size() > historySize )
- {
- actionInvocationStack.remove( 0 );
- }
- }
-
- public void setBackTrack()
- {
- backTrack = true;
- }
-
- public void unsetBackTrack()
- {
- backTrack = false;
- }
-
- public boolean isBackTracked()
- {
- return backTrack;
- }
-}
+++ /dev/null
-package org.codehaus.plexus.redback.struts2.model;
-
-/*
- * 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.Role;
-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 java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Set;
-
-/**
- * @todo incredibly ugly population of the table, needs to be more concise
- */
-public class ApplicationRoleDetails
-{
- private String name;
-
- private String description;
-
- private List<String> assignedRoles;
-
- private List<String> availableRoles;
-
- private List<ModelTemplate> tableHeader;
-
- private List<List<RoleTableCell>> table;
-
- @SuppressWarnings("unchecked")
- public ApplicationRoleDetails( ModelApplication application, Collection<Role> effectivelyAssignedRoles,
- Collection<Role> allAssignedRoles, List<Role> assignableRoles )
- {
- name = application.getId();
- description = application.getDescription();
-
- List<ModelTemplate> templates = application.getTemplates();
- List<ModelRole> roles = application.getRoles();
-
- tableHeader = new LinkedList<ModelTemplate>( templates );
-
- computeRoles( roles, assignableRoles, effectivelyAssignedRoles, allAssignedRoles );
-
- computeTable( gatherResources( templates, assignableRoles ), effectivelyAssignedRoles, allAssignedRoles );
- }
-
- public String getName()
- {
- return name;
- }
-
- public String getDescription()
- {
- return description;
- }
-
- public List<String> getAssignedRoles()
- {
- return assignedRoles;
- }
-
- public List<String> getAvailableRoles()
- {
- return availableRoles;
- }
-
- public List<ModelTemplate> getTableHeader()
- {
- return tableHeader;
- }
-
- public List<List<RoleTableCell>> getTable()
- {
- return table;
- }
-
- private void computeRoles( Collection<ModelRole> applicationRoles, Collection<Role> assignableRoles,
- Collection<Role> effectivelyAssignedRoles, Collection<Role> allAssignedRoles )
- {
- assignedRoles = new ArrayList<String>();
- availableRoles = new ArrayList<String>();
- for ( Iterator<ModelRole> i = applicationRoles.iterator(); i.hasNext(); )
- {
- ModelRole role = i.next();
-
- if ( isInList( role.getName(), allAssignedRoles ) )
- {
- if ( role.isAssignable() )
- {
- assignedRoles.add( role.getName() );
- }
- }
- else if ( isInList( role.getName(), effectivelyAssignedRoles ) )
- {
- // nothing
- }
- else if ( isInList( role.getName(), assignableRoles ) )
- {
- if ( role.isAssignable() )
- {
- availableRoles.add( role.getName() );
- }
- }
- }
-
- Collections.sort( assignedRoles, String.CASE_INSENSITIVE_ORDER );
- Collections.sort( availableRoles, String.CASE_INSENSITIVE_ORDER );
- }
-
- private Set<String> gatherResources( List<ModelTemplate> applicationTemplates, List<Role> roles )
- {
- Set<String> resources = new HashSet<String>();
- for ( ModelTemplate modelTemplate : applicationTemplates )
- {
- for ( 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;
- }
-
- private void computeTable( Collection<String> resources, Collection<Role> effectivelyAssignedRoles,
- Collection<Role> allAssignedRoles )
- {
- table = new LinkedList<List<RoleTableCell>>();
-
- List<String> resourcesList = new ArrayList<String>( resources );
- Collections.sort( resourcesList, String.CASE_INSENSITIVE_ORDER );
-
- for ( String resource : resourcesList )
- {
- LinkedList<RoleTableCell> tableRow = new LinkedList<RoleTableCell>();
-
- RoleTableCell resourceCell = new RoleTableCell();
- resourceCell.setName( resource );
- resourceCell.setLabel( true );
- tableRow.add( resourceCell );
-
- for ( ModelTemplate modelTemplate : tableHeader )
- {
- RoleTableCell cell = new RoleTableCell();
-
- cell.setName( modelTemplate.getNamePrefix() + modelTemplate.getDelimiter() + resource );
- cell.setEffectivelyAssigned( isInList( cell.getName(), effectivelyAssignedRoles ) );
- cell.setAssigned( isInList( cell.getName(), allAssignedRoles ) );
- cell.setLabel( false );
-
- tableRow.add( cell );
- }
-
- table.add( tableRow );
- }
- }
-
- private boolean isInList( String roleName, Collection<Role> effectivelyAssignedRoles )
- {
- for ( Role role : effectivelyAssignedRoles )
- {
- if ( roleName.equals( role.getName() ) )
- {
- return true;
- }
- }
- return false;
- }
-
- public class RoleTableCell
- {
- private String name;
-
- private boolean effectivelyAssigned;
-
- private boolean assigned;
-
- private boolean label;
-
- public String getName()
- {
- return name;
- }
-
- public void setName( String name )
- {
- this.name = name;
- }
-
- public boolean isEffectivelyAssigned()
- {
- return effectivelyAssigned;
- }
-
- public void setEffectivelyAssigned( boolean effectivelyAssigned )
- {
- this.effectivelyAssigned = effectivelyAssigned;
- }
-
- public boolean isAssigned()
- {
- return assigned;
- }
-
- public void setAssigned( boolean assigned )
- {
- this.assigned = assigned;
- }
-
- public boolean isLabel()
- {
- return label;
- }
-
- public void setLabel( boolean label )
- {
- this.label = label;
- }
- }
-}
+++ /dev/null
-package org.codehaus.plexus.redback.struts2.result;
-
-/*
- * 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 java.util.Map;
-import java.util.Set;
-
-import org.apache.struts2.dispatcher.ServletActionRedirectResult;
-import org.codehaus.plexus.redback.struts2.interceptor.ActionInvocationTracker;
-import org.codehaus.plexus.redback.struts2.interceptor.SavedActionInvocation;
-import com.opensymphony.xwork2.ActionInvocation;
-
-@SuppressWarnings("serial")
-public class AbstractBackTrackingResult
- extends ServletActionRedirectResult
-{
- public static final int PREVIOUS = 1;
-
- public static final int CURRENT = 2;
-
- protected boolean setupBackTrackPrevious( ActionInvocation invocation )
- {
- return setupBackTrack( invocation, PREVIOUS );
- }
-
- protected boolean setupBackTrackCurrent( ActionInvocation invocation )
- {
- return setupBackTrack( invocation, CURRENT );
- }
-
- @SuppressWarnings("unchecked")
- protected boolean setupBackTrack( ActionInvocation invocation, int order )
- {
- Map session = invocation.getInvocationContext().getSession();
- ActionInvocationTracker tracker = (ActionInvocationTracker) session.get( ActionInvocationTracker.SESSION_KEY );
-
- if ( tracker != null && tracker.isBackTracked() )
- {
- SavedActionInvocation savedInvocation;
-
- if ( order == PREVIOUS )
- {
- savedInvocation = tracker.getPrevious();
- }
- else
- {
- savedInvocation = tracker.getCurrent();
- }
-
- if ( savedInvocation != null )
- {
- setNamespace( savedInvocation.getNamespace() );
- setActionName( savedInvocation.getActionName() );
- setMethod( savedInvocation.getMethodName() );
-
- invocation.getInvocationContext().getParameters().clear();
- invocation.getInvocationContext().getParameters().putAll( savedInvocation.getParametersMap() );
-
- // hack for REDBACK-188
- String resultCode = invocation.getResultCode();
-
- if( resultCode != null )
- {
- // hack for REDBACK-262
- // set this to null so the ResultConfig parameters won't be added in the ServletActionRedirectResult
- // because we can't clear the parameters of ResultConfig since it's read-only
- invocation.setResultCode( null );
-
- Set<String> keys = savedInvocation.getParametersMap().keySet();
-
- for( String key : keys )
- {
- if ( !getProhibitedResultParams().contains( key ) )
- {
- String value = ( (String[]) savedInvocation.getParametersMap().get( key ) )[0];
- if ( value != null && value.length() > 0 )
- {
- addParameter( key, conditionalParse( value, invocation ) );
- }
- }
- }
- }
-
- tracker.unsetBackTrack();
- }
-
- return true;
- }
-
- return false;
- }
-}
+++ /dev/null
-package org.codehaus.plexus.redback.struts2.result;
-
-/*
- * 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 com.opensymphony.xwork2.ActionInvocation;
-import org.springframework.context.annotation.Scope;
-import org.springframework.stereotype.Controller;
-
-
-/**
- * SecurityExternalResult
- *
- * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
- * @version $Id$
- */
-@SuppressWarnings( "serial" )
-@Controller( "securityExternalResult" )
-@Scope( "prototype" )
-public class SecurityExternalResult
- extends AbstractBackTrackingResult
-{
- /**
- *
- */
- private String externalActionName = "redbackRedirect";
-
- private String externalResult;
-
- @Override
- public void execute( ActionInvocation invocation )
- throws Exception
- {
- // the login redirection is not captured by the http request
- // tracker, so we backtrack to the current request
- if ( !setupBackTrackCurrent( invocation ) )
- {
- setNamespace( "/" );
- setActionName( externalActionName );
- }
-
- super.execute( invocation );
- }
-
- public String getExternalResult()
- {
- return externalResult;
- }
-
- public void setExternalResult( String externalResult )
- {
- this.externalResult = externalResult;
- }
-
-}
<context:annotation-config />
<context:component-scan
- base-package="org.codehaus.plexus.redback.struts2"/>
+ base-package="org.apache.archiva.redback.struts2"/>
</beans>
\ No newline at end of file
--- /dev/null
+<?xml version="1.0" ?>
+
+<!--
+ ~
+ ~ Licensed under the Apache License, Version 2.0 (the "License");
+ ~ you may not use this file except in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~ http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing, software
+ ~ distributed under the License is distributed on an "AS IS" BASIS,
+ ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ~ See the License for the specific language governing permissions and
+ ~ limitations under the License.
+ -->
+
+<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.2//EN"
+ "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
+
+<validators>
+ <field name="username">
+ <field-validator type="requiredstring">
+ <message>You must provide a user name.</message>
+ </field-validator>
+ </field>
+
+ <field name="fullName">
+ <field-validator type="requiredstring">
+ <message>You must provide your full name.</message>
+ </field-validator>
+ </field>
+
+ <field name="email">
+ <field-validator type="required">
+ <message>You must provide your email address.</message>
+ </field-validator>
+ <field-validator type="email">
+ <message>The email address you entered is invalid.</message>
+ </field-validator>
+ </field>
+
+ <field name="password">
+ <field-validator type="expression">
+ <param name="expression">passaword.equals(passwordConfirm)</param>
+ <message>Passwords are not the same.</message>
+ </field-validator>
+ </field>
+</validators>
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" ?>
-
-<!--
- ~
- ~ Licensed under the Apache License, Version 2.0 (the "License");
- ~ you may not use this file except in compliance with the License.
- ~ You may obtain a copy of the License at
- ~
- ~ http://www.apache.org/licenses/LICENSE-2.0
- ~
- ~ Unless required by applicable law or agreed to in writing, software
- ~ distributed under the License is distributed on an "AS IS" BASIS,
- ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- ~ See the License for the specific language governing permissions and
- ~ limitations under the License.
- -->
-
-<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.2//EN"
- "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
-
-<validators>
- <field name="username">
- <field-validator type="requiredstring">
- <message>You must provide a user name.</message>
- </field-validator>
- </field>
-
- <field name="fullName">
- <field-validator type="requiredstring">
- <message>You must provide your full name.</message>
- </field-validator>
- </field>
-
- <field name="email">
- <field-validator type="required">
- <message>You must provide your email address.</message>
- </field-validator>
- <field-validator type="email">
- <message>The email address you entered is invalid.</message>
- </field-validator>
- </field>
-
- <field name="password">
- <field-validator type="expression">
- <param name="expression">passaword.equals(passwordConfirm)</param>
- <message>Passwords are not the same.</message>
- </field-validator>
- </field>
-</validators>
\ No newline at end of file
--- /dev/null
+package org.apache.archiva.redback.struts2;
+
+/*
+ * 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 com.opensymphony.xwork2.ActionContext;
+
+import java.util.HashMap;
+
+public class ActionContextStub
+ extends ActionContext
+{
+ public static final String CONTEXT_NAME = "context_name";
+
+ public static final String PARAMETER_1 = "parameter_1";
+
+ public static final String PARAMETER_2 = "parameter_2";
+
+ public static final String PARAMETER_3 = "parameter_3";
+
+ public static final String VALUE_1 = "value_1";
+
+ public static final String VALUE_2 = "value_2";
+
+ public static final String VALUE_3 = "value_3";
+
+ @SuppressWarnings("unchecked")
+ public ActionContextStub()
+ {
+ super( new HashMap() );
+ this.setName( CONTEXT_NAME );
+ this.setSession( new HashMap() );
+
+ this.setParameters( new HashMap<String,Object>() );
+ this.getParameters().put( PARAMETER_1, VALUE_1 );
+ this.getParameters().put( PARAMETER_2, VALUE_2 );
+ this.getParameters().put( PARAMETER_3, VALUE_3 );
+ }
+}
--- /dev/null
+package org.apache.archiva.redback.struts2;
+
+/*
+ * 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 com.opensymphony.xwork2.ActionContext;
+import com.opensymphony.xwork2.ActionEventListener;
+import com.opensymphony.xwork2.ActionInvocation;
+import com.opensymphony.xwork2.ActionProxy;
+import com.opensymphony.xwork2.Result;
+import com.opensymphony.xwork2.interceptor.PreResultListener;
+import com.opensymphony.xwork2.util.ValueStack;
+
+/**
+ * @noinspection ProhibitedExceptionDeclared
+ */
+public class ActionInvocationStub
+ implements ActionInvocation
+{
+ private ActionContext actionContext = new ActionContextStub();
+
+ private ActionProxy actionProxy = new ActionProxyStub();
+
+ public ActionInvocationStub()
+ {
+ actionContext.setActionInvocation( this );
+ }
+
+ public Object getAction()
+ {
+ return null;
+ }
+
+ public boolean isExecuted()
+ {
+ return false;
+ }
+
+ public ActionContext getInvocationContext()
+ {
+ return actionContext;
+ }
+
+ public ActionProxy getProxy()
+ {
+ return actionProxy;
+ }
+
+ public Result getResult()
+ throws Exception
+ {
+ return null;
+ }
+
+ public String getResultCode()
+ {
+ return null;
+ }
+
+ public void setResultCode( String code )
+ {
+
+ }
+
+ public ValueStack getStack()
+ {
+ return null;
+ }
+
+ public void addPreResultListener( PreResultListener listener )
+ {
+
+ }
+
+ public String invoke()
+ throws Exception
+ {
+ return null;
+ }
+
+ public String invokeActionOnly()
+ throws Exception
+ {
+ return null;
+ }
+
+ public void setActionEventListener(ActionEventListener arg0) {
+
+ }
+
+ public void init(ActionProxy arg0) {
+
+ }
+
+}
--- /dev/null
+package org.apache.archiva.redback.struts2;
+
+/*
+ * 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 com.opensymphony.xwork2.ActionInvocation;
+import com.opensymphony.xwork2.ActionProxy;
+import com.opensymphony.xwork2.config.entities.ActionConfig;
+
+public class ActionProxyStub
+ implements ActionProxy
+{
+ public static final String ACTION_NAME = "stub_action";
+
+ public static final String NAMESPACE = "namespace";
+
+ public static final String METHOD = "method";
+
+ private String methodName;
+
+ private String actionName;
+
+ public Object getAction()
+ {
+ return null;
+ }
+
+ public void setActionName( String name )
+ {
+ actionName = name;
+ }
+
+ public void prepare() throws Exception
+ {
+ //Do nothing
+ }
+
+ public String getActionName()
+ {
+ if ( actionName != null )
+ {
+ return actionName;
+ }
+ else
+ {
+ return ACTION_NAME;
+ }
+ }
+
+ public ActionConfig getConfig()
+ {
+ return null;
+ }
+
+ public void setExecuteResult( boolean result )
+ {
+
+ }
+
+ public boolean getExecuteResult()
+ {
+ return false;
+ }
+
+ public ActionInvocation getInvocation()
+ {
+ return null;
+ }
+
+ public String getNamespace()
+ {
+ return NAMESPACE;
+ }
+
+ public String execute()
+ {
+ return null;
+ }
+
+ public void setMethod( String name )
+ {
+ methodName = name;
+ }
+
+ public String getMethod()
+ {
+ if ( methodName != null )
+ {
+ return methodName;
+ }
+ else
+ {
+ return METHOD;
+ }
+ }
+}
--- /dev/null
+package org.apache.archiva.redback.struts2.action;
+
+/*
+ * 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 static org.easymock.EasyMock.anyObject;
+import static org.easymock.EasyMock.createMock;
+import static org.easymock.EasyMock.expect;
+import static org.easymock.EasyMock.replay;
+import static org.easymock.EasyMock.verify;
+
+import java.util.HashMap;
+
+import org.apache.archiva.redback.policy.DefaultUserSecurityPolicy;
+import org.apache.archiva.redback.policy.MustChangePasswordException;
+import org.apache.archiva.redback.policy.UserSecurityPolicy;
+import org.apache.archiva.redback.policy.UserValidationSettings;
+import org.apache.archiva.redback.struts2.action.LoginAction;
+import org.apache.archiva.redback.users.UserNotFoundException;
+import org.apache.archiva.redback.authentication.AuthenticationDataSource;
+import org.apache.archiva.redback.authentication.AuthenticationException;
+import org.apache.archiva.redback.authentication.AuthenticationResult;
+import org.apache.archiva.redback.policy.AccountLockedException;
+import org.apache.archiva.redback.system.DefaultSecuritySession;
+import org.apache.archiva.redback.system.SecuritySession;
+import org.apache.archiva.redback.system.SecuritySystem;
+
+import com.opensymphony.xwork2.Action;
+import com.opensymphony.xwork2.XWorkTestCase;
+
+public class LoginActionTest
+ extends XWorkTestCase
+{
+
+ LoginAction action;
+
+ protected void setUp()
+ throws Exception
+ {
+ super.setUp();
+ action = new LoginAction();
+ action.session = new HashMap<String, Object>();
+ }
+
+ public void testRedback265()
+ throws SecurityException, NoSuchMethodException, AccountLockedException, MustChangePasswordException,
+ AuthenticationException, UserNotFoundException
+ {
+ String principal = "authenticates_but_does_not_exist";
+
+ // Setup authentication success, with no user found
+ AuthenticationResult result = new AuthenticationResult( true, principal, null );
+ SecuritySession session = new DefaultSecuritySession( result );
+ UserSecurityPolicy policy = new DefaultUserSecurityPolicy();
+
+ SecuritySystem system = createMock( SecuritySystem.class );
+ UserValidationSettings validationSettings = createMock( UserValidationSettings.class );
+ expect( system.authenticate( (AuthenticationDataSource) anyObject() ) ).andReturn( session );
+ expect( system.getPolicy() ).andReturn( policy ).anyTimes();
+ expect( validationSettings.isEmailValidationRequired() ).andReturn( true ).anyTimes();
+
+ // Hook-up action to mock objects
+ action.securitySystem = system;
+ action.setUsername( principal );
+
+ replay( system, validationSettings );
+
+ String actionResult = action.login();
+
+ verify( system, validationSettings );
+
+ assertEquals( Action.ERROR, actionResult );
+ }
+}
--- /dev/null
+package org.apache.archiva.redback.struts2.action.admin;
+
+/*
+ * 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.policy.AccountLockedException;
+import org.apache.archiva.redback.policy.MustChangePasswordException;
+import org.apache.archiva.redback.rbac.RBACManager;
+import org.apache.archiva.redback.rbac.RbacObjectInvalidException;
+import org.apache.archiva.redback.role.RoleManager;
+import org.apache.archiva.redback.struts2.action.AbstractUserCredentialsAction;
+import org.apache.archiva.redback.users.UserManager;
+import org.apache.struts2.StrutsSpringTestCase;
+import org.apache.archiva.redback.authentication.AuthenticationException;
+import org.apache.archiva.redback.authentication.PasswordBasedAuthenticationDataSource;
+import org.apache.archiva.redback.rbac.RbacManagerException;
+import org.apache.archiva.redback.rbac.UserAssignment;
+import org.apache.archiva.redback.system.SecuritySession;
+import org.apache.archiva.redback.system.SecuritySystem;
+import org.apache.archiva.redback.system.SecuritySystemConstants;
+import org.apache.archiva.redback.users.User;
+import org.apache.archiva.redback.users.UserNotFoundException;
+import org.apache.archiva.redback.users.memory.SimpleUser;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+import java.util.Collections;
+
+@RunWith( JUnit4.class )
+public abstract class AbstractUserCredentialsActionTest
+ extends StrutsSpringTestCase
+{
+ protected static final String PASSWORD = "password1";
+
+ //@Inject
+ //@Named( value = "rBACManager#memory" )
+ protected RBACManager rbacManager;
+
+ //@Inject
+ private RoleManager roleManager;
+
+ //@Inject
+ protected SecuritySystem system;
+
+ protected SecuritySession session;
+
+ @Override
+ protected String[] getContextLocations()
+ {
+ return new String[]{ "classpath*:/META-INF/spring-context.xml", "classpath*:/spring-context.xml" };
+ }
+
+ @Before
+ public void setUp()
+ throws Exception
+ {
+ CacheManager.getInstance().clearAll();
+ super.setUp();
+
+ rbacManager = applicationContext.getBean( "rBACManager#memory" , RBACManager.class );
+ roleManager = applicationContext.getBean( RoleManager.class );
+ system = applicationContext.getBean( SecuritySystem.class );
+
+
+ roleManager.loadRoleModel( getClass().getResource( "/redback.xml" ) );
+ roleManager.createTemplatedRole( "project-administrator", "default" );
+ roleManager.createTemplatedRole( "project-administrator", "other" );
+ roleManager.createTemplatedRole( "project-grant-only", "default" );
+
+ UserManager userManager = system.getUserManager();
+
+ User user = new SimpleUser();
+ user.setUsername( "user" );
+ user.setPassword( PASSWORD );
+ userManager.addUserUnchecked( user );
+
+ user = new SimpleUser();
+ user.setUsername( "user2" );
+ user.setPassword( PASSWORD );
+ userManager.addUserUnchecked( user );
+
+ user = new SimpleUser();
+ user.setUsername( "user3" );
+ user.setPassword( PASSWORD );
+ userManager.addUserUnchecked( user );
+
+ user = new SimpleUser();
+ user.setUsername( "admin" );
+ user.setPassword( PASSWORD );
+ userManager.addUserUnchecked( user );
+
+ user = new SimpleUser();
+ user.setUsername( "user-admin" );
+ user.setPassword( PASSWORD );
+ userManager.addUserUnchecked( user );
+
+ UserAssignment assignment = rbacManager.createUserAssignment( "admin" );
+ assignment.addRoleName( "System Administrator" );
+ rbacManager.saveUserAssignment( assignment );
+
+ assignment = rbacManager.createUserAssignment( "user-admin" );
+ assignment.addRoleName( "User Administrator" );
+ rbacManager.saveUserAssignment( assignment );
+
+ assignment = rbacManager.createUserAssignment( "user2" );
+ rbacManager.saveUserAssignment( assignment );
+ }
+
+ @After
+ public void after()
+ {
+ CacheManager.getInstance().clearAll();
+ }
+
+ protected void addAssignment( String principal, String roleName )
+ throws RbacManagerException, RbacObjectInvalidException
+ {
+ UserAssignment assignment;
+
+ if ( rbacManager.userAssignmentExists( principal ) )
+ {
+ assignment = rbacManager.getUserAssignment( principal );
+ }
+ else
+ {
+ assignment = rbacManager.createUserAssignment( principal );
+ }
+ assignment.addRoleName( roleName );
+ rbacManager.saveUserAssignment( assignment );
+ }
+
+ protected void login( AbstractUserCredentialsAction action, String principal, String password )
+ throws AuthenticationException, UserNotFoundException, AccountLockedException, MustChangePasswordException
+ {
+ PasswordBasedAuthenticationDataSource authdatasource = new PasswordBasedAuthenticationDataSource();
+ authdatasource.setPrincipal( principal );
+ authdatasource.setPassword( password );
+ session = system.authenticate( authdatasource );
+ assertTrue( session.isAuthenticated() );
+
+ action.setSession( Collections.singletonMap( SecuritySystemConstants.SECURITY_SESSION_KEY, (Object) session ) );
+ }
+
+}
\ No newline at end of file
--- /dev/null
+package org.apache.archiva.redback.struts2.action.admin;
+
+/*
+ * 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 com.google.common.collect.Lists;
+import com.opensymphony.xwork2.Action;
+import com.opensymphony.xwork2.ActionProxy;
+import org.apache.archiva.redback.authentication.AuthenticationException;
+import org.apache.archiva.redback.rbac.RbacObjectInvalidException;
+import org.apache.archiva.redback.rbac.Role;
+import org.apache.archiva.redback.users.UserNotFoundException;
+import org.apache.archiva.redback.authorization.AuthorizationResult;
+import org.apache.archiva.redback.policy.AccountLockedException;
+import org.apache.archiva.redback.rbac.RbacManagerException;
+import org.apache.archiva.redback.struts2.model.ApplicationRoleDetails;
+import org.apache.archiva.redback.struts2.model.ApplicationRoleDetails.RoleTableCell;
+import org.apache.archiva.redback.integration.interceptor.SecureActionBundle;
+import org.apache.archiva.redback.integration.interceptor.SecureActionException;
+import org.junit.Before;
+import org.junit.Ignore;
+import org.junit.Test;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+/**
+ * @todo missing tests for success/fail on standard show/edit functions (non security testing related)
+ */
+public class AssignmentsActionTest
+ extends AbstractUserCredentialsActionTest
+{
+ private AssignmentsAction action;
+
+ @Before
+ public void setUp()
+ throws Exception
+ {
+ super.setUp();
+
+ ActionProxy actionProxy = getActionProxy( "/security/assignments" );
+ action = (AssignmentsAction) actionProxy.getAction();
+
+ login( action, "user", PASSWORD );
+ action.setPrincipal( "user2" );
+
+ }
+
+ /**
+ * Check security - show/edituser should fail if the permission 'user-management-user-role' is not present, but a
+ * valid 'user-management-role-grant' is.
+ */
+ @Test
+ public void testUserWithOnlyRoleGrantHasNoAccess()
+ throws Exception
+ {
+
+ addAssignment( "user", "Grant Administrator - default" );
+
+ List<SecureActionBundle.AuthorizationTuple> authorizationTuples = getTuples();
+ for ( SecureActionBundle.AuthorizationTuple tuple : authorizationTuples )
+ {
+ AuthorizationResult authzResult = system.authorize( session, tuple.getOperation(), tuple.getResource() );
+
+ assertFalse( authzResult.isAuthorized() );
+ }
+ }
+
+ /**
+ * Check security - check success if the permission 'user-management-user-role' is present along with global
+ * 'user-management-role-grant'.
+ */
+ @Test
+ public void testUserWithOnlyRoleGrantHasAccess()
+ throws Exception
+ {
+ addAssignment( "user", "Project Administrator - default" );
+
+ List<SecureActionBundle.AuthorizationTuple> authorizationTuples = getTuples();
+ boolean result = false;
+ for ( SecureActionBundle.AuthorizationTuple tuple : authorizationTuples )
+ {
+ AuthorizationResult authzResult = system.authorize( session, tuple.getOperation(), tuple.getResource() );
+
+ result |= authzResult.isAuthorized();
+ }
+ assertTrue( result );
+ }
+
+ private List<SecureActionBundle.AuthorizationTuple> getTuples()
+ throws SecureActionException
+ {
+ return action.getSecureActionBundle().getAuthorizationTuples();
+ }
+
+ /**
+ * Check roles can be assigned if the user has no previous assignments.
+ */
+ @Test
+ public void testShowWhenUserHasNoAssignments()
+ throws Exception
+ {
+ addAssignment( "user", "Project Administrator - default" );
+
+ action.setPrincipal( "user3" );
+
+ assertEquals( Action.SUCCESS, action.show() );
+
+ assertEquals( 2, action.getApplicationRoleDetails().size() );
+ }
+
+ /**
+ * Check security - show should filter out roles that the 'user-management-role-grant' is not present for
+ */
+ @Test
+ public void testRoleGrantFilteringOnShow()
+ throws Exception
+ {
+ addAssignment( "user", "Project Administrator - default" );
+
+ assertEquals( Action.SUCCESS, action.show() );
+
+ assertEquals( 2, action.getApplicationRoleDetails().size() );
+ ApplicationRoleDetails details = (ApplicationRoleDetails) action.getApplicationRoleDetails().get( 0 );
+ assertEquals( "System", details.getName() );
+ assertEquals( "Roles that apply system-wide, across all of the applications", details.getDescription() );
+ assertEquals( "found roles " + details.getAvailableRoles(), 0, details.getAvailableRoles().size() );
+ details = (ApplicationRoleDetails) action.getApplicationRoleDetails().get( 1 );
+ assertEquals( "Continuum", details.getName() );
+ assertEquals( "found roles " + details.getAvailableRoles(), 0, details.getAvailableRoles().size() );
+
+ // This table rendering code clearly has to go
+ List<List<RoleTableCell>> table = details.getTable();
+ assertEquals( 1, table.size() );
+ assertRow( table, 0, "default", "Project Administrator - default", false );
+ }
+
+ @SuppressWarnings( "unchecked" )
+ private void assertRow( List table, int index, String name, String label, boolean assigned )
+ {
+ List<RoleTableCell> row = (List<RoleTableCell>) table.get( index );
+ assertEquals( name, row.get( 0 ).getName() );
+ assertEquals( label, row.get( 1 ).getName() );
+ assertEquals( assigned, row.get( 2 ).isAssigned() );
+ }
+
+ /**
+ * Check security - show should not filter out roles if 'user-management-role-grant' is present for the global
+ * resource
+ */
+ // TODO: currently returns all roles - we really want all templated roles
+ // public void testRoleGrantFilteringOnShowGlobalGrant()
+ // throws RbacObjectInvalidException, RbacManagerException
+ // {
+ // addAssignment( "user", "Global Grant Administrator" );
+ //
+ // assertEquals( Action.SUCCESS, action.show() );
+ //
+ // assertEquals( 2, action.getApplicationRoleDetails().size() );
+ // ApplicationRoleDetails details = (ApplicationRoleDetails) action.getApplicationRoleDetails().get( 0 );
+ // assertEquals( "redback-xwork-integration-core", details.getName() );
+ // assertEquals( 0, details.getAvailableRoles().size() );
+ //
+ // details = (ApplicationRoleDetails) action.getApplicationRoleDetails().get( 1 );
+ // assertEquals( "Continuum", details.getName() );
+ // assertEquals( 0, details.getAvailableRoles().size() );
+ //
+ // List table = details.getTable();
+ // assertEquals( 2, table.size() );
+ // assertRow( table, 0, "default", "Project Administrator - default", false );
+ // assertRow( table, 1, "other", "Project Administrator - other", false );
+ // }
+
+ /**
+ * Check security - edituser should skip adding a role that 'user-management-role-grant' is not present for a
+ * non-templated role
+ */
+ @Test
+ public void testRoleGrantFilteringOnAddRolesNotPermittedTemplated()
+ throws RbacObjectInvalidException, RbacManagerException
+ {
+ addAssignment( "user", "Project Administrator - default" );
+
+ // set addDSelectedRoles (dynamic --> Resource Roles) and addNDSelectedRoles (non-dynamic --> Available Roles)
+ List<String> dSelectedRoles = new ArrayList<String>();
+ dSelectedRoles.add( "Project Administrator - other" );
+
+ action.setAddDSelectedRoles( dSelectedRoles );
+
+ assertTrue( rbacManager.getUserAssignment( "user2" ).getRoleNames().isEmpty() );
+
+ assertEquals( Action.SUCCESS, action.edituser() );
+
+ assertTrue( rbacManager.getUserAssignment( "user2" ).getRoleNames().isEmpty() );
+ }
+
+ /**
+ * Check security - edituser should skip adding a role that 'user-management-role-grant' is not present for a
+ * templated role
+ */
+ @Test
+ public void testRoleGrantFilteringOnAddRolesNotPermittedNotTemplated()
+ throws RbacObjectInvalidException, RbacManagerException
+ {
+ addAssignment( "user", "Project Administrator - default" );
+
+ // set addDSelectedRoles (dynamic --> Resource Roles) and addNDSelectedRoles (non-dynamic --> Available Roles)
+ List<String> ndSelectedRoles = new ArrayList<String>();
+ ndSelectedRoles.add( "Continuum Group Project Administrator" );
+
+ action.setAddNDSelectedRoles( ndSelectedRoles );
+
+ assertTrue( rbacManager.getUserAssignment( "user2" ).getRoleNames().isEmpty() );
+
+ assertEquals( Action.SUCCESS, action.edituser() );
+
+ assertTrue( rbacManager.getUserAssignment( "user2" ).getRoleNames().isEmpty() );
+ }
+
+ /**
+ * Check security - edituser should succeed if adding a role that 'user-management-role-grant' is present for
+ * untemplated roles
+ */
+ @Test
+ public void testRoleGrantFilteringOnAddRolesPermittedNotTemplated()
+ throws RbacObjectInvalidException, RbacManagerException, AccountLockedException, AuthenticationException,
+ UserNotFoundException
+ {
+ addAssignment( "user", "Global Grant Administrator" );
+
+ // set addDSelectedRoles (dynamic --> Resource Roles) and addNDSelectedRoles (non-dynamic --> Available Roles)
+ List<String> ndSelectedRoles = new ArrayList<String>();
+ ndSelectedRoles.add( "Continuum Group Project Administrator" );
+
+ action.setAddNDSelectedRoles( ndSelectedRoles );
+
+ assertTrue( rbacManager.getUserAssignment( "user2" ).getRoleNames().isEmpty() );
+
+ assertEquals( Action.SUCCESS, action.edituser() );
+
+ assertEquals( Lists.<String>newArrayList( "Continuum Group Project Administrator" ),
+ rbacManager.getUserAssignment( "user2" ).getRoleNames() );
+ }
+
+ /**
+ * Check security - edituser should succeed if adding a role that 'user-management-role-grant' is present for
+ * templated roles
+ */
+ @Ignore
+ public void testRoleGrantFilteringOnAddRolesPermittedTemplated()
+ throws Exception
+ {
+
+ rbacManager.removeUserAssignment( "user" );
+
+ addAssignment( "user", "Project Administrator - default" );
+
+ // set addDSelectedRoles (dynamic --> Resource Roles) and addNDSelectedRoles (non-dynamic --> Available Roles)
+ List<String> dSelectedRoles = new ArrayList<String>();
+ dSelectedRoles.add( "Project Administrator - default" );
+
+ ActionProxy actionProxy = getActionProxy( "/security/assignments" );
+ AssignmentsAction newAction = (AssignmentsAction) actionProxy.getAction();
+
+ login( newAction, "user", PASSWORD );
+
+ newAction.setPrincipal( "user2" );
+
+ newAction.setAddDSelectedRoles( dSelectedRoles );
+
+ assertTrue( rbacManager.getUserAssignment( "user2" ).getRoleNames().isEmpty() );
+
+ assertEquals( Action.SUCCESS, newAction.edituser() );
+
+ assertEquals( Arrays.asList( "Project Administrator - default" ),
+ rbacManager.getUserAssignment( "user2" ).getRoleNames() );
+ }
+
+ /**
+ * Check security - edituser should succeed if adding a role that 'user-management-role-grant' is present for
+ * templated roles
+ */
+ @Test
+ public void testRoleGrantFilteringOnAddRolesPermittedTemplatedExistingRole()
+ throws Exception
+ {
+ addAssignment( "user", "Project Administrator - default" );
+
+ // cleanup before next test
+ rbacManager.removeUserAssignment( "user2" );
+
+ addAssignment( "user2", "Project Administrator - other" );
+
+ // set addDSelectedRoles (dynamic --> Resource Roles) and addNDSelectedRoles (non-dynamic --> Available Roles)
+ List<String> dSelectedRoles = new ArrayList<String>();
+ dSelectedRoles.add( "Project Administrator - default" );
+
+ ActionProxy actionProxy = getActionProxy( "/security/assignments" );
+ AssignmentsAction newAction = (AssignmentsAction) actionProxy.getAction();
+
+ login( newAction, "user2", PASSWORD );
+
+ newAction.setPrincipal( "user2" );
+
+ newAction.setAddDSelectedRoles( dSelectedRoles );
+
+ assertEquals( Arrays.asList( "Project Administrator - other" ),
+ rbacManager.getUserAssignment( "user2" ).getRoleNames() );
+
+ assertEquals( Action.SUCCESS, newAction.edituser() );
+
+ //assertEquals( Arrays.asList( "Project Administrator - default", "Project Administrator - other" ),
+ // rbacManager.getUserAssignment( "user2" ).getRoleNames() );
+ }
+
+ /**
+ * Check security - edituser should fail if removing a role that 'user-management-role-grant' is not present for
+ * untemplated roles
+ */
+ @Test
+ public void testRoleGrantFilteringOnRemoveRolesNotPermittedNotTemplated()
+ throws Exception
+ {
+
+ rbacManager.removeUserAssignment( "user2" );
+
+ addAssignment( "user", "Project Administrator - default" );
+
+ addAssignment( "user2", "Continuum Group Project Administrator" );
+
+ ActionProxy actionProxy = getActionProxy( "/security/assignments" );
+ AssignmentsAction newAction = (AssignmentsAction) actionProxy.getAction();
+
+ login( newAction, "user2", PASSWORD );
+
+ newAction.setPrincipal( "user2" );
+
+ // set addDSelectedRoles (dynamic --> Resource Roles) and addNDSelectedRoles (non-dynamic --> Available Roles)
+ List<String> ndSelectedRoles = new ArrayList<String>();
+ newAction.setAddNDSelectedRoles( ndSelectedRoles );
+
+ assertEquals( Arrays.asList( "Continuum Group Project Administrator" ),
+ rbacManager.getUserAssignment( "user2" ).getRoleNames() );
+
+ assertEquals( Action.SUCCESS, newAction.edituser() );
+
+ assertEquals( Arrays.asList( "Continuum Group Project Administrator" ),
+ rbacManager.getUserAssignment( "user2" ).getRoleNames() );
+ }
+
+ /**
+ * Check security - edituser should fail if removing a role that 'user-management-role-grant' is not present for
+ * templated roles
+ */
+ @Ignore
+ public void testRoleGrantFilteringOnRemoveRolesNotPermittedTemplated()
+ throws Exception
+ {
+ rbacManager.removeUserAssignment( "user2" );
+
+ addAssignment( "user", "Project Administrator - other" );
+
+ addAssignment( "user2", "Project Administrator - default" );
+
+ // set addDSelectedRoles (dynamic --> Resource Roles) and addNDSelectedRoles (non-dynamic --> Available Roles)
+ List<String> dSelectedRoles = new ArrayList<String>();
+
+ ActionProxy actionProxy = getActionProxy( "/security/assignments" );
+ AssignmentsAction newAction = (AssignmentsAction) actionProxy.getAction();
+
+ login( newAction, "user2", PASSWORD );
+
+ newAction.setPrincipal( "user2" );
+
+ newAction.setAddDSelectedRoles( dSelectedRoles );
+
+ assertEquals( Arrays.asList( "Project Administrator - default" ),
+ rbacManager.getUserAssignment( "user2" ).getRoleNames() );
+
+ assertEquals( Action.SUCCESS, newAction.edituser() );
+
+ assertEquals( Arrays.asList( "Project Administrator - default" ),
+ rbacManager.getUserAssignment( "user2" ).getRoleNames() );
+ }
+
+ /**
+ * Check security - edituser should succeed if removing a role that 'user-management-role-grant' is present for
+ * untemplated roles
+ */
+ @Test
+ public void testRoleGrantFilteringOnRemoveRolesPermittedNotTemplated()
+ throws Exception
+ {
+ addAssignment( "user", "Global Grant Administrator" );
+
+ addAssignment( "user2", "Continuum Group Project Administrator" );
+
+ // set addDSelectedRoles (dynamic --> Resource Roles) and addNDSelectedRoles (non-dynamic --> Available Roles)
+ List<String> ndSelectedRoles = new ArrayList<String>();
+ action.setAddNDSelectedRoles( ndSelectedRoles );
+
+ assertEquals( Arrays.asList( "Continuum Group Project Administrator" ),
+ rbacManager.getUserAssignment( "user2" ).getRoleNames() );
+
+ assertEquals( Action.SUCCESS, action.edituser() );
+
+ assertTrue( rbacManager.getUserAssignment( "user2" ).getRoleNames().isEmpty() );
+ }
+
+ /**
+ * Check security - edituser should succeed if removing a role that 'user-management-role-grant' is present for
+ * templated roles and there is an existing role that is not assignable by the current user.
+ */
+ @Test
+ public void testRoleGrantFilteringOnRemoveRolesPermittedTemplatedExistingRole()
+ throws Exception
+ {
+ addAssignment( "user", "Project Administrator - default" );
+
+ rbacManager.removeUserAssignment( "user2" );
+
+ addAssignment( "user2", "Project Administrator - default" );
+ addAssignment( "user2", "Project Administrator - other" );
+ addAssignment( "user2", "Registered User" );
+
+ // set addDSelectedRoles (dynamic --> Resource Roles) and addNDSelectedRoles (non-dynamic --> Available Roles)
+ List<String> dSelectedRoles = new ArrayList<String>();
+ dSelectedRoles.add( "Project Administrator - other" );
+ dSelectedRoles.add( "Registered User" );
+ action.setAddDSelectedRoles( dSelectedRoles );
+
+ assertEquals(
+ Arrays.asList( "Project Administrator - default", "Project Administrator - other", "Registered User" ),
+ rbacManager.getUserAssignment( "user2" ).getRoleNames() );
+
+ assertEquals( Action.SUCCESS, action.edituser() );
+
+ // Roles may be out of order, due to removal and subsequent re-add
+ List<String> user2roles = rbacManager.getUserAssignment( "user2" ).getRoleNames();
+ assertTrue( user2roles.contains( "Project Administrator - other" ) );
+ assertTrue( user2roles.contains( "Registered User" ) );
+ }
+
+ /**
+ * Check security - edituser should succeed if removing a role that 'user-management-role-grant' is present for
+ * templated roles
+ */
+ @Test
+ public void testRoleGrantFilteringOnRemoveRolesPermittedTemplated()
+ throws Exception
+ {
+ rbacManager.removeUserAssignment( "user2" );
+
+ addAssignment( "user", "Project Administrator - default" );
+
+ addAssignment( "user2", "Project Administrator - default" );
+
+ // set addDSelectedRoles (dynamic --> Resource Roles) and addNDSelectedRoles (non-dynamic --> Available Roles)
+ List<String> dSelectedRoles = new ArrayList<String>();
+ action.setAddDSelectedRoles( dSelectedRoles );
+
+ assertEquals( Arrays.asList( "Project Administrator - default" ),
+ rbacManager.getUserAssignment( "user2" ).getRoleNames() );
+
+ assertEquals( Action.SUCCESS, action.edituser() );
+
+ assertTrue( rbacManager.getUserAssignment( "user2" ).getRoleNames().isEmpty() );
+ }
+
+ /**
+ * Check security - show should succeed and display all roles, even without 'user-management-role-grant' or
+ * 'user-management-user-role' for the user administrators.
+ *
+ * @throws org.apache.archiva.redback.policy.MustChangePasswordException
+ */
+ @Test
+ public void testSystemAdminCanShowRoles()
+ throws Exception
+ {
+
+ login( action, "admin", PASSWORD );
+
+ assertEquals( Action.SUCCESS, action.show() );
+
+ assertEquals( 2, action.getApplicationRoleDetails().size() );
+ ApplicationRoleDetails details = (ApplicationRoleDetails) action.getApplicationRoleDetails().get( 0 );
+ assertEquals( "System", details.getName() );
+ assertEquals( "Roles that apply system-wide, across all of the applications", details.getDescription() );
+ assertEquals( 4, details.getAvailableRoles().size() );
+ assertEquals( "Guest", details.getAvailableRoles().get( 0 ) );
+ assertEquals( "Registered User", details.getAvailableRoles().get( 1 ) );
+ assertEquals( "System Administrator", details.getAvailableRoles().get( 2 ) );
+ assertEquals( "User Administrator", details.getAvailableRoles().get( 3 ) );
+
+ details = (ApplicationRoleDetails) action.getApplicationRoleDetails().get( 1 );
+ assertEquals( "Continuum", details.getName() );
+
+ assertEquals( 2, details.getAvailableRoles().size() );
+ assertEquals( "Continuum Group Project Administrator", details.getAvailableRoles().get( 0 ) );
+ assertEquals( "Global Grant Administrator", details.getAvailableRoles().get( 1 ) );
+
+ List<List<RoleTableCell>> table = details.getTable();
+ assertEquals( 2, table.size() );
+ assertRow( table, 0, "default", "Project Administrator - default", false );
+ assertRow( table, 1, "other", "Project Administrator - other", false );
+ }
+
+ /**
+ * Check security - show should succeed and display all roles, even without 'user-management-role-grant' or
+ * 'user-management-user-role' for the user administrators.
+ */
+ @Test
+ public void testUserAdminCanShowRoles()
+ throws Exception
+ {
+
+ ActionProxy actionProxy = getActionProxy( "/security/assignments" );
+ AssignmentsAction newAction = (AssignmentsAction) actionProxy.getAction();
+
+ login( newAction, "user-admin", PASSWORD );
+
+ newAction.setPrincipal( "user-admin" );
+
+ assertEquals( Action.SUCCESS, newAction.show() );
+
+ assertEquals( 2, newAction.getApplicationRoleDetails().size() );
+ ApplicationRoleDetails details = (ApplicationRoleDetails) newAction.getApplicationRoleDetails().get( 0 );
+ assertEquals( "System", details.getName() );
+ assertEquals( "Roles that apply system-wide, across all of the applications", details.getDescription() );
+ // TODO assertEquals( 3, details.getAvailableRoles().size() );
+ assertEquals( "Guest", details.getAvailableRoles().get( 0 ) );
+ assertEquals( "not role Registered User roles : " + details.getAvailableRoles(), "Registered User",
+ details.getAvailableRoles().get( 1 ) );
+ // TODO: assertEquals( "User Administrator", details.getAvailableRoles().get( 2 ) );
+
+ details = newAction.getApplicationRoleDetails().get( 1 );
+ assertEquals( "Continuum", details.getName() );
+
+ assertEquals( 2, details.getAvailableRoles().size() );
+ assertEquals( "Continuum Group Project Administrator", details.getAvailableRoles().get( 0 ) );
+ assertEquals( "Global Grant Administrator", details.getAvailableRoles().get( 1 ) );
+
+ List<List<RoleTableCell>> table = details.getTable();
+ assertEquals( 2, table.size() );
+ assertRow( table, 0, "default", "Project Administrator - default", false );
+ assertRow( table, 1, "other", "Project Administrator - other", false );
+ }
+
+ /**
+ * Check security - edituser should succeed in adding a role, even without 'user-management-role-grant' or
+ * 'user-management-user-role' for the user administrators.
+ */
+ @Test
+ public void testUserAdminCanAddRoles()
+ throws Exception
+ {
+ login( action, "user-admin", PASSWORD );
+
+ // set addDSelectedRoles (dynamic --> Resource Roles) and addNDSelectedRoles (non-dynamic --> Available Roles)
+ List<String> ndSelectedRoles = new ArrayList<String>();
+ ndSelectedRoles.add( "Continuum Group Project Administrator" );
+
+ action.setAddNDSelectedRoles( ndSelectedRoles );
+
+ // set addDSelectedRoles (dynamic --> Resource Roles) and addNDSelectedRoles (non-dynamic --> Available Roles)
+ List<String> dSelectedRoles = new ArrayList<String>();
+ dSelectedRoles.add( "Project Administrator - default" );
+
+ action.setAddDSelectedRoles( dSelectedRoles );
+
+ assertTrue( rbacManager.getUserAssignment( "user2" ).getRoleNames().isEmpty() );
+
+ assertEquals( Action.SUCCESS, action.edituser() );
+
+ assertEquals( Arrays.asList( "Continuum Group Project Administrator", "Project Administrator - default" ),
+ rbacManager.getUserAssignment( "user2" ).getRoleNames() );
+ }
+
+ /**
+ * Check security - edituser should succeed in removing a role, even without 'user-management-role-grant' or
+ * 'user-management-user-role' for the user administrators.
+ */
+ @Test
+ public void testUserAdminCanRemoveRoles()
+ throws Exception
+ {
+ login( action, "user-admin", PASSWORD );
+
+ rbacManager.removeUserAssignment( "user2" );
+
+ addAssignment( "user2", "Continuum Group Project Administrator" );
+ addAssignment( "user2", "Project Administrator - default" );
+
+ // set addDSelectedRoles (dynamic --> Resource Roles) and addNDSelectedRoles (non-dynamic --> Available Roles)
+ List<String> ndSelectedRoles = new ArrayList<String>();
+ action.setAddNDSelectedRoles( ndSelectedRoles );
+
+ List<String> dSelectedRoles = new ArrayList<String>();
+ action.setAddDSelectedRoles( dSelectedRoles );
+
+ assertEquals( Arrays.asList( "Continuum Group Project Administrator", "Project Administrator - default" ),
+ rbacManager.getUserAssignment( "user2" ).getRoleNames() );
+
+ assertEquals( Action.SUCCESS, action.edituser() );
+
+ assertTrue( rbacManager.getUserAssignment( "user2" ).getRoleNames().isEmpty() );
+ }
+
+ /**
+ * Check that a configured struts2 redback app only removes roles configured for the app. Without this, redback
+ * applications sharing a user database will remove each other's roles on save.
+ */
+ @Test
+ public void testUserAdminCannotRemoveNonAppRoles()
+ throws Exception
+ {
+ login( action, "user-admin", PASSWORD );
+
+ // Create a role that isn't configured for apps
+ String nonAppRoleName = "Other App Role";
+ Role nonAppRole = rbacManager.createRole( nonAppRoleName );
+ rbacManager.saveRole( nonAppRole );
+
+ rbacManager.removeUserAssignment( "user2" );
+
+ addAssignment( "user2", "Continuum Group Project Administrator" );
+ addAssignment( "user2", "Project Administrator - default" );
+ addAssignment( "user2", nonAppRoleName );
+
+ // set addDSelectedRoles (dynamic --> Resource Roles) and addNDSelectedRoles (non-dynamic --> Available Roles)
+ List<String> ndSelectedRoles = new ArrayList<String>();
+ action.setAddNDSelectedRoles( ndSelectedRoles );
+
+ List<String> dSelectedRoles = new ArrayList<String>();
+ action.setAddDSelectedRoles( dSelectedRoles );
+
+ assertEquals(
+ Arrays.asList( "Continuum Group Project Administrator", "Project Administrator - default", nonAppRoleName ),
+ rbacManager.getUserAssignment( "user2" ).getRoleNames() );
+
+ assertEquals( Action.SUCCESS, action.edituser() );
+
+ // All roles except role from other app should be removed.
+ List<String> user2roles = rbacManager.getUserAssignment( "user2" ).getRoleNames();
+ assertTrue( !user2roles.contains( "Continuum Group Project Administrator" ) );
+ assertTrue( !user2roles.contains( "Project Administrator - default" ) );
+ assertTrue( user2roles.contains( nonAppRoleName ) );
+ }
+}
--- /dev/null
+package org.apache.archiva.redback.struts2.action.admin;
+
+/*
+ * 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.struts2.action.admin.SystemInfoAction;
+import org.apache.struts2.StrutsSpringTestCase;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+/**
+ * SystemInfoActionTest
+ *
+ * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
+ * @version $Id$
+ */
+@RunWith( JUnit4.class )
+public class SystemInfoActionTest
+ extends StrutsSpringTestCase
+{
+ private SystemInfoAction systeminfo;
+
+ @Override
+ protected String[] getContextLocations()
+ {
+ return new String[]{ "classpath*:/META-INF/spring-context.xml", "classpath*:/spring-context.xml" };
+ }
+
+ @Before
+ public void setUp()
+ throws Exception
+ {
+ super.setUp();
+
+ systeminfo = (SystemInfoAction) getActionProxy( "/security/systeminfo" ).getAction();
+
+ //systeminfo = (SystemInfoAction) lookup( "com.opensymphony.xwork2.Action", "redback-sysinfo" );
+ }
+
+ @Test
+ public void testSystemInfoDump()
+ {
+ String result = systeminfo.show();
+ assertNotNull( result );
+ assertEquals( "success", result );
+ assertNotNull( systeminfo.getDetails() );
+ }
+}
--- /dev/null
+package org.apache.archiva.redback.struts2.action.admin;
+
+/*
+ * 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 com.opensymphony.xwork2.Action;
+import org.apache.archiva.redback.authentication.AuthenticationException;
+import org.apache.archiva.redback.policy.AccountLockedException;
+import org.apache.archiva.redback.rbac.RbacManagerException;
+import org.apache.archiva.redback.rbac.RbacObjectInvalidException;
+import org.apache.archiva.redback.rbac.Role;
+import org.apache.archiva.redback.users.User;
+import org.apache.archiva.redback.users.UserNotFoundException;
+import org.apache.archiva.redback.authentication.AuthenticationResult;
+import org.apache.archiva.redback.policy.MustChangePasswordException;
+import org.apache.archiva.redback.rbac.RbacObjectNotFoundException;
+import org.apache.archiva.redback.system.DefaultSecuritySession;
+import org.apache.archiva.redback.system.SecuritySession;
+import org.apache.archiva.redback.system.SecuritySystemConstants;
+import org.apache.archiva.redback.users.memory.SimpleUser;
+import org.apache.archiva.redback.integration.model.AdminEditUserCredentials;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+
+/**
+ * @todo missing tests for success/fail on standard show/edit functions (non security testing related)
+ */
+public class UserEditActionTest
+ extends AbstractUserCredentialsActionTest
+{
+
+ private Locale originalLocale;
+
+ @Before
+ public void setUp()
+ throws Exception
+ {
+ super.setUp();
+
+ originalLocale = Locale.getDefault();
+ Locale.setDefault( Locale.ENGLISH );
+ }
+
+ @After
+ public void tearDown()
+ throws Exception
+ {
+ try
+ {
+ super.tearDown();
+ }
+ finally
+ {
+ Locale.setDefault( originalLocale == null ? Locale.ENGLISH : originalLocale );
+ }
+ }
+
+ @Test
+ public void testEditPageShowsAdministratableRoles()
+ throws RbacObjectInvalidException, RbacManagerException, AccountLockedException, AuthenticationException,
+ UserNotFoundException, MustChangePasswordException
+ {
+
+ rbacManager.removeUserAssignment( "user2" );
+
+ addAssignment( "user", "User Administrator" );
+
+ addAssignment( "user2", "Project Administrator - default" );
+ addAssignment( "user2", "Project Administrator - other" );
+
+ UserEditAction action = (UserEditAction) getActionProxy( "/security/useredit" ).getAction();
+ login( action, "user2", PASSWORD );
+ action.setUsername( "user2" );
+ assertEquals( Action.INPUT, action.edit() );
+
+ List<Role> effectivelyAssignedRoles = action.getEffectivelyAssignedRoles();
+ assertEquals( 2, effectivelyAssignedRoles.size() );
+ Role r = effectivelyAssignedRoles.get( 0 );
+ assertEquals( "Project Administrator - default", r.getName() );
+ r = effectivelyAssignedRoles.get( 1 );
+ assertEquals( "Project Administrator - other", r.getName() );
+ assertFalse( action.isHasHiddenRoles() );
+
+ rbacManager.removeUserAssignment( "user2" );
+ }
+
+ @Test
+ public void testEditPageHidesUnadministratableRoles()
+ throws Exception
+ {
+ // REDBACK-29
+ // user should not be able to see the other project admin role of user2, but should be able to see the one
+ // from their own group
+
+ rbacManager.removeUserAssignment( "user" );
+ rbacManager.removeUserAssignment( "user2" );
+
+ addAssignment( "user", "Project Administrator - default" );
+ addAssignment( "user", "User Administrator" );
+ addAssignment( "user", "Grant Administrator" );
+
+ addAssignment( "user2", "Project Administrator - default" );
+ addAssignment( "user2", "Project Administrator - other" );
+
+ UserEditAction action = (UserEditAction) getActionProxy( "/security/useredit" ).getAction();
+ login( action, "user", PASSWORD );
+
+ action.setUsername( "user2" );
+ assertEquals( Action.INPUT, action.edit() );
+
+ List<Role> effectivelyAssignedRoles = action.getEffectivelyAssignedRoles();
+ assertEquals( 2, effectivelyAssignedRoles.size() );
+ Role r = effectivelyAssignedRoles.get( 0 );
+ assertEquals( "Project Administrator - default", r.getName() );
+ //assertTrue( action.isHasHiddenRoles() );
+
+ rbacManager.removeUserAssignment( "user" );
+ rbacManager.removeUserAssignment( "user2" );
+ }
+
+ @Test
+ public void testEditPageHidesUnassignableRoles()
+ throws RbacObjectInvalidException, RbacManagerException, AccountLockedException, AuthenticationException,
+ UserNotFoundException, MustChangePasswordException
+ {
+ // REDBACK-201
+ // user should not be able to see the unassignable roles
+
+ try
+ {
+ if ( rbacManager.getUserAssignment( "user" ) != null )
+ {
+ rbacManager.removeUserAssignment( "user" );
+ }
+ }
+ catch ( RbacObjectNotFoundException e )
+ {
+ // ignore
+ }
+
+ addAssignment( "user", "User Administrator" );
+
+ UserEditAction action = (UserEditAction) getActionProxy( "/security/useredit" ).getAction();
+ login( action, "user", PASSWORD );
+
+ action.setUsername( "user" );
+ assertEquals( Action.INPUT, action.edit() );
+
+ List<Role> effectivelyAssignedRoles = action.getEffectivelyAssignedRoles();
+ assertEquals( 1, effectivelyAssignedRoles.size() );
+ Role r = effectivelyAssignedRoles.get( 0 );
+ assertEquals( "User Administrator", r.getName() );
+ assertFalse( action.isHasHiddenRoles() );
+
+ rbacManager.removeUserAssignment( "user" );
+ }
+
+ @Test
+ public void testRequireOldPWWhenEditingOwnAccountSuccess()
+ throws Exception
+ {
+ addAssignment( "user", "User Administrator" );
+
+ UserEditAction action = (UserEditAction) getActionProxy( "/security/useredit" ).getAction();
+ login( action, "user", PASSWORD );
+
+ action.setUsername( "user" );
+ assertEquals( Action.INPUT, action.edit() );
+
+ assertTrue( action.isSelf() );
+
+ AdminEditUserCredentials user = action.getUser();
+ user.setEmail( "user@example.com" );
+ user.setFullName( "User" );
+ action.setOldPassword( PASSWORD );
+
+ Map<String, Object> mockSession = new HashMap<String, Object>();
+
+ User currentUser = new SimpleUser();
+ currentUser.setUsername( "user" );
+
+ AuthenticationResult authResult = new AuthenticationResult( true, "user", null );
+ SecuritySession securitySession = new DefaultSecuritySession( authResult, currentUser );
+
+ mockSession.put( SecuritySystemConstants.SECURITY_SESSION_KEY, securitySession );
+ action.setSession( mockSession );
+
+ assertEquals( Action.SUCCESS, action.submit() );
+
+ assertEquals( 0, action.getFieldErrors().size() );
+ }
+
+ @Test
+ public void testRequireOldPWWhenEditingOwnAccountFailed()
+ throws Exception
+ {
+ addAssignment( "user", "User Administrator" );
+
+ UserEditAction action = (UserEditAction) getActionProxy( "/security/useredit" ).getAction();
+ login( action, "user", PASSWORD );
+
+ action.setUsername( "user" );
+ assertEquals( Action.INPUT, action.edit() );
+
+ assertTrue( action.isSelf() );
+
+ AdminEditUserCredentials user = action.getUser();
+ user.setEmail( "user@example.com" );
+ user.setFullName( "User" );
+ user.setPassword( PASSWORD );
+ user.setConfirmPassword( PASSWORD );
+
+ action.setOldPassword( "notmatchingoldpassword" );
+
+ assertEquals( Action.ERROR, action.submit() );
+
+ Map<String, List<String>> fieldErrors = action.getFieldErrors();
+ List<String> oldPasswordErrors = fieldErrors.get( "oldPassword" );
+
+ assertNotNull( oldPasswordErrors );
+ assertEquals( 1, oldPasswordErrors.size() );
+
+ assertEquals( action.getText( "password.provided.does.not.match.existing" ), oldPasswordErrors.get( 0 ) );
+
+ rbacManager.removeUserAssignment( "user" );
+ }
+
+ @Test
+ public void testRequireOldPWWhenEditingOwnAccountOldPasswordIsNull()
+ throws Exception
+ {
+ addAssignment( "user", "User Administrator" );
+
+ UserEditAction action = (UserEditAction) getActionProxy( "/security/useredit" ).getAction();
+ login( action, "user", PASSWORD );
+
+ action.setUsername( "user" );
+ assertEquals( Action.INPUT, action.edit() );
+
+ assertTrue( action.isSelf() );
+
+ AdminEditUserCredentials user = action.getUser();
+ user.setEmail( "user@example.com" );
+ user.setFullName( "User" );
+ user.setPassword( PASSWORD );
+ user.setConfirmPassword( PASSWORD );
+
+ action.setOldPassword( null );
+
+ assertEquals( Action.ERROR, action.submit() );
+
+ Map<String, List<String>> fieldErrors = action.getFieldErrors();
+ List<String> oldPasswordErrors = fieldErrors.get( "oldPassword" );
+
+ assertNotNull( oldPasswordErrors );
+ assertEquals( 1, oldPasswordErrors.size() );
+
+ assertEquals( action.getText( "old.password.required" ), oldPasswordErrors.get( 0 ) );
+
+ rbacManager.removeUserAssignment( "user" );
+
+ }
+
+ @Test
+ public void testRequireAdminPWWhenEditingOtherAccountPWIncorrect()
+ throws Exception
+ {
+ addAssignment( "user", "User Administrator" );
+
+ UserEditAction action = (UserEditAction) getActionProxy( "/security/useredit" ).getAction();
+ login( action, "user", PASSWORD );
+
+ action.setUsername( "user2" );
+
+ assertEquals( Action.INPUT, action.edit() );
+
+ assertFalse( action.isSelf() );
+
+ AdminEditUserCredentials user = action.getUser();
+ user.setEmail( "user2@example.com" );
+ user.setFullName( "User2" );
+ user.setPassword( PASSWORD );
+ user.setConfirmPassword( PASSWORD );
+
+ assertEquals( UserEditAction.CONFIRM, action.submit() );
+
+ assertFalse( action.isSelf() );
+
+ action.setUserAdminPassword( "boguspassword" );
+
+ assertEquals( UserEditAction.CONFIRM_ERROR, action.confirmAdminPassword() );
+
+ Collection<String> errors = action.getActionErrors();
+
+ assertNotNull( errors );
+ assertEquals( 1, errors.size() );
+
+ assertEquals( action.getText( "user.admin.password.does.not.match.existing" ), errors.iterator().next() );
+
+ rbacManager.removeUserAssignment( "user" );
+ }
+
+ @Test
+ public void testRequireAdminPWWhenEditingOtherAccountPWEmpty()
+ throws Exception
+ {
+ addAssignment( "user", "User Administrator" );
+
+ UserEditAction action = (UserEditAction) getActionProxy( "/security/useredit" ).getAction();
+ login( action, "user", PASSWORD );
+
+ action.setUsername( "user2" );
+ assertEquals( Action.INPUT, action.edit() );
+
+ assertFalse( action.isSelf() );
+
+ AdminEditUserCredentials user = action.getUser();
+ user.setEmail( "user2@example.com" );
+ user.setFullName( "User2" );
+ user.setPassword( PASSWORD );
+ user.setConfirmPassword( PASSWORD );
+
+ action.setUserAdminPassword( "" );
+
+ assertEquals( UserEditAction.CONFIRM, action.submit() );
+
+ assertFalse( action.isSelf() );
+
+ assertEquals( UserEditAction.CONFIRM_ERROR, action.confirmAdminPassword() );
+
+ Collection<String> errors = action.getActionErrors();
+
+ assertNotNull( errors );
+ assertEquals( 1, errors.size() );
+
+ assertEquals( action.getText( "user.admin.password.required" ), errors.iterator().next() );
+
+ rbacManager.removeUserAssignment( "user" );
+ }
+
+}
--- /dev/null
+package org.apache.archiva.redback.struts2.interceptor;
+
+/*
+ * 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.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+
+import javax.inject.Inject;
+import javax.inject.Named;
+
+
+/**
+ *
+ * @author <a href='mailto:rahul.thakur.xdev@gmail.com'>Rahul Thakur</a>
+ * @version $Id: CustomInterceptorTest.java 1310448 2012-04-06 16:23:16Z olamy $
+ */
+@RunWith( SpringJUnit4ClassRunner.class )
+@ContextConfiguration( locations = { "classpath*:/META-INF/spring-context.xml", "classpath*:/spring-context.xml" } )
+public class CustomInterceptorTest
+ extends TestCase
+{
+
+ @Inject @Named(value = "testCustomInterceptor")
+ MockCustomInterceptor component;
+
+ /**
+ *
+ * @throws Exception on errors
+ */
+ @Test
+ public void testLookup()
+ throws Exception
+ {
+ assertNotNull( component );
+ }
+}
--- /dev/null
+package org.apache.archiva.redback.struts2.interceptor;
+
+/*
+ * 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 <a href='mailto:rahul.thakur.xdev@gmail.com'>Rahul Thakur</a>
+ */
+public interface MockComponent
+{
+ String ROLE = MockComponent.class.getName();
+
+ void displayResult( String result );
+}
--- /dev/null
+package org.apache.archiva.redback.struts2.interceptor;
+
+/*
+ * 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.stereotype.Service;
+
+/**
+ * @author <a href='mailto:rahul.thakur.xdev@gmail.com'>Rahul Thakur</a>
+ * @version $Id: MockComponentImpl.java 1310448 2012-04-06 16:23:16Z olamy $
+ */
+@Service
+public class MockComponentImpl
+ implements MockComponent
+{
+ private String result;
+
+ /* (non-Javadoc)
+ * @see org.codehaus.plexus.xwork.interceptor.TestComponent#execute()
+ */
+ public void displayResult( String result )
+ {
+ this.result = result;
+ }
+
+ public String getResult()
+ {
+ return result;
+ }
+}
--- /dev/null
+package org.apache.archiva.redback.struts2.interceptor;
+
+/*
+ * 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 com.opensymphony.xwork2.ActionInvocation;
+import com.opensymphony.xwork2.interceptor.Interceptor;
+import org.springframework.stereotype.Service;
+
+import javax.inject.Inject;
+
+/**
+ * @author <a href='mailto:rahul.thakur.xdev@gmail.com'>Rahul Thakur</a>
+ * @version $Id: MockCustomInterceptor.java 1310448 2012-04-06 16:23:16Z olamy $
+ */
+@Service("testCustomInterceptor")
+public class MockCustomInterceptor
+ implements Interceptor
+{
+ /**
+ *
+ */
+ @Inject
+ private MockComponent testComponent;
+
+ public MockCustomInterceptor()
+ {
+ }
+
+ public MockCustomInterceptor( MockComponent testComponent )
+ {
+ this.testComponent = testComponent;
+ }
+
+ /* (non-Javadoc)
+ * @see com.opensymphony.xwork2.interceptor.Interceptor#destroy()
+ */
+ public void destroy()
+ {
+ // do nothing
+ }
+
+ /* (non-Javadoc)
+ * @see com.opensymphony.xwork2.interceptor.Interceptor#init()
+ */
+ public void init()
+ {
+ // do nothing
+ }
+
+ /**
+ * @noinspection ProhibitedExceptionDeclared
+ */
+ public String intercept( ActionInvocation invocation )
+ throws Exception
+ {
+ String result = "Hello Custom Interceptor";
+
+ testComponent.displayResult( result );
+
+ return result;
+ }
+
+ public MockComponent getTestComponent()
+ {
+ return testComponent;
+ }
+
+ // Introduce a Composition Exception , see PLX - 278
+ // public void setTestComponent( MockComponent testComponent )
+ // {
+ // this.testComponent = testComponent;
+ // }
+
+}
--- /dev/null
+package org.apache.archiva.redback.struts2.interceptor;
+
+/*
+ * 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.archiva.redback.struts2.ActionContextStub;
+import org.apache.archiva.redback.struts2.ActionInvocationStub;
+import org.apache.archiva.redback.struts2.ActionProxyStub;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+
+import java.util.Map;
+
+@RunWith( SpringJUnit4ClassRunner.class )
+@ContextConfiguration( locations = { "classpath*:/META-INF/spring-context.xml", "classpath*:/spring-context.xml" } )
+public class SimpleActionInvocationTrackerTest
+ extends TestCase
+{
+ private static final int HISTORY_SIZE = 2;
+
+ private ActionInvocationTracker tracker;
+
+
+
+
+ protected String getPlexusConfigLocation()
+ {
+ return "plexus.xml";
+ }
+
+ @Before
+ public void setUp()
+ throws Exception
+ {
+ super.setUp();
+ tracker = new SimpleActionInvocationTracker();
+ }
+
+ @Test
+ public void testAddActionInvocation()
+ throws Exception
+ {
+ tracker.setHistorySize( HISTORY_SIZE );
+
+ tracker.addActionInvocation( new ActionInvocationStub() );
+ assertEquals( 1, tracker.getHistoryCount() );
+
+ // first entry int the stack
+ SavedActionInvocation actionInvocation = tracker.getActionInvocationAt( 0 );
+ Map<String,Object> parametersMap = actionInvocation.getParametersMap();
+
+ assertEquals( ActionProxyStub.ACTION_NAME, actionInvocation.getActionName() );
+ assertEquals( ActionProxyStub.METHOD, actionInvocation.getMethodName() );
+ assertEquals( ActionContextStub.VALUE_1, parametersMap.get( ActionContextStub.PARAMETER_1 ) );
+ assertEquals( ActionContextStub.VALUE_2, parametersMap.get( ActionContextStub.PARAMETER_2 ) );
+ assertEquals( ActionContextStub.VALUE_3, parametersMap.get( ActionContextStub.PARAMETER_3 ) );
+
+ ActionInvocationStub actionInvocationStub = new ActionInvocationStub();
+
+ ActionProxyStub proxyStub = (ActionProxyStub) actionInvocationStub.getProxy();
+ proxyStub.setActionName( "new_action" );
+ proxyStub.setMethod( "new_method" );
+
+ ActionContextStub actionContextStub = (ActionContextStub) actionInvocationStub.getInvocationContext();
+ actionContextStub.getParameters().put( "new_parameter", "new_value" );
+
+ tracker.addActionInvocation( actionInvocationStub );
+ assertEquals( tracker.getHistoryCount(), HISTORY_SIZE );
+
+ // second entry in the stack
+ actionInvocation = tracker.getActionInvocationAt( 1 );
+ parametersMap = actionInvocation.getParametersMap();
+
+ assertEquals( "new_action", actionInvocation.getActionName() );
+ assertEquals( "new_method", actionInvocation.getMethodName() );
+ assertEquals( ActionContextStub.VALUE_1, parametersMap.get( ActionContextStub.PARAMETER_1 ) );
+ assertEquals( ActionContextStub.VALUE_2, parametersMap.get( ActionContextStub.PARAMETER_2 ) );
+ assertEquals( ActionContextStub.VALUE_3, parametersMap.get( ActionContextStub.PARAMETER_3 ) );
+ assertEquals( "new_value", parametersMap.get( "new_parameter" ) );
+
+ // first entry int the stack
+ actionInvocation = tracker.getActionInvocationAt( 0 );
+ parametersMap = actionInvocation.getParametersMap();
+
+ assertEquals( ActionProxyStub.ACTION_NAME, actionInvocation.getActionName() );
+ assertEquals( ActionProxyStub.METHOD, actionInvocation.getMethodName() );
+ assertEquals( ActionContextStub.VALUE_1, parametersMap.get( ActionContextStub.PARAMETER_1 ) );
+ assertEquals( ActionContextStub.VALUE_2, parametersMap.get( ActionContextStub.PARAMETER_2 ) );
+ assertEquals( ActionContextStub.VALUE_3, parametersMap.get( ActionContextStub.PARAMETER_3 ) );
+ }
+
+ @Test
+ public void testHistoryCounter()
+ throws Exception
+ {
+ tracker.setHistorySize( HISTORY_SIZE );
+ tracker.addActionInvocation( new ActionInvocationStub() );
+ assertEquals( 1, tracker.getHistoryCount() );
+
+ tracker.setHistorySize( HISTORY_SIZE );
+ tracker.addActionInvocation( new ActionInvocationStub() );
+ assertEquals( HISTORY_SIZE, tracker.getHistoryCount() );
+
+ tracker.addActionInvocation( new ActionInvocationStub() );
+ tracker.addActionInvocation( new ActionInvocationStub() );
+ tracker.addActionInvocation( new ActionInvocationStub() );
+ assertEquals( HISTORY_SIZE, tracker.getHistoryCount() );
+
+ tracker.addActionInvocation( new ActionInvocationStub() );
+ tracker.addActionInvocation( new ActionInvocationStub() );
+ tracker.addActionInvocation( new ActionInvocationStub() );
+ assertEquals( HISTORY_SIZE, tracker.getHistoryCount() );
+ }
+
+}
--- /dev/null
+package org.apache.archiva.redback.struts2.result;
+
+/*
+ * 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.archiva.redback.struts2.interceptor.ActionInvocationTracker;
+import org.apache.archiva.redback.struts2.interceptor.SimpleActionInvocationTracker;
+import org.apache.archiva.redback.struts2.ActionContextStub;
+import org.apache.archiva.redback.struts2.ActionInvocationStub;
+import org.apache.archiva.redback.struts2.ActionProxyStub;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+
+import java.util.Map;
+
+@RunWith( SpringJUnit4ClassRunner.class )
+@ContextConfiguration( locations = { "classpath*:/META-INF/spring-context.xml", "classpath*:/spring-context.xml" } )
+public class BackTrackingResultTest
+ extends TestCase
+{
+ public static final int HISTORY_SIZE = 2;
+
+ protected String getPlexusConfigLocation()
+ {
+ return "plexus.xml";
+ }
+
+ @Test
+ public void testBackTrackPrevious()
+ throws Exception
+ {
+ // first http request
+ ActionInvocationStub actionInvocation1 = new ActionInvocationStub();
+ SimpleBackTrackingResult backtrackingResult = new SimpleBackTrackingResult( actionInvocation1 );
+
+ // second http request
+ ActionInvocationStub previousActionInvocation = new ActionInvocationStub();
+ ActionProxyStub previousProxyStub = (ActionProxyStub) previousActionInvocation.getProxy();
+ previousProxyStub.setActionName( "previous_action" );
+ previousProxyStub.setMethod( "previous_method" );
+
+ ActionContextStub previousActionContext = (ActionContextStub) previousActionInvocation.getInvocationContext();
+ previousActionContext.getParameters().put( "previous_parameter", "previous_value" );
+
+ // third http request
+ ActionInvocationStub currentActionInvocation = new ActionInvocationStub();
+ ActionProxyStub currentProxyStub = (ActionProxyStub) currentActionInvocation.getProxy();
+ currentProxyStub.setActionName( "current_action" );
+ currentProxyStub.setMethod( "current_method" );
+
+ ActionContextStub currentActionContext = (ActionContextStub) currentActionInvocation.getInvocationContext();
+ currentActionContext.getParameters().put( "current_parameter", "current_value" );
+
+ SimpleActionInvocationTracker tracker = new SimpleActionInvocationTracker();
+
+ // save the second request and third request to the stack
+ tracker.setHistorySize( HISTORY_SIZE );
+ tracker.addActionInvocation( previousActionInvocation );
+ tracker.addActionInvocation( currentActionInvocation );
+ tracker.setBackTrack();
+ // add the tracker to the session
+ actionInvocation1.getInvocationContext().getSession().put( ActionInvocationTracker.SESSION_KEY, tracker );
+
+ // before backtrack
+ Map<String, Object> parametersMap = actionInvocation1.getInvocationContext().getParameters();
+
+ assertEquals( ActionProxyStub.ACTION_NAME, backtrackingResult.getActionName() );
+ assertEquals( ActionProxyStub.METHOD, backtrackingResult.getMethod() );
+ assertEquals( ActionContextStub.VALUE_1, parametersMap.get( ActionContextStub.PARAMETER_1 ) );
+ assertEquals( ActionContextStub.VALUE_2, parametersMap.get( ActionContextStub.PARAMETER_2 ) );
+ assertEquals( ActionContextStub.VALUE_3, parametersMap.get( ActionContextStub.PARAMETER_3 ) );
+
+ backtrackingResult.setupBackTrackPrevious( actionInvocation1 );
+
+ // after backtrack
+ parametersMap = actionInvocation1.getInvocationContext().getParameters();
+
+ assertEquals( "previous_action", backtrackingResult.getActionName() );
+ assertEquals( "previous_method", backtrackingResult.getMethod() );
+ assertEquals( ActionContextStub.VALUE_1, parametersMap.get( ActionContextStub.PARAMETER_1 ) );
+ assertEquals( ActionContextStub.VALUE_2, parametersMap.get( ActionContextStub.PARAMETER_2 ) );
+ assertEquals( ActionContextStub.VALUE_3, parametersMap.get( ActionContextStub.PARAMETER_3 ) );
+ assertEquals( "previous_value", parametersMap.get( "previous_parameter" ) );
+
+ }
+
+ @SuppressWarnings( "unchecked" )
+ public void testBackTrackCurrent()
+ throws Exception
+ {
+ // first http request
+ ActionInvocationStub actionInvocation1 = new ActionInvocationStub();
+ SimpleBackTrackingResult backtrackingResult = new SimpleBackTrackingResult( actionInvocation1 );
+
+ // second http request
+ ActionInvocationStub previousActionInvocation = new ActionInvocationStub();
+ ActionProxyStub previousProxyStub = (ActionProxyStub) previousActionInvocation.getProxy();
+ previousProxyStub.setActionName( "previous_action" );
+ previousProxyStub.setMethod( "previous_method" );
+
+ ActionContextStub previousActionContext = (ActionContextStub) previousActionInvocation.getInvocationContext();
+ previousActionContext.getParameters().put( "previous_parameter", "previous_value" );
+
+ // third http request
+ ActionInvocationStub currentActionInvocation = new ActionInvocationStub();
+ ActionProxyStub currentProxyStub = (ActionProxyStub) currentActionInvocation.getProxy();
+ currentProxyStub.setActionName( "current_action" );
+ currentProxyStub.setMethod( "current_method" );
+
+ ActionContextStub currentActionContext = (ActionContextStub) currentActionInvocation.getInvocationContext();
+ currentActionContext.getParameters().put( "current_parameter", "current_value" );
+
+ SimpleActionInvocationTracker tracker = new SimpleActionInvocationTracker();
+
+ // save the second request and third request to the stack
+ tracker.setHistorySize( HISTORY_SIZE );
+ tracker.addActionInvocation( previousActionInvocation );
+ tracker.addActionInvocation( currentActionInvocation );
+ tracker.setBackTrack();
+ // add the tracker to the session
+ actionInvocation1.getInvocationContext().getSession().put( ActionInvocationTracker.SESSION_KEY, tracker );
+
+ // before backtrack
+ Map<String, Object> parametersMap = actionInvocation1.getInvocationContext().getParameters();
+
+ assertEquals( ActionProxyStub.ACTION_NAME, backtrackingResult.getActionName() );
+ assertEquals( ActionProxyStub.METHOD, backtrackingResult.getMethod() );
+ assertEquals( ActionContextStub.VALUE_1, parametersMap.get( ActionContextStub.PARAMETER_1 ) );
+ assertEquals( ActionContextStub.VALUE_2, parametersMap.get( ActionContextStub.PARAMETER_2 ) );
+ assertEquals( ActionContextStub.VALUE_3, parametersMap.get( ActionContextStub.PARAMETER_3 ) );
+
+ backtrackingResult.setupBackTrackCurrent( actionInvocation1 );
+
+ // after backtrack
+ assertEquals( "current_action", backtrackingResult.getActionName() );
+ assertEquals( "current_method", backtrackingResult.getMethod() );
+ assertEquals( ActionContextStub.VALUE_1, parametersMap.get( ActionContextStub.PARAMETER_1 ) );
+ assertEquals( ActionContextStub.VALUE_2, parametersMap.get( ActionContextStub.PARAMETER_2 ) );
+ assertEquals( ActionContextStub.VALUE_3, parametersMap.get( ActionContextStub.PARAMETER_3 ) );
+ assertEquals( "current_value", parametersMap.get( "current_parameter" ) );
+ }
+}
--- /dev/null
+package org.apache.archiva.redback.struts2.result;
+
+/*
+ * 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.struts2.ActionInvocationStub;
+
+public class SimpleBackTrackingResult
+ extends AbstractBackTrackingResult
+{
+ public SimpleBackTrackingResult( ActionInvocationStub invocation )
+ {
+ super.actionName = invocation.getProxy().getActionName();
+ super.method = invocation.getProxy().getMethod();
+ }
+
+ public String getActionName()
+ {
+ return super.actionName;
+ }
+
+ public String getMethod()
+ {
+ return super.method;
+ }
+}
+++ /dev/null
-package org.codehaus.plexus.redback.struts2;
-
-/*
- * 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 com.opensymphony.xwork2.ActionContext;
-
-import java.util.HashMap;
-
-public class ActionContextStub
- extends ActionContext
-{
- public static final String CONTEXT_NAME = "context_name";
-
- public static final String PARAMETER_1 = "parameter_1";
-
- public static final String PARAMETER_2 = "parameter_2";
-
- public static final String PARAMETER_3 = "parameter_3";
-
- public static final String VALUE_1 = "value_1";
-
- public static final String VALUE_2 = "value_2";
-
- public static final String VALUE_3 = "value_3";
-
- @SuppressWarnings("unchecked")
- public ActionContextStub()
- {
- super( new HashMap() );
- this.setName( CONTEXT_NAME );
- this.setSession( new HashMap() );
-
- this.setParameters( new HashMap<String,Object>() );
- this.getParameters().put( PARAMETER_1, VALUE_1 );
- this.getParameters().put( PARAMETER_2, VALUE_2 );
- this.getParameters().put( PARAMETER_3, VALUE_3 );
- }
-}
+++ /dev/null
-package org.codehaus.plexus.redback.struts2;
-
-/*
- * 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 com.opensymphony.xwork2.ActionContext;
-import com.opensymphony.xwork2.ActionEventListener;
-import com.opensymphony.xwork2.ActionInvocation;
-import com.opensymphony.xwork2.ActionProxy;
-import com.opensymphony.xwork2.Result;
-import com.opensymphony.xwork2.interceptor.PreResultListener;
-import com.opensymphony.xwork2.util.ValueStack;
-
-/**
- * @noinspection ProhibitedExceptionDeclared
- */
-public class ActionInvocationStub
- implements ActionInvocation
-{
- private ActionContext actionContext = new ActionContextStub();
-
- private ActionProxy actionProxy = new ActionProxyStub();
-
- public ActionInvocationStub()
- {
- actionContext.setActionInvocation( this );
- }
-
- public Object getAction()
- {
- return null;
- }
-
- public boolean isExecuted()
- {
- return false;
- }
-
- public ActionContext getInvocationContext()
- {
- return actionContext;
- }
-
- public ActionProxy getProxy()
- {
- return actionProxy;
- }
-
- public Result getResult()
- throws Exception
- {
- return null;
- }
-
- public String getResultCode()
- {
- return null;
- }
-
- public void setResultCode( String code )
- {
-
- }
-
- public ValueStack getStack()
- {
- return null;
- }
-
- public void addPreResultListener( PreResultListener listener )
- {
-
- }
-
- public String invoke()
- throws Exception
- {
- return null;
- }
-
- public String invokeActionOnly()
- throws Exception
- {
- return null;
- }
-
- public void setActionEventListener(ActionEventListener arg0) {
-
- }
-
- public void init(ActionProxy arg0) {
-
- }
-
-}
+++ /dev/null
-package org.codehaus.plexus.redback.struts2;
-
-/*
- * 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 com.opensymphony.xwork2.ActionInvocation;
-import com.opensymphony.xwork2.ActionProxy;
-import com.opensymphony.xwork2.config.entities.ActionConfig;
-
-public class ActionProxyStub
- implements ActionProxy
-{
- public static final String ACTION_NAME = "stub_action";
-
- public static final String NAMESPACE = "namespace";
-
- public static final String METHOD = "method";
-
- private String methodName;
-
- private String actionName;
-
- public Object getAction()
- {
- return null;
- }
-
- public void setActionName( String name )
- {
- actionName = name;
- }
-
- public void prepare() throws Exception
- {
- //Do nothing
- }
-
- public String getActionName()
- {
- if ( actionName != null )
- {
- return actionName;
- }
- else
- {
- return ACTION_NAME;
- }
- }
-
- public ActionConfig getConfig()
- {
- return null;
- }
-
- public void setExecuteResult( boolean result )
- {
-
- }
-
- public boolean getExecuteResult()
- {
- return false;
- }
-
- public ActionInvocation getInvocation()
- {
- return null;
- }
-
- public String getNamespace()
- {
- return NAMESPACE;
- }
-
- public String execute()
- {
- return null;
- }
-
- public void setMethod( String name )
- {
- methodName = name;
- }
-
- public String getMethod()
- {
- if ( methodName != null )
- {
- return methodName;
- }
- else
- {
- return METHOD;
- }
- }
-}
+++ /dev/null
-package org.codehaus.plexus.redback.struts2.action;
-
-/*
- * 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 static org.easymock.EasyMock.anyObject;
-import static org.easymock.EasyMock.createMock;
-import static org.easymock.EasyMock.expect;
-import static org.easymock.EasyMock.replay;
-import static org.easymock.EasyMock.verify;
-
-import java.util.HashMap;
-
-import org.apache.archiva.redback.policy.DefaultUserSecurityPolicy;
-import org.apache.archiva.redback.policy.MustChangePasswordException;
-import org.apache.archiva.redback.policy.UserSecurityPolicy;
-import org.apache.archiva.redback.policy.UserValidationSettings;
-import org.apache.archiva.redback.users.UserNotFoundException;
-import org.apache.archiva.redback.authentication.AuthenticationDataSource;
-import org.apache.archiva.redback.authentication.AuthenticationException;
-import org.apache.archiva.redback.authentication.AuthenticationResult;
-import org.apache.archiva.redback.policy.AccountLockedException;
-import org.apache.archiva.redback.system.DefaultSecuritySession;
-import org.apache.archiva.redback.system.SecuritySession;
-import org.apache.archiva.redback.system.SecuritySystem;
-
-import com.opensymphony.xwork2.Action;
-import com.opensymphony.xwork2.XWorkTestCase;
-
-public class LoginActionTest
- extends XWorkTestCase
-{
-
- LoginAction action;
-
- protected void setUp()
- throws Exception
- {
- super.setUp();
- action = new LoginAction();
- action.session = new HashMap<String, Object>();
- }
-
- public void testRedback265()
- throws SecurityException, NoSuchMethodException, AccountLockedException, MustChangePasswordException,
- AuthenticationException, UserNotFoundException
- {
- String principal = "authenticates_but_does_not_exist";
-
- // Setup authentication success, with no user found
- AuthenticationResult result = new AuthenticationResult( true, principal, null );
- SecuritySession session = new DefaultSecuritySession( result );
- UserSecurityPolicy policy = new DefaultUserSecurityPolicy();
-
- SecuritySystem system = createMock( SecuritySystem.class );
- UserValidationSettings validationSettings = createMock( UserValidationSettings.class );
- expect( system.authenticate( (AuthenticationDataSource) anyObject() ) ).andReturn( session );
- expect( system.getPolicy() ).andReturn( policy ).anyTimes();
- expect( validationSettings.isEmailValidationRequired() ).andReturn( true ).anyTimes();
-
- // Hook-up action to mock objects
- action.securitySystem = system;
- action.setUsername( principal );
-
- replay( system, validationSettings );
-
- String actionResult = action.login();
-
- verify( system, validationSettings );
-
- assertEquals( Action.ERROR, actionResult );
- }
-}
+++ /dev/null
-package org.codehaus.plexus.redback.struts2.action.admin;
-
-/*
- * 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.policy.AccountLockedException;
-import org.apache.archiva.redback.policy.MustChangePasswordException;
-import org.apache.archiva.redback.rbac.RBACManager;
-import org.apache.archiva.redback.rbac.RbacObjectInvalidException;
-import org.apache.archiva.redback.role.RoleManager;
-import org.apache.archiva.redback.users.UserManager;
-import org.apache.struts2.StrutsSpringTestCase;
-import org.apache.archiva.redback.authentication.AuthenticationException;
-import org.apache.archiva.redback.authentication.PasswordBasedAuthenticationDataSource;
-import org.apache.archiva.redback.rbac.RbacManagerException;
-import org.apache.archiva.redback.rbac.UserAssignment;
-import org.codehaus.plexus.redback.struts2.action.AbstractUserCredentialsAction;
-import org.apache.archiva.redback.system.SecuritySession;
-import org.apache.archiva.redback.system.SecuritySystem;
-import org.apache.archiva.redback.system.SecuritySystemConstants;
-import org.apache.archiva.redback.users.User;
-import org.apache.archiva.redback.users.UserNotFoundException;
-import org.apache.archiva.redback.users.memory.SimpleUser;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.runner.RunWith;
-import org.junit.runners.JUnit4;
-
-import java.util.Collections;
-
-@RunWith( JUnit4.class )
-public abstract class AbstractUserCredentialsActionTest
- extends StrutsSpringTestCase
-{
- protected static final String PASSWORD = "password1";
-
- //@Inject
- //@Named( value = "rBACManager#memory" )
- protected RBACManager rbacManager;
-
- //@Inject
- private RoleManager roleManager;
-
- //@Inject
- protected SecuritySystem system;
-
- protected SecuritySession session;
-
- @Override
- protected String[] getContextLocations()
- {
- return new String[]{ "classpath*:/META-INF/spring-context.xml", "classpath*:/spring-context.xml" };
- }
-
- @Before
- public void setUp()
- throws Exception
- {
- CacheManager.getInstance().clearAll();
- super.setUp();
-
- rbacManager = applicationContext.getBean( "rBACManager#memory" , RBACManager.class );
- roleManager = applicationContext.getBean( RoleManager.class );
- system = applicationContext.getBean( SecuritySystem.class );
-
-
- roleManager.loadRoleModel( getClass().getResource( "/redback.xml" ) );
- roleManager.createTemplatedRole( "project-administrator", "default" );
- roleManager.createTemplatedRole( "project-administrator", "other" );
- roleManager.createTemplatedRole( "project-grant-only", "default" );
-
- UserManager userManager = system.getUserManager();
-
- User user = new SimpleUser();
- user.setUsername( "user" );
- user.setPassword( PASSWORD );
- userManager.addUserUnchecked( user );
-
- user = new SimpleUser();
- user.setUsername( "user2" );
- user.setPassword( PASSWORD );
- userManager.addUserUnchecked( user );
-
- user = new SimpleUser();
- user.setUsername( "user3" );
- user.setPassword( PASSWORD );
- userManager.addUserUnchecked( user );
-
- user = new SimpleUser();
- user.setUsername( "admin" );
- user.setPassword( PASSWORD );
- userManager.addUserUnchecked( user );
-
- user = new SimpleUser();
- user.setUsername( "user-admin" );
- user.setPassword( PASSWORD );
- userManager.addUserUnchecked( user );
-
- UserAssignment assignment = rbacManager.createUserAssignment( "admin" );
- assignment.addRoleName( "System Administrator" );
- rbacManager.saveUserAssignment( assignment );
-
- assignment = rbacManager.createUserAssignment( "user-admin" );
- assignment.addRoleName( "User Administrator" );
- rbacManager.saveUserAssignment( assignment );
-
- assignment = rbacManager.createUserAssignment( "user2" );
- rbacManager.saveUserAssignment( assignment );
- }
-
- @After
- public void after()
- {
- CacheManager.getInstance().clearAll();
- }
-
- protected void addAssignment( String principal, String roleName )
- throws RbacManagerException, RbacObjectInvalidException
- {
- UserAssignment assignment;
-
- if ( rbacManager.userAssignmentExists( principal ) )
- {
- assignment = rbacManager.getUserAssignment( principal );
- }
- else
- {
- assignment = rbacManager.createUserAssignment( principal );
- }
- assignment.addRoleName( roleName );
- rbacManager.saveUserAssignment( assignment );
- }
-
- protected void login( AbstractUserCredentialsAction action, String principal, String password )
- throws AuthenticationException, UserNotFoundException, AccountLockedException, MustChangePasswordException
- {
- PasswordBasedAuthenticationDataSource authdatasource = new PasswordBasedAuthenticationDataSource();
- authdatasource.setPrincipal( principal );
- authdatasource.setPassword( password );
- session = system.authenticate( authdatasource );
- assertTrue( session.isAuthenticated() );
-
- action.setSession( Collections.singletonMap( SecuritySystemConstants.SECURITY_SESSION_KEY, (Object) session ) );
- }
-
-}
\ No newline at end of file
+++ /dev/null
-package org.codehaus.plexus.redback.struts2.action.admin;
-
-/*
- * 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 com.google.common.collect.Lists;
-import com.opensymphony.xwork2.Action;
-import com.opensymphony.xwork2.ActionProxy;
-import org.apache.archiva.redback.authentication.AuthenticationException;
-import org.apache.archiva.redback.rbac.RbacObjectInvalidException;
-import org.apache.archiva.redback.rbac.Role;
-import org.apache.archiva.redback.users.UserNotFoundException;
-import org.apache.archiva.redback.authorization.AuthorizationResult;
-import org.apache.archiva.redback.policy.AccountLockedException;
-import org.apache.archiva.redback.rbac.RbacManagerException;
-import org.codehaus.plexus.redback.struts2.model.ApplicationRoleDetails;
-import org.codehaus.plexus.redback.struts2.model.ApplicationRoleDetails.RoleTableCell;
-import org.apache.archiva.redback.integration.interceptor.SecureActionBundle;
-import org.apache.archiva.redback.integration.interceptor.SecureActionException;
-import org.junit.Before;
-import org.junit.Ignore;
-import org.junit.Test;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-/**
- * @todo missing tests for success/fail on standard show/edit functions (non security testing related)
- */
-public class AssignmentsActionTest
- extends AbstractUserCredentialsActionTest
-{
- private AssignmentsAction action;
-
- @Before
- public void setUp()
- throws Exception
- {
- super.setUp();
-
- ActionProxy actionProxy = getActionProxy( "/security/assignments" );
- action = (AssignmentsAction) actionProxy.getAction();
-
- login( action, "user", PASSWORD );
- action.setPrincipal( "user2" );
-
- }
-
- /**
- * Check security - show/edituser should fail if the permission 'user-management-user-role' is not present, but a
- * valid 'user-management-role-grant' is.
- */
- @Test
- public void testUserWithOnlyRoleGrantHasNoAccess()
- throws Exception
- {
-
- addAssignment( "user", "Grant Administrator - default" );
-
- List<SecureActionBundle.AuthorizationTuple> authorizationTuples = getTuples();
- for ( SecureActionBundle.AuthorizationTuple tuple : authorizationTuples )
- {
- AuthorizationResult authzResult = system.authorize( session, tuple.getOperation(), tuple.getResource() );
-
- assertFalse( authzResult.isAuthorized() );
- }
- }
-
- /**
- * Check security - check success if the permission 'user-management-user-role' is present along with global
- * 'user-management-role-grant'.
- */
- @Test
- public void testUserWithOnlyRoleGrantHasAccess()
- throws Exception
- {
- addAssignment( "user", "Project Administrator - default" );
-
- List<SecureActionBundle.AuthorizationTuple> authorizationTuples = getTuples();
- boolean result = false;
- for ( SecureActionBundle.AuthorizationTuple tuple : authorizationTuples )
- {
- AuthorizationResult authzResult = system.authorize( session, tuple.getOperation(), tuple.getResource() );
-
- result |= authzResult.isAuthorized();
- }
- assertTrue( result );
- }
-
- private List<SecureActionBundle.AuthorizationTuple> getTuples()
- throws SecureActionException
- {
- return action.getSecureActionBundle().getAuthorizationTuples();
- }
-
- /**
- * Check roles can be assigned if the user has no previous assignments.
- */
- @Test
- public void testShowWhenUserHasNoAssignments()
- throws Exception
- {
- addAssignment( "user", "Project Administrator - default" );
-
- action.setPrincipal( "user3" );
-
- assertEquals( Action.SUCCESS, action.show() );
-
- assertEquals( 2, action.getApplicationRoleDetails().size() );
- }
-
- /**
- * Check security - show should filter out roles that the 'user-management-role-grant' is not present for
- */
- @Test
- public void testRoleGrantFilteringOnShow()
- throws Exception
- {
- addAssignment( "user", "Project Administrator - default" );
-
- assertEquals( Action.SUCCESS, action.show() );
-
- assertEquals( 2, action.getApplicationRoleDetails().size() );
- ApplicationRoleDetails details = (ApplicationRoleDetails) action.getApplicationRoleDetails().get( 0 );
- assertEquals( "System", details.getName() );
- assertEquals( "Roles that apply system-wide, across all of the applications", details.getDescription() );
- assertEquals( "found roles " + details.getAvailableRoles(), 0, details.getAvailableRoles().size() );
- details = (ApplicationRoleDetails) action.getApplicationRoleDetails().get( 1 );
- assertEquals( "Continuum", details.getName() );
- assertEquals( "found roles " + details.getAvailableRoles(), 0, details.getAvailableRoles().size() );
-
- // This table rendering code clearly has to go
- List<List<RoleTableCell>> table = details.getTable();
- assertEquals( 1, table.size() );
- assertRow( table, 0, "default", "Project Administrator - default", false );
- }
-
- @SuppressWarnings( "unchecked" )
- private void assertRow( List table, int index, String name, String label, boolean assigned )
- {
- List<RoleTableCell> row = (List<RoleTableCell>) table.get( index );
- assertEquals( name, row.get( 0 ).getName() );
- assertEquals( label, row.get( 1 ).getName() );
- assertEquals( assigned, row.get( 2 ).isAssigned() );
- }
-
- /**
- * Check security - show should not filter out roles if 'user-management-role-grant' is present for the global
- * resource
- */
- // TODO: currently returns all roles - we really want all templated roles
- // public void testRoleGrantFilteringOnShowGlobalGrant()
- // throws RbacObjectInvalidException, RbacManagerException
- // {
- // addAssignment( "user", "Global Grant Administrator" );
- //
- // assertEquals( Action.SUCCESS, action.show() );
- //
- // assertEquals( 2, action.getApplicationRoleDetails().size() );
- // ApplicationRoleDetails details = (ApplicationRoleDetails) action.getApplicationRoleDetails().get( 0 );
- // assertEquals( "redback-xwork-integration-core", details.getName() );
- // assertEquals( 0, details.getAvailableRoles().size() );
- //
- // details = (ApplicationRoleDetails) action.getApplicationRoleDetails().get( 1 );
- // assertEquals( "Continuum", details.getName() );
- // assertEquals( 0, details.getAvailableRoles().size() );
- //
- // List table = details.getTable();
- // assertEquals( 2, table.size() );
- // assertRow( table, 0, "default", "Project Administrator - default", false );
- // assertRow( table, 1, "other", "Project Administrator - other", false );
- // }
-
- /**
- * Check security - edituser should skip adding a role that 'user-management-role-grant' is not present for a
- * non-templated role
- */
- @Test
- public void testRoleGrantFilteringOnAddRolesNotPermittedTemplated()
- throws RbacObjectInvalidException, RbacManagerException
- {
- addAssignment( "user", "Project Administrator - default" );
-
- // set addDSelectedRoles (dynamic --> Resource Roles) and addNDSelectedRoles (non-dynamic --> Available Roles)
- List<String> dSelectedRoles = new ArrayList<String>();
- dSelectedRoles.add( "Project Administrator - other" );
-
- action.setAddDSelectedRoles( dSelectedRoles );
-
- assertTrue( rbacManager.getUserAssignment( "user2" ).getRoleNames().isEmpty() );
-
- assertEquals( Action.SUCCESS, action.edituser() );
-
- assertTrue( rbacManager.getUserAssignment( "user2" ).getRoleNames().isEmpty() );
- }
-
- /**
- * Check security - edituser should skip adding a role that 'user-management-role-grant' is not present for a
- * templated role
- */
- @Test
- public void testRoleGrantFilteringOnAddRolesNotPermittedNotTemplated()
- throws RbacObjectInvalidException, RbacManagerException
- {
- addAssignment( "user", "Project Administrator - default" );
-
- // set addDSelectedRoles (dynamic --> Resource Roles) and addNDSelectedRoles (non-dynamic --> Available Roles)
- List<String> ndSelectedRoles = new ArrayList<String>();
- ndSelectedRoles.add( "Continuum Group Project Administrator" );
-
- action.setAddNDSelectedRoles( ndSelectedRoles );
-
- assertTrue( rbacManager.getUserAssignment( "user2" ).getRoleNames().isEmpty() );
-
- assertEquals( Action.SUCCESS, action.edituser() );
-
- assertTrue( rbacManager.getUserAssignment( "user2" ).getRoleNames().isEmpty() );
- }
-
- /**
- * Check security - edituser should succeed if adding a role that 'user-management-role-grant' is present for
- * untemplated roles
- */
- @Test
- public void testRoleGrantFilteringOnAddRolesPermittedNotTemplated()
- throws RbacObjectInvalidException, RbacManagerException, AccountLockedException, AuthenticationException,
- UserNotFoundException
- {
- addAssignment( "user", "Global Grant Administrator" );
-
- // set addDSelectedRoles (dynamic --> Resource Roles) and addNDSelectedRoles (non-dynamic --> Available Roles)
- List<String> ndSelectedRoles = new ArrayList<String>();
- ndSelectedRoles.add( "Continuum Group Project Administrator" );
-
- action.setAddNDSelectedRoles( ndSelectedRoles );
-
- assertTrue( rbacManager.getUserAssignment( "user2" ).getRoleNames().isEmpty() );
-
- assertEquals( Action.SUCCESS, action.edituser() );
-
- assertEquals( Lists.<String>newArrayList( "Continuum Group Project Administrator" ),
- rbacManager.getUserAssignment( "user2" ).getRoleNames() );
- }
-
- /**
- * Check security - edituser should succeed if adding a role that 'user-management-role-grant' is present for
- * templated roles
- */
- @Ignore
- public void testRoleGrantFilteringOnAddRolesPermittedTemplated()
- throws Exception
- {
-
- rbacManager.removeUserAssignment( "user" );
-
- addAssignment( "user", "Project Administrator - default" );
-
- // set addDSelectedRoles (dynamic --> Resource Roles) and addNDSelectedRoles (non-dynamic --> Available Roles)
- List<String> dSelectedRoles = new ArrayList<String>();
- dSelectedRoles.add( "Project Administrator - default" );
-
- ActionProxy actionProxy = getActionProxy( "/security/assignments" );
- AssignmentsAction newAction = (AssignmentsAction) actionProxy.getAction();
-
- login( newAction, "user", PASSWORD );
-
- newAction.setPrincipal( "user2" );
-
- newAction.setAddDSelectedRoles( dSelectedRoles );
-
- assertTrue( rbacManager.getUserAssignment( "user2" ).getRoleNames().isEmpty() );
-
- assertEquals( Action.SUCCESS, newAction.edituser() );
-
- assertEquals( Arrays.asList( "Project Administrator - default" ),
- rbacManager.getUserAssignment( "user2" ).getRoleNames() );
- }
-
- /**
- * Check security - edituser should succeed if adding a role that 'user-management-role-grant' is present for
- * templated roles
- */
- @Test
- public void testRoleGrantFilteringOnAddRolesPermittedTemplatedExistingRole()
- throws Exception
- {
- addAssignment( "user", "Project Administrator - default" );
-
- // cleanup before next test
- rbacManager.removeUserAssignment( "user2" );
-
- addAssignment( "user2", "Project Administrator - other" );
-
- // set addDSelectedRoles (dynamic --> Resource Roles) and addNDSelectedRoles (non-dynamic --> Available Roles)
- List<String> dSelectedRoles = new ArrayList<String>();
- dSelectedRoles.add( "Project Administrator - default" );
-
- ActionProxy actionProxy = getActionProxy( "/security/assignments" );
- AssignmentsAction newAction = (AssignmentsAction) actionProxy.getAction();
-
- login( newAction, "user2", PASSWORD );
-
- newAction.setPrincipal( "user2" );
-
- newAction.setAddDSelectedRoles( dSelectedRoles );
-
- assertEquals( Arrays.asList( "Project Administrator - other" ),
- rbacManager.getUserAssignment( "user2" ).getRoleNames() );
-
- assertEquals( Action.SUCCESS, newAction.edituser() );
-
- //assertEquals( Arrays.asList( "Project Administrator - default", "Project Administrator - other" ),
- // rbacManager.getUserAssignment( "user2" ).getRoleNames() );
- }
-
- /**
- * Check security - edituser should fail if removing a role that 'user-management-role-grant' is not present for
- * untemplated roles
- */
- @Test
- public void testRoleGrantFilteringOnRemoveRolesNotPermittedNotTemplated()
- throws Exception
- {
-
- rbacManager.removeUserAssignment( "user2" );
-
- addAssignment( "user", "Project Administrator - default" );
-
- addAssignment( "user2", "Continuum Group Project Administrator" );
-
- ActionProxy actionProxy = getActionProxy( "/security/assignments" );
- AssignmentsAction newAction = (AssignmentsAction) actionProxy.getAction();
-
- login( newAction, "user2", PASSWORD );
-
- newAction.setPrincipal( "user2" );
-
- // set addDSelectedRoles (dynamic --> Resource Roles) and addNDSelectedRoles (non-dynamic --> Available Roles)
- List<String> ndSelectedRoles = new ArrayList<String>();
- newAction.setAddNDSelectedRoles( ndSelectedRoles );
-
- assertEquals( Arrays.asList( "Continuum Group Project Administrator" ),
- rbacManager.getUserAssignment( "user2" ).getRoleNames() );
-
- assertEquals( Action.SUCCESS, newAction.edituser() );
-
- assertEquals( Arrays.asList( "Continuum Group Project Administrator" ),
- rbacManager.getUserAssignment( "user2" ).getRoleNames() );
- }
-
- /**
- * Check security - edituser should fail if removing a role that 'user-management-role-grant' is not present for
- * templated roles
- */
- @Ignore
- public void testRoleGrantFilteringOnRemoveRolesNotPermittedTemplated()
- throws Exception
- {
- rbacManager.removeUserAssignment( "user2" );
-
- addAssignment( "user", "Project Administrator - other" );
-
- addAssignment( "user2", "Project Administrator - default" );
-
- // set addDSelectedRoles (dynamic --> Resource Roles) and addNDSelectedRoles (non-dynamic --> Available Roles)
- List<String> dSelectedRoles = new ArrayList<String>();
-
- ActionProxy actionProxy = getActionProxy( "/security/assignments" );
- AssignmentsAction newAction = (AssignmentsAction) actionProxy.getAction();
-
- login( newAction, "user2", PASSWORD );
-
- newAction.setPrincipal( "user2" );
-
- newAction.setAddDSelectedRoles( dSelectedRoles );
-
- assertEquals( Arrays.asList( "Project Administrator - default" ),
- rbacManager.getUserAssignment( "user2" ).getRoleNames() );
-
- assertEquals( Action.SUCCESS, newAction.edituser() );
-
- assertEquals( Arrays.asList( "Project Administrator - default" ),
- rbacManager.getUserAssignment( "user2" ).getRoleNames() );
- }
-
- /**
- * Check security - edituser should succeed if removing a role that 'user-management-role-grant' is present for
- * untemplated roles
- */
- @Test
- public void testRoleGrantFilteringOnRemoveRolesPermittedNotTemplated()
- throws Exception
- {
- addAssignment( "user", "Global Grant Administrator" );
-
- addAssignment( "user2", "Continuum Group Project Administrator" );
-
- // set addDSelectedRoles (dynamic --> Resource Roles) and addNDSelectedRoles (non-dynamic --> Available Roles)
- List<String> ndSelectedRoles = new ArrayList<String>();
- action.setAddNDSelectedRoles( ndSelectedRoles );
-
- assertEquals( Arrays.asList( "Continuum Group Project Administrator" ),
- rbacManager.getUserAssignment( "user2" ).getRoleNames() );
-
- assertEquals( Action.SUCCESS, action.edituser() );
-
- assertTrue( rbacManager.getUserAssignment( "user2" ).getRoleNames().isEmpty() );
- }
-
- /**
- * Check security - edituser should succeed if removing a role that 'user-management-role-grant' is present for
- * templated roles and there is an existing role that is not assignable by the current user.
- */
- @Test
- public void testRoleGrantFilteringOnRemoveRolesPermittedTemplatedExistingRole()
- throws Exception
- {
- addAssignment( "user", "Project Administrator - default" );
-
- rbacManager.removeUserAssignment( "user2" );
-
- addAssignment( "user2", "Project Administrator - default" );
- addAssignment( "user2", "Project Administrator - other" );
- addAssignment( "user2", "Registered User" );
-
- // set addDSelectedRoles (dynamic --> Resource Roles) and addNDSelectedRoles (non-dynamic --> Available Roles)
- List<String> dSelectedRoles = new ArrayList<String>();
- dSelectedRoles.add( "Project Administrator - other" );
- dSelectedRoles.add( "Registered User" );
- action.setAddDSelectedRoles( dSelectedRoles );
-
- assertEquals(
- Arrays.asList( "Project Administrator - default", "Project Administrator - other", "Registered User" ),
- rbacManager.getUserAssignment( "user2" ).getRoleNames() );
-
- assertEquals( Action.SUCCESS, action.edituser() );
-
- // Roles may be out of order, due to removal and subsequent re-add
- List<String> user2roles = rbacManager.getUserAssignment( "user2" ).getRoleNames();
- assertTrue( user2roles.contains( "Project Administrator - other" ) );
- assertTrue( user2roles.contains( "Registered User" ) );
- }
-
- /**
- * Check security - edituser should succeed if removing a role that 'user-management-role-grant' is present for
- * templated roles
- */
- @Test
- public void testRoleGrantFilteringOnRemoveRolesPermittedTemplated()
- throws Exception
- {
- rbacManager.removeUserAssignment( "user2" );
-
- addAssignment( "user", "Project Administrator - default" );
-
- addAssignment( "user2", "Project Administrator - default" );
-
- // set addDSelectedRoles (dynamic --> Resource Roles) and addNDSelectedRoles (non-dynamic --> Available Roles)
- List<String> dSelectedRoles = new ArrayList<String>();
- action.setAddDSelectedRoles( dSelectedRoles );
-
- assertEquals( Arrays.asList( "Project Administrator - default" ),
- rbacManager.getUserAssignment( "user2" ).getRoleNames() );
-
- assertEquals( Action.SUCCESS, action.edituser() );
-
- assertTrue( rbacManager.getUserAssignment( "user2" ).getRoleNames().isEmpty() );
- }
-
- /**
- * Check security - show should succeed and display all roles, even without 'user-management-role-grant' or
- * 'user-management-user-role' for the user administrators.
- *
- * @throws org.apache.archiva.redback.policy.MustChangePasswordException
- */
- @Test
- public void testSystemAdminCanShowRoles()
- throws Exception
- {
-
- login( action, "admin", PASSWORD );
-
- assertEquals( Action.SUCCESS, action.show() );
-
- assertEquals( 2, action.getApplicationRoleDetails().size() );
- ApplicationRoleDetails details = (ApplicationRoleDetails) action.getApplicationRoleDetails().get( 0 );
- assertEquals( "System", details.getName() );
- assertEquals( "Roles that apply system-wide, across all of the applications", details.getDescription() );
- assertEquals( 4, details.getAvailableRoles().size() );
- assertEquals( "Guest", details.getAvailableRoles().get( 0 ) );
- assertEquals( "Registered User", details.getAvailableRoles().get( 1 ) );
- assertEquals( "System Administrator", details.getAvailableRoles().get( 2 ) );
- assertEquals( "User Administrator", details.getAvailableRoles().get( 3 ) );
-
- details = (ApplicationRoleDetails) action.getApplicationRoleDetails().get( 1 );
- assertEquals( "Continuum", details.getName() );
-
- assertEquals( 2, details.getAvailableRoles().size() );
- assertEquals( "Continuum Group Project Administrator", details.getAvailableRoles().get( 0 ) );
- assertEquals( "Global Grant Administrator", details.getAvailableRoles().get( 1 ) );
-
- List<List<RoleTableCell>> table = details.getTable();
- assertEquals( 2, table.size() );
- assertRow( table, 0, "default", "Project Administrator - default", false );
- assertRow( table, 1, "other", "Project Administrator - other", false );
- }
-
- /**
- * Check security - show should succeed and display all roles, even without 'user-management-role-grant' or
- * 'user-management-user-role' for the user administrators.
- */
- @Test
- public void testUserAdminCanShowRoles()
- throws Exception
- {
-
- ActionProxy actionProxy = getActionProxy( "/security/assignments" );
- AssignmentsAction newAction = (AssignmentsAction) actionProxy.getAction();
-
- login( newAction, "user-admin", PASSWORD );
-
- newAction.setPrincipal( "user-admin" );
-
- assertEquals( Action.SUCCESS, newAction.show() );
-
- assertEquals( 2, newAction.getApplicationRoleDetails().size() );
- ApplicationRoleDetails details = (ApplicationRoleDetails) newAction.getApplicationRoleDetails().get( 0 );
- assertEquals( "System", details.getName() );
- assertEquals( "Roles that apply system-wide, across all of the applications", details.getDescription() );
- // TODO assertEquals( 3, details.getAvailableRoles().size() );
- assertEquals( "Guest", details.getAvailableRoles().get( 0 ) );
- assertEquals( "not role Registered User roles : " + details.getAvailableRoles(), "Registered User",
- details.getAvailableRoles().get( 1 ) );
- // TODO: assertEquals( "User Administrator", details.getAvailableRoles().get( 2 ) );
-
- details = newAction.getApplicationRoleDetails().get( 1 );
- assertEquals( "Continuum", details.getName() );
-
- assertEquals( 2, details.getAvailableRoles().size() );
- assertEquals( "Continuum Group Project Administrator", details.getAvailableRoles().get( 0 ) );
- assertEquals( "Global Grant Administrator", details.getAvailableRoles().get( 1 ) );
-
- List<List<RoleTableCell>> table = details.getTable();
- assertEquals( 2, table.size() );
- assertRow( table, 0, "default", "Project Administrator - default", false );
- assertRow( table, 1, "other", "Project Administrator - other", false );
- }
-
- /**
- * Check security - edituser should succeed in adding a role, even without 'user-management-role-grant' or
- * 'user-management-user-role' for the user administrators.
- */
- @Test
- public void testUserAdminCanAddRoles()
- throws Exception
- {
- login( action, "user-admin", PASSWORD );
-
- // set addDSelectedRoles (dynamic --> Resource Roles) and addNDSelectedRoles (non-dynamic --> Available Roles)
- List<String> ndSelectedRoles = new ArrayList<String>();
- ndSelectedRoles.add( "Continuum Group Project Administrator" );
-
- action.setAddNDSelectedRoles( ndSelectedRoles );
-
- // set addDSelectedRoles (dynamic --> Resource Roles) and addNDSelectedRoles (non-dynamic --> Available Roles)
- List<String> dSelectedRoles = new ArrayList<String>();
- dSelectedRoles.add( "Project Administrator - default" );
-
- action.setAddDSelectedRoles( dSelectedRoles );
-
- assertTrue( rbacManager.getUserAssignment( "user2" ).getRoleNames().isEmpty() );
-
- assertEquals( Action.SUCCESS, action.edituser() );
-
- assertEquals( Arrays.asList( "Continuum Group Project Administrator", "Project Administrator - default" ),
- rbacManager.getUserAssignment( "user2" ).getRoleNames() );
- }
-
- /**
- * Check security - edituser should succeed in removing a role, even without 'user-management-role-grant' or
- * 'user-management-user-role' for the user administrators.
- */
- @Test
- public void testUserAdminCanRemoveRoles()
- throws Exception
- {
- login( action, "user-admin", PASSWORD );
-
- rbacManager.removeUserAssignment( "user2" );
-
- addAssignment( "user2", "Continuum Group Project Administrator" );
- addAssignment( "user2", "Project Administrator - default" );
-
- // set addDSelectedRoles (dynamic --> Resource Roles) and addNDSelectedRoles (non-dynamic --> Available Roles)
- List<String> ndSelectedRoles = new ArrayList<String>();
- action.setAddNDSelectedRoles( ndSelectedRoles );
-
- List<String> dSelectedRoles = new ArrayList<String>();
- action.setAddDSelectedRoles( dSelectedRoles );
-
- assertEquals( Arrays.asList( "Continuum Group Project Administrator", "Project Administrator - default" ),
- rbacManager.getUserAssignment( "user2" ).getRoleNames() );
-
- assertEquals( Action.SUCCESS, action.edituser() );
-
- assertTrue( rbacManager.getUserAssignment( "user2" ).getRoleNames().isEmpty() );
- }
-
- /**
- * Check that a configured struts2 redback app only removes roles configured for the app. Without this, redback
- * applications sharing a user database will remove each other's roles on save.
- */
- @Test
- public void testUserAdminCannotRemoveNonAppRoles()
- throws Exception
- {
- login( action, "user-admin", PASSWORD );
-
- // Create a role that isn't configured for apps
- String nonAppRoleName = "Other App Role";
- Role nonAppRole = rbacManager.createRole( nonAppRoleName );
- rbacManager.saveRole( nonAppRole );
-
- rbacManager.removeUserAssignment( "user2" );
-
- addAssignment( "user2", "Continuum Group Project Administrator" );
- addAssignment( "user2", "Project Administrator - default" );
- addAssignment( "user2", nonAppRoleName );
-
- // set addDSelectedRoles (dynamic --> Resource Roles) and addNDSelectedRoles (non-dynamic --> Available Roles)
- List<String> ndSelectedRoles = new ArrayList<String>();
- action.setAddNDSelectedRoles( ndSelectedRoles );
-
- List<String> dSelectedRoles = new ArrayList<String>();
- action.setAddDSelectedRoles( dSelectedRoles );
-
- assertEquals(
- Arrays.asList( "Continuum Group Project Administrator", "Project Administrator - default", nonAppRoleName ),
- rbacManager.getUserAssignment( "user2" ).getRoleNames() );
-
- assertEquals( Action.SUCCESS, action.edituser() );
-
- // All roles except role from other app should be removed.
- List<String> user2roles = rbacManager.getUserAssignment( "user2" ).getRoleNames();
- assertTrue( !user2roles.contains( "Continuum Group Project Administrator" ) );
- assertTrue( !user2roles.contains( "Project Administrator - default" ) );
- assertTrue( user2roles.contains( nonAppRoleName ) );
- }
-}
+++ /dev/null
-package org.codehaus.plexus.redback.struts2.action.admin;
-
-/*
- * 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.struts2.StrutsSpringTestCase;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.JUnit4;
-import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-
-/**
- * SystemInfoActionTest
- *
- * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
- * @version $Id$
- */
-@RunWith( JUnit4.class )
-public class SystemInfoActionTest
- extends StrutsSpringTestCase
-{
- private SystemInfoAction systeminfo;
-
- @Override
- protected String[] getContextLocations()
- {
- return new String[]{ "classpath*:/META-INF/spring-context.xml", "classpath*:/spring-context.xml" };
- }
-
- @Before
- public void setUp()
- throws Exception
- {
- super.setUp();
-
- systeminfo = (SystemInfoAction) getActionProxy( "/security/systeminfo" ).getAction();
-
- //systeminfo = (SystemInfoAction) lookup( "com.opensymphony.xwork2.Action", "redback-sysinfo" );
- }
-
- @Test
- public void testSystemInfoDump()
- {
- String result = systeminfo.show();
- assertNotNull( result );
- assertEquals( "success", result );
- assertNotNull( systeminfo.getDetails() );
- }
-}
+++ /dev/null
-package org.codehaus.plexus.redback.struts2.action.admin;
-
-/*
- * 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 com.opensymphony.xwork2.Action;
-import org.apache.archiva.redback.authentication.AuthenticationException;
-import org.apache.archiva.redback.policy.AccountLockedException;
-import org.apache.archiva.redback.rbac.RbacManagerException;
-import org.apache.archiva.redback.rbac.RbacObjectInvalidException;
-import org.apache.archiva.redback.rbac.Role;
-import org.apache.archiva.redback.users.User;
-import org.apache.archiva.redback.users.UserNotFoundException;
-import org.apache.archiva.redback.authentication.AuthenticationResult;
-import org.apache.archiva.redback.policy.MustChangePasswordException;
-import org.apache.archiva.redback.rbac.RbacObjectNotFoundException;
-import org.apache.archiva.redback.system.DefaultSecuritySession;
-import org.apache.archiva.redback.system.SecuritySession;
-import org.apache.archiva.redback.system.SecuritySystemConstants;
-import org.apache.archiva.redback.users.memory.SimpleUser;
-import org.apache.archiva.redback.integration.model.AdminEditUserCredentials;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Locale;
-import java.util.Map;
-
-/**
- * @todo missing tests for success/fail on standard show/edit functions (non security testing related)
- */
-public class UserEditActionTest
- extends AbstractUserCredentialsActionTest
-{
-
- private Locale originalLocale;
-
- @Before
- public void setUp()
- throws Exception
- {
- super.setUp();
-
- originalLocale = Locale.getDefault();
- Locale.setDefault( Locale.ENGLISH );
- }
-
- @After
- public void tearDown()
- throws Exception
- {
- try
- {
- super.tearDown();
- }
- finally
- {
- Locale.setDefault( originalLocale == null ? Locale.ENGLISH : originalLocale );
- }
- }
-
- @Test
- public void testEditPageShowsAdministratableRoles()
- throws RbacObjectInvalidException, RbacManagerException, AccountLockedException, AuthenticationException,
- UserNotFoundException, MustChangePasswordException
- {
-
- rbacManager.removeUserAssignment( "user2" );
-
- addAssignment( "user", "User Administrator" );
-
- addAssignment( "user2", "Project Administrator - default" );
- addAssignment( "user2", "Project Administrator - other" );
-
- UserEditAction action = (UserEditAction) getActionProxy( "/security/useredit" ).getAction();
- login( action, "user2", PASSWORD );
- action.setUsername( "user2" );
- assertEquals( Action.INPUT, action.edit() );
-
- List<Role> effectivelyAssignedRoles = action.getEffectivelyAssignedRoles();
- assertEquals( 2, effectivelyAssignedRoles.size() );
- Role r = effectivelyAssignedRoles.get( 0 );
- assertEquals( "Project Administrator - default", r.getName() );
- r = effectivelyAssignedRoles.get( 1 );
- assertEquals( "Project Administrator - other", r.getName() );
- assertFalse( action.isHasHiddenRoles() );
-
- rbacManager.removeUserAssignment( "user2" );
- }
-
- @Test
- public void testEditPageHidesUnadministratableRoles()
- throws Exception
- {
- // REDBACK-29
- // user should not be able to see the other project admin role of user2, but should be able to see the one
- // from their own group
-
- rbacManager.removeUserAssignment( "user" );
- rbacManager.removeUserAssignment( "user2" );
-
- addAssignment( "user", "Project Administrator - default" );
- addAssignment( "user", "User Administrator" );
- addAssignment( "user", "Grant Administrator" );
-
- addAssignment( "user2", "Project Administrator - default" );
- addAssignment( "user2", "Project Administrator - other" );
-
- UserEditAction action = (UserEditAction) getActionProxy( "/security/useredit" ).getAction();
- login( action, "user", PASSWORD );
-
- action.setUsername( "user2" );
- assertEquals( Action.INPUT, action.edit() );
-
- List<Role> effectivelyAssignedRoles = action.getEffectivelyAssignedRoles();
- assertEquals( 2, effectivelyAssignedRoles.size() );
- Role r = effectivelyAssignedRoles.get( 0 );
- assertEquals( "Project Administrator - default", r.getName() );
- //assertTrue( action.isHasHiddenRoles() );
-
- rbacManager.removeUserAssignment( "user" );
- rbacManager.removeUserAssignment( "user2" );
- }
-
- @Test
- public void testEditPageHidesUnassignableRoles()
- throws RbacObjectInvalidException, RbacManagerException, AccountLockedException, AuthenticationException,
- UserNotFoundException, MustChangePasswordException
- {
- // REDBACK-201
- // user should not be able to see the unassignable roles
-
- try
- {
- if ( rbacManager.getUserAssignment( "user" ) != null )
- {
- rbacManager.removeUserAssignment( "user" );
- }
- }
- catch ( RbacObjectNotFoundException e )
- {
- // ignore
- }
-
- addAssignment( "user", "User Administrator" );
-
- UserEditAction action = (UserEditAction) getActionProxy( "/security/useredit" ).getAction();
- login( action, "user", PASSWORD );
-
- action.setUsername( "user" );
- assertEquals( Action.INPUT, action.edit() );
-
- List<Role> effectivelyAssignedRoles = action.getEffectivelyAssignedRoles();
- assertEquals( 1, effectivelyAssignedRoles.size() );
- Role r = effectivelyAssignedRoles.get( 0 );
- assertEquals( "User Administrator", r.getName() );
- assertFalse( action.isHasHiddenRoles() );
-
- rbacManager.removeUserAssignment( "user" );
- }
-
- @Test
- public void testRequireOldPWWhenEditingOwnAccountSuccess()
- throws Exception
- {
- addAssignment( "user", "User Administrator" );
-
- UserEditAction action = (UserEditAction) getActionProxy( "/security/useredit" ).getAction();
- login( action, "user", PASSWORD );
-
- action.setUsername( "user" );
- assertEquals( Action.INPUT, action.edit() );
-
- assertTrue( action.isSelf() );
-
- AdminEditUserCredentials user = action.getUser();
- user.setEmail( "user@example.com" );
- user.setFullName( "User" );
- action.setOldPassword( PASSWORD );
-
- Map<String, Object> mockSession = new HashMap<String, Object>();
-
- User currentUser = new SimpleUser();
- currentUser.setUsername( "user" );
-
- AuthenticationResult authResult = new AuthenticationResult( true, "user", null );
- SecuritySession securitySession = new DefaultSecuritySession( authResult, currentUser );
-
- mockSession.put( SecuritySystemConstants.SECURITY_SESSION_KEY, securitySession );
- action.setSession( mockSession );
-
- assertEquals( Action.SUCCESS, action.submit() );
-
- assertEquals( 0, action.getFieldErrors().size() );
- }
-
- @Test
- public void testRequireOldPWWhenEditingOwnAccountFailed()
- throws Exception
- {
- addAssignment( "user", "User Administrator" );
-
- UserEditAction action = (UserEditAction) getActionProxy( "/security/useredit" ).getAction();
- login( action, "user", PASSWORD );
-
- action.setUsername( "user" );
- assertEquals( Action.INPUT, action.edit() );
-
- assertTrue( action.isSelf() );
-
- AdminEditUserCredentials user = action.getUser();
- user.setEmail( "user@example.com" );
- user.setFullName( "User" );
- user.setPassword( PASSWORD );
- user.setConfirmPassword( PASSWORD );
-
- action.setOldPassword( "notmatchingoldpassword" );
-
- assertEquals( Action.ERROR, action.submit() );
-
- Map<String, List<String>> fieldErrors = action.getFieldErrors();
- List<String> oldPasswordErrors = fieldErrors.get( "oldPassword" );
-
- assertNotNull( oldPasswordErrors );
- assertEquals( 1, oldPasswordErrors.size() );
-
- assertEquals( action.getText( "password.provided.does.not.match.existing" ), oldPasswordErrors.get( 0 ) );
-
- rbacManager.removeUserAssignment( "user" );
- }
-
- @Test
- public void testRequireOldPWWhenEditingOwnAccountOldPasswordIsNull()
- throws Exception
- {
- addAssignment( "user", "User Administrator" );
-
- UserEditAction action = (UserEditAction) getActionProxy( "/security/useredit" ).getAction();
- login( action, "user", PASSWORD );
-
- action.setUsername( "user" );
- assertEquals( Action.INPUT, action.edit() );
-
- assertTrue( action.isSelf() );
-
- AdminEditUserCredentials user = action.getUser();
- user.setEmail( "user@example.com" );
- user.setFullName( "User" );
- user.setPassword( PASSWORD );
- user.setConfirmPassword( PASSWORD );
-
- action.setOldPassword( null );
-
- assertEquals( Action.ERROR, action.submit() );
-
- Map<String, List<String>> fieldErrors = action.getFieldErrors();
- List<String> oldPasswordErrors = fieldErrors.get( "oldPassword" );
-
- assertNotNull( oldPasswordErrors );
- assertEquals( 1, oldPasswordErrors.size() );
-
- assertEquals( action.getText( "old.password.required" ), oldPasswordErrors.get( 0 ) );
-
- rbacManager.removeUserAssignment( "user" );
-
- }
-
- @Test
- public void testRequireAdminPWWhenEditingOtherAccountPWIncorrect()
- throws Exception
- {
- addAssignment( "user", "User Administrator" );
-
- UserEditAction action = (UserEditAction) getActionProxy( "/security/useredit" ).getAction();
- login( action, "user", PASSWORD );
-
- action.setUsername( "user2" );
-
- assertEquals( Action.INPUT, action.edit() );
-
- assertFalse( action.isSelf() );
-
- AdminEditUserCredentials user = action.getUser();
- user.setEmail( "user2@example.com" );
- user.setFullName( "User2" );
- user.setPassword( PASSWORD );
- user.setConfirmPassword( PASSWORD );
-
- assertEquals( UserEditAction.CONFIRM, action.submit() );
-
- assertFalse( action.isSelf() );
-
- action.setUserAdminPassword( "boguspassword" );
-
- assertEquals( UserEditAction.CONFIRM_ERROR, action.confirmAdminPassword() );
-
- Collection<String> errors = action.getActionErrors();
-
- assertNotNull( errors );
- assertEquals( 1, errors.size() );
-
- assertEquals( action.getText( "user.admin.password.does.not.match.existing" ), errors.iterator().next() );
-
- rbacManager.removeUserAssignment( "user" );
- }
-
- @Test
- public void testRequireAdminPWWhenEditingOtherAccountPWEmpty()
- throws Exception
- {
- addAssignment( "user", "User Administrator" );
-
- UserEditAction action = (UserEditAction) getActionProxy( "/security/useredit" ).getAction();
- login( action, "user", PASSWORD );
-
- action.setUsername( "user2" );
- assertEquals( Action.INPUT, action.edit() );
-
- assertFalse( action.isSelf() );
-
- AdminEditUserCredentials user = action.getUser();
- user.setEmail( "user2@example.com" );
- user.setFullName( "User2" );
- user.setPassword( PASSWORD );
- user.setConfirmPassword( PASSWORD );
-
- action.setUserAdminPassword( "" );
-
- assertEquals( UserEditAction.CONFIRM, action.submit() );
-
- assertFalse( action.isSelf() );
-
- assertEquals( UserEditAction.CONFIRM_ERROR, action.confirmAdminPassword() );
-
- Collection<String> errors = action.getActionErrors();
-
- assertNotNull( errors );
- assertEquals( 1, errors.size() );
-
- assertEquals( action.getText( "user.admin.password.required" ), errors.iterator().next() );
-
- rbacManager.removeUserAssignment( "user" );
- }
-
-}
+++ /dev/null
-package org.codehaus.plexus.redback.struts2.interceptor;
-
-/*
- * 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.junit.Test;
-import org.junit.runner.RunWith;
-import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-
-import javax.inject.Inject;
-import javax.inject.Named;
-
-
-/**
- *
- * @author <a href='mailto:rahul.thakur.xdev@gmail.com'>Rahul Thakur</a>
- * @version $Id$
- */
-@RunWith( SpringJUnit4ClassRunner.class )
-@ContextConfiguration( locations = { "classpath*:/META-INF/spring-context.xml", "classpath*:/spring-context.xml" } )
-public class CustomInterceptorTest
- extends TestCase
-{
-
- @Inject @Named(value = "testCustomInterceptor")
- MockCustomInterceptor component;
-
- /**
- *
- * @throws Exception on errors
- */
- @Test
- public void testLookup()
- throws Exception
- {
- assertNotNull( component );
- }
-}
+++ /dev/null
-package org.codehaus.plexus.redback.struts2.interceptor;
-
-/*
- * 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 <a href='mailto:rahul.thakur.xdev@gmail.com'>Rahul Thakur</a>
- */
-public interface MockComponent
-{
- String ROLE = MockComponent.class.getName();
-
- void displayResult( String result );
-}
+++ /dev/null
-package org.codehaus.plexus.redback.struts2.interceptor;
-
-/*
- * 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.stereotype.Service;
-
-/**
- * @author <a href='mailto:rahul.thakur.xdev@gmail.com'>Rahul Thakur</a>
- * @version $Id$
- */
-@Service
-public class MockComponentImpl
- implements MockComponent
-{
- private String result;
-
- /* (non-Javadoc)
- * @see org.codehaus.plexus.xwork.interceptor.TestComponent#execute()
- */
- public void displayResult( String result )
- {
- this.result = result;
- }
-
- public String getResult()
- {
- return result;
- }
-}
+++ /dev/null
-package org.codehaus.plexus.redback.struts2.interceptor;
-
-/*
- * 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 com.opensymphony.xwork2.ActionInvocation;
-import com.opensymphony.xwork2.interceptor.Interceptor;
-import org.springframework.stereotype.Service;
-
-import javax.inject.Inject;
-
-/**
- * @author <a href='mailto:rahul.thakur.xdev@gmail.com'>Rahul Thakur</a>
- * @version $Id$
- */
-@Service("testCustomInterceptor")
-public class MockCustomInterceptor
- implements Interceptor
-{
- /**
- *
- */
- @Inject
- private MockComponent testComponent;
-
- public MockCustomInterceptor()
- {
- }
-
- public MockCustomInterceptor( MockComponent testComponent )
- {
- this.testComponent = testComponent;
- }
-
- /* (non-Javadoc)
- * @see com.opensymphony.xwork2.interceptor.Interceptor#destroy()
- */
- public void destroy()
- {
- // do nothing
- }
-
- /* (non-Javadoc)
- * @see com.opensymphony.xwork2.interceptor.Interceptor#init()
- */
- public void init()
- {
- // do nothing
- }
-
- /**
- * @noinspection ProhibitedExceptionDeclared
- */
- public String intercept( ActionInvocation invocation )
- throws Exception
- {
- String result = "Hello Custom Interceptor";
-
- testComponent.displayResult( result );
-
- return result;
- }
-
- public MockComponent getTestComponent()
- {
- return testComponent;
- }
-
- // Introduce a Composition Exception , see PLX - 278
- // public void setTestComponent( MockComponent testComponent )
- // {
- // this.testComponent = testComponent;
- // }
-
-}
+++ /dev/null
-package org.codehaus.plexus.redback.struts2.interceptor;
-
-/*
- * 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.codehaus.plexus.redback.struts2.ActionContextStub;
-import org.codehaus.plexus.redback.struts2.ActionInvocationStub;
-import org.codehaus.plexus.redback.struts2.ActionProxyStub;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-
-import java.util.Map;
-
-@RunWith( SpringJUnit4ClassRunner.class )
-@ContextConfiguration( locations = { "classpath*:/META-INF/spring-context.xml", "classpath*:/spring-context.xml" } )
-public class SimpleActionInvocationTrackerTest
- extends TestCase
-{
- private static final int HISTORY_SIZE = 2;
-
- private ActionInvocationTracker tracker;
-
-
-
-
- protected String getPlexusConfigLocation()
- {
- return "plexus.xml";
- }
-
- @Before
- public void setUp()
- throws Exception
- {
- super.setUp();
- tracker = new SimpleActionInvocationTracker();
- }
-
- @Test
- public void testAddActionInvocation()
- throws Exception
- {
- tracker.setHistorySize( HISTORY_SIZE );
-
- tracker.addActionInvocation( new ActionInvocationStub() );
- assertEquals( 1, tracker.getHistoryCount() );
-
- // first entry int the stack
- SavedActionInvocation actionInvocation = tracker.getActionInvocationAt( 0 );
- Map<String,Object> parametersMap = actionInvocation.getParametersMap();
-
- assertEquals( ActionProxyStub.ACTION_NAME, actionInvocation.getActionName() );
- assertEquals( ActionProxyStub.METHOD, actionInvocation.getMethodName() );
- assertEquals( ActionContextStub.VALUE_1, parametersMap.get( ActionContextStub.PARAMETER_1 ) );
- assertEquals( ActionContextStub.VALUE_2, parametersMap.get( ActionContextStub.PARAMETER_2 ) );
- assertEquals( ActionContextStub.VALUE_3, parametersMap.get( ActionContextStub.PARAMETER_3 ) );
-
- ActionInvocationStub actionInvocationStub = new ActionInvocationStub();
-
- ActionProxyStub proxyStub = (ActionProxyStub) actionInvocationStub.getProxy();
- proxyStub.setActionName( "new_action" );
- proxyStub.setMethod( "new_method" );
-
- ActionContextStub actionContextStub = (ActionContextStub) actionInvocationStub.getInvocationContext();
- actionContextStub.getParameters().put( "new_parameter", "new_value" );
-
- tracker.addActionInvocation( actionInvocationStub );
- assertEquals( tracker.getHistoryCount(), HISTORY_SIZE );
-
- // second entry in the stack
- actionInvocation = tracker.getActionInvocationAt( 1 );
- parametersMap = actionInvocation.getParametersMap();
-
- assertEquals( "new_action", actionInvocation.getActionName() );
- assertEquals( "new_method", actionInvocation.getMethodName() );
- assertEquals( ActionContextStub.VALUE_1, parametersMap.get( ActionContextStub.PARAMETER_1 ) );
- assertEquals( ActionContextStub.VALUE_2, parametersMap.get( ActionContextStub.PARAMETER_2 ) );
- assertEquals( ActionContextStub.VALUE_3, parametersMap.get( ActionContextStub.PARAMETER_3 ) );
- assertEquals( "new_value", parametersMap.get( "new_parameter" ) );
-
- // first entry int the stack
- actionInvocation = tracker.getActionInvocationAt( 0 );
- parametersMap = actionInvocation.getParametersMap();
-
- assertEquals( ActionProxyStub.ACTION_NAME, actionInvocation.getActionName() );
- assertEquals( ActionProxyStub.METHOD, actionInvocation.getMethodName() );
- assertEquals( ActionContextStub.VALUE_1, parametersMap.get( ActionContextStub.PARAMETER_1 ) );
- assertEquals( ActionContextStub.VALUE_2, parametersMap.get( ActionContextStub.PARAMETER_2 ) );
- assertEquals( ActionContextStub.VALUE_3, parametersMap.get( ActionContextStub.PARAMETER_3 ) );
- }
-
- @Test
- public void testHistoryCounter()
- throws Exception
- {
- tracker.setHistorySize( HISTORY_SIZE );
- tracker.addActionInvocation( new ActionInvocationStub() );
- assertEquals( 1, tracker.getHistoryCount() );
-
- tracker.setHistorySize( HISTORY_SIZE );
- tracker.addActionInvocation( new ActionInvocationStub() );
- assertEquals( HISTORY_SIZE, tracker.getHistoryCount() );
-
- tracker.addActionInvocation( new ActionInvocationStub() );
- tracker.addActionInvocation( new ActionInvocationStub() );
- tracker.addActionInvocation( new ActionInvocationStub() );
- assertEquals( HISTORY_SIZE, tracker.getHistoryCount() );
-
- tracker.addActionInvocation( new ActionInvocationStub() );
- tracker.addActionInvocation( new ActionInvocationStub() );
- tracker.addActionInvocation( new ActionInvocationStub() );
- assertEquals( HISTORY_SIZE, tracker.getHistoryCount() );
- }
-
-}
+++ /dev/null
-package org.codehaus.plexus.redback.struts2.result;
-
-/*
- * 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.codehaus.plexus.redback.struts2.ActionContextStub;
-import org.codehaus.plexus.redback.struts2.ActionInvocationStub;
-import org.codehaus.plexus.redback.struts2.ActionProxyStub;
-import org.codehaus.plexus.redback.struts2.interceptor.ActionInvocationTracker;
-import org.codehaus.plexus.redback.struts2.interceptor.SimpleActionInvocationTracker;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-
-import java.util.Map;
-
-@RunWith( SpringJUnit4ClassRunner.class )
-@ContextConfiguration( locations = { "classpath*:/META-INF/spring-context.xml", "classpath*:/spring-context.xml" } )
-public class BackTrackingResultTest
- extends TestCase
-{
- public static final int HISTORY_SIZE = 2;
-
- protected String getPlexusConfigLocation()
- {
- return "plexus.xml";
- }
-
- @Test
- public void testBackTrackPrevious()
- throws Exception
- {
- // first http request
- ActionInvocationStub actionInvocation1 = new ActionInvocationStub();
- SimpleBackTrackingResult backtrackingResult = new SimpleBackTrackingResult( actionInvocation1 );
-
- // second http request
- ActionInvocationStub previousActionInvocation = new ActionInvocationStub();
- ActionProxyStub previousProxyStub = (ActionProxyStub) previousActionInvocation.getProxy();
- previousProxyStub.setActionName( "previous_action" );
- previousProxyStub.setMethod( "previous_method" );
-
- ActionContextStub previousActionContext = (ActionContextStub) previousActionInvocation.getInvocationContext();
- previousActionContext.getParameters().put( "previous_parameter", "previous_value" );
-
- // third http request
- ActionInvocationStub currentActionInvocation = new ActionInvocationStub();
- ActionProxyStub currentProxyStub = (ActionProxyStub) currentActionInvocation.getProxy();
- currentProxyStub.setActionName( "current_action" );
- currentProxyStub.setMethod( "current_method" );
-
- ActionContextStub currentActionContext = (ActionContextStub) currentActionInvocation.getInvocationContext();
- currentActionContext.getParameters().put( "current_parameter", "current_value" );
-
- SimpleActionInvocationTracker tracker = new SimpleActionInvocationTracker();
-
- // save the second request and third request to the stack
- tracker.setHistorySize( HISTORY_SIZE );
- tracker.addActionInvocation( previousActionInvocation );
- tracker.addActionInvocation( currentActionInvocation );
- tracker.setBackTrack();
- // add the tracker to the session
- actionInvocation1.getInvocationContext().getSession().put( ActionInvocationTracker.SESSION_KEY, tracker );
-
- // before backtrack
- Map<String,Object> parametersMap = actionInvocation1.getInvocationContext().getParameters();
-
- assertEquals( ActionProxyStub.ACTION_NAME, backtrackingResult.getActionName() );
- assertEquals( ActionProxyStub.METHOD, backtrackingResult.getMethod() );
- assertEquals( ActionContextStub.VALUE_1, parametersMap.get( ActionContextStub.PARAMETER_1 ) );
- assertEquals( ActionContextStub.VALUE_2, parametersMap.get( ActionContextStub.PARAMETER_2 ) );
- assertEquals( ActionContextStub.VALUE_3, parametersMap.get( ActionContextStub.PARAMETER_3 ) );
-
- backtrackingResult.setupBackTrackPrevious( actionInvocation1 );
-
- // after backtrack
- parametersMap = actionInvocation1.getInvocationContext().getParameters();
-
- assertEquals( "previous_action", backtrackingResult.getActionName() );
- assertEquals( "previous_method", backtrackingResult.getMethod() );
- assertEquals( ActionContextStub.VALUE_1, parametersMap.get( ActionContextStub.PARAMETER_1 ) );
- assertEquals( ActionContextStub.VALUE_2, parametersMap.get( ActionContextStub.PARAMETER_2 ) );
- assertEquals( ActionContextStub.VALUE_3, parametersMap.get( ActionContextStub.PARAMETER_3 ) );
- assertEquals( "previous_value", parametersMap.get( "previous_parameter" ) );
-
- }
-
- @SuppressWarnings("unchecked")
- public void testBackTrackCurrent()
- throws Exception
- {
- // first http request
- ActionInvocationStub actionInvocation1 = new ActionInvocationStub();
- SimpleBackTrackingResult backtrackingResult = new SimpleBackTrackingResult( actionInvocation1 );
-
- // second http request
- ActionInvocationStub previousActionInvocation = new ActionInvocationStub();
- ActionProxyStub previousProxyStub = (ActionProxyStub) previousActionInvocation.getProxy();
- previousProxyStub.setActionName( "previous_action" );
- previousProxyStub.setMethod( "previous_method" );
-
- ActionContextStub previousActionContext = (ActionContextStub) previousActionInvocation.getInvocationContext();
- previousActionContext.getParameters().put( "previous_parameter", "previous_value" );
-
- // third http request
- ActionInvocationStub currentActionInvocation = new ActionInvocationStub();
- ActionProxyStub currentProxyStub = (ActionProxyStub) currentActionInvocation.getProxy();
- currentProxyStub.setActionName( "current_action" );
- currentProxyStub.setMethod( "current_method" );
-
- ActionContextStub currentActionContext = (ActionContextStub) currentActionInvocation.getInvocationContext();
- currentActionContext.getParameters().put( "current_parameter", "current_value" );
-
- SimpleActionInvocationTracker tracker = new SimpleActionInvocationTracker();
-
- // save the second request and third request to the stack
- tracker.setHistorySize( HISTORY_SIZE );
- tracker.addActionInvocation( previousActionInvocation );
- tracker.addActionInvocation( currentActionInvocation );
- tracker.setBackTrack();
- // add the tracker to the session
- actionInvocation1.getInvocationContext().getSession().put( ActionInvocationTracker.SESSION_KEY, tracker );
-
- // before backtrack
- Map<String, Object> parametersMap = actionInvocation1.getInvocationContext().getParameters();
-
- assertEquals( ActionProxyStub.ACTION_NAME, backtrackingResult.getActionName() );
- assertEquals( ActionProxyStub.METHOD, backtrackingResult.getMethod() );
- assertEquals( ActionContextStub.VALUE_1, parametersMap.get( ActionContextStub.PARAMETER_1 ) );
- assertEquals( ActionContextStub.VALUE_2, parametersMap.get( ActionContextStub.PARAMETER_2 ) );
- assertEquals( ActionContextStub.VALUE_3, parametersMap.get( ActionContextStub.PARAMETER_3 ) );
-
- backtrackingResult.setupBackTrackCurrent( actionInvocation1 );
-
- // after backtrack
- assertEquals( "current_action", backtrackingResult.getActionName() );
- assertEquals( "current_method", backtrackingResult.getMethod() );
- assertEquals( ActionContextStub.VALUE_1, parametersMap.get( ActionContextStub.PARAMETER_1 ) );
- assertEquals( ActionContextStub.VALUE_2, parametersMap.get( ActionContextStub.PARAMETER_2 ) );
- assertEquals( ActionContextStub.VALUE_3, parametersMap.get( ActionContextStub.PARAMETER_3 ) );
- assertEquals( "current_value", parametersMap.get( "current_parameter" ) );
- }
-}
+++ /dev/null
-package org.codehaus.plexus.redback.struts2.result;
-
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-import org.codehaus.plexus.redback.struts2.ActionInvocationStub;
-
-public class SimpleBackTrackingResult
- extends AbstractBackTrackingResult
-{
- public SimpleBackTrackingResult( ActionInvocationStub invocation )
- {
- super.actionName = invocation.getProxy().getActionName();
- super.method = invocation.getProxy().getMethod();
- }
-
- public String getActionName()
- {
- return super.actionName;
- }
-
- public String getMethod()
- {
- return super.method;
- }
-}
--- /dev/null
+jdbc.url=jdbc:hsqldb:mem:UnitTests
+#
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+# --------------------------------------------------------------------
+# Application Configuration
+
+application.timestamp=EEE d MMM yyyy HH:mm:ss Z
+
+# --------------------------------------------------------------------
+# JDBC Setup
+
+jdbc.driver.name=org.hsqldb.jdbcDriver
+jdbc.username=sa
+jdbc.password=
+
+# --------------------------------------------------------------------
+# Email Settings
+
+email.jndiSessionName=java:comp/env/mail/Session
+email.smtp.host=localhost
+email.smtp.port=25
+email.smtp.ssl.enabled=false
+email.smtp.tls.enabled=false
+email.smtp.username=
+email.smtp.password=
+
+#TODO: move description elsewhere, remove bad default
+# All emails sent by the system will be from the following address
+#email.from.address=${user.name}@localhost
+# All emails sent by the system will be from the following user name (used in conjunction with address)
+#email.from.name=Unconfigured Username
+
+# If all email addresses (from new user registration) require an account validation email.
+email.validation.required=true
+# Timeout (in minutes) for the key generated for an email validation to remain valid.
+# 2880 minutes = 48 hours
+email.validation.timeout=2880
+# The subject line for the email message.
+email.validation.subject=Welcome
+
+#TODO: move description elsewhere, remove bad default
+# Get the Feedback to use for any outgoing emails.
+# NOTE: if feedback.path starts with a "/" it is appended to the end of the value provided in application.url
+# This value can be in the format/syntax of "/feedback.action" or even "mailto:feedback@application.com"
+#email.feedback.path=/feedback.action
+
+#Set the application base URL. The default is to derive it from the HTTP request
+#application.url=http://myurl.mycompany.com
+
+# --------------------------------------------------------------------
+# Auto Login Settings
+
+security.rememberme.enabled=true
+# Timeout in minutes ( 525600 minutes = 1 year )
+security.rememberme.timeout=525600
+
+# Single Sign On
+# Timeout in minutes
+security.signon.timeout=30
+
+# --------------------------------------------------------------------
+# Default Username Values
+redback.default.admin=admin
+
+# --------------------------------------------------------------------
+# Security Policies
+
+#security.policy.password.encoder=
+security.policy.password.previous.count=6
+security.policy.password.expiration.enabled=true
+security.policy.password.expiration.days=90
+security.policy.password.expiration.notify.days=10
+security.policy.allowed.login.attempt=10
+
+# turn off the perclick enforcement of various security policies, slightly
+# more heavyweight since it will ensure that the User object on each click
+# is up to date
+security.policy.strict.enforcement.enabled=true
+security.policy.strict.force.password.change.enabled=true
+
+# --------------------------------------------------------------------
+# Password Rules
+security.policy.password.rule.alphanumeric.enabled=false
+security.policy.password.rule.alphacount.enabled=true
+security.policy.password.rule.alphacount.minimum=1
+security.policy.password.rule.characterlength.enabled=true
+security.policy.password.rule.characterlength.minimum=1
+security.policy.password.rule.characterlength.maximum=24
+security.policy.password.rule.musthave.enabled=true
+security.policy.password.rule.numericalcount.enabled=true
+security.policy.password.rule.numericalcount.minimum=1
+security.policy.password.rule.reuse.enabled=true
+security.policy.password.rule.nowhitespace.enabled=true
+
+# --------------------------------------------------------------------
+# ldap settings
+#
+ldap.bind.authenticator.enabled=false
+
+# ldap options for configuration via properties file
+#ldap.config.hostname=
+#ldap.config.port=
+#ldap.config.base.dn=
+#ldap.config.context.factory=
+#ldap.config.bind.dn=
+#ldap.config.password=
+#ldap.config.authentication.method=
+
+# config parameter for the ConfigurableUserManager
+user.manager.impl=cached
+
+
+
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ ~ 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.
+ -->
+
+<component-set>
+ <components>
+ <component>
+ <role>org.apache.archiva.redback.rbac.RBACManager</role>
+ <role-hint>cached</role-hint>
+ <implementation>org.apache.archiva.redback.rbac.cached.CachedRbacManager</implementation>
+ <description>CachedRbacManager is a wrapped RBACManager with caching.</description>
+ <requirements>
+ <requirement>
+ <role>org.apache.archiva.redback.rbac.RBACManager</role>
+ <role-hint>memory</role-hint>
+ <field-name>rbacImpl</field-name>
+ </requirement>
+ <requirement>
+ <role>org.codehaus.plexus.cache.Cache</role>
+ <role-hint>operations</role-hint>
+ <field-name>operationsCache</field-name>
+ </requirement>
+ <requirement>
+ <role>org.codehaus.plexus.cache.Cache</role>
+ <role-hint>permissions</role-hint>
+ <field-name>permissionsCache</field-name>
+ </requirement>
+ <requirement>
+ <role>org.codehaus.plexus.cache.Cache</role>
+ <role-hint>resources</role-hint>
+ <field-name>resourcesCache</field-name>
+ </requirement>
+ <requirement>
+ <role>org.codehaus.plexus.cache.Cache</role>
+ <role-hint>roles</role-hint>
+ <field-name>rolesCache</field-name>
+ </requirement>
+ <requirement>
+ <role>org.codehaus.plexus.cache.Cache</role>
+ <role-hint>userAssignments</role-hint>
+ <field-name>userAssignmentsCache</field-name>
+ </requirement>
+ <requirement>
+ <role>org.codehaus.plexus.cache.Cache</role>
+ <role-hint>userPermissions</role-hint>
+ <field-name>userPermissionsCache</field-name>
+ </requirement>
+ <requirement>
+ <role>org.codehaus.plexus.cache.Cache</role>
+ <role-hint>effectiveRoleSet</role-hint>
+ <field-name>effectiveRoleSetCache</field-name>
+ </requirement>
+ </requirements>
+ </component>
+ <component>
+ <role>org.apache.archiva.redback.users.UserManager</role>
+ <role-hint>cached</role-hint>
+ <implementation>org.apache.archiva.redback.users.cached.CachedUserManager</implementation>
+ <description>CachedUserManager</description>
+ <requirements>
+ <requirement>
+ <role>org.apache.archiva.redback.users.UserManager</role>
+ <role-hint>memory</role-hint>
+ <field-name>userImpl</field-name>
+ </requirement>
+ <requirement>
+ <role>org.codehaus.plexus.cache.Cache</role>
+ <role-hint>users</role-hint>
+ <field-name>usersCache</field-name>
+ </requirement>
+ </requirements>
+ </component>
+ <component>
+ <role>org.apache.archiva.redback.keys.KeyManager</role>
+ <role-hint>cached</role-hint>
+ <implementation>org.apache.archiva.redback.keys.cached.CachedKeyManager</implementation>
+ <description>CachedKeyManager</description>
+ <requirements>
+ <requirement>
+ <role>org.apache.archiva.redback.keys.KeyManager</role>
+ <role-hint>memory</role-hint>
+ <field-name>keyImpl</field-name>
+ </requirement>
+ <requirement>
+ <role>org.codehaus.plexus.cache.Cache</role>
+ <role-hint>keys</role-hint>
+ <field-name>keysCache</field-name>
+ </requirement>
+ </requirements>
+ </component>
+
+ <component>
+ <role>org.codehaus.plexus.jdo.JdoFactory</role>
+ <role-hint>users</role-hint>
+ <implementation>org.codehaus.plexus.jdo.DefaultConfigurableJdoFactory</implementation>
+ <configuration>
+ <persistenceManagerFactoryClass>org.jpox.PersistenceManagerFactoryImpl</persistenceManagerFactoryClass>
+ <driverName>org.hsqldb.jdbcDriver</driverName>
+ <url>jdbc:hsqldb:mem:MailGeneratorTest</url>
+ <userName>sa</userName>
+ <otherProperties>
+ <property>
+ <name>javax.jdo.PersistenceManagerFactoryClass</name>
+ <value>org.jpox.PersistenceManagerFactoryImpl</value>
+ </property>
+ <property>
+ <name>org.jpox.autoCreateTables</name>
+ <value>true</value>
+ </property>
+ <property>
+ <name>org.jpox.rdbms.dateTimezone</name>
+ <value>JDK_DEFAULT_TIMEZONE</value>
+ </property>
+
+ </otherProperties>
+ </configuration>
+ </component>
+
+ </components>
+</component-set>
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ ~ 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.
+ -->
+
+<component-set>
+ <components>
+
+ <component>
+ <role>org.codehaus.plexus.jdo.JdoFactory</role>
+ <role-hint>users</role-hint>
+ <implementation>org.codehaus.plexus.jdo.DefaultConfigurableJdoFactory</implementation>
+ <configuration>
+ <!-- Database Configuration -->
+ <driverName>org.hsqldb.jdbcDriver</driverName>
+ <url>jdbc:hsqldb:mem:SystemInfoDB</url>
+ <userName>sa</userName>
+ <password></password>
+ <persistenceManagerFactoryClass>org.jpox.PersistenceManagerFactoryImpl</persistenceManagerFactoryClass>
+
+ <otherProperties>
+ <!-- JPOX and JDO configuration -->
+ <property>
+ <name>org.jpox.autoCreateSchema</name>
+ <value>true</value>
+ </property>
+ <property>
+ <name>org.jpox.autoStartMechanism</name>
+ <value>SchemaTable</value>
+ </property>
+ <property>
+ <name>org.jpox.autoStartMechanismMode</name>
+ <value>Ignored</value>
+ </property>
+ <property>
+ <name>org.jpox.transactionIsolation</name>
+ <value>READ_COMMITTED</value>
+ </property>
+ <property>
+ <name>org.jpox.poid.transactionIsolation</name>
+ <value>READ_COMMITTED</value>
+ </property>
+ <property>
+ <name>org.jpox.rdbms.dateTimezone</name>
+ <value>JDK_DEFAULT_TIMEZONE</value>
+ </property>
+ </otherProperties>
+ </configuration>
+ </component>
+ <component>
+ <role>org.apache.archiva.redback.common.ldap.connection.LdapConnectionFactory</role>
+ <role-hint>configurable</role-hint>
+ <implementation>org.apache.archiva.redback.common.ldap.connection.ConfigurableLdapConnectionFactory</implementation>
+ <description></description>
+ <configuration>
+ <hostname>localhost</hostname>
+ <port>10390</port>
+ <baseDn>dc=redback,dc=plexus,dc=codehaus,dc=org</baseDn>
+ <contextFactory>com.sun.jndi.ldap.LdapCtxFactory</contextFactory>
+ <password>secret</password>
+ <bindDn>uid=admin,ou=system</bindDn>
+ </configuration>
+ <requirements>
+ <requirement>
+ <role>org.apache.archiva.redback.configuration.UserConfiguration</role>
+ <field-name>userConf</field-name>
+ </requirement>
+ </requirements>
+ </component>
+ </components>
+
+</component-set>
\ No newline at end of file
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ ~ 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.
+ -->
+
+<component-set>
+ <components>
+ <component>
+ <role>org.apache.archiva.redback.rbac.RBACManager</role>
+ <role-hint>cached</role-hint>
+ <implementation>org.apache.archiva.redback.rbac.cached.CachedRbacManager</implementation>
+ <description>CachedRbacManager is a wrapped RBACManager with caching.</description>
+ <requirements>
+ <requirement>
+ <role>org.apache.archiva.redback.rbac.RBACManager</role>
+ <role-hint>memory</role-hint>
+ <field-name>rbacImpl</field-name>
+ </requirement>
+ <requirement>
+ <role>org.codehaus.plexus.cache.Cache</role>
+ <role-hint>operations</role-hint>
+ <field-name>operationsCache</field-name>
+ </requirement>
+ <requirement>
+ <role>org.codehaus.plexus.cache.Cache</role>
+ <role-hint>permissions</role-hint>
+ <field-name>permissionsCache</field-name>
+ </requirement>
+ <requirement>
+ <role>org.codehaus.plexus.cache.Cache</role>
+ <role-hint>resources</role-hint>
+ <field-name>resourcesCache</field-name>
+ </requirement>
+ <requirement>
+ <role>org.codehaus.plexus.cache.Cache</role>
+ <role-hint>roles</role-hint>
+ <field-name>rolesCache</field-name>
+ </requirement>
+ <requirement>
+ <role>org.codehaus.plexus.cache.Cache</role>
+ <role-hint>userAssignments</role-hint>
+ <field-name>userAssignmentsCache</field-name>
+ </requirement>
+ <requirement>
+ <role>org.codehaus.plexus.cache.Cache</role>
+ <role-hint>userPermissions</role-hint>
+ <field-name>userPermissionsCache</field-name>
+ </requirement>
+ <requirement>
+ <role>org.codehaus.plexus.cache.Cache</role>
+ <role-hint>effectiveRoleSet</role-hint>
+ <field-name>effectiveRoleSetCache</field-name>
+ </requirement>
+ </requirements>
+ </component>
+ <component>
+ <role>org.apache.archiva.redback.users.UserManager</role>
+ <role-hint>cached</role-hint>
+ <implementation>org.apache.archiva.redback.users.cached.CachedUserManager</implementation>
+ <description>CachedUserManager</description>
+ <requirements>
+ <requirement>
+ <role>org.apache.archiva.redback.users.UserManager</role>
+ <role-hint>memory</role-hint>
+ <field-name>userImpl</field-name>
+ </requirement>
+ <requirement>
+ <role>org.codehaus.plexus.cache.Cache</role>
+ <role-hint>users</role-hint>
+ <field-name>usersCache</field-name>
+ </requirement>
+ </requirements>
+ </component>
+ <component>
+ <role>org.apache.archiva.redback.keys.KeyManager</role>
+ <role-hint>cached</role-hint>
+ <implementation>org.apache.archiva.redback.keys.cached.CachedKeyManager</implementation>
+ <description>CachedKeyManager</description>
+ <requirements>
+ <requirement>
+ <role>org.apache.archiva.redback.keys.KeyManager</role>
+ <role-hint>memory</role-hint>
+ <field-name>keyImpl</field-name>
+ </requirement>
+ <requirement>
+ <role>org.codehaus.plexus.cache.Cache</role>
+ <role-hint>keys</role-hint>
+ <field-name>keysCache</field-name>
+ </requirement>
+ </requirements>
+ </component>
+
+ <component>
+ <role>org.codehaus.plexus.jdo.JdoFactory</role>
+ <role-hint>users</role-hint>
+ <implementation>org.codehaus.plexus.jdo.DefaultConfigurableJdoFactory</implementation>
+ <configuration>
+ <persistenceManagerFactoryClass>org.jpox.PersistenceManagerFactoryImpl</persistenceManagerFactoryClass>
+ <driverName>org.hsqldb.jdbcDriver</driverName>
+ <url>jdbc:hsqldb:mem:MailGeneratorTest</url>
+ <userName>sa</userName>
+ <otherProperties>
+ <property>
+ <name>javax.jdo.PersistenceManagerFactoryClass</name>
+ <value>org.jpox.PersistenceManagerFactoryImpl</value>
+ </property>
+ <property>
+ <name>org.jpox.autoCreateTables</name>
+ <value>true</value>
+ </property>
+ <property>
+ <name>org.jpox.rdbms.dateTimezone</name>
+ <value>JDK_DEFAULT_TIMEZONE</value>
+ </property>
+
+ </otherProperties>
+ </configuration>
+ </component>
+
+ </components>
+</component-set>
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ ~ 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.
+ -->
+
+<component-set>
+ <components>
+ <component>
+ <role>com.opensymphony.xwork2.Action</role>
+ <role-hint>testAction</role-hint>
+ <implementation>org.codehaus.plexus.redback.struts2.action.TestPlexusAction</implementation>
+ </component>
+ <component>
+ <role>com.opensymphony.xwork2.interceptor.Interceptor</role>
+ <role-hint>testCustomInterceptor</role-hint>
+ <implementation>org.apache.archiva.redback.struts2.interceptor.MockCustomInterceptor</implementation>
+ <requirements>
+ <requirement>
+ <role>org.apache.archiva.redback.struts2.interceptor.MockComponent</role>
+ </requirement>
+ </requirements>
+ </component>
+ <component>
+ <role>org.apache.archiva.redback.struts2.interceptor.MockComponent</role>
+ <implementation>org.apache.archiva.redback.struts2.interceptor.MockComponentImpl</implementation>
+ </component>
+ <component>
+ <role>org.codehaus.plexus.jdo.JdoFactory</role>
+ <role-hint>users</role-hint>
+ <implementation>org.codehaus.plexus.jdo.DefaultConfigurableJdoFactory</implementation>
+ <configuration>
+ <persistenceManagerFactoryClass>org.jpox.PersistenceManagerFactoryImpl</persistenceManagerFactoryClass>
+ <driverName>org.hsqldb.jdbcDriver</driverName>
+ <url>jdbc:hsqldb:mem:MailGeneratorTest</url>
+ <userName>sa</userName>
+ <otherProperties>
+ <property>
+ <name>org.jpox.rdbms.dateTimezone</name>
+ <value>JDK_DEFAULT_TIMEZONE</value>
+ </property>
+
+ </otherProperties>
+ </configuration>
+ </component>
+ </components>
+</component-set>
+++ /dev/null
-jdbc.url=jdbc:hsqldb:mem:UnitTests
-#
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-# --------------------------------------------------------------------
-# Application Configuration
-
-application.timestamp=EEE d MMM yyyy HH:mm:ss Z
-
-# --------------------------------------------------------------------
-# JDBC Setup
-
-jdbc.driver.name=org.hsqldb.jdbcDriver
-jdbc.username=sa
-jdbc.password=
-
-# --------------------------------------------------------------------
-# Email Settings
-
-email.jndiSessionName=java:comp/env/mail/Session
-email.smtp.host=localhost
-email.smtp.port=25
-email.smtp.ssl.enabled=false
-email.smtp.tls.enabled=false
-email.smtp.username=
-email.smtp.password=
-
-#TODO: move description elsewhere, remove bad default
-# All emails sent by the system will be from the following address
-#email.from.address=${user.name}@localhost
-# All emails sent by the system will be from the following user name (used in conjunction with address)
-#email.from.name=Unconfigured Username
-
-# If all email addresses (from new user registration) require an account validation email.
-email.validation.required=true
-# Timeout (in minutes) for the key generated for an email validation to remain valid.
-# 2880 minutes = 48 hours
-email.validation.timeout=2880
-# The subject line for the email message.
-email.validation.subject=Welcome
-
-#TODO: move description elsewhere, remove bad default
-# Get the Feedback to use for any outgoing emails.
-# NOTE: if feedback.path starts with a "/" it is appended to the end of the value provided in application.url
-# This value can be in the format/syntax of "/feedback.action" or even "mailto:feedback@application.com"
-#email.feedback.path=/feedback.action
-
-#Set the application base URL. The default is to derive it from the HTTP request
-#application.url=http://myurl.mycompany.com
-
-# --------------------------------------------------------------------
-# Auto Login Settings
-
-security.rememberme.enabled=true
-# Timeout in minutes ( 525600 minutes = 1 year )
-security.rememberme.timeout=525600
-
-# Single Sign On
-# Timeout in minutes
-security.signon.timeout=30
-
-# --------------------------------------------------------------------
-# Default Username Values
-redback.default.admin=admin
-
-# --------------------------------------------------------------------
-# Security Policies
-
-#security.policy.password.encoder=
-security.policy.password.previous.count=6
-security.policy.password.expiration.enabled=true
-security.policy.password.expiration.days=90
-security.policy.password.expiration.notify.days=10
-security.policy.allowed.login.attempt=10
-
-# turn off the perclick enforcement of various security policies, slightly
-# more heavyweight since it will ensure that the User object on each click
-# is up to date
-security.policy.strict.enforcement.enabled=true
-security.policy.strict.force.password.change.enabled=true
-
-# --------------------------------------------------------------------
-# Password Rules
-security.policy.password.rule.alphanumeric.enabled=false
-security.policy.password.rule.alphacount.enabled=true
-security.policy.password.rule.alphacount.minimum=1
-security.policy.password.rule.characterlength.enabled=true
-security.policy.password.rule.characterlength.minimum=1
-security.policy.password.rule.characterlength.maximum=24
-security.policy.password.rule.musthave.enabled=true
-security.policy.password.rule.numericalcount.enabled=true
-security.policy.password.rule.numericalcount.minimum=1
-security.policy.password.rule.reuse.enabled=true
-security.policy.password.rule.nowhitespace.enabled=true
-
-# --------------------------------------------------------------------
-# ldap settings
-#
-ldap.bind.authenticator.enabled=false
-
-# ldap options for configuration via properties file
-#ldap.config.hostname=
-#ldap.config.port=
-#ldap.config.base.dn=
-#ldap.config.context.factory=
-#ldap.config.bind.dn=
-#ldap.config.password=
-#ldap.config.authentication.method=
-
-# config parameter for the ConfigurableUserManager
-user.manager.impl=cached
-
-
-
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- ~ 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.
- -->
-
-<component-set>
- <components>
- <component>
- <role>org.apache.archiva.redback.rbac.RBACManager</role>
- <role-hint>cached</role-hint>
- <implementation>org.apache.archiva.redback.rbac.cached.CachedRbacManager</implementation>
- <description>CachedRbacManager is a wrapped RBACManager with caching.</description>
- <requirements>
- <requirement>
- <role>org.apache.archiva.redback.rbac.RBACManager</role>
- <role-hint>memory</role-hint>
- <field-name>rbacImpl</field-name>
- </requirement>
- <requirement>
- <role>org.codehaus.plexus.cache.Cache</role>
- <role-hint>operations</role-hint>
- <field-name>operationsCache</field-name>
- </requirement>
- <requirement>
- <role>org.codehaus.plexus.cache.Cache</role>
- <role-hint>permissions</role-hint>
- <field-name>permissionsCache</field-name>
- </requirement>
- <requirement>
- <role>org.codehaus.plexus.cache.Cache</role>
- <role-hint>resources</role-hint>
- <field-name>resourcesCache</field-name>
- </requirement>
- <requirement>
- <role>org.codehaus.plexus.cache.Cache</role>
- <role-hint>roles</role-hint>
- <field-name>rolesCache</field-name>
- </requirement>
- <requirement>
- <role>org.codehaus.plexus.cache.Cache</role>
- <role-hint>userAssignments</role-hint>
- <field-name>userAssignmentsCache</field-name>
- </requirement>
- <requirement>
- <role>org.codehaus.plexus.cache.Cache</role>
- <role-hint>userPermissions</role-hint>
- <field-name>userPermissionsCache</field-name>
- </requirement>
- <requirement>
- <role>org.codehaus.plexus.cache.Cache</role>
- <role-hint>effectiveRoleSet</role-hint>
- <field-name>effectiveRoleSetCache</field-name>
- </requirement>
- </requirements>
- </component>
- <component>
- <role>org.apache.archiva.redback.users.UserManager</role>
- <role-hint>cached</role-hint>
- <implementation>org.apache.archiva.redback.users.cached.CachedUserManager</implementation>
- <description>CachedUserManager</description>
- <requirements>
- <requirement>
- <role>org.apache.archiva.redback.users.UserManager</role>
- <role-hint>memory</role-hint>
- <field-name>userImpl</field-name>
- </requirement>
- <requirement>
- <role>org.codehaus.plexus.cache.Cache</role>
- <role-hint>users</role-hint>
- <field-name>usersCache</field-name>
- </requirement>
- </requirements>
- </component>
- <component>
- <role>org.apache.archiva.redback.keys.KeyManager</role>
- <role-hint>cached</role-hint>
- <implementation>org.apache.archiva.redback.keys.cached.CachedKeyManager</implementation>
- <description>CachedKeyManager</description>
- <requirements>
- <requirement>
- <role>org.apache.archiva.redback.keys.KeyManager</role>
- <role-hint>memory</role-hint>
- <field-name>keyImpl</field-name>
- </requirement>
- <requirement>
- <role>org.codehaus.plexus.cache.Cache</role>
- <role-hint>keys</role-hint>
- <field-name>keysCache</field-name>
- </requirement>
- </requirements>
- </component>
-
- <component>
- <role>org.codehaus.plexus.jdo.JdoFactory</role>
- <role-hint>users</role-hint>
- <implementation>org.codehaus.plexus.jdo.DefaultConfigurableJdoFactory</implementation>
- <configuration>
- <persistenceManagerFactoryClass>org.jpox.PersistenceManagerFactoryImpl</persistenceManagerFactoryClass>
- <driverName>org.hsqldb.jdbcDriver</driverName>
- <url>jdbc:hsqldb:mem:MailGeneratorTest</url>
- <userName>sa</userName>
- <otherProperties>
- <property>
- <name>javax.jdo.PersistenceManagerFactoryClass</name>
- <value>org.jpox.PersistenceManagerFactoryImpl</value>
- </property>
- <property>
- <name>org.jpox.autoCreateTables</name>
- <value>true</value>
- </property>
- <property>
- <name>org.jpox.rdbms.dateTimezone</name>
- <value>JDK_DEFAULT_TIMEZONE</value>
- </property>
-
- </otherProperties>
- </configuration>
- </component>
-
- </components>
-</component-set>
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- ~ 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.
- -->
-
-<component-set>
- <components>
-
- <component>
- <role>org.codehaus.plexus.jdo.JdoFactory</role>
- <role-hint>users</role-hint>
- <implementation>org.codehaus.plexus.jdo.DefaultConfigurableJdoFactory</implementation>
- <configuration>
- <!-- Database Configuration -->
- <driverName>org.hsqldb.jdbcDriver</driverName>
- <url>jdbc:hsqldb:mem:SystemInfoDB</url>
- <userName>sa</userName>
- <password></password>
- <persistenceManagerFactoryClass>org.jpox.PersistenceManagerFactoryImpl</persistenceManagerFactoryClass>
-
- <otherProperties>
- <!-- JPOX and JDO configuration -->
- <property>
- <name>org.jpox.autoCreateSchema</name>
- <value>true</value>
- </property>
- <property>
- <name>org.jpox.autoStartMechanism</name>
- <value>SchemaTable</value>
- </property>
- <property>
- <name>org.jpox.autoStartMechanismMode</name>
- <value>Ignored</value>
- </property>
- <property>
- <name>org.jpox.transactionIsolation</name>
- <value>READ_COMMITTED</value>
- </property>
- <property>
- <name>org.jpox.poid.transactionIsolation</name>
- <value>READ_COMMITTED</value>
- </property>
- <property>
- <name>org.jpox.rdbms.dateTimezone</name>
- <value>JDK_DEFAULT_TIMEZONE</value>
- </property>
- </otherProperties>
- </configuration>
- </component>
- <component>
- <role>org.apache.archiva.redback.common.ldap.connection.LdapConnectionFactory</role>
- <role-hint>configurable</role-hint>
- <implementation>org.apache.archiva.redback.common.ldap.connection.ConfigurableLdapConnectionFactory</implementation>
- <description></description>
- <configuration>
- <hostname>localhost</hostname>
- <port>10390</port>
- <baseDn>dc=redback,dc=plexus,dc=codehaus,dc=org</baseDn>
- <contextFactory>com.sun.jndi.ldap.LdapCtxFactory</contextFactory>
- <password>secret</password>
- <bindDn>uid=admin,ou=system</bindDn>
- </configuration>
- <requirements>
- <requirement>
- <role>org.apache.archiva.redback.configuration.UserConfiguration</role>
- <field-name>userConf</field-name>
- </requirement>
- </requirements>
- </component>
- </components>
-
-</component-set>
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- ~ 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.
- -->
-
-<component-set>
- <components>
- <component>
- <role>org.apache.archiva.redback.rbac.RBACManager</role>
- <role-hint>cached</role-hint>
- <implementation>org.apache.archiva.redback.rbac.cached.CachedRbacManager</implementation>
- <description>CachedRbacManager is a wrapped RBACManager with caching.</description>
- <requirements>
- <requirement>
- <role>org.apache.archiva.redback.rbac.RBACManager</role>
- <role-hint>memory</role-hint>
- <field-name>rbacImpl</field-name>
- </requirement>
- <requirement>
- <role>org.codehaus.plexus.cache.Cache</role>
- <role-hint>operations</role-hint>
- <field-name>operationsCache</field-name>
- </requirement>
- <requirement>
- <role>org.codehaus.plexus.cache.Cache</role>
- <role-hint>permissions</role-hint>
- <field-name>permissionsCache</field-name>
- </requirement>
- <requirement>
- <role>org.codehaus.plexus.cache.Cache</role>
- <role-hint>resources</role-hint>
- <field-name>resourcesCache</field-name>
- </requirement>
- <requirement>
- <role>org.codehaus.plexus.cache.Cache</role>
- <role-hint>roles</role-hint>
- <field-name>rolesCache</field-name>
- </requirement>
- <requirement>
- <role>org.codehaus.plexus.cache.Cache</role>
- <role-hint>userAssignments</role-hint>
- <field-name>userAssignmentsCache</field-name>
- </requirement>
- <requirement>
- <role>org.codehaus.plexus.cache.Cache</role>
- <role-hint>userPermissions</role-hint>
- <field-name>userPermissionsCache</field-name>
- </requirement>
- <requirement>
- <role>org.codehaus.plexus.cache.Cache</role>
- <role-hint>effectiveRoleSet</role-hint>
- <field-name>effectiveRoleSetCache</field-name>
- </requirement>
- </requirements>
- </component>
- <component>
- <role>org.apache.archiva.redback.users.UserManager</role>
- <role-hint>cached</role-hint>
- <implementation>org.apache.archiva.redback.users.cached.CachedUserManager</implementation>
- <description>CachedUserManager</description>
- <requirements>
- <requirement>
- <role>org.apache.archiva.redback.users.UserManager</role>
- <role-hint>memory</role-hint>
- <field-name>userImpl</field-name>
- </requirement>
- <requirement>
- <role>org.codehaus.plexus.cache.Cache</role>
- <role-hint>users</role-hint>
- <field-name>usersCache</field-name>
- </requirement>
- </requirements>
- </component>
- <component>
- <role>org.apache.archiva.redback.keys.KeyManager</role>
- <role-hint>cached</role-hint>
- <implementation>org.apache.archiva.redback.keys.cached.CachedKeyManager</implementation>
- <description>CachedKeyManager</description>
- <requirements>
- <requirement>
- <role>org.apache.archiva.redback.keys.KeyManager</role>
- <role-hint>memory</role-hint>
- <field-name>keyImpl</field-name>
- </requirement>
- <requirement>
- <role>org.codehaus.plexus.cache.Cache</role>
- <role-hint>keys</role-hint>
- <field-name>keysCache</field-name>
- </requirement>
- </requirements>
- </component>
-
- <component>
- <role>org.codehaus.plexus.jdo.JdoFactory</role>
- <role-hint>users</role-hint>
- <implementation>org.codehaus.plexus.jdo.DefaultConfigurableJdoFactory</implementation>
- <configuration>
- <persistenceManagerFactoryClass>org.jpox.PersistenceManagerFactoryImpl</persistenceManagerFactoryClass>
- <driverName>org.hsqldb.jdbcDriver</driverName>
- <url>jdbc:hsqldb:mem:MailGeneratorTest</url>
- <userName>sa</userName>
- <otherProperties>
- <property>
- <name>javax.jdo.PersistenceManagerFactoryClass</name>
- <value>org.jpox.PersistenceManagerFactoryImpl</value>
- </property>
- <property>
- <name>org.jpox.autoCreateTables</name>
- <value>true</value>
- </property>
- <property>
- <name>org.jpox.rdbms.dateTimezone</name>
- <value>JDK_DEFAULT_TIMEZONE</value>
- </property>
-
- </otherProperties>
- </configuration>
- </component>
-
- </components>
-</component-set>
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- ~ 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.
- -->
-
-<component-set>
- <components>
- <component>
- <role>com.opensymphony.xwork2.Action</role>
- <role-hint>testAction</role-hint>
- <implementation>org.codehaus.plexus.redback.struts2.action.TestPlexusAction</implementation>
- </component>
- <component>
- <role>com.opensymphony.xwork2.interceptor.Interceptor</role>
- <role-hint>testCustomInterceptor</role-hint>
- <implementation>org.codehaus.plexus.redback.struts2.interceptor.MockCustomInterceptor</implementation>
- <requirements>
- <requirement>
- <role>org.codehaus.plexus.redback.struts2.interceptor.MockComponent</role>
- </requirement>
- </requirements>
- </component>
- <component>
- <role>org.codehaus.plexus.redback.struts2.interceptor.MockComponent</role>
- <implementation>org.codehaus.plexus.redback.struts2.interceptor.MockComponentImpl</implementation>
- </component>
- <component>
- <role>org.codehaus.plexus.jdo.JdoFactory</role>
- <role-hint>users</role-hint>
- <implementation>org.codehaus.plexus.jdo.DefaultConfigurableJdoFactory</implementation>
- <configuration>
- <persistenceManagerFactoryClass>org.jpox.PersistenceManagerFactoryImpl</persistenceManagerFactoryClass>
- <driverName>org.hsqldb.jdbcDriver</driverName>
- <url>jdbc:hsqldb:mem:MailGeneratorTest</url>
- <userName>sa</userName>
- <otherProperties>
- <property>
- <name>org.jpox.rdbms.dateTimezone</name>
- <value>JDK_DEFAULT_TIMEZONE</value>
- </property>
-
- </otherProperties>
- </configuration>
- </component>
- </components>
-</component-set>