public UserInfo(User user) { this.id = user.getId().toString(); this.login = user.getLogin(); this.name = user.getName(); this.firstName = user.getFirstName(); this.middleName = user.getMiddleName(); this.lastName = user.getLastName(); this.position = user.getPosition(); this.email = user.getEmail(); this.timeZone = user.getTimeZone(); this._instanceName = user.getInstanceName(); this.language = user.getLanguage(); }
User user = event.getSource(); log.info("Handling user invalidation: {}", user.getLogin()); (user.equals(session.getUser()) || user.equals(session.getSubstitutedUser()))) .map(UserSession::getId) .collect(Collectors.toList()); serverTokenStore.getAccessTokenValuesByUserLogin(user.getLogin()) .forEach(serverTokenStore::removeAccessToken); serverTokenStore.getRefreshTokenValuesByUserLogin(user.getLogin()) .forEach(serverTokenStore::removeRefreshToken); userManagementService.resetRememberMeTokens(Collections.singletonList(user.getId())); log.info("UserSessions, REST API & 'Remember me' tokens were invalidated for a user: {}", user.getLogin()); } catch (Throwable t) { log.error("An error occurred while handling user invalidation for user: {}.", user.getLogin(), t);
/** * Get user session attribute. Attribute is a named serializable object bound to session. * * @param name attribute name. The following names have predefined values: * <ul> * <li>userId - current or substituted user ID</li> * <li>userLogin - current or substituted user login in lower case</li> * </ul> * @return attribute value or null if attribute with the given name is not found */ @SuppressWarnings("unchecked") @Nullable public <T> T getAttribute(String name) { if ("userId".equals(name)) return (T) getCurrentOrSubstitutedUser().getId(); if ("userLogin".equals(name)) return (T) getCurrentOrSubstitutedUser().getLoginLowerCase(); else return (T) attributes.get(name); }
public UserInfo(User user) { this.login = user.getLogin(); this.name = user.getName(); this.timeZone = user.getTimeZone(); this.language = user.getLanguage(); } }
public User createTestUser() { User user = new User(); user.setId(UUID.fromString(USER_ID)); user.setLogin("test_admin"); user.setName("Test Administrator"); user.setPassword(DigestUtils.md5Hex("test_admin")); return user; }
@Override public Map<UUID, String> changePasswordsAtLogon(List<UUID> userIds, boolean generatePassword) { checkNotNullArgument(userIds, "Null users list"); checkUpdatePermission(User.class); if (userIds.isEmpty()) return Collections.emptyMap(); Map<User, String> modifiedUsers = updateUserPasswords(userIds, generatePassword); Map<UUID, String> userPasswords = new LinkedHashMap<>(); for (Map.Entry<User, String> entry : modifiedUsers.entrySet()) userPasswords.put(entry.getKey().getId(), entry.getValue()); return userPasswords; }
/** * INTERNAL */ public UserSession(UserSession src, User user, Collection<Role> roles, Locale locale) { this(src.id, user, roles, locale, src.system); this.user = src.user; this.substitutedUser = this.user.equals(user) ? null : user; }
protected synchronized void writeLog(File file, boolean remove) { File rootDir; try { rootDir = file.getParentFile().getParentFile().getParentFile().getParentFile(); } catch (NullPointerException e) { log.error("Unable to write log: invalid file storage structure", e); return; } SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); UserSession userSession = userSessionSource.getUserSession(); String userLogin = userSession.getUser().getLogin(); String userId = userSession.getUser().getId().toString(); StringBuilder sb = new StringBuilder(); sb.append(df.format(timeSource.currentTimestamp())).append(" "); sb.append("[").append(userLogin).append("--").append(userId).append("] "); sb.append(remove ? "REMOVE" : "CREATE").append(" "); sb.append("\"").append(file.getAbsolutePath()).append("\"\n"); File logFile = new File(rootDir, "storage.log"); try { try (FileOutputStream fos = new FileOutputStream(logFile, true)) { IOUtils.write(sb.toString(), fos, StandardCharsets.UTF_8); } } catch (IOException e) { log.error("Unable to write log", e); } }
@Override public void setQueryParam(Query query, String paramName) { if (paramName.startsWith(CONSTRAINT_PARAM_SESSION_ATTR)) { UserSession userSession = userSessionSource.getUserSession(); String attrName = paramName.substring(CONSTRAINT_PARAM_SESSION_ATTR.length()); if (CONSTRAINT_PARAM_USER_LOGIN.equals(attrName)) { String userLogin = userSession.getSubstitutedUser() != null ? userSession.getSubstitutedUser().getLogin() : userSession.getUser().getLogin(); query.setParameter(paramName, userLogin); } else if (CONSTRAINT_PARAM_USER_ID.equals(attrName)) { UUID userId = userSession.getSubstitutedUser() != null ? userSession.getSubstitutedUser().getId() : userSession.getUser().getId(); query.setParameter(paramName, userId); } else if (CONSTRAINT_PARAM_USER_GROUP_ID.equals(attrName)) { Object groupId = userSession.getSubstitutedUser() == null ? userSession.getUser().getGroup().getId() : userSession.getSubstitutedUser().getGroup().getId(); query.setParameter(paramName, groupId); } else { Serializable value = userSession.getAttribute(attrName); query.setParameter(paramName, value); } } }
@Override public UserTimeZone loadOwnTimeZone() { Transaction tx = persistence.createTransaction(); try { EntityManager em = persistence.getEntityManager(); User user = em.find(User.class, userSessionSource.getUserSession().getUser().getId(), "user.timeZone"); if (user == null) throw new EntityAccessException(User.class, userSessionSource.getUserSession().getUser().getId()); tx.commit(); return new UserTimeZone(user.getTimeZone(), Boolean.TRUE.equals(user.getTimeZoneAuto())); } finally { tx.end(); } }
protected void updateLoginLowerCase(User user) { user.setLoginLowerCase(user.getLogin() != null ? user.getLogin().toLowerCase() : null); }
@Override protected void postInit() { activeField.setEnabled(!userManagementService.isAnonymousUser(getItem().getLogin())); setCaption(PersistenceHelper.isNew(getItem()) ? getMessage("createCaption") : formatMessage("editCaption", getItem().getLogin())); timeZoneLookup.setEnabled(!Boolean.TRUE.equals(getItem().getTimeZoneAuto())); // Do not show roles which are not allowed by security constraints LoadContext<Role> lc = new LoadContext<>(Role.class); lc.setQueryString("select r from sec$Role r"); lc.setView(View.MINIMAL); List<Role> allowedRoles = dataSupplier.loadList(lc); Collection<UserRole> userRoles = new ArrayList<>(rolesDs.getItems()); for (UserRole userRole : userRoles) { if (!allowedRoles.contains(userRole.getRole())) { rolesDs.excludeItem(userRole); } } if (BooleanUtils.isTrue(initCopy)) { initCopy(); } // if we add default roles, rolesDs becomes modified on setItem ((AbstractDatasource) rolesDs).setModified(false); }
protected Map<User, String> updateUserPasswords(List<UUID> userIds, boolean generatePassword) { Map<User, String> modifiedUsers = new LinkedHashMap<>(); Transaction tx = persistence.getTransaction(); try { EntityManager em = persistence.getEntityManager(); TypedQuery<User> query = em.createQuery("select u from sec$User u where u.id in :userIds", User.class); query.setParameter("userIds", userIds); query.setViewName(RESET_PASSWORD_VIEW); List<User> users = query.getResultList(); if (users == null || users.size() != userIds.size()) throw new IllegalStateException("Not all users found in database"); for (User user : users) { String password = null; if (generatePassword) { password = passwordEncryption.generateRandomPassword(); user.setPasswordEncryption(passwordEncryption.getHashMethod()); String passwordHash = passwordEncryption.getPasswordHash(user.getId(), password); user.setPassword(passwordHash); } user.setChangePasswordAtNextLogon(true); modifiedUsers.put(user, password); } resetRememberMeTokens(userIds); tx.commit(); } finally { tx.end(); } return modifiedUsers; }
selectedUser = dataSupplier.reload(selectedUser, "user.edit"); User newUser = metadata.create(User.class); if (selectedUser.getUserRoles() != null) { List<UserRole> userRoles = new ArrayList<>(); for (UserRole oldUserRole : selectedUser.getUserRoles()) { Role oldRole = dataSupplier.reload(oldUserRole.getRole(), "_local"); if (BooleanUtils.isTrue(oldRole.getDefaultRole())) { userRoles.add(role); newUser.setUserRoles(userRoles); newUser.setGroup(selectedUser.getGroup()); AbstractEditor editor = openEditor("sec$User.edit", newUser, OpenType.THIS_TAB, ParamsMap.of("initCopy", true));
@Nonnull @Override public UserSession substituteUser(User substitutedUser) { UserSession currentSession = userSessionSource.getUserSession(); try (Transaction tx = persistence.createTransaction()) { EntityManager em = persistence.getEntityManager(); User user; if (currentSession.getUser().equals(substitutedUser)) { user = em.find(User.class, substitutedUser.getId()); if (user == null) { throw new NoResultException("User not found"); } } else { user = loadSubstitutedUser(substitutedUser, currentSession, em); } UserSession session = userSessionManager.createSession(currentSession, user); withSecurityContext(new SecurityContext(serverSession), () -> publishUserSubstitutedEvent(currentSession, session) ); tx.commit(); userSessions.remove(currentSession); userSessionManager.clearPermissionsOnUser(session); userSessions.add(session); return session; } }
protected UserSessionEntity createUserSessionEntity(UserSession session, long since, long lastUsedTs) { UserSessionEntity use = metadata.create(UserSessionEntity.class); use.setId(session.getId()); use.setLogin(session.getUser().getLoginLowerCase()); use.setUserName(session.getUser().getName()); use.setAddress(session.getAddress()); use.setClientInfo(session.getClientInfo()); use.setSince(new Date(since)); use.setLastUsedTs(new Date(lastUsedTs)); use.setSystem(session.isSystem()); return use; }
public Integer getPermissionValue(User user, PermissionType permissionType, String target) { Integer result; List<Role> roles = new ArrayList<>(); Transaction tx = persistence.createTransaction(); try { EntityManager em = persistence.getEntityManager(); user = em.find(User.class, user.getId()); for (UserRole userRole : user.getUserRoles()) { if (userRole.getRole() != null) { roles.add(userRole.getRole()); } } UserSession session = new UserSession(uuidSource.createUuid(), user, roles, userSessionSource.getLocale(), false); compilePermissions(session, roles); result = session.getPermissionValue(permissionType, target); tx.commit(); } finally { tx.end(); } return result; }