001/*
002 *  Copyright 2017 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.web.site;
017
018import java.io.IOException;
019
020import org.apache.avalon.framework.service.ServiceException;
021import org.apache.cocoon.ProcessingException;
022import org.apache.cocoon.environment.ObjectModelHelper;
023import org.apache.cocoon.environment.Request;
024import org.apache.cocoon.generation.ServiceableGenerator;
025import org.apache.cocoon.xml.XMLUtils;
026import org.apache.commons.lang.StringUtils;
027import org.xml.sax.SAXException;
028
029import org.ametys.core.authentication.token.AuthenticationTokenManager;
030import org.ametys.core.user.UserIdentity;
031
032/**
033 * Validates a given token and return in xml the associated login/populationId
034 */
035public class ValidateTokenGenerator extends ServiceableGenerator
036{
037    /** The authentication token manager */
038    protected AuthenticationTokenManager _authenticateTokenManager;
039
040    public void generate() throws IOException, SAXException, ProcessingException
041    {
042        if (_authenticateTokenManager == null)
043        {
044            try
045            {
046                _authenticateTokenManager = (AuthenticationTokenManager) manager.lookup(AuthenticationTokenManager.ROLE);
047            }
048            catch (ServiceException e)
049            {
050                throw new ProcessingException(e);
051            }
052        }
053
054        Request request = ObjectModelHelper.getRequest(objectModel);
055        String token = request.getParameter("token");
056        String tokenContext = request.getParameter("tokenContext");
057        
058        contentHandler.startDocument();
059        XMLUtils.startElement(contentHandler, "token");
060        
061        UserIdentity identity = _authenticateTokenManager.validateToken(token, tokenContext);
062        if (identity != null)
063        {
064            XMLUtils.createElement(contentHandler, "login", StringUtils.defaultString(identity.getLogin()));
065            XMLUtils.createElement(contentHandler, "populationId", StringUtils.defaultString(identity.getPopulationId()));
066        }
067        
068        XMLUtils.endElement(contentHandler, "token");
069        contentHandler.endDocument();
070    }
071}