/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.evasion.plugin.common;
import com.evasion.dao.api.DefaultDAO;
import com.evasion.entity.Civilite;
import com.evasion.entity.Individual;
import com.evasion.entity.Person;
import com.evasion.entity.security.Authority;
import com.evasion.entity.security.GroupSec;
import com.evasion.entity.security.User;
import com.evasion.exception.EvasionException;
import com.evasion.exception.PersistenceViolationException;
import com.evasion.module.common.CommonModuleException;
import com.evasion.plugin.common.dao.AccountDAOImpl;
import com.evasion.plugin.common.dao.AuthorityDAO;
import com.evasion.plugin.common.dao.GroupSecDAO;
import com.evasion.plugin.common.dao.UserDAO;
import com.evasion.plugin.common.entity.Account;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import javax.persistence.EntityManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author sebastien.glon
*/
public class AccountManager {
/**
* LOGGER
*/
private static final Logger LOGGER = LoggerFactory.getLogger(
AccountManager.class);
private AccountDAOImpl accountDAO = new AccountDAOImpl();
private AuthorityDAO authDAO = new AuthorityDAO();
private GroupSecDAO grpSecDAO = new GroupSecDAO();
private UserDAO userDAO = new UserDAO();
private DefaultDAO defaultDAO = new DefaultDAO();
private EntityManager em;
public AccountManager(EntityManager em) {
this.em = em;
accountDAO.setEntityManager(em);
authDAO.setEntityManager(em);
grpSecDAO.setEntityManager(em);
userDAO.setEntityManager(em);
defaultDAO.setEntityManager(em);
}
public Account findAccountById(Long id) {
return accountDAO.findById(id);
}
/**
* {@inheritDoc }
*/
public void createAccount(Account account) throws EvasionException {
if (account.getPerson() == null || account.getPerson().getId() == null) {
throw new CommonModuleException("person for account is null or not commited");
}
account.getUser().setEmail(account.getPerson().getEmail());
createUser(account.getUser());
LOGGER.debug("Create an account for user: {}", account.getUser().getUsername());
try {
accountDAO.persist(account);
} catch (Exception e) {
LOGGER.error("Erreur dans la validation du compte utilisateur", e);
throw new PersistenceViolationException("Erreur dans la validation du compte utilisateur", e.fillInStackTrace());
}
}
/**
* {@inheritDoc }
*/
public void deleteAccount(Long id) {
throw new UnsupportedOperationException("Not supported yet.");
}
/**
* {@inheritDoc }
*/
public Account updateAccount(Account u) {
updateUser(u.getUser());
return em.merge(u);
}
public Authority findOrCreateAdminAuthority() {
Authority auth = authDAO.findByAuthorityName("ROLE_ADMIN");
if (auth == null) {
auth = new Authority("ROLE_ADMIN");
authDAO.persist(auth);
}
return auth;
}
public Account findOrCreateAdminAccount() throws EvasionException {
Account acc = accountDAO.findAccountByUsername("admin");
if (acc == null) {
User admin = userDAO.findById("admin");
if (admin == null) {
admin = new User();
admin.setEnabled(true);
admin.setUsername("admin");
admin.setPassword("adminadmin");
admin.setEmail("admin@localhost");
}
Person person = new Individual("", Civilite.monsieur, "admin", "admin", new Date());
defaultDAO.persist(person);
acc = new Account(admin, person);
createAccount(acc);
}
return acc;
}
public void checkOrUpdateAdminAuth() throws EvasionException {
Authority auth = findOrCreateAdminAuthority();
User admin = findOrCreateAdminAccount().getUser();
if (!admin.getAuthorities().contains(auth)) {
admin.addAuthority(auth);
updateUser(admin);
}
}
public Account findAccountByUserName(String u) {
return accountDAO.findAccountByUsername(u);
}
public User createUser(User u) throws PersistenceViolationException {
validGrantedAuthority(u);
encodPassword(u);
if (findAccountByUserName(u.getUsername()) == null) {
em.persist(u);
} else {
throw new PersistenceViolationException("user already exists");
}
return u;
}
public User updateUser(User u) {
final User userBDD = em.find(User.class, u.getUsername());
LOGGER.debug("Mise à jour du user: {}", u.toString());
validGrantedAuthority(u);
if (!userBDD.getPassword().equals(u.getPassword())) {
encodPassword(u);
}
return em.merge(u);
}
/*
* Interface pour la gestion des groupes
*/
public List<GroupSec> listGroups() {
return grpSecDAO.findAll();
}
private void validGrantedAuthority(User user) {
if (user == null) {
throw new IllegalArgumentException();
}
boolean result;
result = (user.getAuthorities() != null && !user.getAuthorities().isEmpty())
|| (user.getGroups() != null && !user.getGroups().isEmpty());
if (!result) {
HashSet<Authority> auth = (new HashSet<Authority>());
auth.add(getDefaultAuthority());
user.addAllAuthority(auth);
}
}
/**
* Fourni le role par défaut et le créé si besoin.
*
* @return role par défaut de tout les utilisateurs.
*/
private Authority getDefaultAuthority() {
Authority result = authDAO.findByAuthorityName(Constante.DEFAULT_AUTH_NAME);
if (result == null) {
result = authDAO.merge(new Authority(Constante.DEFAULT_AUTH_NAME));
}
return result;
}
private void encodPassword(User user) {
try {
LOGGER.debug("Encodage du password");
// Encodage du passord et salt;
Class clazz = Class.forName("com.evasion.sam.PasswordEncoder");
Method meth = clazz.getDeclaredMethod("encodePassword", Object.class, String.class);
String encodedPassword = (String) meth.invoke(null, user.getUsername(), user.getPassword());
user.setPassword(encodedPassword);
} catch (IllegalAccessException ex) {
LOGGER.error("Error Password Encoder ", ex);
} catch (IllegalArgumentException ex) {
LOGGER.error("Error Password Encoder ", ex);
} catch (InvocationTargetException ex) {
LOGGER.error("Error Password Encoder ", ex);
} catch (NoSuchMethodException ex) {
LOGGER.error("Error Password Encoder ", ex);
} catch (SecurityException ex) {
LOGGER.error("Error Password Encoder ", ex);
} catch (ClassNotFoundException ex) {
LOGGER.error("Error Password Encoder ", ex);
}
}
public List<Account> findAllAccount() {
return accountDAO.findAll();
}
}