001/*
002 * This library is part of OpenCms -
003 * the Open Source Content Management System
004 *
005 * Copyright (c) Alkacon Software GmbH & Co. KG (http://www.alkacon.com)
006 *
007 * This library is free software; you can redistribute it and/or
008 * modify it under the terms of the GNU Lesser General Public
009 * License as published by the Free Software Foundation; either
010 * version 2.1 of the License, or (at your option) any later version.
011 *
012 * This library is distributed in the hope that it will be useful,
013 * but WITHOUT ANY WARRANTY; without even the implied warranty of
014 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
015 * Lesser General Public License for more details.
016 *
017 * For further information about Alkacon Software GmbH & Co. KG, please see the
018 * company website: http://www.alkacon.com
019 *
020 * For further information about OpenCms, please see the
021 * project website: http://www.opencms.org
022 *
023 * You should have received a copy of the GNU Lesser General Public
024 * License along with this library; if not, write to the Free Software
025 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
026 */
027
028package org.opencms.workplace;
029
030import org.opencms.db.CmsUserSettings;
031import org.opencms.file.CmsProject;
032import org.opencms.i18n.CmsEncoder;
033import org.opencms.main.CmsException;
034import org.opencms.main.OpenCms;
035import org.opencms.security.CmsRole;
036import org.opencms.security.CmsSecurityException;
037import org.opencms.site.CmsSite;
038import org.opencms.util.CmsStringUtil;
039
040import java.util.Iterator;
041
042import javax.servlet.http.HttpServletRequest;
043import javax.servlet.http.HttpServletResponse;
044import javax.servlet.http.HttpSession;
045import javax.servlet.jsp.PageContext;
046
047/**
048 * Handles front-end login of users to the OpenCms workplace into the given site and project.<p>
049 *
050 * @since 7.0.3
051 */
052public class CmsLoginHelper extends CmsWorkplace {
053
054    /** The login exception. */
055    private CmsException m_loginException;
056
057    /**
058     * Public constructor with JSP variables.<p>
059     *
060     * @param context the JSP page context
061     * @param req the JSP request
062     * @param res the JSP response
063     */
064    public CmsLoginHelper(PageContext context, HttpServletRequest req, HttpServletResponse res) {
065
066        super(context, req, res);
067    }
068
069    /**
070     * Returns the loginException.<p>
071     *
072     * @return the loginException
073     */
074    public CmsException getLoginException() {
075
076        return m_loginException;
077    }
078
079    /**
080     * Returns the formatted stack trace.<p>
081     *
082     * @return the formatted stack trace
083     */
084    public String getStacktrace() {
085
086        String stacktrace = CmsException.getStackTraceAsString(getLoginException());
087        stacktrace = CmsEncoder.escapeXml(stacktrace);
088        return stacktrace;
089    }
090
091    /**
092     * Logs the user into the given project and site.<p>
093     *
094     * Check the {@link #getLoginException()} for the error message.<p>
095     *
096     * @param userName the user name
097     * @param password the password
098     * @param projectName the optional project name, if <code>null</code> the default project is used
099     * @param siteRoot the site of the resource, if <code>null</code> the default site is used
100     * @param resourceName the resource to display
101     *
102     * @return <code>true</code> if the login has been successful
103     */
104    public boolean login(String userName, String password, String projectName, String siteRoot, String resourceName) {
105
106        if (getCms().getRequestContext().getCurrentUser().isGuestUser()) {
107            if (CmsStringUtil.isEmptyOrWhitespaceOnly(userName) || CmsStringUtil.isEmptyOrWhitespaceOnly(password)) {
108                return false;
109            }
110            // login the user
111            try {
112                getCms().loginUser(userName, password, getCms().getRequestContext().getRemoteAddress());
113            } catch (CmsException e) {
114                m_loginException = e;
115                return false;
116            }
117        }
118
119        // the user is logged in
120        CmsUserSettings userSettings = new CmsUserSettings(getCms());
121        // set the project
122        try {
123            if (CmsStringUtil.isEmptyOrWhitespaceOnly(projectName)) {
124                // use the default project of the user
125                projectName = userSettings.getStartProject();
126            }
127            // read the project
128            CmsProject project = getCms().readProject(projectName);
129            if (OpenCms.getOrgUnitManager().getAllAccessibleProjects(getCms(), project.getOuFqn(), false).contains(
130                project)) {
131                // user has access to the project, set this as current project
132                getCms().getRequestContext().setCurrentProject(project);
133            } else {
134                throw new CmsSecurityException(
135                    Messages.get().container(Messages.ERR_PROJECT_NOT_ACCESSIBLE_2, userName, projectName));
136            }
137        } catch (CmsException e) {
138            m_loginException = e;
139        }
140
141        if (m_loginException == null) {
142            // set the site
143            try {
144                if (CmsStringUtil.isEmptyOrWhitespaceOnly(siteRoot)) {
145                    // set the default site root of the user
146                    siteRoot = userSettings.getStartSite();
147                }
148                // set the site root if accessible
149                String oldSite = getCms().getRequestContext().getSiteRoot();
150                try {
151                    getCms().getRequestContext().setSiteRoot("");
152                    getCms().readResource(siteRoot);
153                } finally {
154                    getCms().getRequestContext().setSiteRoot(oldSite);
155                }
156                boolean hasAccess = false;
157                CmsSite site = OpenCms.getSiteManager().getSiteForSiteRoot(siteRoot);
158                Iterator<CmsSite> accessibles = OpenCms.getSiteManager().getAvailableSites(getCms(), false).iterator();
159                while (accessibles.hasNext() && !hasAccess && (site != null)) {
160                    CmsSite accessible = accessibles.next();
161                    if (accessible.getSiteRoot().equals(site.getSiteRoot())) {
162                        hasAccess = true;
163                    }
164                }
165                if (hasAccess) {
166                    // user has access to the site, set this as current site
167                    getCms().getRequestContext().setSiteRoot(siteRoot);
168                } else {
169                    throw new CmsSecurityException(
170                        Messages.get().container(Messages.ERR_SITE_NOT_ACCESSIBLE_2, userName, siteRoot));
171                }
172            } catch (CmsException e) {
173                m_loginException = e;
174            }
175        }
176
177        // try to read the resource to display
178        try {
179            getCms().readResource(resourceName);
180        } catch (CmsException e) {
181            m_loginException = e;
182        }
183
184        if (m_loginException != null) {
185            // if an error occurred during login, invalidate the session
186            HttpSession session = getJsp().getRequest().getSession(false);
187            if (session != null) {
188                session.invalidate();
189            }
190            return false;
191        }
192
193        // only for content creators so that direct edit works
194        if (OpenCms.getRoleManager().hasRole(getCms(), CmsRole.ELEMENT_AUTHOR)) {
195            // get / create the workplace settings
196            CmsWorkplaceSettings wpSettings = getSettings();
197            if (wpSettings == null) {
198                // create the settings object
199                wpSettings = new CmsWorkplaceSettings();
200                wpSettings = initWorkplaceSettings(getCms(), wpSettings, false);
201            }
202            // set the settings for the workplace
203            wpSettings.setSite(getCms().getRequestContext().getSiteRoot());
204            wpSettings.setProject(getCms().getRequestContext().getCurrentProject().getUuid());
205            wpSettings.setUser(getCms().getRequestContext().getCurrentUser());
206            HttpSession session = getJsp().getRequest().getSession(true);
207            storeSettings(session, wpSettings);
208        }
209
210        return true;
211    }
212
213    /**
214     * @see org.opencms.workplace.CmsWorkplace#checkRole()
215     */
216    @Override
217    protected void checkRole() {
218
219        // do not check
220    }
221
222    /**
223     * @see org.opencms.workplace.CmsWorkplace#initWorkplaceRequestValues(org.opencms.workplace.CmsWorkplaceSettings, javax.servlet.http.HttpServletRequest)
224     */
225    @Override
226    protected void initWorkplaceRequestValues(CmsWorkplaceSettings settings, HttpServletRequest request) {
227
228        // empty
229    }
230}