diff --git a/modules/org.openbravo.client.kernel/src/org/openbravo/client/kernel/KernelServlet.java b/modules/org.openbravo.client.kernel/src/org/openbravo/client/kernel/KernelServlet.java
--- a/modules/org.openbravo.client.kernel/src/org/openbravo/client/kernel/KernelServlet.java
+++ b/modules/org.openbravo.client.kernel/src/org/openbravo/client/kernel/KernelServlet.java
@@ -107,10 +107,6 @@
     }
   }
 
-  public ServletContext getServletContext() {
-    return servletContext;
-  }
-
   protected void processComponentRequest(HttpServletRequest request, HttpServletResponse response)
       throws IOException, ServletException {
 
@@ -219,7 +215,7 @@
     throw new UnsupportedOperationException("Only GET/POST is supported");
   }
 
-  @SuppressWarnings("unchecked")
+  @SuppressWarnings("rawtypes")
   private Map<String, Object> getParameterMap(HttpServletRequest request) {
     final Map<String, Object> parameterMap = new HashMap<String, Object>();
     for (Enumeration keys = request.getParameterNames(); keys.hasMoreElements();) {
diff --git a/modules/org.openbravo.service.integration.google/src/org/openbravo/service/integration/google/GoogleAuthServlet.java b/modules/org.openbravo.service.integration.google/src/org/openbravo/service/integration/google/GoogleAuthServlet.java
--- a/modules/org.openbravo.service.integration.google/src/org/openbravo/service/integration/google/GoogleAuthServlet.java
+++ b/modules/org.openbravo.service.integration.google/src/org/openbravo/service/integration/google/GoogleAuthServlet.java
@@ -19,17 +19,13 @@
 package org.openbravo.service.integration.google;
 
 import java.io.IOException;
-import java.io.PrintWriter;
 import java.util.Map;
 
 import javax.servlet.ServletException;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
-import javax.servlet.http.HttpSession;
 
 import org.apache.log4j.Logger;
-import org.codehaus.jettison.json.JSONException;
-import org.codehaus.jettison.json.JSONObject;
 import org.hibernate.exception.ConstraintViolationException;
 import org.openbravo.base.HttpBaseServlet;
 import org.openbravo.base.VariablesBase;
@@ -39,21 +35,15 @@
 import org.openbravo.dal.core.OBContext;
 import org.openbravo.dal.service.OBCriteria;
 import org.openbravo.dal.service.OBDal;
-import org.openbravo.dal.service.OBQuery;
 import org.openbravo.erpCommon.obps.ActivationKey;
 import org.openbravo.erpCommon.security.SessionLogin;
 import org.openbravo.erpCommon.utility.OBError;
-import org.openbravo.erpCommon.utility.OBVersion;
 import org.openbravo.erpCommon.utility.Utility;
-import org.openbravo.model.ad.access.Session;
 import org.openbravo.model.ad.access.User;
 import org.openbravo.model.ad.access.UserRoles;
-import org.openbravo.model.ad.module.Module;
 import org.openbravo.model.ad.system.Client;
-import org.openbravo.model.ad.system.SystemInformation;
 import org.openbravo.service.integration.openid.OBSOIDUserIdentifier;
 import org.openbravo.service.integration.openid.OpenIDManager;
-import org.openbravo.xmlEngine.XmlDocument;
 import org.openid4java.discovery.Identifier;
 
 /**
@@ -159,18 +149,14 @@
         }
       }
 
-      HttpSession session = req.getSession(true);
-      session.setAttribute("#Authenticated_user", null);
+      vars.removeSessionValue("#Authenticated_user");
 
-      // TODO: Refactor LoginHandler/AuthenticationManager/HttpSecureAppServlet to make this part
-      // of the code extensible with a module
-      // Code copied from LoginHandler
       String sessionId = createDBSession(req, user.getUsername(), user.getId());
-      session.setAttribute("#Authenticated_user", user.getId());
-      session.setAttribute("#AD_SESSION_ID", sessionId);
-      session.setAttribute("#LOGGINGIN", "Y");
+      vars.setSessionValue("#Authenticated_user", user.getId());
+      vars.setSessionValue("#AD_SESSION_ID", sessionId);
+      vars.setSessionValue("#LOGGINGIN", "Y");
 
-      checkLicenseAndGo(req, resp, vars, user.getId(), sessionId, true);
+      resp.sendRedirect(strDireccion + "/security/Menu.html");
 
     } catch (Exception e) {
       log.error("Error processing return of Google Auth Service:" + e.getMessage(), e);
@@ -286,177 +272,4 @@
       return null;
     }
   }
-
-  @SuppressWarnings("incomplete-switch")
-  private void checkLicenseAndGo(HttpServletRequest req, HttpServletResponse res,
-      VariablesSecureApp vars, String strUserAuth, String sessionId, boolean doRedirect)
-      throws IOException, ServletException {
-    OBContext.setAdminMode();
-    try {
-      ActivationKey ak = ActivationKey.getInstance();
-      boolean hasSystem = false;
-
-      try {
-        hasSystem = hasSystemRole(strUserAuth);
-      } catch (Exception ignore) {
-        log4j.error(ignore);
-      }
-      String msgType, action;
-      if (hasSystem) {
-        msgType = "Warning";
-        action = "../security/Menu.html";
-      } else {
-        msgType = "Error";
-        action = "../security/Login_FS.html";
-      }
-
-      // We check if there is a Openbravo Professional Subscription restriction in the license,
-      // or if the last rebuild didn't go well. If any of these are true, then the user is
-      // allowed to login only as system administrator
-      switch (ak.checkOPSLimitations(sessionId)) {
-      case NUMBER_OF_CONCURRENT_USERS_REACHED:
-        String msg = Utility.messageBD(myPool, "NUMBER_OF_CONCURRENT_USERS_REACHED",
-            vars.getLanguage());
-        String title = Utility.messageBD(myPool, "NUMBER_OF_CONCURRENT_USERS_REACHED_TITLE",
-            vars.getLanguage());
-        log4j.warn("Concurrent Users Reached - Session: " + sessionId);
-        updateDBSession(sessionId, msgType.equals("Warning"), "CUR");
-        goToRetry(res, vars, msg, title, msgType, action, doRedirect);
-        return;
-      case NUMBER_OF_SOFT_USERS_REACHED:
-        msg = Utility.messageBD(myPool, "NUMBER_OF_SOFT_USERS_REACHED", vars.getLanguage());
-        title = Utility.messageBD(myPool, "NUMBER_OF_SOFT_USERS_REACHED_TITLE", vars.getLanguage());
-        action = "../security/Menu.html";
-        msgType = "Warning";
-        log4j.warn("Soft Users Reached - Session: " + sessionId);
-        updateDBSession(sessionId, true, "SUR");
-        goToRetry(res, vars, msg, title, msgType, action, doRedirect);
-        return;
-      case OPS_INSTANCE_NOT_ACTIVE:
-        msg = Utility.messageBD(myPool, "OPS_INSTANCE_NOT_ACTIVE", vars.getLanguage());
-        title = Utility.messageBD(myPool, "OPS_INSTANCE_NOT_ACTIVE_TITLE", vars.getLanguage());
-        log4j.warn("Innactive OBPS instance - Session: " + sessionId);
-        updateDBSession(sessionId, msgType.equals("Warning"), "IOBPS");
-        goToRetry(res, vars, msg, title, msgType, action, doRedirect);
-        return;
-      case MODULE_EXPIRED:
-        msg = Utility.messageBD(myPool, "OPS_MODULE_EXPIRED", vars.getLanguage());
-        title = Utility.messageBD(myPool, "OPS_MODULE_EXPIRED_TITLE", vars.getLanguage());
-        StringBuffer expiredMoudules = new StringBuffer();
-        log4j.warn("Expired modules - Session: " + sessionId);
-        for (Module module : ak.getExpiredInstalledModules()) {
-          expiredMoudules.append("<br/>").append(module.getName());
-          log4j.warn("  module:" + module.getName());
-        }
-        msg += expiredMoudules.toString();
-        updateDBSession(sessionId, msgType.equals("Warning"), "ME");
-        goToRetry(res, vars, msg, title, msgType, action, doRedirect);
-        return;
-      }
-
-      // Build checks
-      SystemInformation sysInfo = OBDal.getInstance().get(SystemInformation.class, "0");
-      if (sysInfo.getSystemStatus() == null || sysInfo.getSystemStatus().equals("RB70")
-          || this.globalParameters.getOBProperty("safe.mode", "false").equalsIgnoreCase("false")) {
-        // Last build went fine and tomcat was restarted. We should continue with the rest of checks
-      } else if (sysInfo.getSystemStatus().equals("RB60")
-          || sysInfo.getSystemStatus().equals("RB51")) {
-        String msg = Utility.messageBD(myPool, "TOMCAT_NOT_RESTARTED", vars.getLanguage());
-        String title = Utility.messageBD(myPool, "TOMCAT_NOT_RESTARTED_TITLE", vars.getLanguage());
-        log4j.warn("Tomcat not restarted");
-        updateDBSession(sessionId, true, "RT");
-        goToRetry(res, vars, msg, title, "Warning", "../security/Menu.html", doRedirect);
-        return;
-      } else {
-        String msg = Utility.messageBD(myPool, "LAST_BUILD_FAILED", vars.getLanguage());
-        String title = Utility.messageBD(myPool, "LAST_BUILD_FAILED_TITLE", vars.getLanguage());
-        updateDBSession(sessionId, msgType.equals("Warning"), "LBF");
-        goToRetry(res, vars, msg, title, msgType, action, doRedirect);
-        return;
-      }
-
-      // All checks passed successfully, continue logging in
-      res.sendRedirect(strDireccion);
-    } finally {
-      OBContext.restorePreviousMode();
-    }
-  }
-
-  private void updateDBSession(String sessionId, boolean sessionActive, String status) {
-    try {
-      OBContext.setAdminMode();
-      Session session = OBDal.getInstance().get(Session.class, sessionId);
-      session.setSessionActive(sessionActive);
-      session.setLoginStatus(status);
-      OBDal.getInstance().flush();
-    } catch (Exception e) {
-      log4j.error("Error updating session in DB", e);
-    } finally {
-      OBContext.restorePreviousMode();
-    }
-
-  }
-
-  private void goToRetry(HttpServletResponse response, VariablesSecureApp vars, String message,
-      String title, String msgType, String action, boolean doRedirect) throws IOException,
-      ServletException {
-    String msg = (message != null && !message.equals("")) ? message
-        : "Please enter your username and password.";
-
-    if (OBVersion.getInstance().is30() && !doRedirect) {
-      // 3.0 instances show the message in the same login window, return a json object with the info
-      // to print the message
-      try {
-        JSONObject jsonMsg = new JSONObject();
-        jsonMsg.put("showMessage", true);
-        jsonMsg.put("target", "Error".equals(msgType) ? null : action);
-        jsonMsg.put("messageType", msgType);
-        jsonMsg.put("messageTitle", title);
-        jsonMsg.put("messageText", msg);
-
-        response.setContentType("application/json;charset=UTF-8");
-        final PrintWriter out = response.getWriter();
-        out.print(jsonMsg.toString());
-        out.close();
-      } catch (JSONException e) {
-        log4j.error("Error setting login msg", e);
-        throw new ServletException(e);
-      }
-    } else {
-      // 2.50 instances show the message in a new window, print that window
-      String discard[] = { "" };
-
-      if (msgType.equals("Error")) {
-        discard[0] = "continueButton";
-      } else {
-        discard[0] = "backButton";
-      }
-
-      final XmlDocument xmlDocument = xmlEngine.readXmlTemplate(
-          "org/openbravo/base/secureApp/HtmlErrorLogin", discard).createXmlDocument();
-
-      // pass relevant mesasge to show inside the error page
-      xmlDocument.setParameter("theme", vars.getTheme());
-      xmlDocument.setParameter("messageType", msgType);
-      xmlDocument.setParameter("action", action);
-      xmlDocument.setParameter("messageTitle", title);
-      xmlDocument.setParameter("messageMessage", msg.replaceAll("\\\\n", "<br>"));
-
-      response.setContentType("text/html");
-      final PrintWriter out = response.getWriter();
-      out.println(xmlDocument.print());
-      out.close();
-    }
-  }
-
-  private boolean hasSystemRole(String userId) throws Exception {
-    OBQuery<UserRoles> urQuery = OBDal.getInstance().createQuery(UserRoles.class,
-        "userContact.id = :userid and role.userLevel = 'S'");
-    urQuery.setNamedParameter("userid", userId);
-    urQuery.setFilterOnReadableClients(false);
-    urQuery.setFilterOnReadableOrganization(false);
-
-    return urQuery.count() > 0;
-  }
-
 }
diff --git a/src/index.jsp b/src/index.jsp
--- a/src/index.jsp
+++ b/src/index.jsp
@@ -7,7 +7,7 @@
 <%@ page import="org.apache.log4j.Logger" %>
 <%@ page contentType="text/html; charset=UTF-8" %>
 <%
-/*
+  /*
  *************************************************************************
  * The contents of this file are subject to the Openbravo  Public  License
  * Version  1.1  (the  "License"),  being   the  Mozilla   Public  License
diff --git a/src/org/openbravo/authentication/AuthenticationException.java b/src/org/openbravo/authentication/AuthenticationException.java
--- a/src/org/openbravo/authentication/AuthenticationException.java
+++ b/src/org/openbravo/authentication/AuthenticationException.java
@@ -1,6 +1,6 @@
 /*
  ************************************************************************************
- * Copyright (C) 2001-2010 Openbravo S.L.U.
+ * Copyright (C) 2001-2011 Openbravo S.L.U.
  * Licensed under the Apache Software License version 2.0
  * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
  * Unless required by applicable law or agreed to  in writing,  software  distributed
@@ -12,31 +12,34 @@
 
 package org.openbravo.authentication;
 
+import org.openbravo.base.exception.OBException;
+import org.openbravo.erpCommon.utility.OBError;
+
 /**
  * 
  * @author adrianromero
+ * @author iperdomo
  */
-public class AuthenticationException extends java.lang.Exception {
+public class AuthenticationException extends OBException {
   private static final long serialVersionUID = 1L;
+  private OBError error;
 
-  /**
-   * Creates a new instance of <code>AuthenticationException</code> without detail message.
-   */
-  public AuthenticationException() {
+  public AuthenticationException(String msg) {
+    super(msg);
+    this.error = null;
   }
 
-  /**
-   * Constructs an instance of <code>AuthenticationException</code> with the specified detail
-   * message.
-   * 
-   * @param msg
-   *          the detail message.
-   */
-  public AuthenticationException(String msg) {
-    super(msg);
+  public AuthenticationException(String msg, Throwable cause) {
+    super(msg, cause);
+    this.error = null;
   }
 
-  public AuthenticationException(String msg, Throwable t) {
-    super(msg, t);
+  public AuthenticationException(String msg, OBError error) {
+    super(msg);
+    this.error = error;
+  }
+
+  public OBError getOBError() {
+    return error;
   }
 }
diff --git a/src/org/openbravo/authentication/AuthenticationManager.java b/src/org/openbravo/authentication/AuthenticationManager.java
--- a/src/org/openbravo/authentication/AuthenticationManager.java
+++ b/src/org/openbravo/authentication/AuthenticationManager.java
@@ -1,6 +1,6 @@
 /*
  ************************************************************************************
- * Copyright (C) 2001-2010 Openbravo S.L.U.
+ * Copyright (C) 2001-2011 Openbravo S.L.U.
  * Licensed under the Apache Software License version 2.0
  * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
  * Unless required by applicable law or agreed to  in writing,  software  distributed
@@ -13,23 +13,291 @@
 package org.openbravo.authentication;
 
 import java.io.IOException;
+import java.io.PrintWriter;
 
 import javax.servlet.ServletException;
 import javax.servlet.http.HttpServlet;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 
+import org.apache.log4j.Logger;
+import org.codehaus.jettison.json.JSONException;
+import org.codehaus.jettison.json.JSONObject;
+import org.openbravo.base.HttpBaseUtils;
+import org.openbravo.base.VariablesBase;
+import org.openbravo.base.secureApp.DefaultValidationException;
+import org.openbravo.base.secureApp.LoginUtils;
+import org.openbravo.base.secureApp.VariablesSecureApp;
+import org.openbravo.base.session.OBPropertiesProvider;
+import org.openbravo.dal.core.OBContext;
+import org.openbravo.dal.service.OBDal;
+import org.openbravo.dal.service.OBQuery;
+import org.openbravo.database.ConnectionProvider;
+import org.openbravo.erpCommon.obps.ActivationKey;
+import org.openbravo.erpCommon.utility.OBError;
+import org.openbravo.erpCommon.utility.Utility;
+import org.openbravo.model.ad.access.Session;
+import org.openbravo.model.ad.access.UserRoles;
+import org.openbravo.model.ad.module.Module;
+import org.openbravo.model.ad.system.SystemInformation;
+import org.openbravo.service.db.DalConnectionProvider;
+
 /**
  * 
  * @author adrianromero
+ * @author iperdomo
  */
-public interface AuthenticationManager {
+public abstract class AuthenticationManager {
 
-  public void init(HttpServlet s) throws AuthenticationException;
+  private static final Logger log4j = Logger.getLogger(AuthenticationManager.class);
 
-  public String authenticate(HttpServletRequest request, HttpServletResponse response)
+  protected ConnectionProvider conn = null;
+  protected String defaultServletUrl = null;
+  protected String localAdress = null;
+
+  public AuthenticationManager() {
+  }
+
+  public AuthenticationManager(HttpServlet s) throws AuthenticationException {
+    init(s);
+  }
+
+  protected void bdErrorAjax(HttpServletResponse response, String strType, String strTitle,
+      String strText) throws IOException {
+    response.setContentType("text/xml; charset=UTF-8");
+    PrintWriter out = response.getWriter();
+    out.println("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n");
+    out.println("<xml-structure>\n");
+    out.println("  <status>\n");
+    out.println("    <type>" + strType + "</type>\n");
+    out.println("    <title>" + strTitle + "</title>\n");
+    out.println("    <description><![CDATA[" + strText + "]]></description>\n");
+    out.println("  </status>\n");
+    out.println("</xml-structure>\n");
+    out.close();
+  }
+
+  public void init(HttpServlet s) throws AuthenticationException {
+    if (s instanceof ConnectionProvider) {
+      conn = (ConnectionProvider) s;
+    } else {
+      conn = new DalConnectionProvider();
+    }
+    defaultServletUrl = s.getServletConfig().getServletContext()
+        .getInitParameter("ServletSinIdentificar");
+  }
+
+  public final String authenticate(HttpServletRequest request, HttpServletResponse response)
+      throws AuthenticationException, ServletException, IOException {
+
+    if (localAdress == null) {
+      localAdress = HttpBaseUtils.getLocalAddress(request);
+    }
+
+    final String userId = doAuthenticate(request, response);
+
+    if (userId == null && !response.isCommitted()) {
+      response.sendRedirect(localAdress + defaultServletUrl);
+      return null;
+    }
+
+    return userId;
+  }
+
+  public final void logout(HttpServletRequest request, HttpServletResponse response)
+      throws ServletException, IOException {
+
+    VariablesBase vars = new VariablesBase(request);
+    vars.clearSession(true);
+
+    doLogout(request, response);
+  }
+
+  protected abstract String doAuthenticate(HttpServletRequest request, HttpServletResponse response)
       throws AuthenticationException, ServletException, IOException;
 
-  public void logout(HttpServletRequest request, HttpServletResponse response)
+  protected abstract void doLogout(HttpServletRequest request, HttpServletResponse response)
       throws ServletException, IOException;
+
+  private void checkLicense(HttpServletResponse res, VariablesSecureApp vars, String strUserAuth,
+      String sessionId) throws IOException, ServletException {
+    OBContext.setAdminMode();
+    try {
+      final ActivationKey ak = ActivationKey.getInstance();
+      final OBError errorMsg = new OBError();
+      String msgType = "Warning", msg = null, title = null;
+
+      try {
+        msgType = hasSystemRole(strUserAuth) ? "Warning" : "Error";
+      } catch (Exception ignore) {
+      }
+
+      // We check if there is a Openbravo Professional Subscription restriction in the license,
+      // or if the last rebuild didn't go well. If any of these are true, then the user is
+      // allowed to login only as system administrator
+      switch (ak.checkOPSLimitations(sessionId)) {
+      case NUMBER_OF_CONCURRENT_USERS_REACHED:
+        msg = Utility.messageBD(conn, "NUMBER_OF_CONCURRENT_USERS_REACHED", vars.getLanguage());
+        title = Utility.messageBD(conn, "NUMBER_OF_CONCURRENT_USERS_REACHED_TITLE",
+            vars.getLanguage());
+        log4j.warn("Concurrent Users Reached - Session: " + sessionId);
+        updateDBSession(sessionId, msgType.equals("Warning"), "CUR");
+        errorMsg.setMessage(msg);
+        errorMsg.setTitle(title);
+        break;
+      case NUMBER_OF_SOFT_USERS_REACHED:
+        msg = Utility.messageBD(conn, "NUMBER_OF_SOFT_USERS_REACHED", vars.getLanguage());
+        title = Utility.messageBD(conn, "NUMBER_OF_SOFT_USERS_REACHED_TITLE", vars.getLanguage());
+        log4j.warn("Soft Users Reached - Session: " + sessionId);
+        updateDBSession(sessionId, true, "SUR");
+        errorMsg.setMessage(msg);
+        errorMsg.setTitle(title);
+        break;
+      case OPS_INSTANCE_NOT_ACTIVE:
+        msg = Utility.messageBD(conn, "OPS_INSTANCE_NOT_ACTIVE", vars.getLanguage());
+        title = Utility.messageBD(conn, "OPS_INSTANCE_NOT_ACTIVE_TITLE", vars.getLanguage());
+        log4j.warn("Innactive OBPS instance - Session: " + sessionId);
+        updateDBSession(sessionId, msgType.equals("Warning"), "IOBPS");
+        errorMsg.setMessage(msg);
+        errorMsg.setTitle(title);
+        break;
+      case MODULE_EXPIRED:
+        msg = Utility.messageBD(conn, "OPS_MODULE_EXPIRED", vars.getLanguage());
+        title = Utility.messageBD(conn, "OPS_MODULE_EXPIRED_TITLE", vars.getLanguage());
+        StringBuffer expiredMoudules = new StringBuffer();
+        log4j.warn("Expired modules - Session: " + sessionId);
+        for (Module module : ak.getExpiredInstalledModules()) {
+          expiredMoudules.append("<br/>").append(module.getName());
+          log4j.warn("  module:" + module.getName());
+        }
+        msg += expiredMoudules.toString();
+        updateDBSession(sessionId, msgType.equals("Warning"), "ME");
+        errorMsg.setMessage(msg);
+        errorMsg.setTitle(title);
+        return;
+      case NO_RESTRICTION:
+        break;
+      }
+
+      // Build checks
+      SystemInformation sysInfo = OBDal.getInstance().get(SystemInformation.class, "0");
+      if (sysInfo.getSystemStatus() == null
+          || sysInfo.getSystemStatus().equals("RB70")
+          || OBPropertiesProvider.getInstance().getOpenbravoProperties()
+              .getProperty("safe.mode", "false").equalsIgnoreCase("false")) {
+        // Last build went fine and tomcat was restarted. We should continue with the rest of checks
+      } else if (sysInfo.getSystemStatus().equals("RB60")
+          || sysInfo.getSystemStatus().equals("RB51")) {
+        msg = Utility.messageBD(conn, "TOMCAT_NOT_RESTARTED", vars.getLanguage());
+        title = Utility.messageBD(conn, "TOMCAT_NOT_RESTARTED_TITLE", vars.getLanguage());
+        log4j.warn("Tomcat not restarted");
+        updateDBSession(sessionId, true, "RT");
+
+        return;
+      } else {
+        msg = Utility.messageBD(conn, "LAST_BUILD_FAILED", vars.getLanguage());
+        title = Utility.messageBD(conn, "LAST_BUILD_FAILED_TITLE", vars.getLanguage());
+        updateDBSession(sessionId, msgType.equals("Warning"), "LBF");
+
+        return;
+      }
+
+      try {
+        LoginUtils.getLoginDefaults(strUserAuth, "", conn);
+      } catch (DefaultValidationException e) {
+        updateDBSession(sessionId, false, "F");
+        title = Utility.messageBD(conn, "InvalidDefaultLoginTitle", vars.getLanguage()).replace(
+            "%0", e.getDefaultField());
+        msg = Utility.messageBD(conn, "InvalidDefaultLoginMsg", vars.getLanguage()).replace("%0",
+            e.getDefaultField());
+
+        return;
+      }
+
+      // All checks passed successfully, continue logging in
+
+    } finally {
+      OBContext.restorePreviousMode();
+    }
+
+  }
+
+  private void updateDBSession(String sessionId, boolean sessionActive, String status) {
+    try {
+      OBContext.setAdminMode();
+      Session session = OBDal.getInstance().get(Session.class, sessionId);
+      session.setSessionActive(sessionActive);
+      session.setLoginStatus(status);
+      OBDal.getInstance().flush();
+    } catch (Exception e) {
+      log4j.error("Error updating session in DB", e);
+    } finally {
+      OBContext.restorePreviousMode();
+    }
+
+  }
+
+  private void goToTarget(HttpServletResponse response, VariablesSecureApp vars, boolean doRedirect)
+      throws IOException, ServletException {
+
+    String target = vars.getSessionValue("target");
+
+    if (target.equals("")) {
+      target = localAdress + "/security/Menu.html";
+    }
+
+    if (doRedirect) {
+      response.sendRedirect(target);
+      return;
+    }
+
+    try {
+      JSONObject jsonResult = new JSONObject();
+      jsonResult.put("showMessage", false);
+      jsonResult.put("target", target);
+
+      response.setContentType("application/json;charset=UTF-8");
+      final PrintWriter out = response.getWriter();
+      out.print(jsonResult.toString());
+      out.close();
+    } catch (JSONException e) {
+      log4j.error("Error setting login msg", e);
+      throw new ServletException(e);
+    }
+  }
+
+  private void goToRetry(HttpServletResponse response, VariablesSecureApp vars, String message,
+      String title, String msgType, String action, boolean doRedirect) throws IOException,
+      ServletException {
+    String msg = (message != null && !message.equals("")) ? message
+        : "Please enter your username and password.";
+
+    try {
+      JSONObject jsonMsg = new JSONObject();
+      jsonMsg.put("showMessage", true);
+      jsonMsg.put("target", "Error".equals(msgType) ? null : action);
+      jsonMsg.put("messageType", msgType);
+      jsonMsg.put("messageTitle", title);
+      jsonMsg.put("messageText", msg);
+
+      response.setContentType("application/json;charset=UTF-8");
+      final PrintWriter out = response.getWriter();
+      out.print(jsonMsg.toString());
+      out.close();
+    } catch (JSONException e) {
+      log4j.error("Error setting login msg", e);
+      throw new ServletException(e);
+    }
+
+  }
+
+  private boolean hasSystemRole(String userId) throws Exception {
+    OBQuery<UserRoles> urQuery = OBDal.getInstance().createQuery(UserRoles.class,
+        "userContact.id = :userid and role.userLevel = 'S'");
+    urQuery.setNamedParameter("userid", userId);
+    urQuery.setFilterOnReadableClients(false);
+    urQuery.setFilterOnReadableOrganization(false);
+
+    return urQuery.count() > 0;
+  }
 }
diff --git a/src/org/openbravo/authentication/basic/AutologonAuthenticationManager.java b/src/org/openbravo/authentication/basic/AutologonAuthenticationManager.java
--- a/src/org/openbravo/authentication/basic/AutologonAuthenticationManager.java
+++ b/src/org/openbravo/authentication/basic/AutologonAuthenticationManager.java
@@ -1,6 +1,6 @@
 /*
  ************************************************************************************
- * Copyright (C) 2001-2010 Openbravo S.L.U.
+ * Copyright (C) 2001-2011 Openbravo S.L.U.
  * Licensed under the Apache Software License version 2.0
  * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
  * Unless required by applicable law or agreed to  in writing,  software  distributed
@@ -24,42 +24,48 @@
 import org.openbravo.authentication.AuthenticationManager;
 import org.openbravo.base.ConfigParameters;
 import org.openbravo.base.HttpBaseUtils;
-import org.openbravo.database.ConnectionProvider;
 
 /**
  * 
  * @author adrianromero
+ * @author iperdomo
  */
-public class AutologonAuthenticationManager implements AuthenticationManager {
+public class AutologonAuthenticationManager extends AuthenticationManager {
 
   private String m_sAutologonUsername;
   private String m_sUserId = null;
 
-  /** Creates a new instance of FixedAuthenticationManager */
   public AutologonAuthenticationManager() {
   }
 
+  public AutologonAuthenticationManager(HttpServlet s) throws AuthenticationException {
+    super(s);
+  }
+
+  @Override
   public void init(HttpServlet s) throws AuthenticationException {
 
-    if (s instanceof ConnectionProvider) {
-      ConnectionProvider conn = (ConnectionProvider) s;
-      m_sAutologonUsername = ConfigParameters
-          .retrieveFrom(s.getServletConfig().getServletContext()).getOBProperty(
-              "authentication.autologon.username");
-      try {
-        m_sUserId = AuthenticationData.getUserId(conn, m_sAutologonUsername);
-      } catch (ServletException e) {
-        throw new AuthenticationException("Cannot authenticate user: " + m_sAutologonUsername, e);
-      }
+    super.init(s);
 
-    } else {
-      throw new AuthenticationException("Connection provider required for Autologon authentication");
+    m_sAutologonUsername = ConfigParameters.retrieveFrom(s.getServletConfig().getServletContext())
+        .getOBProperty("authentication.autologon.username");
+
+    try {
+      m_sUserId = AuthenticationData.getUserId(conn, m_sAutologonUsername);
+    } catch (ServletException e) {
+      throw new AuthenticationException("Cannot authenticate user: " + m_sAutologonUsername, e);
     }
   }
 
-  public String authenticate(HttpServletRequest request, HttpServletResponse response)
+  @Override
+  protected void doLogout(HttpServletRequest request, HttpServletResponse response)
+      throws ServletException, IOException {
+    response.sendRedirect(HttpBaseUtils.getLocalAddress(request));
+  }
+
+  @Override
+  protected String doAuthenticate(HttpServletRequest request, HttpServletResponse response)
       throws AuthenticationException, ServletException, IOException {
-
     if (m_sUserId == null || m_sUserId.equals("") || m_sUserId.equals("-1")) {
       if (m_sAutologonUsername == null || m_sAutologonUsername.equals("")) {
         throw new AuthenticationException("Autologon user emtpy.");
@@ -71,10 +77,4 @@
       return m_sUserId;
     }
   }
-
-  public void logout(HttpServletRequest request, HttpServletResponse response)
-      throws ServletException, IOException {
-    // Never logs out this manager, just go to menu.
-    response.sendRedirect(HttpBaseUtils.getLocalAddress(request) + "/security/Menu.html");
-  }
 }
\ No newline at end of file
diff --git a/src/org/openbravo/authentication/basic/DefaultAuthenticationManager.java b/src/org/openbravo/authentication/basic/DefaultAuthenticationManager.java
--- a/src/org/openbravo/authentication/basic/DefaultAuthenticationManager.java
+++ b/src/org/openbravo/authentication/basic/DefaultAuthenticationManager.java
@@ -13,120 +13,164 @@
 package org.openbravo.authentication.basic;
 
 import java.io.IOException;
-import java.io.PrintWriter;
 
 import javax.servlet.ServletException;
 import javax.servlet.http.HttpServlet;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
-import javax.servlet.http.HttpSession;
 
+import org.apache.commons.lang.StringUtils;
 import org.apache.log4j.Logger;
 import org.openbravo.authentication.AuthenticationException;
 import org.openbravo.authentication.AuthenticationManager;
 import org.openbravo.base.HttpBaseUtils;
+import org.openbravo.base.secureApp.LoginUtils;
 import org.openbravo.base.secureApp.VariablesHistory;
-import org.openbravo.database.ConnectionProvider;
+import org.openbravo.base.secureApp.VariablesSecureApp;
+import org.openbravo.dal.core.OBContext;
+import org.openbravo.dal.service.OBDal;
+import org.openbravo.erpCommon.security.SessionLogin;
+import org.openbravo.erpCommon.utility.OBError;
 import org.openbravo.erpCommon.utility.Utility;
+import org.openbravo.model.ad.access.Session;
 
 /**
  * 
  * @author adrianromero
+ * @author iperdomo
  */
-public class DefaultAuthenticationManager implements AuthenticationManager {
+public class DefaultAuthenticationManager extends AuthenticationManager {
 
-  private ConnectionProvider conn = null;
-  private String strServletSinIdentificar = null;
-  private Logger log4j = Logger.getLogger(DefaultAuthenticationManager.class);
+  private static final Logger log4j = Logger.getLogger(DefaultAuthenticationManager.class);
 
-  /** Creates a new instance of DefaultAuthenticationManager */
   public DefaultAuthenticationManager() {
   }
 
-  public void init(HttpServlet s) throws AuthenticationException {
-    if (s instanceof ConnectionProvider) {
-      conn = (ConnectionProvider) s;
-      strServletSinIdentificar = s.getServletConfig().getServletContext()
-          .getInitParameter("ServletSinIdentificar");
+  public DefaultAuthenticationManager(HttpServlet s) throws AuthenticationException {
+    super(s);
+  }
+
+  @Override
+  protected String doAuthenticate(HttpServletRequest request, HttpServletResponse response)
+      throws AuthenticationException, ServletException, IOException {
+
+    final VariablesSecureApp vars = new VariablesSecureApp(request);
+    final String sUserId = (String) request.getSession().getAttribute("#Authenticated_user");
+    final String strAjax = vars.getStringParameter("IsAjaxCall");
+
+    if (!StringUtils.isEmpty(sUserId)) {
+      return sUserId;
+    }
+
+    VariablesHistory variables = new VariablesHistory(request);
+
+    // Begins code related to login process
+
+    final String strUser = vars.getStringParameter("user");
+    final String strPass = vars.getStringParameter("password");
+
+    if (StringUtils.isEmpty(strUser)) {
+      return null; // just give up, return null
+    }
+
+    final String userId = LoginUtils.getValidUserId(conn, strUser, strPass);
+    final String sessionId = createDBSession(request, strUser, userId);
+
+    if (userId == null) {
+
+      OBError errorMsg = new OBError();
+      errorMsg.setType("Error");
+
+      if (LoginUtils.checkUserPassword(conn, strUser, "") == null) {
+        log4j.debug("Failed user/password. Username: " + strUser + " - Session ID:" + sessionId);
+        errorMsg.setTitle("IDENTIFICATION_FAILURE_TITLE");
+        errorMsg.setMessage("IDENTIFICATION_FAILURE_MSG");
+      } else {
+        log4j.debug(strUser + " is locked cannot activate session ID " + sessionId);
+        errorMsg.setTitle("LOCKED_USER_TITLE");
+        errorMsg.setMessage("LOCKED_USER_MSG");
+        updateDBSession(sessionId, false, "LU");
+      }
+
+      // throw error message will be caught by LoginHandler
+      throw new AuthenticationException("IDENTIFICATION_FAILURE_TITLE", errorMsg);
+    }
+
+    // Using the Servlet API instead of vars.setSessionValue to avoid breaking code
+    // vars.setSessionValue always transform the key to upper-case
+    request.getSession(true).setAttribute("#Authenticated_user", userId);
+
+    vars.setSessionValue("#AD_SESSION_ID", sessionId);
+    vars.setSessionValue("#LogginIn", "Y");
+
+    if (!StringUtils.isEmpty(strAjax) && StringUtils.isEmpty(userId)) {
+      bdErrorAjax(response, "Error", "",
+          Utility.messageBD(this.conn, "NotLogged", variables.getLanguage()));
+      return null;
     } else {
-      throw new AuthenticationException("Connection provider required for default authentication");
+      // redirects to the menu or the menu with the target
+      String strTarget = request.getRequestURL().toString();
+      String qString = request.getQueryString();
+      String strDireccionLocal = HttpBaseUtils.getLocalAddress(request);
+
+      if (!strTarget.endsWith("/security/Menu.html")) {
+        variables.setSessionValue("targetmenu", strTarget);
+      }
+
+      // Storing target string to redirect after a successful login
+      variables.setSessionValue("target", strDireccionLocal + "/security/Menu.html"
+          + (qString != null && !qString.equals("") ? "?" + qString : ""));
+      if (qString != null && !qString.equals("")) {
+        variables.setSessionValue("targetQueryString", qString);
+      }
+    }
+
+    return userId;
+  }
+
+  private String createDBSession(HttpServletRequest req, String strUser, String strUserAuth) {
+    try {
+      String usr = strUserAuth == null ? "0" : strUserAuth;
+
+      final SessionLogin sl = new SessionLogin(req, "0", "0", usr);
+
+      if (strUserAuth == null) {
+        sl.setStatus("F");
+      } else {
+        sl.setStatus("S");
+      }
+
+      sl.setUserName(strUser);
+      sl.setServerUrl(HttpBaseUtils.getLocalAddress(req));
+      sl.save();
+      return sl.getSessionID();
+    } catch (Exception e) {
+      log4j.error("Error creating DB session", e);
+      return null;
     }
   }
 
-  public String authenticate(HttpServletRequest request, HttpServletResponse response)
-      throws AuthenticationException, ServletException, IOException {
-    String sUserId = (String) request.getSession(true).getAttribute("#Authenticated_user");
+  private void updateDBSession(String sessionId, boolean sessionActive, String status) {
+    try {
+      OBContext.setAdminMode();
+      Session session = OBDal.getInstance().get(Session.class, sessionId);
+      session.setSessionActive(sessionActive);
+      session.setLoginStatus(status);
+      OBDal.getInstance().flush();
+    } catch (Exception e) {
+      log4j.error("Error updating session in DB", e);
+    } finally {
+      OBContext.restorePreviousMode();
+    }
 
-    if (sUserId == null || sUserId.equals("")) {
-      String strAjax = "";
-      // strHidden and strPopUp not implemented
-      /*
-       * String strHidden = ""; String strPopUp = "";
-       */
-      try {
-        strAjax = request.getParameter("IsAjaxCall");
-      } catch (Exception ignored) {
-      }
-      /*
-       * try { strHidden = request.getParameter("IsHiddenCall"); } catch (Exception ignored) {} try
-       * { strPopUp = request.getParameter("IsPopUpCall"); } catch (Exception ignored) {}
-       */
-      VariablesHistory variables = new VariablesHistory(request);
+  }
 
-      if (strAjax != null && !strAjax.equals("")) {
-        bdErrorAjax(response, "Error", "",
-            Utility.messageBD(this.conn, "NotLogged", variables.getLanguage()));
-      } else {
-        // redirects to the menu or the menu with the target
-        String strTarget = request.getRequestURL().toString();
-        if (!strTarget.endsWith("/security/Menu.html")) {
-          variables.setSessionValue("targetmenu", strTarget);
-        }
+  @Override
+  protected void doLogout(HttpServletRequest request, HttpServletResponse response)
+      throws ServletException, IOException {
 
-        String qString = request.getQueryString();
-
-        String strDireccionLocal = HttpBaseUtils.getLocalAddress(request);
-
-        // Storing target string to redirect after a successful login
-        variables.setSessionValue("target", strDireccionLocal + "/security/Menu.html"
-            + (qString != null && !qString.equals("") ? "?" + qString : ""));
-        if (qString != null && !qString.equals("")) {
-          variables.setSessionValue("targetQueryString", qString);
-        }
-        response.sendRedirect(strDireccionLocal + strServletSinIdentificar);
-      }
-      return null;
-    } else {
-      return sUserId;
+    if (!response.isCommitted()) {
+      response.sendRedirect(HttpBaseUtils.getLocalAddress(request));
     }
   }
-
-  private void bdErrorAjax(HttpServletResponse response, String strType, String strTitle,
-      String strText) throws IOException {
-    response.setContentType("text/xml; charset=UTF-8");
-    PrintWriter out = response.getWriter();
-    out.println("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n");
-    out.println("<xml-structure>\n");
-    out.println("  <status>\n");
-    out.println("    <type>" + strType + "</type>\n");
-    out.println("    <title>" + strTitle + "</title>\n");
-    out.println("    <description><![CDATA[" + strText + "]]></description>\n");
-    out.println("  </status>\n");
-    out.println("</xml-structure>\n");
-    out.close();
-  }
-
-  public void logout(HttpServletRequest request, HttpServletResponse response)
-      throws ServletException, IOException {
-
-    // if HttpSession is still valid, then 'logout' by removing #Authenticated_user from it
-    HttpSession session = request.getSession(false);
-    if (session != null) {
-      session.removeAttribute("#Authenticated_user");
-    }
-
-    if (!response.isCommitted())
-      response.sendRedirect(HttpBaseUtils.getLocalAddress(request));
-  }
-
 }
diff --git a/src/org/openbravo/base/secureApp/HttpSecureAppServlet.java b/src/org/openbravo/base/secureApp/HttpSecureAppServlet.java
--- a/src/org/openbravo/base/secureApp/HttpSecureAppServlet.java
+++ b/src/org/openbravo/base/secureApp/HttpSecureAppServlet.java
@@ -138,25 +138,25 @@
 
     try {
       m_AuthManager = (AuthenticationManager) Class.forName(sAuthManagerClass).newInstance();
+      m_AuthManager.init(this);
     } catch (final Exception e) {
       log4j
           .error("Defined authentication manager cannot be loaded. Verify the 'authentication.class' entry in Openbravo.properties");
-      m_AuthManager = new DefaultAuthenticationManager();
+      try {
+        m_AuthManager = new DefaultAuthenticationManager(this);
+      } catch (AuthenticationException e1) {
+        log4j.error("Error trying to initilize Authentication Manager", e1);
+        return;
+      }
     }
 
-    try {
-      m_AuthManager.init(this);
-    } catch (final AuthenticationException e) {
-      log4j.error("Unable to initialize authentication manager", e);
-    }
-
-    if (log4j.isDebugEnabled())
-      log4j.debug("strdireccion: " + strDireccion);
+    log4j.debug("strdireccion: " + strDireccion);
 
     // Calculate class info
     try {
-      if (log4j.isDebugEnabled())
-        log4j.debug("Servlet request for class info: " + this.getClass());
+
+      log4j.debug("Servlet request for class info: " + this.getClass());
+
       if (classInfo == null) {
         ClassInfoData[] classInfoAux = ClassInfoData.select(this, this.getClass().getName());
         if (classInfoAux != null && classInfoAux.length > 0)
@@ -313,6 +313,7 @@
             logout(request, response);
             return;
           }
+          variables.removeSessionValue("#LOGGINGIN");
         } else {
           variables.updateHistory(request);
         }
@@ -657,23 +658,6 @@
    * 
    * @param response
    *          the HttpServletResponse object
-   * @param strTitle
-   *          the title of the popup window
-   * @param strText
-   *          the text to be displayed in the popup message area
-   * @throws IOException
-   *           if an error occurs writing to the output stream
-   */
-  private void advisePopUpRefresh(HttpServletRequest request, HttpServletResponse response,
-      String strTitle, String strText) throws IOException {
-    advisePopUpRefresh(request, response, "Error", strTitle, strText);
-  }
-
-  /**
-   * Creates a pop up that when closed, will refresh the parent window.
-   * 
-   * @param response
-   *          the HttpServletResponse object
    * @param strType
    *          the type of message to be displayed (e.g. ERROR, SUCCESS)
    * @param strTitle
@@ -952,9 +936,8 @@
   protected void whitePage(HttpServletResponse response, String strAlert) throws IOException {
     final XmlDocument xmlDocument = xmlEngine.readXmlTemplate(
         "org/openbravo/base/secureApp/HtmlWhitePage").createXmlDocument();
-    if (strAlert == null)
-      strAlert = "";
-    xmlDocument.setParameter("body", strAlert);
+
+    xmlDocument.setParameter("body", strAlert == null ? "" : strAlert);
 
     response.setContentType("text/html; charset=UTF-8");
     final PrintWriter out = response.getWriter();
@@ -982,19 +965,6 @@
     printPageClosePopUp(response, vars, "");
   }
 
-  private void printPageClosePopUpWindow(HttpServletResponse response, VariablesSecureApp vars)
-      throws IOException, ServletException {
-    if (log4j.isDebugEnabled())
-      log4j.debug("Output: PopUp Response");
-    final XmlDocument xmlDocument = xmlEngine.readXmlTemplate(
-        "org/openbravo/base/secureApp/PopUp_Close").createXmlDocument();
-    xmlDocument.setParameter("language", "defaultLang=\"" + vars.getLanguage() + "\";");
-    response.setContentType("text/html; charset=UTF-8");
-    final PrintWriter out = response.getWriter();
-    out.println(xmlDocument.print());
-    out.close();
-  }
-
   protected void printPagePopUpDownload(ServletOutputStream os, String fileName)
       throws IOException, ServletException {
     if (log4j.isDebugEnabled())
diff --git a/src/org/openbravo/base/secureApp/LoginHandler.java b/src/org/openbravo/base/secureApp/LoginHandler.java
--- a/src/org/openbravo/base/secureApp/LoginHandler.java
+++ b/src/org/openbravo/base/secureApp/LoginHandler.java
@@ -14,20 +14,24 @@
 import java.io.IOException;
 import java.io.PrintWriter;
 
-import javax.servlet.ServletConfig;
 import javax.servlet.ServletException;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
-import javax.servlet.http.HttpSession;
 
+import org.apache.commons.lang.StringUtils;
 import org.codehaus.jettison.json.JSONException;
 import org.codehaus.jettison.json.JSONObject;
+import org.openbravo.authentication.AuthenticationException;
+import org.openbravo.authentication.AuthenticationManager;
+import org.openbravo.authentication.basic.DefaultAuthenticationManager;
 import org.openbravo.base.HttpBaseServlet;
+import org.openbravo.base.session.OBPropertiesProvider;
+import org.openbravo.base.util.OBClassLoader;
 import org.openbravo.dal.core.OBContext;
 import org.openbravo.dal.service.OBDal;
 import org.openbravo.erpCommon.obps.ActivationKey;
 import org.openbravo.erpCommon.security.Login;
-import org.openbravo.erpCommon.security.SessionLogin;
+import org.openbravo.erpCommon.utility.OBError;
 import org.openbravo.erpCommon.utility.OBVersion;
 import org.openbravo.erpCommon.utility.Utility;
 import org.openbravo.model.ad.access.Session;
@@ -51,26 +55,18 @@
  */
 public class LoginHandler extends HttpBaseServlet {
   private static final long serialVersionUID = 1L;
-  private static final String APRM_MIGRATION_TOOL_ID = "4BD3D4B262B048518FE62496EF09D549";
-  private String strServletPorDefecto;
-
-  @Override
-  public void init(ServletConfig config) {
-    super.init(config);
-    strServletPorDefecto = config.getServletContext().getInitParameter("DefaultServlet");
-  }
+  private static final String DEFAULT_AUTH_CLASS = "org.openbravo.authentication.basic.DefaultAuthenticationManager";
 
   @Override
   public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException,
       ServletException {
 
-    if (log4j.isDebugEnabled()) {
-      log4j.debug("start doPost");
-    }
+    log4j.debug("start doPost");
+
     final VariablesSecureApp vars = new VariablesSecureApp(req);
 
     // Empty session
-    req.getSession(true).setAttribute("#Authenticated_user", null);
+    vars.removeSessionValue("#Authenticated_user");
 
     final String strUser = vars.getStringParameter("user");
 
@@ -89,37 +85,47 @@
       if (strUser.equals("") && !OBVersion.getInstance().is30()) {
         res.sendRedirect(res.encodeRedirectURL(strDireccion + "/security/Login_F1.html"));
       } else {
-        final String strPass = vars.getStringParameter("password");
-        final String strUserAuth = LoginUtils.getValidUserId(myPool, strUser, strPass);
 
-        String sessionId = createDBSession(req, strUser, strUserAuth);
-        if (strUserAuth != null) {
-          HttpSession session = req.getSession(true);
-          session.setAttribute("#Authenticated_user", strUserAuth);
-          session.setAttribute("#AD_SESSION_ID", sessionId);
-          // #logginigIn attribute is used in HttpSecureAppServlet to determine whether the logging
-          // process is complete or not. At this stage is not complete, we only have a user ID, but
-          // no the rest of session info: client, org, role...
-          session.setAttribute("#LOGGINGIN", "Y");
-          log4j.debug("Correct user/password. Username: " + strUser + " - Session ID:" + sessionId);
+        try {
+
+          AuthenticationManager authManager;
+          String authClass = OBPropertiesProvider.getInstance().getOpenbravoProperties()
+              .getProperty("authentication.class", DEFAULT_AUTH_CLASS);
+
+          try {
+            authManager = (AuthenticationManager) OBClassLoader.getInstance().loadClass(authClass)
+                .newInstance();
+            authManager.init(this);
+          } catch (Exception e) {
+            log4j.error("Error trying to instantiate auth-manager class: " + e.getMessage(), e);
+            authManager = new DefaultAuthenticationManager(this);
+          }
+
+          final String strUserAuth = authManager.authenticate(req, res);
+          final String sessionId = vars.getSessionValue("#AD_Session_ID");
+
+          if (StringUtils.isEmpty(strUserAuth)) {
+            throw new AuthenticationException("Message");// FIXME
+          }
+
           checkLicenseAndGo(res, vars, strUserAuth, sessionId, doRedirect);
-        } else {
-          // strUserAuth can be null because a failed user/password or because the user is locked
-          String failureTitle;
-          String failureMessage;
-          if (LoginUtils.checkUserPassword(myPool, strUser, strPass) == null) {
-            log4j
-                .debug("Failed user/password. Username: " + strUser + " - Session ID:" + sessionId);
-            failureTitle = Utility.messageBD(this, "IDENTIFICATION_FAILURE_TITLE", language);
-            failureMessage = Utility.messageBD(this, "IDENTIFICATION_FAILURE_MSG", language);
+
+        } catch (AuthenticationException e) {
+
+          final OBError errorMsg = e.getOBError();
+
+          if (errorMsg != null) {
+            vars.removeSessionValue("#LoginErrorMsg");
+
+            final String failureTitle = Utility.messageBD(this, errorMsg.getTitle(), language);
+            final String failureMessage = Utility.messageBD(this, errorMsg.getMessage(), language);
+
+            goToRetry(res, vars, failureMessage, failureTitle, "Error",
+                "../security/Login_FS.html", doRedirect);
+
           } else {
-            failureTitle = Utility.messageBD(this, "LOCKED_USER_TITLE", language);
-            failureMessage = Utility.messageBD(this, "LOCKED_USER_MSG", language);
-            log4j.debug(strUser + " is locked cannot activate session ID " + sessionId);
-            updateDBSession(sessionId, false, "LU");
+            throw new ServletException("Error"); // FIXME
           }
-          goToRetry(res, vars, failureMessage, failureTitle, "Error", "../security/Login_FS.html",
-              doRedirect);
         }
       }
     } finally {
@@ -127,32 +133,6 @@
     }
   }
 
-  /**
-   * Stores session in DB. If the user is valid, it is inserted in the createdBy column, if not user
-   * 0 is used.
-   */
-  private String createDBSession(HttpServletRequest req, String strUser, String strUserAuth) {
-    try {
-      String usr = strUserAuth == null ? "0" : strUserAuth;
-
-      final SessionLogin sl = new SessionLogin(req, "0", "0", usr);
-
-      if (strUserAuth == null) {
-        sl.setStatus("F");
-      } else {
-        sl.setStatus("S");
-      }
-
-      sl.setUserName(strUser);
-      sl.setServerUrl(strDireccion);
-      sl.save();
-      return sl.getSessionID();
-    } catch (Exception e) {
-      log4j.error("Error creating DB session", e);
-      return null;
-    }
-  }
-
   private void checkLicenseAndGo(HttpServletResponse res, VariablesSecureApp vars,
       String strUserAuth, String sessionId, boolean doRedirect) throws IOException,
       ServletException {
@@ -217,6 +197,8 @@
         updateDBSession(sessionId, msgType.equals("Warning"), "ME");
         goToRetry(res, vars, msg, title, msgType, action, doRedirect);
         return;
+      case NO_RESTRICTION:
+        break;
       }
 
       // Build checks
diff --git a/src/org/openbravo/base/secureApp/LoginUtils.java b/src/org/openbravo/base/secureApp/LoginUtils.java
--- a/src/org/openbravo/base/secureApp/LoginUtils.java
+++ b/src/org/openbravo/base/secureApp/LoginUtils.java
@@ -317,7 +317,7 @@
    * Obtains defaults defined for a user and throws DefaultValidationException in case they are not
    * correct.
    */
-  static RoleDefaults getLoginDefaults(String strUserAuth, String role, ConnectionProvider cp)
+  public static RoleDefaults getLoginDefaults(String strUserAuth, String role, ConnectionProvider cp)
       throws ServletException, DefaultValidationException {
     String strRole = role;
     if (strRole.equals("")) {
