class SoapSecurityService extends AbstractService implements SecurityService {

	@Override
	public long storeUser(String sid, WSUser user) throws Exception {
		checkAdministrator(sid);
		User sessionUser = validateSession(sid);

		try {
			GroupDAO gDao = (GroupDAO) Context.get().getBean(GroupDAO.class);
			UserDAO dao = (UserDAO) Context.get().getBean(UserDAO.class);
			User usr = user.toUser();
			usr.setTenantId(sessionUser.getTenantId());

			if (user.getId() != 0) {
				usr = dao.findById(user.getId());
				if (usr.getType() != User.TYPE_DEFAULT) {
					throw new Exception("You cannot edit user with id " + usr.getId() + " because it is a system user");
				}
				usr.setCity(user.getCity());
				usr.setCountry(user.getCountry());
				usr.setEmail(user.getEmail());
				usr.setEmailSignature(user.getEmailSignature());
				usr.setEmail2(user.getEmail2());
				usr.setEmailSignature2(user.getEmailSignature2());
				usr.setFirstName(user.getFirstName());
				usr.setName(user.getName());
				usr.setLanguage(user.getLanguage());
				usr.setPostalcode(user.getPostalcode());
				usr.setState(user.getState());
				usr.setStreet(user.getStreet());
				usr.setTelephone(user.getTelephone());
				usr.setTelephone2(user.getTelephone2());
				usr.setUsername(user.getUsername());
				usr.setEnabled(user.getEnabled());
				usr.setPasswordExpires(user.getPasswordExpires());
				usr.setQuota(user.getQuota());
				usr.setType(user.getType());
				usr.setSource(user.getSource());
			}

			if (StringUtils.isEmpty(usr.getUsername()))
				throw new Exception("Missing mandatory value 'UserName'");
			else if (StringUtils.isEmpty(usr.getEmail()))
				throw new Exception("Missing mandatory value 'Email'");
			else if (StringUtils.isEmpty(usr.getName()))
				throw new Exception("Missing mandatory value 'Name'");
			else if (StringUtils.isEmpty(usr.getFirstName()))
				throw new Exception("Missing mandatory value 'FirstName'");

			if (!dao.store(usr))
				throw new Exception("Unable to store the user");

			if (user.getGroupIds() != null && user.getGroupIds().length > 0) {
				usr.removeGroupMemberships(null);
				for (long groupId : user.getGroupIds())
					usr.addGroup(gDao.findById(groupId));
				dao.store(usr);
			}

			return usr.getId();
		} catch (Throwable t) {
			log.error(t.getMessage(), t);
			throw new Exception(t.getMessage());
		}
	}

}