001/* 
002    Licensed to the Apache Software Foundation (ASF) under one
003    or more contributor license agreements.  See the NOTICE file
004    distributed with this work for additional information
005    regarding copyright ownership.  The ASF licenses this file
006    to you under the Apache License, Version 2.0 (the
007    "License"); you may not use this file except in compliance
008    with the License.  You may obtain a copy of the License at
009
010       http://www.apache.org/licenses/LICENSE-2.0
011
012    Unless required by applicable law or agreed to in writing,
013    software distributed under the License is distributed on an
014    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015    KIND, either express or implied.  See the License for the
016    specific language governing permissions and limitations
017    under the License.  
018 */
019package org.apache.wiki.tags;
020
021import org.apache.wiki.api.core.Engine;
022import org.apache.wiki.api.core.Session;
023import org.apache.wiki.api.spi.Wiki;
024import org.apache.wiki.i18n.InternationalizationManager;
025import org.apache.wiki.preferences.Preferences;
026import org.apache.wiki.util.TextUtil;
027
028import javax.servlet.http.HttpServletRequest;
029import java.io.IOException;
030import java.security.Principal;
031import java.util.regex.Pattern;
032
033
034/**
035 *  Returns the current user name, or empty, if the user has not been validated.
036 *
037 *  @since 2.0
038 */
039public class UserNameTag extends WikiTagBase {
040
041    private static final long serialVersionUID = 0L;
042
043    private static final String notStartWithBlankOrColon = "^[^( |:)]";
044
045    private static final String noColons = "[^:]*";
046
047    private static final Pattern VALID_USER_NAME_PATTERN = Pattern.compile(notStartWithBlankOrColon + noColons);
048
049    @Override
050    public final int doWikiStartTag() throws IOException {
051        final Engine engine = m_wikiContext.getEngine();
052        final Session wikiSession = Wiki.session().find( engine, ( HttpServletRequest )pageContext.getRequest() );
053        final Principal user = wikiSession.getUserPrincipal();
054
055        if( user != null ) {
056            if( VALID_USER_NAME_PATTERN.matcher( user.getName() ).matches() ) {
057                pageContext.getOut().print( TextUtil.replaceEntities( user.getName() ) );
058            } else {
059                pageContext.getOut().print( Preferences.getBundle( m_wikiContext, InternationalizationManager.CORE_BUNDLE )
060                                                       .getString( "security.user.fullname.invalid" ) );
061            }
062        }
063
064        return SKIP_BODY;
065    }
066
067}