Subversion Repositories bacoAlunos

Rev

Rev 1317 | Rev 1554 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

package pt.estgp.estgweb.services.authenticate;

import jomm.dao.impl.AbstractDao;
import jomm.utils.BytesUtils;
import jomm.utils.DesUtils;
import openldap.ILdapManager;
import openldap.LdapManagerFactory;
import org.apache.log4j.Logger;
import pt.estgp.estgweb.Globals;
import pt.estgp.estgweb.domain.*;
import pt.estgp.estgweb.domain.dao.DaoFactory;
import pt.estgp.estgweb.services.common.CommonServicesManager;
import pt.estgp.estgweb.services.expceptions.ServiceException;
import pt.estgp.estgweb.services.ftpservices.FtpService;
import pt.estgp.estgweb.utils.ConfigProperties;
import pt.utl.ist.berserk.logic.serviceManager.IService;

import java.util.*;


/*
 * @author Goncalo Luiz gedl [AT] rnl [DOT] ist [DOT] utl [DOT] pt
 *
 *
 * Created at 17/Out/2003 , 23:45:24
 *
 */

/**
 * @author Jorge Machado
 *
 *
 * Created at 17/Out/2003 , 23:45:24
 *
 */

public class AuthenticateService implements IService
{
    private static final 1.5.0/docs/api/java/util/logging/Logger.html">Logger logger = 1.5.0/docs/api/java/util/logging/Logger.html">Logger.getLogger(AuthenticateService.class);

    private static final boolean USE_LDAP = ConfigProperties.getBooleanProperty("use.ldap");

    ILdapManager ldapManager = LdapManagerFactory.getLdapManager();

    public UserSession run(1.5.0/docs/api/java/lang/String.html">String username, 1.5.0/docs/api/java/lang/String.html">String password, UserSession userSession) throws ServiceException
    {
        if(userSession.getUser() != null)
            throw new AuthenticateException(AuthenticateException.ALREADY_AUTHENTICATED);

        if(username == null || username.trim().length() == 0 || password == null || password.trim().length() == 0)
            throw new AuthenticateException(AuthenticateException.FAIL_AUTHENTICATION);
        boolean go = false;
        if(USE_LDAP)
            go = ldapManager.login(username,password);

        User u = null;
        if(!go)
        {
            u = DaoFactory.getUserDaoImpl().loadByUsernameAndPassword(username,password);
            if(u == null)
            {
                logger.warn("user:" + username + " fail password");
                throw new AuthenticateException(AuthenticateException.FAIL_AUTHENTICATION);
            }

            logger.warn("user:" + username + " fail LDAP but pass local authentication");
        }
        else
            try
            {
                u = DaoFactory.getUserDaoImpl().loadByUsername(username);
            }
            catch(1.5.0/docs/api/java/lang/Throwable.html">Throwable e){}

        if(u == null)
        {
            logger.warn("user:" + username + " does not exist");
            throw new AuthenticateException(AuthenticateException.DOES_NOT_EXIST);
            /*
            u = getUserInfo(username);
            u.setPassword(password);
            //put password to be complete for advising
            CommonServicesManager.getInstance().adviseNew(u);
//            u.setPassword(null); OLD Line now we save the last sucessfully password in DB
            u.setPassword(jomm.utils.BytesUtils.getDigestMD5Hex(password));
            if(u.getRoles().contains("teacher"))
            {

            }
            else if (u.getRoles().contains("student"))
            {

            }*/

        }
        else
        {
//            String passwordAux = u.getPassword();
            u.setPassword(password);

            CommonServicesManager.getInstance().adviseUpdate(u);
//            u.setPassword(passwordAux);
            u.setPassword(jomm.utils.BytesUtils.getDigestMD5Hex(password));
        }

        //CHECK USER BLOCK's
        if(!u.isAdmin() && !u.isSuperuser())
        {
            if(u.isAutoBlockMode() && u.isAutoBlock()
                    ||
                    !u.isAutoBlockMode() && u.isManualBlock())
            {
                logger.warn("user:" + username + " blocked");
                throw  new AuthenticateException(AuthenticateException.BLOCKED);
            }
        }

        logger.warn("user:" + username + " authenticated");

        //((UserSessionImpl)userSession).reset();
        //((UserSessionImpl)userSession).clearObjectsWithOpenTransaction();

        //DaoFactory.getUserSessionDaoImpl().flush();

        //PASSWORD PARA SERVICOS FTP CLIENT
                ((UserSessionImpl) userSession).put(FtpService.FTP_PASSWORD, DesUtils.getInstance().encrypt(password));
        //put password to be complete for advising
        userSession.setName(u.getName());
        userSession.setUsername(u.getUsername());
        userSession.setUser(u);
        if(u.getRoles() == null || u.getRoles().trim().length() == 0)
            u.setRoles(Globals.ROLE_INVITED);

        DaoFactory.getUserSessionDaoImpl().reattach(userSession);
        return userSession;
    }

    private User getUserInfo(1.5.0/docs/api/java/lang/String.html">String username)
    {
        1.5.0/docs/api/java/util/HashMap.html">HashMap map = ldapManager.getUserInfo(username);
        UserImpl u = DomainObjectFactory.createUserImpl();
        u.setUsername(username);
        u.setName(getName(map));
        u.setRoles(getRoles(map));
        u.setNewUser(true);
        /*todo call commonServices Manager advise New put Password First*/
        DaoFactory.getUserDaoImpl().save(u);
        return u;
    }

    private 1.5.0/docs/api/java/lang/String.html">String getName(1.5.0/docs/api/java/util/HashMap.html">HashMap text)
    {
        1.5.0/docs/api/java/util/Set.html">Set s = text.entrySet();
        1.5.0/docs/api/java/util/Iterator.html">Iterator iter = s.iterator();
        int iterCount=0;
        1.5.0/docs/api/java/lang/String.html">String name=null;

        while(iter.hasNext())
        {
            1.5.0/docs/api/java/util/Map.Entry.html">Map.Entry e = (1.5.0/docs/api/java/util/Map.Entry.html">Map.Entry) iter.next();
            if(iterCount==3)
            {
                name=e.getValue().toString();
            }
            iterCount++;
        }
        return name;
    }

    public 1.5.0/docs/api/java/lang/String.html">String getRoles(1.5.0/docs/api/java/util/HashMap.html">HashMap text)
    {
        1.5.0/docs/api/java/util/Set.html">Set s = text.entrySet();
        1.5.0/docs/api/java/util/Iterator.html">Iterator iter = s.iterator();
        int iterCount=0;
        1.5.0/docs/api/java/lang/String.html">String roles=null;

        while(iter.hasNext())
        {
            1.5.0/docs/api/java/util/Map.Entry.html">Map.Entry e = (1.5.0/docs/api/java/util/Map.Entry.html">Map.Entry) iter.next();
            if(iterCount==0)
            {
                1.5.0/docs/api/java/lang/String.html">String[] splitText=e.getValue().toString().split(",");
                if(splitText[1].contains("CN"))
                {
                    roles="student";
                }
                else if(splitText[1].contains("OU"))
                {
                    roles="teacher";
                }
            }
            iterCount++;
        }
        return roles;
    }


    public UserSession loginPae(1.5.0/docs/api/java/lang/String.html">String username, 1.5.0/docs/api/java/lang/String.html">String password, UserSession userSession) throws ServiceException
    {
        if(userSession.getUser() != null)
        {
            new LogoutService().run(userSession);
        }

        if(username == null || username.trim().length() == 0 || password == null || password.trim().length() == 0)
            throw new AuthenticateException(AuthenticateException.FAIL_AUTHENTICATION);

        User u = null;

        boolean go = false;
        try{
            try{
            u = DaoFactory.getUserDaoImpl().loadBySigesCode(new 1.5.0/docs/api/java/lang/Integer.html">Integer(username));
            }catch(1.5.0/docs/api/java/lang/Exception.html">Exception e){}
            if(u == null)
                u = DaoFactory.getUserDaoImpl().loadByUsername(username);

            if(u == null)
                throw new AuthenticateException(AuthenticateException.DOES_NOT_EXIST);
            go = u.getPasswordSiges() != null && u.getPasswordSiges().equals(jomm.utils.BytesUtils.getDigestMD5Hex(password));
            if(go)
            {
                logger.info("siges:" + username + " login:PASSSIGES");
            }
            else
            {
                go = u.getPassword() != null && u.getPassword().equals(jomm.utils.BytesUtils.getDigestMD5Hex(password));
                if(go)
                {
                    logger.info("siges:" + username + " login:PASSBACO");
                }
                else
                {
                    go = u.getBi() != null && u.getBi().equals(password);
                    if(go)
                    {
                        logger.info("siges:" + username + " login:BI");
                    }
                }
            }
        }
        catch(1.5.0/docs/api/java/lang/Throwable.html">Throwable e)
        {

        }
        if(!go)
        {
            logger.warn("siges:" + username + " fail password");
            throw new AuthenticateException(AuthenticateException.FAIL_AUTHENTICATION);
        }




        //CHECK USER BLOCK's
        if(!u.isAdmin() && !u.isSuperuser())
        {
            if(u.isAutoBlockMode() && u.isAutoBlock()
                    ||
                    !u.isAutoBlockMode() && u.isManualBlock())
            {
                logger.warn("siges:" + username + " blocked");
                throw new AuthenticateException(AuthenticateException.BLOCKED);
            }
        }

        logger.warn("siges:" + username + " authenticated");

        userSession.setName(u.getName());
        userSession.setUsername(u.getUsername());
        userSession.setUser(u);
        if(u.getRoles() == null || u.getRoles().trim().length() == 0)
            u.setRoles(Globals.ROLE_INVITED);

        DaoFactory.getUserSessionDaoImpl().reattach(userSession);
        return userSession;
    }

    public UserSession loginCertificate(1.5.0/docs/api/java/lang/String.html">String certificate, UserSession userSession) throws ServiceException
    {
        if(userSession.getUser() != null)
        {
            new LogoutService().run(userSession);
        }

        if(certificate == null || certificate.trim().length() == 0)
            throw new AuthenticateException(AuthenticateException.FAIL_AUTHENTICATION);

        User u = null;

        List<User> users = DaoFactory.getUserDaoImpl().loadByCertificate(certificate);
        if(users == null || users.size() > 1 || users.size()== 0)
        {
            if(users.size() > 1)
                logger.error("Erro dois users com o mesmo certificado");
            throw  new AuthenticateException(AuthenticateException.FAIL_AUTHENTICATION);
        }
        u = users.get(0);
        logger.info("certificate:" + u.getUsername() + " login:certificate:" + certificate);
        //CHECK USER BLOCK's
        if(!u.isAdmin() && !u.isSuperuser())
        {
            if(u.isAutoBlockMode() && u.isAutoBlock()
                    ||
                    !u.isAutoBlockMode() && u.isManualBlock())
            {
                logger.warn("certificate:" + u.getUsername() + " blocked");
                throw new AuthenticateException(AuthenticateException.BLOCKED);
            }
        }

        logger.warn("certificate:" + u.getUsername() + " authenticated");

        userSession.setName(u.getName());
        userSession.setUsername(u.getUsername());
        userSession.setUser(u);
        if(u.getRoles() == null || u.getRoles().trim().length() == 0)
            u.setRoles(Globals.ROLE_INVITED);

        DaoFactory.getUserSessionDaoImpl().reattach(userSession);
        return userSession;
    }

    /**
     * Create a new Certificate for usage in URL auto login
     *
     * @param userId
     * @return the certificate string to use in URL
     */

    public 1.5.0/docs/api/java/lang/String.html">String createCertificateForId(long userId, UserSession usersession)
    {
        User u = DaoFactory.getUserDaoImpl().load(userId);
        return createCertificate(u, usersession);
    }
    /**
     * Create a new Certificate for usage in URL auto login
     *
     * @param user to crate certificate
     * @return the certificate string
     */

    public 1.5.0/docs/api/java/lang/String.html">String createCertificate(User user, UserSession usersession)
    {
        1.5.0/docs/api/java/lang/String.html">String certificate = user.getId()
                + "-" + 1.5.0/docs/api/java/lang/System.html">System.currentTimeMillis()
                + "-" + 1.5.0/docs/api/java/lang/Thread.html">Thread.currentThread().hashCode()
                + "-" +  1.5.0/docs/api/java/lang/Runtime.html">Runtime.getRuntime().freeMemory();
        1.5.0/docs/api/java/lang/String.html">String md5 = BytesUtils.getMD5(certificate);
        user.setAuthenticationCertificate(md5);
        //3600 seconds = 1 hour = 3600.000 milis * 24 = 1 day * 15 = 15 days
        long daysInMilis =  3600 * 1000 * 24 * Globals.CERTIFICATES_EXPIRTATION_IN_DAYS;
        user.setAuthenticationCertificateExpire(new 5+0%2Fdocs%2Fapi+Date">Date(1.5.0/docs/api/java/lang/System.html">System.currentTimeMillis()+daysInMilis));
        return md5;
    }

    public static void main(1.5.0/docs/api/java/lang/String.html">String [] args)
    {
        AbstractDao.getCurrentSession().beginTransaction();
        1.5.0/docs/api/java/lang/String.html">String certificate = new AuthenticateService().createCertificateForId(1691,null);
        AbstractDao.getCurrentSession().getTransaction().commit();

    }
}