[New] New PrivilegeModelException sub class of PrivilegeException for REST

This commit is contained in:
Robert von Burg 2019-03-07 14:27:42 +01:00
parent 349dcce6f7
commit 5520180254
6 changed files with 122 additions and 58 deletions

View File

@ -44,6 +44,7 @@ import li.strolch.model.timedstate.StrolchTimedState;
import li.strolch.model.timevalue.IValue; import li.strolch.model.timevalue.IValue;
import li.strolch.privilege.base.AccessDeniedException; import li.strolch.privilege.base.AccessDeniedException;
import li.strolch.privilege.base.PrivilegeException; import li.strolch.privilege.base.PrivilegeException;
import li.strolch.privilege.base.PrivilegeModelException;
import li.strolch.privilege.model.Certificate; import li.strolch.privilege.model.Certificate;
import li.strolch.privilege.model.PrivilegeContext; import li.strolch.privilege.model.PrivilegeContext;
import li.strolch.runtime.StrolchConstants; import li.strolch.runtime.StrolchConstants;
@ -350,6 +351,8 @@ public abstract class AbstractTransaction implements StrolchTransaction {
private void assertQueryAllowed(StrolchQuery query) { private void assertQueryAllowed(StrolchQuery query) {
try { try {
getPrivilegeContext().validateAction(query); getPrivilegeContext().validateAction(query);
} catch (PrivilegeModelException e) {
throw e;
} catch (PrivilegeException e) { } catch (PrivilegeException e) {
throw new StrolchAccessDeniedException(this.certificate, query, ExceptionHelper.getExceptionMessage(e), e); throw new StrolchAccessDeniedException(this.certificate, query, ExceptionHelper.getExceptionMessage(e), e);
} }

View File

@ -8,6 +8,7 @@ import li.strolch.model.StrolchModelConstants;
import li.strolch.model.StrolchRootElement; import li.strolch.model.StrolchRootElement;
import li.strolch.persistence.api.StrolchTransaction; import li.strolch.persistence.api.StrolchTransaction;
import li.strolch.privilege.base.PrivilegeException; import li.strolch.privilege.base.PrivilegeException;
import li.strolch.privilege.base.PrivilegeModelException;
import li.strolch.privilege.model.Restrictable; import li.strolch.privilege.model.Restrictable;
import li.strolch.utils.dbc.DBC; import li.strolch.utils.dbc.DBC;
import li.strolch.utils.helper.ExceptionHelper; import li.strolch.utils.helper.ExceptionHelper;
@ -85,6 +86,8 @@ public abstract class StrolchSearch<T extends StrolchRootElement>
public RootElementSearchResult<T> search(StrolchTransaction tx) { public RootElementSearchResult<T> search(StrolchTransaction tx) {
try { try {
tx.getPrivilegeContext().validateAction(this); tx.getPrivilegeContext().validateAction(this);
} catch (PrivilegeModelException e) {
throw e;
} catch (PrivilegeException e) { } catch (PrivilegeException e) {
throw new StrolchAccessDeniedException(tx.getCertificate(), this, ExceptionHelper.getExceptionMessage(e), throw new StrolchAccessDeniedException(tx.getCertificate(), this, ExceptionHelper.getExceptionMessage(e),
e); e);

View File

@ -1,12 +1,12 @@
/* /*
* Copyright 2013 Robert von Burg <eitch@eitchnet.ch> * Copyright 2013 Robert von Burg <eitch@eitchnet.ch>
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -22,6 +22,7 @@ import li.strolch.agent.api.StrolchComponent;
import li.strolch.exception.StrolchAccessDeniedException; import li.strolch.exception.StrolchAccessDeniedException;
import li.strolch.exception.StrolchException; import li.strolch.exception.StrolchException;
import li.strolch.privilege.base.PrivilegeException; import li.strolch.privilege.base.PrivilegeException;
import li.strolch.privilege.base.PrivilegeModelException;
import li.strolch.privilege.model.Certificate; import li.strolch.privilege.model.Certificate;
import li.strolch.privilege.model.PrivilegeContext; import li.strolch.privilege.model.PrivilegeContext;
import li.strolch.runtime.configuration.ComponentConfiguration; import li.strolch.runtime.configuration.ComponentConfiguration;
@ -76,8 +77,9 @@ public class DefaultServiceHandler extends StrolchComponent implements ServiceHa
long end = System.nanoTime(); long end = System.nanoTime();
String msg = "User {0}: Service {1} failed after {2} due to {3}"; //$NON-NLS-1$ String msg = "User {0}: Service {1} failed after {2} due to {3}"; //$NON-NLS-1$
msg = MessageFormat.format(msg, username, service.getClass().getName(), msg = MessageFormat
StringHelper.formatNanoDuration(end - start), e.getMessage()); .format(msg, username, service.getClass().getName(), StringHelper.formatNanoDuration(end - start),
e.getMessage());
logger.error(msg); logger.error(msg);
if (!this.throwOnPrivilegeFail && service instanceof AbstractService) { if (!this.throwOnPrivilegeFail && service instanceof AbstractService) {
@ -86,13 +88,18 @@ public class DefaultServiceHandler extends StrolchComponent implements ServiceHa
AbstractService<?, ?> abstractService = (AbstractService<?, ?>) service; AbstractService<?, ?> abstractService = (AbstractService<?, ?>) service;
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
U arg = (U) abstractService.getResultInstance(); U arg = (U) abstractService.getResultInstance();
arg.setState(ServiceResultState.ACCESS_DENIED); arg.setState(e instanceof PrivilegeModelException ?
ServiceResultState.FAILED :
ServiceResultState.ACCESS_DENIED);
arg.setMessage(e.getMessage()); arg.setMessage(e.getMessage());
arg.setThrowable(e); arg.setThrowable(e);
return arg; return arg;
} }
throw new StrolchAccessDeniedException(certificate, service, e.getMessage(), e); if (e instanceof PrivilegeModelException)
throw new StrolchException(e.getMessage(), e);
else
throw new StrolchAccessDeniedException(certificate, service, e.getMessage(), e);
} }
try { try {
@ -118,8 +125,9 @@ public class DefaultServiceHandler extends StrolchComponent implements ServiceHa
} catch (Exception e) { } catch (Exception e) {
long end = System.nanoTime(); long end = System.nanoTime();
String msg = "User {0}: Service failed {1} after {2} due to {3}"; //$NON-NLS-1$ String msg = "User {0}: Service failed {1} after {2} due to {3}"; //$NON-NLS-1$
msg = MessageFormat.format(msg, username, service.getClass().getName(), msg = MessageFormat
StringHelper.formatNanoDuration(end - start), e.getMessage()); .format(msg, username, service.getClass().getName(), StringHelper.formatNanoDuration(end - start),
e.getMessage());
logger.error(msg); logger.error(msg);
throw new StrolchException(msg, e); throw new StrolchException(msg, e);
} }
@ -130,8 +138,8 @@ public class DefaultServiceHandler extends StrolchComponent implements ServiceHa
long end = System.nanoTime(); long end = System.nanoTime();
String msg = "User {0}: Service {1} took {2}"; //$NON-NLS-1$ String msg = "User {0}: Service {1} took {2}"; //$NON-NLS-1$
msg = MessageFormat.format(msg, username, service.getClass().getName(), msg = MessageFormat
StringHelper.formatNanoDuration(end - start)); .format(msg, username, service.getClass().getName(), StringHelper.formatNanoDuration(end - start));
if (serviceResult.getState() == ServiceResultState.SUCCESS) { if (serviceResult.getState() == ServiceResultState.SUCCESS) {
logger.info(msg); logger.info(msg);

View File

@ -0,0 +1,46 @@
/*
* Copyright 2013 Robert von Burg <eitch@eitchnet.ch>
*
* 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.
*/
package li.strolch.privilege.base;
/**
* Main {@link RuntimeException} thrown if something goes wrong in Privilege's model
*
* @author Robert von Burg <eitch@eitchnet.ch>
*/
public class PrivilegeModelException extends PrivilegeException {
/**
* Default constructor
*
* @param string
* message to go with the exception
*/
public PrivilegeModelException(String string) {
super(string);
}
/**
* Constructor with underlying exception
*
* @param string
* message to go with the exception
* @param t
* throwable to wrap with this exception which is the underlying exception of this exception
*/
public PrivilegeModelException(String string, Throwable t) {
super(string, t);
}
}

View File

@ -362,7 +362,7 @@ public class DefaultPrivilegeHandler implements PrivilegeHandler {
// make sure userId is not set // make sure userId is not set
if (StringHelper.isNotEmpty(userRepParam.getUserId())) { if (StringHelper.isNotEmpty(userRepParam.getUserId())) {
String msg = "UserId can not be set when adding a new user!"; String msg = "UserId can not be set when adding a new user!";
throw new PrivilegeException(MessageFormat.format(msg, userRepParam.getUsername())); throw new PrivilegeModelException(MessageFormat.format(msg, userRepParam.getUsername()));
} }
UserRep userRep = userRepParam.clone(); UserRep userRep = userRepParam.clone();
@ -378,7 +378,7 @@ public class DefaultPrivilegeHandler implements PrivilegeHandler {
// validate user does not already exist // validate user does not already exist
if (this.persistenceHandler.getUser(userRep.getUsername()) != null) { if (this.persistenceHandler.getUser(userRep.getUsername()) != null) {
String msg = "User {0} can not be added as it already exists!"; String msg = "User {0} can not be added as it already exists!";
throw new PrivilegeException(MessageFormat.format(msg, userRep.getUsername())); throw new PrivilegeModelException(MessageFormat.format(msg, userRep.getUsername()));
} }
byte[] passwordHash = null; byte[] passwordHash = null;
@ -433,14 +433,14 @@ public class DefaultPrivilegeHandler implements PrivilegeHandler {
User existingUser = this.persistenceHandler.getUser(userRep.getUsername()); User existingUser = this.persistenceHandler.getUser(userRep.getUsername());
if (existingUser == null) { if (existingUser == null) {
String msg = "User {0} can not be replaced as it does not exist!"; String msg = "User {0} can not be replaced as it does not exist!";
throw new PrivilegeException(MessageFormat.format(msg, userRep.getUsername())); throw new PrivilegeModelException(MessageFormat.format(msg, userRep.getUsername()));
} }
// validate same userId // validate same userId
if (!existingUser.getUserId().equals(userRep.getUserId())) { if (!existingUser.getUserId().equals(userRep.getUserId())) {
String msg = "UserId of existing user {0} does not match userRep {1}"; String msg = "UserId of existing user {0} does not match userRep {1}";
msg = MessageFormat.format(msg, existingUser.getUserId(), userRep.getUserId()); msg = MessageFormat.format(msg, existingUser.getUserId(), userRep.getUserId());
throw new PrivilegeException(MessageFormat.format(msg, userRep.getUsername())); throw new PrivilegeModelException(MessageFormat.format(msg, userRep.getUsername()));
} }
byte[] passwordHash = null; byte[] passwordHash = null;
@ -483,7 +483,7 @@ public class DefaultPrivilegeHandler implements PrivilegeHandler {
if (this.persistenceHandler.getRole(role) == null) { if (this.persistenceHandler.getRole(role) == null) {
String msg = "Can not add user {0} as role {1} does not exist!"; String msg = "Can not add user {0} as role {1} does not exist!";
msg = MessageFormat.format(msg, userRep.getUsername(), role); msg = MessageFormat.format(msg, userRep.getUsername(), role);
throw new PrivilegeException(msg); throw new PrivilegeModelException(msg);
} }
} }
} }
@ -513,7 +513,7 @@ public class DefaultPrivilegeHandler implements PrivilegeHandler {
// get existing user // get existing user
User existingUser = this.persistenceHandler.getUser(userRep.getUsername()); User existingUser = this.persistenceHandler.getUser(userRep.getUsername());
if (existingUser == null) { if (existingUser == null) {
throw new PrivilegeException( throw new PrivilegeModelException(
MessageFormat.format("User {0} does not exist!", userRep.getUsername())); //$NON-NLS-1$ MessageFormat.format("User {0} does not exist!", userRep.getUsername())); //$NON-NLS-1$
} }
@ -521,7 +521,7 @@ public class DefaultPrivilegeHandler implements PrivilegeHandler {
if (StringHelper.isEmpty(userRep.getFirstname()) && StringHelper.isEmpty(userRep.getLastname()) if (StringHelper.isEmpty(userRep.getFirstname()) && StringHelper.isEmpty(userRep.getLastname())
&& userRep.getLocale() == null && (userRep.getProperties() == null || userRep.getProperties() && userRep.getLocale() == null && (userRep.getProperties() == null || userRep.getProperties()
.isEmpty())) { .isEmpty())) {
throw new PrivilegeException( throw new PrivilegeModelException(
MessageFormat.format("All updateable fields are empty for update of user {0}", //$NON-NLS-1$ MessageFormat.format("All updateable fields are empty for update of user {0}", //$NON-NLS-1$
userRep.getUsername())); userRep.getUsername()));
} }
@ -588,7 +588,7 @@ public class DefaultPrivilegeHandler implements PrivilegeHandler {
User existingUser = this.persistenceHandler.getUser(username); User existingUser = this.persistenceHandler.getUser(username);
if (existingUser == null) { if (existingUser == null) {
String msg = "Can not remove User {0} because user does not exist!"; String msg = "Can not remove User {0} because user does not exist!";
throw new PrivilegeException(MessageFormat.format(msg, username)); throw new PrivilegeModelException(MessageFormat.format(msg, username));
} }
// validate this user may remove this user // validate this user may remove this user
@ -612,7 +612,7 @@ public class DefaultPrivilegeHandler implements PrivilegeHandler {
// get user // get user
User existingUser = this.persistenceHandler.getUser(username); User existingUser = this.persistenceHandler.getUser(username);
if (existingUser == null) { if (existingUser == null) {
throw new PrivilegeException(MessageFormat.format("User {0} does not exist!", username)); //$NON-NLS-1$ throw new PrivilegeModelException(MessageFormat.format("User {0} does not exist!", username)); //$NON-NLS-1$
} }
// validate that this user may add this role to this user // validate that this user may add this role to this user
@ -622,13 +622,13 @@ public class DefaultPrivilegeHandler implements PrivilegeHandler {
Set<String> currentRoles = existingUser.getRoles(); Set<String> currentRoles = existingUser.getRoles();
if (currentRoles.contains(roleName)) { if (currentRoles.contains(roleName)) {
String msg = MessageFormat.format("User {0} already has role {1}", username, roleName); //$NON-NLS-1$ String msg = MessageFormat.format("User {0} already has role {1}", username, roleName); //$NON-NLS-1$
throw new PrivilegeException(msg); throw new PrivilegeModelException(msg);
} }
// validate that the role exists // validate that the role exists
if (this.persistenceHandler.getRole(roleName) == null) { if (this.persistenceHandler.getRole(roleName) == null) {
String msg = MessageFormat.format("Role {0} does not exist!", roleName); //$NON-NLS-1$ String msg = MessageFormat.format("Role {0} does not exist!", roleName); //$NON-NLS-1$
throw new PrivilegeException(msg); throw new PrivilegeModelException(msg);
} }
// create new user // create new user
@ -664,7 +664,7 @@ public class DefaultPrivilegeHandler implements PrivilegeHandler {
// get User // get User
User existingUser = this.persistenceHandler.getUser(username); User existingUser = this.persistenceHandler.getUser(username);
if (existingUser == null) { if (existingUser == null) {
throw new PrivilegeException(MessageFormat.format("User {0} does not exist!", username)); //$NON-NLS-1$ throw new PrivilegeModelException(MessageFormat.format("User {0} does not exist!", username)); //$NON-NLS-1$
} }
// validate that this user may remove this role from this user // validate that this user may remove this role from this user
@ -676,7 +676,7 @@ public class DefaultPrivilegeHandler implements PrivilegeHandler {
if (!currentRoles.contains(roleName)) { if (!currentRoles.contains(roleName)) {
String msg = MessageFormat String msg = MessageFormat
.format("User {0} does not have role {1}", existingUser.getUsername(), roleName); //$NON-NLS-1$ .format("User {0} does not have role {1}", existingUser.getUsername(), roleName); //$NON-NLS-1$
throw new PrivilegeException(msg); throw new PrivilegeModelException(msg);
} }
// create new user // create new user
@ -708,7 +708,7 @@ public class DefaultPrivilegeHandler implements PrivilegeHandler {
// get User // get User
User existingUser = this.persistenceHandler.getUser(username); User existingUser = this.persistenceHandler.getUser(username);
if (existingUser == null) { if (existingUser == null) {
throw new PrivilegeException(MessageFormat.format("User {0} does not exist!", username)); //$NON-NLS-1$ throw new PrivilegeModelException(MessageFormat.format("User {0} does not exist!", username)); //$NON-NLS-1$
} }
// create new user // create new user
@ -746,7 +746,7 @@ public class DefaultPrivilegeHandler implements PrivilegeHandler {
// get User // get User
User existingUser = this.persistenceHandler.getUser(username); User existingUser = this.persistenceHandler.getUser(username);
if (existingUser == null) { if (existingUser == null) {
throw new PrivilegeException(MessageFormat.format("User {0} does not exist!", username)); //$NON-NLS-1$ throw new PrivilegeModelException(MessageFormat.format("User {0} does not exist!", username)); //$NON-NLS-1$
} }
byte[] passwordHash = null; byte[] passwordHash = null;
@ -805,7 +805,7 @@ public class DefaultPrivilegeHandler implements PrivilegeHandler {
// get User // get User
User existingUser = this.persistenceHandler.getUser(username); User existingUser = this.persistenceHandler.getUser(username);
if (existingUser == null) { if (existingUser == null) {
throw new PrivilegeException(MessageFormat.format("User {0} does not exist!", username)); //$NON-NLS-1$ throw new PrivilegeModelException(MessageFormat.format("User {0} does not exist!", username)); //$NON-NLS-1$
} }
// create new user // create new user
@ -838,7 +838,7 @@ public class DefaultPrivilegeHandler implements PrivilegeHandler {
// validate role does not exist // validate role does not exist
if (this.persistenceHandler.getRole(roleRep.getName()) != null) { if (this.persistenceHandler.getRole(roleRep.getName()) != null) {
String msg = MessageFormat.format("Can not add role {0} as it already exists!", roleRep.getName()); String msg = MessageFormat.format("Can not add role {0} as it already exists!", roleRep.getName());
throw new PrivilegeException(msg); throw new PrivilegeModelException(msg);
} }
// create new role from RoleRep // create new role from RoleRep
@ -872,7 +872,7 @@ public class DefaultPrivilegeHandler implements PrivilegeHandler {
Role existingRole = this.persistenceHandler.getRole(roleRep.getName()); Role existingRole = this.persistenceHandler.getRole(roleRep.getName());
if (existingRole == null) { if (existingRole == null) {
String msg = MessageFormat.format("Can not replace role {0} as it does not exist!", roleRep.getName()); String msg = MessageFormat.format("Can not replace role {0} as it does not exist!", roleRep.getName());
throw new PrivilegeException(msg); throw new PrivilegeModelException(msg);
} }
// create new role from RoleRep // create new role from RoleRep
@ -913,14 +913,14 @@ public class DefaultPrivilegeHandler implements PrivilegeHandler {
String usersS = usersWithRole.stream().map(UserRep::getUsername).collect(Collectors.joining(", ")); String usersS = usersWithRole.stream().map(UserRep::getUsername).collect(Collectors.joining(", "));
String msg = "The role {0} can not be removed as the following {1} user have the role assigned: {2}"; String msg = "The role {0} can not be removed as the following {1} user have the role assigned: {2}";
msg = MessageFormat.format(msg, roleName, usersWithRole.size(), usersS); msg = MessageFormat.format(msg, roleName, usersWithRole.size(), usersS);
throw new PrivilegeException(msg); throw new PrivilegeModelException(msg);
} }
// validate role exists // validate role exists
Role existingRole = this.persistenceHandler.getRole(roleName); Role existingRole = this.persistenceHandler.getRole(roleName);
if (existingRole == null) { if (existingRole == null) {
String msg = "Can not remove Role {0} because role does not exist!"; String msg = "Can not remove Role {0} because role does not exist!";
throw new PrivilegeException(MessageFormat.format(msg, roleName)); throw new PrivilegeModelException(MessageFormat.format(msg, roleName));
} }
// validate that this user may remove this role // validate that this user may remove this role
@ -948,7 +948,7 @@ public class DefaultPrivilegeHandler implements PrivilegeHandler {
Role existingRole = this.persistenceHandler.getRole(roleName); Role existingRole = this.persistenceHandler.getRole(roleName);
if (existingRole == null) { if (existingRole == null) {
String msg = MessageFormat.format("Role {0} does not exist!", roleName); //$NON-NLS-1$ String msg = MessageFormat.format("Role {0} does not exist!", roleName); //$NON-NLS-1$
throw new PrivilegeException(msg); throw new PrivilegeModelException(msg);
} }
// validate that policy exists if needed // validate that policy exists if needed
@ -956,7 +956,7 @@ public class DefaultPrivilegeHandler implements PrivilegeHandler {
if (policy != null && !this.policyMap.containsKey(policy)) { if (policy != null && !this.policyMap.containsKey(policy)) {
String msg = "Policy {0} for Privilege {1} does not exist"; //$NON-NLS-1$ String msg = "Policy {0} for Privilege {1} does not exist"; //$NON-NLS-1$
msg = MessageFormat.format(msg, policy, privilegeRep.getName()); msg = MessageFormat.format(msg, policy, privilegeRep.getName());
throw new PrivilegeException(msg); throw new PrivilegeModelException(msg);
} }
// create new role with the additional privilege // create new role with the additional privilege
@ -1003,14 +1003,14 @@ public class DefaultPrivilegeHandler implements PrivilegeHandler {
// get role // get role
Role existingRole = this.persistenceHandler.getRole(roleName); Role existingRole = this.persistenceHandler.getRole(roleName);
if (existingRole == null) { if (existingRole == null) {
throw new PrivilegeException(MessageFormat.format("Role {0} does not exist!", roleName)); //$NON-NLS-1$ throw new PrivilegeModelException(MessageFormat.format("Role {0} does not exist!", roleName)); //$NON-NLS-1$
} }
// ignore if role does not have privilege // ignore if role does not have privilege
if (!existingRole.hasPrivilege(privilegeName)) { if (!existingRole.hasPrivilege(privilegeName)) {
String msg = MessageFormat String msg = MessageFormat
.format("Role {0} does not have Privilege {1}", roleName, privilegeName); //$NON-NLS-1$ .format("Role {0} does not have Privilege {1}", roleName, privilegeName); //$NON-NLS-1$
throw new PrivilegeException(msg); throw new PrivilegeModelException(msg);
} }
// create new set of privileges with out the to removed privilege // create new set of privileges with out the to removed privilege
@ -1089,7 +1089,7 @@ public class DefaultPrivilegeHandler implements PrivilegeHandler {
// get User // get User
User user = this.persistenceHandler.getUser(username); User user = this.persistenceHandler.getUser(username);
if (user == null) { if (user == null) {
throw new PrivilegeException(MessageFormat.format("User {0} does not exist!", username)); //$NON-NLS-1$ throw new PrivilegeModelException(MessageFormat.format("User {0} does not exist!", username)); //$NON-NLS-1$
} }
// initiate the challenge // initiate the challenge
@ -1104,7 +1104,7 @@ public class DefaultPrivilegeHandler implements PrivilegeHandler {
// get User // get User
User user = this.persistenceHandler.getUser(username); User user = this.persistenceHandler.getUser(username);
if (user == null) { if (user == null) {
throw new PrivilegeException(MessageFormat.format("User {0} does not exist!", username)); //$NON-NLS-1$ throw new PrivilegeModelException(MessageFormat.format("User {0} does not exist!", username)); //$NON-NLS-1$
} }
// validate the response // validate the response
@ -1262,7 +1262,7 @@ public class DefaultPrivilegeHandler implements PrivilegeHandler {
} }
if (!this.persistSessionsPath.isFile()) if (!this.persistSessionsPath.isFile())
throw new PrivilegeException( throw new PrivilegeModelException(
"Sessions data file is not a file but exists at " + this.persistSessionsPath.getAbsolutePath()); "Sessions data file is not a file but exists at " + this.persistSessionsPath.getAbsolutePath());
List<CertificateStub> certificateStubs; List<CertificateStub> certificateStubs;
@ -1442,7 +1442,7 @@ public class DefaultPrivilegeHandler implements PrivilegeHandler {
if (privilege == null) { if (privilege == null) {
String msg = "The Privilege {0} does not exist for role {1}"; //$NON-NLS-1$ String msg = "The Privilege {0} does not exist for role {1}"; //$NON-NLS-1$
msg = MessageFormat.format(msg, privilegeName, roleName); msg = MessageFormat.format(msg, privilegeName, roleName);
throw new PrivilegeException(msg); throw new PrivilegeModelException(msg);
} }
// cache the privilege // cache the privilege
@ -1450,7 +1450,7 @@ public class DefaultPrivilegeHandler implements PrivilegeHandler {
if (this.privilegeConflictResolution.isStrict()) { if (this.privilegeConflictResolution.isStrict()) {
String msg = "User has conflicts for privilege {0} with role {1}"; String msg = "User has conflicts for privilege {0} with role {1}";
msg = MessageFormat.format(msg, privilegeName, roleName); msg = MessageFormat.format(msg, privilegeName, roleName);
throw new PrivilegeException(msg); throw new PrivilegeModelException(msg);
} }
IPrivilege priv = privileges.get(privilegeName); IPrivilege priv = privileges.get(privilegeName);
@ -1483,7 +1483,7 @@ public class DefaultPrivilegeHandler implements PrivilegeHandler {
if (policy == null) { if (policy == null) {
String msg = "The Policy {0} does not exist for Privilege {1}"; //$NON-NLS-1$ String msg = "The Policy {0} does not exist for Privilege {1}"; //$NON-NLS-1$
msg = MessageFormat.format(msg, policyName, privilegeName); msg = MessageFormat.format(msg, policyName, privilegeName);
throw new PrivilegeException(msg); throw new PrivilegeModelException(msg);
} }
policies.put(policyName, policy); policies.put(policyName, policy);
} }
@ -1557,11 +1557,11 @@ public class DefaultPrivilegeHandler implements PrivilegeHandler {
public void validatePassword(char[] password) throws PrivilegeException { public void validatePassword(char[] password) throws PrivilegeException {
if (password == null || password.length == 0) { if (password == null || password.length == 0) {
throw new PrivilegeException("A password may not be empty!"); //$NON-NLS-1$ throw new PrivilegeModelException("A password may not be empty!"); //$NON-NLS-1$
} }
if (password.length < 3) { if (password.length < 3) {
throw new PrivilegeException("The given password is shorter than 3 characters"); //$NON-NLS-1$ throw new PrivilegeModelException("The given password is shorter than 3 characters"); //$NON-NLS-1$
} }
} }
@ -1621,7 +1621,7 @@ public class DefaultPrivilegeHandler implements PrivilegeHandler {
SingleSignOnHandler ssoHandler, Map<String, Class<PrivilegePolicy>> policyMap) { SingleSignOnHandler ssoHandler, Map<String, Class<PrivilegePolicy>> policyMap) {
if (this.initialized) if (this.initialized)
throw new PrivilegeException("Already initialized!"); //$NON-NLS-1$ throw new PrivilegeModelException("Already initialized!"); //$NON-NLS-1$
this.policyMap = policyMap; this.policyMap = policyMap;
this.encryptionHandler = encryptionHandler; this.encryptionHandler = encryptionHandler;
@ -1675,20 +1675,20 @@ public class DefaultPrivilegeHandler implements PrivilegeHandler {
if (StringHelper.isEmpty(persistSessionsPathS)) { if (StringHelper.isEmpty(persistSessionsPathS)) {
String msg = "Parameter {0} has illegal value {1}."; //$NON-NLS-1$ String msg = "Parameter {0} has illegal value {1}."; //$NON-NLS-1$
msg = MessageFormat.format(msg, PARAM_PERSIST_SESSIONS_PATH, persistSessionsPathS); msg = MessageFormat.format(msg, PARAM_PERSIST_SESSIONS_PATH, persistSessionsPathS);
throw new PrivilegeException(msg); throw new PrivilegeModelException(msg);
} }
File persistSessionsPath = new File(persistSessionsPathS); File persistSessionsPath = new File(persistSessionsPathS);
if (!persistSessionsPath.getParentFile().isDirectory()) { if (!persistSessionsPath.getParentFile().isDirectory()) {
String msg = "Path for param {0} is invalid as parent does not exist or is not a directory. Value: {1}"; //$NON-NLS-1$ String msg = "Path for param {0} is invalid as parent does not exist or is not a directory. Value: {1}"; //$NON-NLS-1$
msg = MessageFormat.format(msg, PARAM_PERSIST_SESSIONS_PATH, persistSessionsPath.getAbsolutePath()); msg = MessageFormat.format(msg, PARAM_PERSIST_SESSIONS_PATH, persistSessionsPath.getAbsolutePath());
throw new PrivilegeException(msg); throw new PrivilegeModelException(msg);
} }
if (persistSessionsPath.exists() && (!persistSessionsPath.isFile() || !persistSessionsPath.canWrite())) { if (persistSessionsPath.exists() && (!persistSessionsPath.isFile() || !persistSessionsPath.canWrite())) {
String msg = "Path for param {0} is invalid as file exists but is not a file or not writeable. Value: {1}"; //$NON-NLS-1$ String msg = "Path for param {0} is invalid as file exists but is not a file or not writeable. Value: {1}"; //$NON-NLS-1$
msg = MessageFormat.format(msg, PARAM_PERSIST_SESSIONS_PATH, persistSessionsPath.getAbsolutePath()); msg = MessageFormat.format(msg, PARAM_PERSIST_SESSIONS_PATH, persistSessionsPath.getAbsolutePath());
throw new PrivilegeException(msg); throw new PrivilegeModelException(msg);
} }
this.persistSessionsPath = persistSessionsPath; this.persistSessionsPath = persistSessionsPath;
@ -1715,7 +1715,7 @@ public class DefaultPrivilegeHandler implements PrivilegeHandler {
} catch (Exception e) { } catch (Exception e) {
String msg = "Parameter {0} has illegal value {1}."; //$NON-NLS-1$ String msg = "Parameter {0} has illegal value {1}."; //$NON-NLS-1$
msg = MessageFormat.format(msg, PARAM_PRIVILEGE_CONFLICT_RESOLUTION, privilegeConflictResolutionS); msg = MessageFormat.format(msg, PARAM_PRIVILEGE_CONFLICT_RESOLUTION, privilegeConflictResolutionS);
throw new PrivilegeException(msg); throw new PrivilegeModelException(msg);
} }
} }
logger.info("Privilege conflict resolution set to " + this.privilegeConflictResolution); //$NON-NLS-1$ logger.info("Privilege conflict resolution set to " + this.privilegeConflictResolution); //$NON-NLS-1$
@ -1730,14 +1730,14 @@ public class DefaultPrivilegeHandler implements PrivilegeHandler {
if (StringHelper.isEmpty(secretKeyS)) { if (StringHelper.isEmpty(secretKeyS)) {
String msg = "Parameter {0} may not be empty if parameter {1} is enabled."; //$NON-NLS-1$ String msg = "Parameter {0} may not be empty if parameter {1} is enabled."; //$NON-NLS-1$
msg = MessageFormat.format(msg, PARAM_SECRET_KEY, PARAM_PRIVILEGE_CONFLICT_RESOLUTION); msg = MessageFormat.format(msg, PARAM_SECRET_KEY, PARAM_PRIVILEGE_CONFLICT_RESOLUTION);
throw new PrivilegeException(msg); throw new PrivilegeModelException(msg);
} }
String secretSaltS = parameterMap.get(PARAM_SECRET_SALT); String secretSaltS = parameterMap.get(PARAM_SECRET_SALT);
if (StringHelper.isEmpty(secretSaltS)) { if (StringHelper.isEmpty(secretSaltS)) {
String msg = "Parameter {0} may not be empty if parameter {1} is enabled."; //$NON-NLS-1$ String msg = "Parameter {0} may not be empty if parameter {1} is enabled."; //$NON-NLS-1$
msg = MessageFormat.format(msg, PARAM_SECRET_SALT, PARAM_PRIVILEGE_CONFLICT_RESOLUTION); msg = MessageFormat.format(msg, PARAM_SECRET_SALT, PARAM_PRIVILEGE_CONFLICT_RESOLUTION);
throw new PrivilegeException(msg); throw new PrivilegeModelException(msg);
} }
this.secretKey = AesCryptoHelper.buildSecret(secretKeyS.toCharArray(), secretSaltS.getBytes()); this.secretKey = AesCryptoHelper.buildSecret(secretKeyS.toCharArray(), secretSaltS.getBytes());
@ -1759,7 +1759,7 @@ public class DefaultPrivilegeHandler implements PrivilegeHandler {
for (String conflict : conflicts) { for (String conflict : conflicts) {
logger.error(conflict); logger.error(conflict);
} }
throw new PrivilegeException("There are " + conflicts.size() + " privilege conflicts!"); throw new PrivilegeModelException("There are " + conflicts.size() + " privilege conflicts!");
} }
} }
@ -1768,8 +1768,8 @@ public class DefaultPrivilegeHandler implements PrivilegeHandler {
Map<String, String> privilegeNames = new HashMap<>(); Map<String, String> privilegeNames = new HashMap<>();
List<String> conflicts = detectPrivilegeConflicts(privilegeNames, user); List<String> conflicts = detectPrivilegeConflicts(privilegeNames, user);
if (!conflicts.isEmpty()) { if (!conflicts.isEmpty()) {
String msg = conflicts.stream().collect(Collectors.joining("\n")); String msg = String.join("\n", conflicts);
throw new PrivilegeException(msg); throw new PrivilegeModelException(msg);
} }
} }
} }
@ -1792,7 +1792,7 @@ public class DefaultPrivilegeHandler implements PrivilegeHandler {
if (!conflicts.isEmpty()) { if (!conflicts.isEmpty()) {
String msg = String.join("\n", conflicts); String msg = String.join("\n", conflicts);
throw new PrivilegeException(msg); throw new PrivilegeModelException(msg);
} }
} }
@ -1830,7 +1830,7 @@ public class DefaultPrivilegeHandler implements PrivilegeHandler {
if (policy != null && !this.policyMap.containsKey(policy)) { if (policy != null && !this.policyMap.containsKey(policy)) {
String msg = "Policy {0} for Privilege {1} does not exist on role {2}"; //$NON-NLS-1$ String msg = "Policy {0} for Privilege {1} does not exist on role {2}"; //$NON-NLS-1$
msg = MessageFormat.format(msg, policy, privilege.getName(), role); msg = MessageFormat.format(msg, policy, privilege.getName(), role);
throw new PrivilegeException(msg); throw new PrivilegeModelException(msg);
} }
} }
} }
@ -2002,7 +2002,7 @@ public class DefaultPrivilegeHandler implements PrivilegeHandler {
} catch (Exception e) { } catch (Exception e) {
String msg = "The class for the policy with the name {0} does not exist!{1}"; //$NON-NLS-1$ String msg = "The class for the policy with the name {0} does not exist!{1}"; //$NON-NLS-1$
msg = MessageFormat.format(msg, policyName, policyName); msg = MessageFormat.format(msg, policyName, policyName);
throw new PrivilegeException(msg, e); throw new PrivilegeModelException(msg, e);
} }
return policy; return policy;

View File

@ -15,6 +15,7 @@ import com.google.gson.JsonElement;
import com.google.gson.JsonObject; import com.google.gson.JsonObject;
import li.strolch.privilege.base.AccessDeniedException; import li.strolch.privilege.base.AccessDeniedException;
import li.strolch.privilege.base.PrivilegeException; import li.strolch.privilege.base.PrivilegeException;
import li.strolch.privilege.base.PrivilegeModelException;
import li.strolch.service.api.ServiceResult; import li.strolch.service.api.ServiceResult;
import li.strolch.utils.collections.Paging; import li.strolch.utils.collections.Paging;
import li.strolch.utils.helper.ExceptionHelper; import li.strolch.utils.helper.ExceptionHelper;
@ -133,6 +134,8 @@ public class ResponseUtil {
Status status; Status status;
if (t instanceof AccessDeniedException) { if (t instanceof AccessDeniedException) {
status = Status.FORBIDDEN; status = Status.FORBIDDEN;
} else if (t instanceof PrivilegeModelException) {
status = Status.INTERNAL_SERVER_ERROR;
} else if (t instanceof PrivilegeException) { } else if (t instanceof PrivilegeException) {
status = Status.UNAUTHORIZED; status = Status.UNAUTHORIZED;
} else { } else {
@ -145,6 +148,8 @@ public class ResponseUtil {
public static Response toResponse(Throwable t) { public static Response toResponse(Throwable t) {
if (t instanceof AccessDeniedException) { if (t instanceof AccessDeniedException) {
return ResponseUtil.toResponse(Status.FORBIDDEN, t); return ResponseUtil.toResponse(Status.FORBIDDEN, t);
} else if (t instanceof PrivilegeModelException) {
return ResponseUtil.toResponse(Status.INTERNAL_SERVER_ERROR, t);
} else if (t instanceof PrivilegeException) { } else if (t instanceof PrivilegeException) {
return ResponseUtil.toResponse(Status.UNAUTHORIZED, t); return ResponseUtil.toResponse(Status.UNAUTHORIZED, t);
} else { } else {
@ -189,8 +194,7 @@ public class ResponseUtil {
List<JsonObject> page = paging.getPage(); List<JsonObject> page = paging.getPage();
JsonArray data = new JsonArray(); JsonArray data = new JsonArray();
for (JsonObject jsonObject : page) { for (JsonObject jsonObject : page) {
JsonObject element = jsonObject; data.add(jsonObject);
data.add(element);
} }
response.add(DATA, data); response.add(DATA, data);