All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.smartcosmos.cluster.userdetails.repository.UserRepositoryImpl Maven / Gradle / Ivy

The newest version!
package net.smartcosmos.cluster.userdetails.repository;

import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import javax.validation.ConstraintViolationException;

import org.apache.commons.lang.exception.ExceptionUtils;
import org.hibernate.Hibernate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionException;
import org.springframework.util.Assert;

import net.smartcosmos.cluster.userdetails.domain.AuthorityEntity;
import net.smartcosmos.cluster.userdetails.domain.RoleEntity;
import net.smartcosmos.cluster.userdetails.domain.UserEntity;

import static java.util.stream.Collectors.toSet;

@Component
public class UserRepositoryImpl implements UserRepositoryCustom {

    @Lazy
    private final UserRepository userRepository;

    @Lazy
    private final RoleRepository roleRepository;

    private final PasswordEncoder passwordEncoder;

    @Lazy
    @Autowired
    public UserRepositoryImpl(UserRepository userRepository, RoleRepository roleRepository, PasswordEncoder passwordEncoder) {

        this.userRepository = userRepository;
        this.roleRepository = roleRepository;
        this.passwordEncoder = passwordEncoder;
    }

    @Override
    public UserEntity persist(UserEntity entity) throws ConstraintViolationException, TransactionException {

        try {
            return userRepository.save(entity);
        } catch (TransactionException e) {
            // we expect constraint violations to be the root cause for exceptions here,
            // so we throw this particular exception back to the caller
            if (ExceptionUtils.getRootCause(e) instanceof ConstraintViolationException) {
                throw (ConstraintViolationException) ExceptionUtils.getRootCause(e);
            } else {
                throw e;
            }
        }
    }

    @Override
    public Optional getUserByCredentials(String username, String password) throws IllegalArgumentException {

        Assert.notNull(username, "username must not be null");
        Assert.notNull(password, "password must not be null");

        Optional userOptional = userRepository.findByUsernameIgnoreCase(username);

        if (userOptional.isPresent() && passwordEncoder.matches(password,
                                                                userOptional.get()
                                                                    .getPassword())) {
            return userOptional;
        }

        return Optional.empty();
    }

    @Override
    public Optional> getAuthorities(UUID tenantId, UUID userId) {

        Optional userOptional = userRepository.findByTenantIdAndId(tenantId, userId);
        if (userOptional.isPresent()) {
            Set authorities = new LinkedHashSet<>();

            UserEntity user = userOptional.get();
            user.getRoles()
                .stream()
                .filter(RoleEntity::getActive)
                .forEach(role -> authorities.addAll(role.getAuthorities()));

            return Optional.of(authorities);
        }

        return Optional.empty();
    }

    @Override
    public Optional addRolesToUser(UUID tenantId, UUID userId, Collection roleNames) throws IllegalArgumentException {

        Optional userOptional = userRepository.findByTenantIdAndId(tenantId, userId);
        if (userOptional.isPresent()) {
            UserEntity user = userOptional.get();

            Set roleSet = initRoleEntities(user);
            Set newRoleSet = getRoleEntities(tenantId, roleNames);
            roleSet.addAll(newRoleSet);

            return Optional.of(user);
        }

        return Optional.empty();
    }

    private Set getRoleEntities(UUID tenantId, Collection roleNames) {

        return roleNames
            .stream()
            .map(roleName -> {
                Optional role = roleRepository.findByTenantIdAndNameIgnoreCase(tenantId, roleName);
                if (role.isPresent()) {
                    return role.get();
                } else {
                    String msg = String.format("Role '%s' does not exist", roleName);
                    throw new IllegalArgumentException(msg);
                }
            })
            .collect(toSet());
    }

    private Set initRoleEntities(UserEntity user) {

        Set roleEntities = user.getRoles();

        if (!Hibernate.isInitialized(roleEntities)) {
            Hibernate.initialize(roleEntities);
        }

        return roleEntities;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy