001/*
002 * (C) Copyright 2010 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 * Contributors:
016 *     Nuxeo - initial API and implementation
017 */
018
019package org.nuxeo.ecm.platform.shibboleth.auth.exceptionhandling;
020
021import static org.nuxeo.ecm.platform.ui.web.auth.NXAuthConstants.USERIDENT_KEY;
022
023import javax.servlet.http.HttpServletRequest;
024
025import org.apache.commons.logging.Log;
026import org.apache.commons.logging.LogFactory;
027import org.nuxeo.ecm.platform.shibboleth.service.ShibbolethAuthenticationService;
028import org.nuxeo.ecm.platform.ui.web.auth.CachableUserIdentificationInfo;
029import org.nuxeo.ecm.platform.web.common.exceptionhandling.DefaultNuxeoExceptionHandler;
030import org.nuxeo.runtime.api.Framework;
031
032import java.security.Principal;
033import java.util.Optional;
034
035/**
036 * @author <a href="mailto:troger@nuxeo.com">Thomas Roger</a>
037 */
038public class ShibbolethSecurityExceptionHandler extends DefaultNuxeoExceptionHandler {
039
040    private static final Log log = LogFactory.getLog(ShibbolethSecurityExceptionHandler.class);
041
042    @Override
043    public String getLoginURL(HttpServletRequest request) {
044        ShibbolethAuthenticationService shibService = Framework.getService(ShibbolethAuthenticationService.class);
045        if (shibService == null) {
046            return null;
047        }
048        String loginURL = shibService.getLoginURL(request);
049        if (loginURL == null) {
050            log.error("Unable to handle Shibboleth login, no loginURL registered");
051            return null;
052        }
053        return loginURL;
054    }
055
056    @Override
057    protected Principal getPrincipal(HttpServletRequest request) {
058        Principal principal = super.getPrincipal(request);
059        if (principal == null) {
060            principal = Optional.ofNullable(request.getSession(false))
061                                .map(s -> (CachableUserIdentificationInfo) s.getAttribute(USERIDENT_KEY))
062                                .map(CachableUserIdentificationInfo::getPrincipal)
063                                .orElse(null);
064        }
065        return principal;
066    }
067
068}