Skip to content

Commit 75cbbcb

Browse files
committed
2 parents b7867d2 + ede28bd commit 75cbbcb

5 files changed

Lines changed: 150 additions & 13 deletions

File tree

knowage-core/src/main/java/it/eng/knowage/security/ProductProfiler.java

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,21 @@ public static boolean canUseFunctions() {
147147
}
148148
}
149149

150+
public static boolean canAddAUser(int numberOfUsers, boolean isAdmin) {
151+
if (isCommunity) {
152+
return true;
153+
} else {
154+
boolean toReturn = false;
155+
try {
156+
Method canAddAUser = productProfilerEE.getMethod("canAddAUser", int.class, boolean.class);
157+
toReturn = (boolean) canAddAUser.invoke(productProfilerEE, numberOfUsers, isAdmin);
158+
} catch (Exception e) {
159+
logger.error("Error while adding a user: ", e);
160+
}
161+
return toReturn;
162+
}
163+
}
164+
150165
private ProductProfiler() {
151166

152167
}

knowage-core/src/main/java/it/eng/spagobi/api/v2/UserResource.java

Lines changed: 82 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -18,13 +18,8 @@
1818
package it.eng.spagobi.api.v2;
1919

2020
import java.net.URI;
21-
import java.util.ArrayList;
22-
import java.util.HashMap;
23-
import java.util.HashSet;
24-
import java.util.List;
25-
import java.util.Locale;
21+
import java.util.*;
2622
import java.util.Map.Entry;
27-
import java.util.Set;
2823

2924
import javax.validation.Valid;
3025
import javax.ws.rs.Consumes;
@@ -39,6 +34,8 @@
3934
import javax.ws.rs.core.MediaType;
4035
import javax.ws.rs.core.Response;
4136

37+
import it.eng.knowage.security.ProductProfiler;
38+
import it.eng.spagobi.commons.dao.IRoleDAO;
4239
import org.apache.logging.log4j.LogManager;
4340
import org.apache.logging.log4j.Logger;
4441
import org.owasp.esapi.Encoder;
@@ -76,6 +73,8 @@
7673
public class UserResource extends AbstractSpagoBIResource {
7774

7875
private static final Logger LOGGER = LogManager.getLogger(UserResource.class);
76+
private static final String[] ADMIN_ROLES = { "admin", "dev_role", "model_admin" };
77+
private static final String[] USER_ROLES = { "user", "test_role" };
7978
private static final String CHARSET = "; charset=UTF-8";
8079

8180
@GET
@@ -172,15 +171,20 @@ public Response insertUser(@Valid UserBO requestDTO) {
172171
MessageBuilder msgBuilder = new MessageBuilder();
173172
Locale locale = msgBuilder.getLocale(request);
174173

175-
ISbiUserDAO usersDao = null;
176-
177174
String userId = requestDTO.getUserId();
178175
if (userId.startsWith(PublicProfile.PUBLIC_USER_PREFIX)) {
179176
LOGGER.error("public is reserved prefix for user id");
180177
throw new SpagoBIServiceException("SPAGOBI_SERVICE", "public_ is a reserved prefix for user name", null);
181178
}
179+
ISbiUserDAO usersDao = DAOFactory.getSbiUserDAO();
180+
181+
boolean isAdmin = userRequestDtoIsAdmin(requestDTO);
182+
183+
if (!userCanBeAdded(requestDTO, usersDao, isAdmin)) {
184+
LOGGER.error("The limit for creating {} users has been reached.", isAdmin ? "admin " : "end ");
185+
throw new SpagoBIServiceException("Create user", "The limit for creating " + (isAdmin ? "admin " : "end ") + "users has been reached.");
186+
}
182187

183-
usersDao = DAOFactory.getSbiUserDAO();
184188
usersDao.setUserProfile(getUserProfile());
185189
SbiUser existingUser = usersDao.loadSbiUserByUserId(userId);
186190
if (existingUser != null && userId.equals(existingUser.getUserId())) {
@@ -234,14 +238,12 @@ public Response insertUser(@Valid UserBO requestDTO) {
234238
}
235239
}
236240

237-
//if (password != null && password.length() > 0) {
238241
try {
239242
sbiUser.setPassword(Password.hashPassword(password));
240243
} catch (Exception e) {
241244
LOGGER.error("Impossible to encrypt Password", e);
242245
throw new SpagoBIServiceException("SPAGOBI_SERVICE", "Impossible to encrypt Password", e);
243246
}
244-
//}
245247

246248
try {
247249
Integer id = usersDao.fullSaveOrUpdateSbiUser(sbiUser);
@@ -254,6 +256,67 @@ public Response insertUser(@Valid UserBO requestDTO) {
254256
}
255257
}
256258

259+
private boolean userCanBeAdded(UserBO requestDTO, ISbiUserDAO usersDao, boolean isAdmin) {
260+
List<SbiUser> dbUsers = usersDao.loadAllTenantsUsers();
261+
262+
List<SbiUser> usersToCheck = filterUsersToCheck(dbUsers, isAdmin);
263+
return ProductProfiler.canAddAUser(usersToCheck.size(), isAdmin);
264+
}
265+
266+
private List<SbiUser> filterUsersToCheck(List<SbiUser> sbiUsers, boolean isAdmin) {
267+
ISbiUserDAO usersDao = DAOFactory.getSbiUserDAO();
268+
usersDao.setUserProfile(getUserProfile());
269+
270+
return filterUsersWithRoles(sbiUsers, isAdmin, usersDao);
271+
}
272+
273+
private List<SbiUser> filterUsersWithRoles(List<SbiUser> sbiUsers, boolean isAdmin, ISbiUserDAO usersDao) {
274+
return sbiUsers.stream()
275+
.filter(user -> hasApplicableRoles(user, isAdmin, usersDao))
276+
.toList();
277+
}
278+
279+
private boolean hasApplicableRoles(SbiUser user, boolean isAdmin, ISbiUserDAO usersDao) {
280+
try {
281+
ArrayList<SbiExtRoles> userRoles = usersDao.loadSbiUserRolesByIdAllTenants(user.getId());
282+
283+
return userRoles.stream()
284+
.anyMatch(role -> role != null && isRoleApplicable(role, isAdmin));
285+
} catch (Exception e) {
286+
LOGGER.error("Error loading roles for user with id: {}", user.getId(), e);
287+
return false;
288+
}
289+
}
290+
291+
292+
private boolean userRequestDtoIsAdmin(@Valid UserBO requestDTO) {
293+
List<Integer> sbiExtUserRoleses = requestDTO.getSbiExtUserRoleses();
294+
IRoleDAO rolesDao = DAOFactory.getRoleDAO();
295+
List<SbiExtRoles> adminRoles = new ArrayList<>();
296+
if (sbiExtUserRoleses != null) {
297+
for (Integer roleId : sbiExtUserRoleses) {
298+
try {
299+
SbiExtRoles role = rolesDao.loadSbiExtRoleById(roleId);
300+
if (role != null && isRoleApplicable(role, true)) adminRoles.add(role);
301+
} catch (Exception e) {
302+
LOGGER.error("Error loading role with id: {}", roleId, e);
303+
return false;
304+
}
305+
}
306+
}
307+
return !adminRoles.isEmpty();
308+
}
309+
310+
private static boolean isThereAMatchInRoleArray(SbiExtRoles role, String... roles) {
311+
return Arrays.stream(roles).anyMatch(role.getRoleTypeCode()::equalsIgnoreCase);
312+
}
313+
314+
private static boolean isRoleApplicable(SbiExtRoles role, boolean checkAdmin) {
315+
if (checkAdmin) return isThereAMatchInRoleArray(role, ADMIN_ROLES);
316+
317+
return isThereAMatchInRoleArray(role, USER_ROLES) && !isThereAMatchInRoleArray(role, ADMIN_ROLES);
318+
}
319+
257320
@PUT
258321
@Path("/{id}")
259322
@UserConstraint(functionalities = { CommunityFunctionalityConstants.PROFILE_MANAGEMENT,
@@ -274,6 +337,14 @@ public Response updateUser(@PathParam("id") Integer id, @Valid UserBO requestDTO
274337
throw new SpagoBIServiceException("SPAGOBI_SERVICE", "public_ is a reserved prefix for user name", null);
275338
}
276339

340+
usersDao = DAOFactory.getSbiUserDAO();
341+
boolean isAdmin = userRequestDtoIsAdmin(requestDTO);
342+
343+
if (!userCanBeAdded(requestDTO, usersDao, isAdmin)) {
344+
LOGGER.error("The limit for creating {} users has been reached.", isAdmin ? "admin " : "end ");
345+
throw new SpagoBIServiceException("Update user", "The limit for creating " + (isAdmin ? "admin " : "end ") + "users has been reached.");
346+
}
347+
277348
SbiUser sbiUser = new SbiUser();
278349
sbiUser.changeId(id);
279350
sbiUser.setUserId(requestDTO.getUserId());
@@ -300,7 +371,6 @@ public Response updateUser(@PathParam("id") Integer id, @Valid UserBO requestDTO
300371
ISbiAttributeDAO objDao = null;
301372

302373
try {
303-
usersDao = DAOFactory.getSbiUserDAO();
304374
usersDao.setUserProfile(getUserProfile());
305375
sbiUserOriginal = usersDao.loadSbiUserById(sbiUser.getId());
306376
objDao = DAOFactory.getSbiAttributeDAO();

knowage/src/main/webapp/WEB-INF/conf/webapp/static_menu.xml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -219,7 +219,7 @@
219219
</TECHNICAL_USER_FUNCTIONALITIES>
220220

221221
<COMMON_USER_FUNCTIONALITIES>
222-
<ITEM label="menu.home" iconCls="pi pi-fw pi-home" to="/" />
222+
<ITEM label="menu.home" iconCls="fa-solid fa-house" to="/" />
223223
<ITEM label="menu.Languages" iconCls="fab fa-font-awesome-flag"
224224
command="languageSelection" />
225225
<ITEM label="menu.RoleSelection" iconCls="fas fa-users-cog"

knowagedao/src/main/java/it/eng/spagobi/profiling/dao/ISbiUserDAO.java

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,8 @@ public interface ISbiUserDAO extends ISpagoBIDao, EmittingEventDAO<UserEventsEme
5050

5151
ArrayList<SbiUser> loadSbiUsers();
5252

53+
ArrayList<SbiUser> loadAllTenantsUsers();
54+
5355
ArrayList<UserBO> loadUsers();
5456

5557
List<UserBO> loadUsers(QueryFilters filters);
@@ -88,4 +90,5 @@ public interface ISbiUserDAO extends ISpagoBIDao, EmittingEventDAO<UserEventsEme
8890

8991
void resetOtpSecret(Integer userId);
9092

93+
ArrayList<SbiExtRoles> loadSbiUserRolesByIdAllTenants(int id);
9194
}

knowagedao/src/main/java/it/eng/spagobi/profiling/dao/SbiUserDAOHibImpl.java

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -229,6 +229,31 @@ public void resetOtpSecret(Integer userId) {
229229
}
230230
}
231231

232+
@Override
233+
public ArrayList<SbiExtRoles> loadSbiUserRolesByIdAllTenants(int id) {
234+
LOGGER.debug("IN");
235+
236+
Session aSession = null;
237+
Transaction tx = null;
238+
try {
239+
aSession = getSession();
240+
disableTenantFilter(aSession);
241+
tx = aSession.beginTransaction();
242+
String q = "select us.sbiExtUserRoleses from SbiUser us where us.id = :id";
243+
Query query = aSession.createQuery(q);
244+
query.setInteger("id", id);
245+
246+
ArrayList<SbiExtRoles> result = (ArrayList<SbiExtRoles>) query.list();
247+
return result;
248+
} catch (HibernateException he) {
249+
rollbackIfActive(tx);
250+
throw new SpagoBIDAOException("Error while loading user role with id " + id, he);
251+
} finally {
252+
LOGGER.debug("OUT");
253+
closeSessionIfOpen(aSession);
254+
}
255+
}
256+
232257
/**
233258
* Insert SbiUser
234259
*
@@ -423,6 +448,30 @@ public ArrayList<SbiUser> loadSbiUsers() {
423448
}
424449
}
425450

451+
@Override
452+
public ArrayList<SbiUser> loadAllTenantsUsers() {
453+
LOGGER.debug("IN");
454+
455+
Session aSession = null;
456+
Transaction tx = null;
457+
try {
458+
aSession = getSession();
459+
this.disableTenantFilter(aSession);
460+
tx = aSession.beginTransaction();
461+
String q = "from SbiUser ";
462+
Query query = aSession.createQuery(q);
463+
464+
ArrayList<SbiUser> result = (ArrayList<SbiUser>) query.list();
465+
return result;
466+
} catch (HibernateException he) {
467+
rollbackIfActive(tx);
468+
throw new SpagoBIDAOException("Error while loading users", he);
469+
} finally {
470+
LOGGER.debug("OUT");
471+
closeSessionIfOpen(aSession);
472+
}
473+
}
474+
426475
@Override
427476
public Integer fullSaveOrUpdateSbiUser(SbiUser user) {
428477
LOGGER.debug("IN");

0 commit comments

Comments
 (0)