Search in sources :

Example 6 with Login

use of org.compiere.util.Login in project adempiere by adempiere.

the class AdempiereRealm method authenticate.

public String[] authenticate(String username, String password) {
    KeyNamePair[] roles = null;
    // do authentication
    if (username != null && password != null) {
        // perform db authentication
        Login login = new Login(Env.getCtx());
        roles = login.getRoles(username, password);
    } else {
        // no username or password
        roles = null;
    }
    String[] groups = new String[0];
    List<String> grpList = new ArrayList<String>();
    if (roles != null && roles.length > 0) {
        grpList.add("adempiereUsers");
        for (KeyNamePair knp : roles) {
            grpList.add(knp.getName());
        }
        groupCache.remove(username);
        groupCache.put(username, grpList);
        groups = grpList.toArray(groups);
    }
    return groups;
}
Also used : ArrayList(java.util.ArrayList) KeyNamePair(org.compiere.util.KeyNamePair) Login(org.compiere.util.Login)

Example 7 with Login

use of org.compiere.util.Login in project adempiere by adempiere.

the class WLogin method doPost.

//	doGet
/**
	 *	Process the HTTP Post request.
	 *  <pre>
	 *  - Optionally create Session
	 *  - Check database connection
	 *  - LoginInfo from request?
	 *      - Yes: DoLogin success ?
	 *          - Yes: return (second) preferences page
	 *          - No: return (first) user/password page
	 *      - No: User Principal ?
	 *          - Yes: DoLogin success ?
	 *              - Yes: return (second) preferences page
	 *              - No: return (first) user/password page
	 *          - No: return (first) user/password page
	 *  </pre>
	 *  @param request request
	 *  @param response response
	 *  @throws ServletException
	 *  @throws IOException
	 */
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    log.info("");
    //  Create New Session
    HttpSession sess = request.getSession(true);
    sess.setMaxInactiveInterval(MobileEnv.TIMEOUT);
    //  Get Cookie Properties
    Properties cProp = MobileUtil.getCookieProprties(request);
    //  Create Context
    MobileSessionCtx wsc = MobileSessionCtx.get(request);
    //  Page
    MobileDoc doc = null;
    //  Check DB connection
    if (!DB.isConnected()) {
        String msg = Msg.getMsg(wsc.ctx, "WLoginNoDB");
        if (msg.equals("WLoginNoDB"))
            msg = "No Database Connection";
        doc = MobileDoc.createWindow(msg);
    }
    //  Get Parameters: Role, Client, Org, Warehouse, Date
    String role = MobileUtil.getParameter(request, WLogin.P_ROLE);
    String client = MobileUtil.getParameter(request, WLogin.P_CLIENT);
    String org = MobileUtil.getParameter(request, WLogin.P_ORG);
    String language = MobileUtil.getParameter(request, Env.LANGUAGE);
    if (role != null && client != null && org != null) {
        //  Get Info from Context - User, Role, Client
        int AD_User_ID = Env.getAD_User_ID(wsc.ctx);
        int AD_Role_ID = Env.getAD_Role_ID(wsc.ctx);
        int AD_Client_ID = Env.getAD_Client_ID(wsc.ctx);
        //  Not available in context yet - Org, Warehouse
        int AD_Org_ID = -1;
        int M_Warehouse_ID = -1;
        //  Get latest info from context
        try {
            int req_role = Integer.parseInt(role);
            if (req_role != AD_Role_ID) {
                log.fine("AD_Role_ID - changed from " + AD_Role_ID);
                AD_Role_ID = req_role;
                Env.setContext(wsc.ctx, "#AD_Role_ID", AD_Role_ID);
            }
            log.fine("AD_Role_ID = " + AD_Role_ID);
            //
            int req_client = Integer.parseInt(client);
            if (req_client != AD_Client_ID) {
                log.fine("AD_Client_ID - changed from " + AD_Client_ID);
                AD_Client_ID = req_client;
                Env.setContext(wsc.ctx, "#AD_Client_ID", AD_Client_ID);
            }
            log.fine("AD_Client_ID = " + AD_Client_ID);
            //
            AD_Org_ID = Integer.parseInt(org);
            log.fine("AD_Org_ID = " + AD_Org_ID);
        //
        } catch (Exception e) {
            log.log(Level.SEVERE, "Parameter", e);
            MobileUtil.createTimeoutPage(request, response, this, Msg.getMsg(wsc.ctx, "ParameterMissing"));
            return;
        }
        //  Check Login info and set environment
        wsc.loginInfo = checkLogin(wsc.ctx, AD_User_ID, AD_Role_ID, AD_Client_ID, AD_Org_ID, M_Warehouse_ID);
        if (wsc.loginInfo == null) {
            MobileUtil.createErrorPage(request, response, this, Msg.getMsg(wsc.ctx, "RoleInconsistent"));
            return;
        }
        //  Set Date
        Timestamp ts = MobileUtil.getParameterAsDate(request, WLogin.P_DATE);
        if (ts == null)
            ts = new Timestamp(System.currentTimeMillis());
        //  JDBC format
        Env.setContext(wsc.ctx, "#Date", ts);
        cProp.setProperty(P_ROLE, Integer.toString(AD_Role_ID));
        cProp.setProperty(P_ORG, Integer.toString(AD_Org_ID));
        //  Update Cookie - overwrite
        if (cProp != null) {
            Cookie cookie = new Cookie(MobileEnv.COOKIE_INFO, MobileUtil.propertiesEncode(cProp));
            cookie.setComment("(c) adempiere, Inc - Jorg Janke");
            cookie.setSecure(false);
            cookie.setPath("/");
            if (cProp.size() == 0)
                //  delete cookie
                cookie.setMaxAge(0);
            else
                //  30 days in seconds   60*60*24*30
                cookie.setMaxAge(2592000);
            response.addCookie(cookie);
        }
        response.sendRedirect(MobileEnv.getBaseDirectory("/WMenu"));
        return;
    } else //  Login Info from request?
    {
        //  Get Parameters:     UserName/Password
        String usr = MobileUtil.getParameter(request, P_USERNAME);
        String pwd = MobileUtil.getParameter(request, P_PASSWORD);
        //  Get Principle
        Principal userPrincipal = request.getUserPrincipal();
        log.info("Principal=" + userPrincipal + "; User=" + usr);
        //  Login info not from request and not pre-authorized
        if (userPrincipal == null && (usr == null || pwd == null))
            doc = createFirstPage(cProp, request, "");
        else //  Login info from request or authorized
        {
            KeyNamePair[] roles = null;
            Login login = new Login(wsc.ctx);
            //  Pre-authorized
            if (userPrincipal != null) {
                roles = login.getRoles(userPrincipal);
                usr = userPrincipal.getName();
            } else
                roles = login.getRoles(usr, pwd);
            //
            if (roles == null)
                doc = createFirstPage(cProp, request, Msg.getMsg(wsc.ctx, "UserPwdError"));
            else {
                String sql = "SELECT AD_Role_ID, Name FROM AD_Role WHERE IsMobileAccessible='Y'";
                ArrayList<KeyNamePair> validRoles = new ArrayList();
                try {
                    ValueNamePair[] mobileRoles = DB.getValueNamePairs(sql, false, null);
                    for (KeyNamePair role1 : roles) {
                        for (ValueNamePair mobileRole : mobileRoles) {
                            if (role1.getKey() == Integer.parseInt(mobileRole.getValue())) {
                                validRoles.add(role1);
                                break;
                            }
                        }
                    }
                    roles = new KeyNamePair[validRoles.size()];
                    roles = validRoles.toArray(roles);
                } catch (Exception e) {
                // IsMobileAccessible not supported, allow any role
                }
                cProp.setProperty(P_USERNAME, usr);
                cProp.setProperty(Env.LANGUAGE, language);
                if (roles.length == 0)
                    doc = createFirstPage(cProp, request, Msg.getMsg(wsc.ctx, "UserPwdError"));
                else {
                    String roleData = (cProp.getProperty(P_ROLE, null));
                    doc = createSecondPage(cProp, request, MobileUtil.convertToOption(roles, roleData), "");
                    //	Create adempiere Session - user id in ctx
                    MSession.get(wsc.ctx, request.getRemoteAddr(), request.getRemoteHost(), sess.getId());
                    MobileUtil.createResponseFragment(request, response, this, cProp, doc);
                    return;
                }
            }
        }
    }
    MobileUtil.createResponse(request, response, this, cProp, doc, false);
}
Also used : Cookie(javax.servlet.http.Cookie) HttpSession(javax.servlet.http.HttpSession) ArrayList(java.util.ArrayList) Login(org.compiere.util.Login) Properties(java.util.Properties) Timestamp(java.sql.Timestamp) ServletException(javax.servlet.ServletException) SQLException(java.sql.SQLException) IOException(java.io.IOException) KeyNamePair(org.compiere.util.KeyNamePair) ValueNamePair(org.compiere.util.ValueNamePair) Principal(java.security.Principal)

Example 8 with Login

use of org.compiere.util.Login in project adempiere by adempiere.

the class WLogin method checkLogin.

/**
	 *  Check Login information and set context.
	 *  @return    true if login info are OK
	 *  @param ctx context
	 *  @param AD_User_ID user
	 *  @param AD_Role_ID role
	 *  @param AD_Client_ID client
	 *  @param AD_Org_ID org
	 *  @param M_Warehouse_ID warehouse
	 */
private String checkLogin(Properties ctx, int AD_User_ID, int AD_Role_ID, int AD_Client_ID, int AD_Org_ID, int M_Warehouse_ID) {
    //  Get Login Info
    String loginInfo = null;
    //  Verify existance of User/Client/Org/Role and User's acces to Client & Org
    String sql = "SELECT u.Name || '@' || c.Name || '.' || o.Name || ' [' || INITCAP(USER) || ']' AS Text " + "FROM AD_User u, AD_Client c, AD_Org o, AD_User_Roles ur " + //  #1
    "WHERE u.AD_User_ID=?" + //  #2
    " AND c.AD_Client_ID=?" + //  #3
    " AND o.AD_Org_ID=?" + //  #4
    " AND ur.AD_Role_ID=?" + " AND ur.AD_User_ID=u.AD_User_ID" + " AND (o.AD_Client_ID = 0 OR o.AD_Client_ID=c.AD_Client_ID)" + " AND c.AD_Client_ID IN (SELECT AD_Client_ID FROM AD_Role_OrgAccess ca WHERE ca.AD_Role_ID=ur.AD_Role_ID)" + " AND o.AD_Org_ID IN (SELECT AD_Org_ID FROM AD_Role_OrgAccess ca WHERE ca.AD_Role_ID=ur.AD_Role_ID)";
    try {
        PreparedStatement pstmt = DB.prepareStatement(sql, null);
        pstmt.setInt(1, AD_User_ID);
        pstmt.setInt(2, AD_Client_ID);
        pstmt.setInt(3, AD_Org_ID);
        pstmt.setInt(4, AD_Role_ID);
        ResultSet rs = pstmt.executeQuery();
        if (rs.next())
            loginInfo = rs.getString(1);
        rs.close();
        pstmt.close();
    } catch (SQLException e) {
        log.log(Level.SEVERE, sql, e);
    }
    //  not verified
    if (loginInfo == null)
        return null;
    //  Set Preferences
    KeyNamePair org = new KeyNamePair(AD_Org_ID, String.valueOf(AD_Org_ID));
    KeyNamePair wh = null;
    if (M_Warehouse_ID > 0)
        wh = new KeyNamePair(M_Warehouse_ID, String.valueOf(M_Warehouse_ID));
    //
    Timestamp date = null;
    String printer = null;
    Login login = new Login(ctx);
    login.loadPreferences(org, wh, date, printer);
    //	Don't Show Acct/Trl Tabs on HTML UI
    Env.setContext(ctx, "#ShowAcct", "N");
    Env.setContext(ctx, "#ShowTrl", "N");
    //
    return loginInfo;
}
Also used : SQLException(java.sql.SQLException) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement) KeyNamePair(org.compiere.util.KeyNamePair) Login(org.compiere.util.Login) Timestamp(java.sql.Timestamp)

Example 9 with Login

use of org.compiere.util.Login in project adempiere by adempiere.

the class WLogin method createSecondPage.

//  createFirstPage
/**
	 *  Create Second Page
	 *  @param request request
	 *  @param roleOptions role options
	 *  @param errorMessage error message
	 *  @return WDoc page
	 */
private MobileDoc createSecondPage(Properties cProp, HttpServletRequest request, option[] roleOptions, String errorMessage) {
    log.info(" - " + errorMessage);
    MobileSessionCtx wsc = MobileSessionCtx.get(request);
    String windowTitle = Msg.getMsg(wsc.language, "Login");
    //	Form - Get Menu
    String action = MobileEnv.getBaseDirectory("WLogin");
    form myForm = new form(action).setName("Login2");
    myForm.setID(windowTitle);
    myForm.setTitle(windowTitle);
    myForm.addAttribute("selected", "true");
    myForm.setClass("panel");
    myForm.setMethod("post");
    myForm.setTarget("_self");
    //	Role Pick
    fieldset fs = new fieldset();
    div div1 = new div();
    div1.setClass("row");
    //Modified by Rob Klein 4/29/07
    label roleLabel = new label().setFor(P_ROLE + "F").addElement(Msg.translate(wsc.language, "AD_Role_ID"));
    roleLabel.setID(P_ROLE + "L");
    div1.addElement(roleLabel);
    select role = new select(P_ROLE, roleOptions);
    role.setID(P_ROLE + "F");
    //  sets Client & Org
    role.setOnChange("loginDynUpdate(this);");
    div1.addElement(role);
    fs.addElement(div1);
    Login login = new Login(wsc.ctx);
    //  Get Data
    KeyNamePair[] clients = null;
    if (roleOptions.length > 0)
        clients = login.getClients(new KeyNamePair(Integer.parseInt(roleOptions[0].getAttribute("value")), roleOptions[0].getAttribute("value")));
    //	Client Pick
    div1 = new div();
    div1.setClass("row");
    label clientLabel = new label().setFor(P_CLIENT + "F").addElement(Msg.translate(wsc.language, "AD_Client_ID"));
    clientLabel.setID(P_CLIENT + "L");
    div1.addElement(clientLabel);
    select client = new select(P_CLIENT, MobileUtil.convertToOption(clients, null));
    client.setID(P_CLIENT + "F");
    div1.addElement(new td().addElement(client));
    fs.addElement(div1);
    KeyNamePair[] orgs = null;
    if (clients.length > 0)
        orgs = login.getOrgs(clients[0]);
    //	Org Pick
    div1 = new div();
    div1.setClass("row");
    label orgLabel = new label().setFor(P_ORG + "F").addElement(Msg.translate(wsc.language, "AD_Org_ID"));
    orgLabel.setID(P_ORG + "L");
    div1.addElement(orgLabel);
    String orgData = cProp.getProperty(P_ORG, null);
    select org = new select(P_ORG, MobileUtil.convertToOption(orgs, orgData));
    org.setID(P_ORG + "F");
    div1.addElement(org);
    fs.addElement(div1);
    //  ErrorMessage
    if (errorMessage != null && errorMessage.length() > 0) {
        div1 = new div();
        div1.setClass("row");
        div1.addElement(new strong(errorMessage));
        fs.addElement(div1);
    }
    myForm.addElement(fs);
    //  Finish
    a button = new a("#", "OK");
    button.addAttribute("type", "submit");
    button.setClass("whiteButton");
    myForm.addElement(button);
    //  Document
    MobileDoc doc = MobileDoc.createWindow(windowTitle);
    doc.getBody().addElement(myForm).setTitle("Login");
    return doc;
}
Also used : org.apache.ecs.xhtml.a(org.apache.ecs.xhtml.a) org.apache.ecs.xhtml.meta(org.apache.ecs.xhtml.meta) org.apache.ecs.xhtml.strong(org.apache.ecs.xhtml.strong) org.apache.ecs.xhtml.select(org.apache.ecs.xhtml.select) org.apache.ecs.xhtml.fieldset(org.apache.ecs.xhtml.fieldset) org.apache.ecs.xhtml.label(org.apache.ecs.xhtml.label) Login(org.compiere.util.Login) org.apache.ecs.xhtml.div(org.apache.ecs.xhtml.div) org.apache.ecs.xhtml.td(org.apache.ecs.xhtml.td) org.apache.ecs.xhtml.form(org.apache.ecs.xhtml.form) KeyNamePair(org.compiere.util.KeyNamePair)

Example 10 with Login

use of org.compiere.util.Login in project adempiere by adempiere.

the class LoginPanel method validateLogin.

/**
     *  validates user name and password when logging in
     *
    **/
public void validateLogin() {
    Login login = new Login(ctx);
    String userId = txtUserId.getValue();
    String userPassword = txtPassword.getValue();
    //check is token
    String token = (String) txtPassword.getAttribute("user.token.hash");
    if (token != null && token.equals(userPassword)) {
        userPassword = "";
        int AD_Session_ID = (Integer) txtPassword.getAttribute("user.token.sid");
        MSession session = new MSession(Env.getCtx(), AD_Session_ID, null);
        if (session.get_ID() == AD_Session_ID) {
            MUser user = MUser.get(Env.getCtx(), session.getCreatedBy());
            if (BrowserToken.validateToken(session, user, token)) {
                userPassword = user.getPassword();
            }
        }
    }
    KeyNamePair[] rolesKNPairs = login.getRoles(userId, userPassword);
    if (rolesKNPairs == null || rolesKNPairs.length == 0)
        throw new WrongValueException("User Id or Password invalid!!!");
    else {
        String langName = null;
        if (lstLanguage.getSelectedItem() != null)
            langName = (String) lstLanguage.getSelectedItem().getLabel();
        else
            langName = Language.getBaseLanguage().getName();
        Language language = findLanguage(langName);
        wndLogin.loginOk(userId, userPassword);
        // Elaine 2009/02/06
        Env.setContext(ctx, UserPreference.LANGUAGE_NAME, language.getName());
        Locales.setThreadLocal(language.getLocale());
        String timeoutText = getUpdateTimeoutTextScript();
        if (!Strings.isEmpty(timeoutText))
            Clients.response("zkLocaleJavaScript2", new AuScript(null, timeoutText));
    }
    // This temporary validation code is added to check the reported bug
    // [ adempiere-ZK Web Client-2832968 ] User context lost?
    // https://sourceforge.net/tracker/?func=detail&atid=955896&aid=2832968&group_id=176962
    // it's harmless, if there is no bug then this must never fail
    Session currSess = Executions.getCurrent().getDesktop().getSession();
    currSess.setAttribute("Check_AD_User_ID", Env.getAD_User_ID(ctx));
    // End of temporary code for [ adempiere-ZK Web Client-2832968 ] User context lost?
    Env.setContext(ctx, BrowserToken.REMEMBER_ME, chkRememberMe.isChecked());
    /* Check DB version */
    String version = DB.getSQLValueString(null, "SELECT Version FROM AD_System");
    //  Identical DB version
    if (!Adempiere.DB_VERSION.equals(version)) {
        String AD_Message = "DatabaseVersionError";
        //  Code assumes Database version {0}, but Database has Version {1}.
        //  complete message
        String msg = Msg.getMsg(ctx, AD_Message);
        msg = MessageFormat.format(msg, new Object[] { Adempiere.DB_VERSION, version });
        throw new ApplicationException(msg);
    }
}
Also used : MSession(org.compiere.model.MSession) Login(org.compiere.util.Login) AuScript(org.zkoss.zk.au.out.AuScript) ApplicationException(org.adempiere.webui.exception.ApplicationException) Language(org.compiere.util.Language) KeyNamePair(org.compiere.util.KeyNamePair) MUser(org.compiere.model.MUser) WrongValueException(org.zkoss.zk.ui.WrongValueException) MSession(org.compiere.model.MSession) Session(org.zkoss.zk.ui.Session)

Aggregations

Login (org.compiere.util.Login)29 KeyNamePair (org.compiere.util.KeyNamePair)22 org.apache.ecs.xhtml.p (org.apache.ecs.xhtml.p)8 org.apache.ecs.xhtml.script (org.apache.ecs.xhtml.script)8 Properties (java.util.Properties)6 SQLException (java.sql.SQLException)5 IOException (java.io.IOException)4 PreparedStatement (java.sql.PreparedStatement)4 ResultSet (java.sql.ResultSet)4 Timestamp (java.sql.Timestamp)4 ServletException (javax.servlet.ServletException)3 Principal (java.security.Principal)2 ArrayList (java.util.ArrayList)2 HttpSession (javax.servlet.http.HttpSession)2 Language (org.compiere.util.Language)2 PrintWriter (java.io.PrintWriter)1 AccessException (java.rmi.AccessException)1 Callback (javax.security.auth.callback.Callback)1 NameCallback (javax.security.auth.callback.NameCallback)1 PasswordCallback (javax.security.auth.callback.PasswordCallback)1