Commit fd5b6407 authored by Piotr Gawron's avatar Piotr Gawron
Browse files

user is automatically created when local user doesn't exist and authentication goes via ldap

parent 8d0dc7af
......@@ -221,7 +221,7 @@ public enum ConfigurationElementType {
ConfigurationElementTypeGroup.LDAP_CONFIGURATION), //
LDAP_EMAIL_ATTRIBUTE("LDAP email attribute", "mail", ConfigurationElementEditType.STRING, true,
ConfigurationElementTypeGroup.LDAP_CONFIGURATION),//
LDAP_FILTER("LDAP filter ", "(memberof=cn=gitlab,cn=groups,cn=accounts,dc=uni,dc=lu)", ConfigurationElementEditType.STRING, true,
LDAP_FILTER("LDAP filter ", "(memberof=cn=minerva,cn=groups,cn=accounts,dc=uni,dc=lu)", ConfigurationElementEditType.STRING, true,
ConfigurationElementTypeGroup.LDAP_CONFIGURATION), //
;
......
......@@ -118,8 +118,13 @@ public class User implements Serializable {
*/
private boolean removed = false;
@Column(name="terms_of_use_consent")
private boolean termsOfUseConsent = false;
/**
* User is connected to LDAP directory.
*/
private boolean connectedToLdap = false;
@Column(name = "terms_of_use_consent")
private boolean termsOfUseConsent = false;
/**
* Set of user privileges.
......@@ -378,4 +383,12 @@ public class User implements Serializable {
this.termsOfUseConsent = termsOfUseConsent;
}
public boolean isConnectedToLdap() {
return connectedToLdap;
}
public void setConnectedToLdap(boolean connectedToLdap) {
this.connectedToLdap = connectedToLdap;
}
}
-- user account can be connected to LDAP directory
alter table user_table add column connectedtoldap boolean default false;
......@@ -2,9 +2,6 @@ package lcsb.mapviewer.persist.dao.user;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import lcsb.mapviewer.model.user.User;
import lcsb.mapviewer.persist.dao.BaseDao;
......@@ -16,102 +13,80 @@ import lcsb.mapviewer.persist.dao.BaseDao;
*/
public class UserDao extends BaseDao<User> {
/**
* Service that provides password encoding.
*/
@Autowired
private PasswordEncoder passwordEncoder;
/**
* Default constructor.
*/
public UserDao() {
super(User.class, "removed");
}
/**
* Returns user with a given login and password.
*
* @param login
* user login
* @param password
* - user password (plain text)
* @return user for given login and password
*/
public User getUserByLoginAndPassword(String login, String password) {
if (password == null) {
return getUserByLoginAndCryptedPassword(login, null);
}
return getUserByLoginAndCryptedPassword(login, passwordEncoder.encode(password));
}
/**
* Default constructor.
*/
public UserDao() {
super(User.class, "removed");
}
/**
* Returns user with a given login and password.
*
* @param login
* user login
* @param password
* - user password (encrypted)
* @return user for given login and password
*/
public User getUserByLoginAndCryptedPassword(String login, String password) {
List<?> list = getSession()
.createQuery(" from User where login=:login and cryptedPassword =:passwd " + removableAndStatemant()).setParameter("login", login)
.setParameter("passwd", password).list();
if (list.size() == 0) {
return null;
} else {
User user = (User) list.get(0);
return user;
}
}
/**
* Returns user with a given login and password.
*
* @param login
* user login
* @param password
* - user password (encrypted)
* @return user for given login and password
*/
public User getUserByLoginAndCryptedPassword(String login, String password) {
List<?> list = getSession()
.createQuery(" from User where login=:login and cryptedPassword =:passwd " + removableAndStatemant())
.setParameter("login", login).setParameter("passwd", password).list();
if (list.size() == 0) {
return null;
} else {
User user = (User) list.get(0);
return user;
}
}
/**
* Returns user with a given login.
*
* @param login
* user login
* @return user for a given login
*/
public User getUserByLogin(String login) {
return getByParameter("login", login);
}
/**
* Returns user with a given login.
*
* @param login
* user login
* @return user for a given login
*/
public User getUserByLogin(String login) {
return getByParameter("login", login);
}
/**
* Returns user with a given email.
*
* @param email
* user email
* @return user for a given email
*/
public User getUserByEmail(String email) {
return getByParameter("email", email);
}
/**
* Returns user with a given email.
*
* @param email
* user email
* @return user for a given email
*/
public User getUserByEmail(String email) {
return getByParameter("email", email);
}
@Override
public void delete(User object) {
object.setRemoved(true);
object.setLogin("[REMOVED]_" + object.getId() + "_" + object.getLogin());
update(object);
}
@Override
public void delete(User object) {
object.setRemoved(true);
object.setLogin("[REMOVED]_" + object.getId() + "_" + object.getLogin());
update(object);
}
/**
* Returns {@link User} for given "name surname" string.
*
* @param nameSurnameString
* string identifing user with name and surname separated by single
* space
* @return {@link User} for given "name surname" string
*/
public User getUserByNameSurname(String nameSurnameString) {
List<?> list = getSession()
.createQuery(" from " + this.getClazz().getSimpleName() + " where concat(name, ' ', surname) " + " = :param_val " + removableAndStatemant())
.setParameter("param_val", nameSurnameString).list();
if (list.size() == 0) {
return null;
} else {
return (User) list.get(0);
}
}
/**
* Returns {@link User} for given "name surname" string.
*
* @param nameSurnameString
* string identifing user with name and surname separated by single
* space
* @return {@link User} for given "name surname" string
*/
public User getUserByNameSurname(String nameSurnameString) {
List<?> list = getSession().createQuery(" from " + this.getClazz().getSimpleName()
+ " where concat(name, ' ', surname) " + " = :param_val " + removableAndStatemant())
.setParameter("param_val", nameSurnameString).list();
if (list.size() == 0) {
return null;
} else {
return (User) list.get(0);
}
}
}
......@@ -122,49 +122,6 @@ public class UserDaoTest extends PersistTestFunctions {
}
}
@Test
public void testGetUserByLoginAndPassword() throws Exception {
try {
User user = new User();
user.setCryptedPassword(passwordEncoder.encode(testPasswd));
user.setLogin(testLogin);
userDao.add(user);
User user2 = userDao.getUserByLoginAndPassword(testLogin, testPasswd);
assertNotNull(user2);
assertEquals(user2.getId(), user.getId());
assertEquals(user2.getLogin(), user.getLogin());
assertEquals(user2.getCryptedPassword(), user.getCryptedPassword());
userDao.delete(user);
// after we remove it we shouldn't be able to get it
User user3 = userDao.getUserByLoginAndPassword(testLogin, testPasswd);
assertNull(user3);
// after we remove it we shouldn't be able to get the removed and modified
// object
User user4 = userDao.getUserByLoginAndPassword(user2.getLogin(), testPasswd);
assertNull(user4);
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
@Test
public void testGetUserByLoginAndEmptyPassword() throws Exception {
try {
User user = new User();
user.setCryptedPassword(passwordEncoder.encode(testPasswd));
user.setLogin(testLogin);
userDao.add(user);
User user2 = userDao.getUserByLoginAndPassword(testLogin, null);
assertNull(user2);
userDao.delete(user);
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
@Test
public void testGetUserByLogin() throws Exception {
try {
......
......@@ -78,7 +78,7 @@ public class LdapService implements ILdapService {
@Override
public boolean login(String login, String password) throws LDAPException {
if (!isValidConfiguratio()) {
if (!isValidConfiguration()) {
logger.warn("Invalid LDAP configuration");
return false;
}
......@@ -98,7 +98,7 @@ public class LdapService implements ILdapService {
@Override
public List<String> getUsernames() throws LDAPException {
if (!isValidConfiguratio()) {
if (!isValidConfiguration()) {
logger.warn("Invalid LDAP configuration");
return new ArrayList<>();
}
......@@ -128,7 +128,7 @@ public class LdapService implements ILdapService {
@Override
public UserDTO getUserByLogin(String login) throws LDAPException {
if (!isValidConfiguratio()) {
if (!isValidConfiguration()) {
logger.warn("Invalid LDAP configuration");
return null;
}
......@@ -187,11 +187,11 @@ public class LdapService implements ILdapService {
}
}
private Filter createObjectClassFilter() {
private Filter createObjectClassFilter() throws LDAPException {
String objectClass = configurationService.getConfigurationValue(ConfigurationElementType.LDAP_OBJECT_CLASS);
if (objectClass == null || objectClass.trim().isEmpty()) {
objectClass = "*";
if (objectClass == null || objectClass.trim().isEmpty() || objectClass .equals( "*")) {
return Filter.create("objectClass=*");
}
return Filter.createEqualityFilter("objectClass", objectClass);
......@@ -220,7 +220,7 @@ public class LdapService implements ILdapService {
}
@Override
public boolean isValidConfiguratio() {
public boolean isValidConfiguration() {
try {
String baseDn = configurationService.getConfigurationValue(ConfigurationElementType.LDAP_BASE_DN);
if (baseDn == null || baseDn.trim().isEmpty()) {
......
......@@ -5,7 +5,6 @@ import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
......@@ -60,7 +59,6 @@ import lcsb.mapviewer.converter.zip.ZipEntryFile;
import lcsb.mapviewer.model.Project;
import lcsb.mapviewer.model.ProjectStatus;
import lcsb.mapviewer.model.cache.UploadedFileEntry;
import lcsb.mapviewer.model.graphics.MapCanvasType;
import lcsb.mapviewer.model.log.LogType;
import lcsb.mapviewer.model.map.BioEntity;
import lcsb.mapviewer.model.map.MiriamData;
......@@ -477,20 +475,7 @@ public class ProjectService implements IProjectService {
for (User user : userDao.getAll()) {
if (!processedUser.contains(user)) {
processedUser.add(user);
for (PrivilegeType type : PrivilegeType.values()) {
if (Project.class.equals(type.getPrivilegeObjectType())) {
int level = userService.getUserPrivilegeLevel(user, type, (Integer) null);
if (level < 0) {
if (configurationService.getValue(type).getValue().equalsIgnoreCase("true")) {
level = 1;
} else {
level = 0;
}
}
ObjectPrivilege privilege = new ObjectPrivilege(project, level, type, user);
userService.setUserPrivilege(user, privilege);
}
}
userService.createDefaultProjectPrivilegesForUser(project, user);
}
}
......
package lcsb.mapviewer.services.impl;
import java.awt.Color;
import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.session.SessionInformation;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import lcsb.mapviewer.commands.ColorExtractor;
import lcsb.mapviewer.common.Configuration;
import lcsb.mapviewer.common.ObjectUtils;
import lcsb.mapviewer.common.comparator.IntegerComparator;
import lcsb.mapviewer.common.exception.InvalidArgumentException;
import lcsb.mapviewer.common.geometry.ColorParser;
import lcsb.mapviewer.model.Project;
import lcsb.mapviewer.model.log.LogType;
import lcsb.mapviewer.model.user.BasicPrivilege;
import lcsb.mapviewer.model.user.ConfigurationElementType;
import lcsb.mapviewer.model.user.ObjectPrivilege;
import lcsb.mapviewer.model.user.PrivilegeType;
import lcsb.mapviewer.model.user.User;
import lcsb.mapviewer.persist.dao.ProjectDao;
import lcsb.mapviewer.persist.dao.user.PrivilegeDao;
import lcsb.mapviewer.persist.dao.user.UserDao;
import lcsb.mapviewer.services.SecurityException;
import lcsb.mapviewer.services.interfaces.IConfigurationService;
import lcsb.mapviewer.services.interfaces.ILogService;
import lcsb.mapviewer.services.interfaces.ILogService.LogParams;
import lcsb.mapviewer.services.interfaces.IUserService;
/**
* Implementation of the service that manages users.
*
* @author Piotr Gawron
*
*/
@Transactional(value = "txManager")
public class UserService implements IUserService {
/**
* Default class logger.
*/
private static Logger logger = Logger.getLogger(UserService.class);
/**
* Data access object for users.
*/
@Autowired
private UserDao userDao;
/**
* Data access object for projects.
*/
@Autowired
private ProjectDao projectDao;
/**
* Data access object for privileges.
*/
@Autowired
private PrivilegeDao privilegeDao;
@Autowired
private SessionRegistry sessionRegistry;
/**
* Service that provides password encoding.
*/
@Autowired
private PasswordEncoder passwordEncoder;
/**
* Service used for logging.
*/
@Autowired
private ILogService logService;
/**
* Service used for accessing configuration parameters.
*/
@Autowired
private IConfigurationService configurationService;
@Override
public String login(String login, String password) {
Random random = new SecureRandom();
String id = new BigInteger(130, random).toString(32);
return this.login(login, password, id);
}
@Override
public boolean userHasPrivilege(User user, PrivilegeType type) {
return getUserPrivilegeLevel(user, type) > 0;
}
@Override
public boolean userHasPrivilege(User user, PrivilegeType type, Object object) {
return getUserPrivilegeLevel(user, type, object) > 0;
}
@Override
public void setUserPrivilege(User user, BasicPrivilege privilege) {
updateUserPrivilegesWithoutDbModification(user, privilege);
updateUser(user);
userDao.flush();
}
private void updateUserPrivilegesWithoutDbModification(User user, BasicPrivilege privilege) {
BasicPrivilege oldPrivilege = null;
for (BasicPrivilege privilegeIter : user.getPrivileges()) {
if (privilegeIter.equalsPrivilege(privilege)) {
oldPrivilege = privilegeIter;
}
}
if (oldPrivilege != null) {
privilege.setUser(null);
oldPrivilege.setLevel(privilege.getLevel());
} else {
privilege.setUser(user);
user.getPrivileges().add(privilege);
}
}
@Override
public void addUser(User user) {
userDao.add(user);
LogParams params = new LogParams().description("User " + user.getLogin() + " created.").type(LogType.USER_CREATED)
.object(user);
logService.log(params);
}
@Override
public void updateUser(User user) {
userDao.update(user);
}
@Override
public void deleteUser(User user) {
userDao.delete(user);
LogParams params = new LogParams().description("User " + user.getLogin() + " removed.").type(LogType.USER_CREATED)
.object(user);
logService.log(params);
}
@Override
public User getUserById(int id) {
User result = userDao.getById(id);
if (result != null) {
userDao.refresh(result);
}
return result;
}
@Override
public User getUserByLogin(String login) {
User result = userDao.getUserByLogin(login);
if (result != null) {
userDao.refresh(result);
}
return result;
}
@Override
public void dropPrivilegesForObjectType(PrivilegeType type, int id) {
IntegerComparator integerComparator = new IntegerComparator();
// this will be slow when number of user will increase (we fetch all
// users and drop privileges one by one)
List<User> users = userDao.getAll();
for (User user : users) {
List<BasicPrivilege> toRemove = new ArrayList<BasicPrivilege>();
for (BasicPrivilege privilege : user.getPrivileges()) {
if (privilege.getType().equals(type) && privilege instanceof ObjectPrivilege
&& integerComparator.compare(((ObjectPrivilege) privilege).getIdObject(), id) == 0) {
toRemove.add(privilege);
}
}
if (toRemove.size() > 0) {
user.getPrivileges().removeAll(toRemove);
userDao.update(user);
}
}
}
@Override
public int getUserPrivilegeLevel(User user, PrivilegeType type) {
if (type.getPrivilegeClassType() != BasicPrivilege.class) {
throw new InvalidArgumentException("This privilege requires additional information");
}
for (BasicPrivilege privilege : user.getPrivileges()) {
if (privilege.getType().equals(type)) {
return privilege.getLevel();
}
}
return 0;
}
@Override
public int getUserPrivilegeLevel(User user, PrivilegeType type, Object object) {
Integer id = null;
if (object != null) {
try {
id = ObjectUtils.getIdOfObject(object);
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new InvalidArgumentException("Internal server error. Problem with accessing id of the parameter object");
}
if (!type.getPrivilegeObjectType().isAssignableFrom(object.getClass())) {
throw new InvalidArgumentException("This privilege accept only " + type.getPrivilegeObjectType()