001/*
002 *  Copyright 2022 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.site.authentication;
017
018import java.nio.charset.StandardCharsets;
019import java.util.ArrayList;
020import java.util.List;
021import java.util.Optional;
022
023import org.apache.cocoon.environment.Request;
024import org.apache.hc.client5.http.classic.methods.HttpPost;
025import org.apache.hc.client5.http.entity.UrlEncodedFormEntity;
026import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
027import org.apache.hc.core5.http.ClassicHttpResponse;
028import org.apache.hc.core5.http.NameValuePair;
029import org.apache.hc.core5.http.message.BasicNameValuePair;
030
031import org.ametys.core.user.UserIdentity;
032import org.ametys.core.user.population.UserPopulationDAO;
033import org.ametys.plugins.site.Site;
034import org.ametys.runtime.config.Config;
035import org.ametys.site.BackOfficeRequestHelper;
036
037/**
038 * The component to handle Multifactor authentication
039 * Provides methods to generate, send and check MFA codes
040 */
041public class MultifactorAuthenticationManager extends org.ametys.plugins.core.authentication.MultifactorAuthenticationManager
042{
043    @Override
044    public void sendMultifactorAuthenticationCodeByMail(Request request, UserIdentity userIdentity, String multifactorAuthenticationCode) throws RuntimeException
045    {
046        if (userIdentity.getPopulationId().equals(UserPopulationDAO.ADMIN_POPULATION_ID))
047        {
048            super.sendMultifactorAuthenticationCodeByMail(request, userIdentity, multifactorAuthenticationCode);
049        }
050        else
051        {
052            _sendMFACodeFromBackOffice(request, userIdentity, multifactorAuthenticationCode);
053        }
054    }
055
056    /**
057     * Request the back-office application to send a mail the code
058     * @param request the current request
059     * @param userIdentity the identity of the user trying to authenticate
060     * @param multifactorAuthenticationCode the authentication code to transmit to the user
061     */
062    protected void _sendMFACodeFromBackOffice(Request request, UserIdentity userIdentity, String multifactorAuthenticationCode)
063    {
064        // FIXME CMS-12715 Reuse the same client for all request from site to cms
065        try (CloseableHttpClient httpClient = BackOfficeRequestHelper.getHttpClient())
066        {
067            String cmsURL = Config.getInstance().getValue("org.ametys.site.bo");
068            
069            HttpPost httpPost = new HttpPost(cmsURL + "/_send_mfa_code.xml");
070            httpPost.addHeader("X-Ametys-FO", "true");
071            
072            List<NameValuePair> nvps = new ArrayList<>();
073            nvps.add(new BasicNameValuePair("code", multifactorAuthenticationCode));
074            nvps.add(new BasicNameValuePair("login", userIdentity.getLogin()));
075            nvps.add(new BasicNameValuePair("populationId", userIdentity.getPopulationId()));
076            
077            Optional.ofNullable(request.getAttribute("site"))
078                                       .filter(Site.class::isInstance)
079                                       .map(Site.class::cast)
080                                       .map(Site::getName)
081                                       .ifPresent(siteName -> nvps.add(new BasicNameValuePair("siteName", siteName)));
082            
083            httpPost.setEntity(new UrlEncodedFormEntity(nvps, StandardCharsets.UTF_8));
084            
085            
086            int statusCode = httpClient.execute(httpPost, ClassicHttpResponse::getCode);
087            switch (statusCode)
088            {
089                case 200:
090                    // MFA code has been sent - nothing to do
091                    break;
092                    
093                case 403:
094                    throw new IllegalStateException("The CMS back-office refused the connection");
095                    
096                case 500:
097                default:
098                    throw new IllegalStateException("The CMS back-office returned an error with code " + statusCode);
099            }
100        }
101        catch (Exception e)
102        {
103            throw new RuntimeException("Unable to send the multifactor authentication code to user " + UserIdentity.userIdentityToString(userIdentity) + ".", e);
104        }
105    }
106}