001/*
002 *  Copyright 2020 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.mobileapp.site;
017
018import java.util.regex.Matcher;
019import java.util.regex.Pattern;
020
021import org.apache.cocoon.environment.Request;
022import org.apache.commons.lang3.StringUtils;
023
024import org.ametys.core.authentication.AuthenticateAction;
025import org.ametys.plugins.site.token.GetToken;
026
027/**
028 * Handle token for mobileapp requests.
029 */
030public class MobileappToken implements GetToken
031{
032    /** Regexp for webdav uri */
033    public static final Pattern MOBILEAPP_URI_PATTERN = Pattern.compile("(?:.*/)?_plugins/mobileapp/[0-9.]+/([^/]+)/(.+)");
034    
035    public String getToken(Request request)
036    {
037        String uri = request.getSitemapURI();
038        
039        Matcher matcher = MOBILEAPP_URI_PATTERN.matcher(uri);
040        if (matcher.matches())
041        {
042            String token = request.getHeader(AuthenticateAction.HEADER_TOKEN);
043            if (StringUtils.isBlank(token))
044            {
045                token = request.getParameter(AuthenticateAction.REQUEST_PARAMETER_TOKEN);
046            }
047            return token;
048        }
049        
050        return null;
051    }
052
053    public String getTokenContext(Request request)
054    {
055        String uri = request.getSitemapURI();
056        
057        Matcher matcher = MOBILEAPP_URI_PATTERN.matcher(uri);
058        if (matcher.matches())
059        {
060            return "mobileapp";
061        }
062        return null;
063    }
064}