001/*
002 *  Copyright 2024 Anyware Services
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 */
016package org.ametys.plugins.extrausermgt.proxy;
017
018import org.apache.cocoon.environment.Request;
019import org.apache.http.client.methods.HttpUriRequest;
020import org.slf4j.Logger;
021
022import org.ametys.core.authentication.CredentialProvider;
023import org.ametys.plugins.extrausermgt.authentication.msal.AbstractMSALCredentialProvider;
024import org.ametys.plugins.site.proxy.SessionAttributeRequestProxy;
025import org.ametys.runtime.plugin.component.LogEnabled;
026import org.ametys.site.FrontAuthenticateAction;
027
028/**
029 * Request proxy to forward the MS authentication token to the back office.
030 * If needed, the token is refreshed before the forward
031 */
032public class MSALSessionAttributeRequestProxy extends SessionAttributeRequestProxy implements LogEnabled
033{
034    // FIXME make SessionAttributeRequestProxy extends AbstractLogEnabled
035    private Logger _logger;
036
037    /**
038     * Returns the {@link Logger}.
039     * @return the {@link Logger}.
040     */
041    // FIXME make SessionAttributeRequestProxy extends AbstractLogEnabled
042    protected Logger getLogger()
043    {
044        return _logger;
045    }
046
047    // FIXME make SessionAttributeRequestProxy extends AbstractLogEnabled
048    public void setLogger(Logger logger)
049    {
050        _logger = logger;
051    }
052
053    @Override
054    public void prepareBackOfficeRequest(Request request, HttpUriRequest backOfficeRequest)
055    {
056        CredentialProvider credentialProvider = FrontAuthenticateAction.getCredentialProviderFromSession(request);
057        if (credentialProvider instanceof AbstractMSALCredentialProvider msalCP)
058        {
059            try
060            {
061                msalCP.refreshTokenIfNeeded(request.getSession());
062                super.prepareBackOfficeRequest(request, backOfficeRequest);
063            }
064            catch (Exception e)
065            {
066                getLogger().warn("An error prevented refreshing the token before forwaring it to the back office. See previous exception for more details", e);
067            }
068        }
069    }
070}