001    /*
002     * Copyright (c) 2011, Cloudera, Inc. All Rights Reserved.
003     *
004     * Cloudera, Inc. licenses this file to you under the Apache License,
005     * Version 2.0 (the "License"). You may not use this file except in
006     * compliance with the License. You may obtain a copy of the License at
007     *
008     *     http://www.apache.org/licenses/LICENSE-2.0
009     *
010     * This software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
011     * CONDITIONS OF ANY KIND, either express or implied. See the License for
012     * the specific language governing permissions and limitations under the
013     * License.
014     */
015    package com.cloudera.lib.wsrs;
016    
017    import com.sun.jersey.api.core.HttpContext;
018    import com.sun.jersey.core.spi.component.ComponentContext;
019    import com.sun.jersey.core.spi.component.ComponentScope;
020    import com.sun.jersey.server.impl.inject.AbstractHttpContextInjectable;
021    import com.sun.jersey.spi.inject.Injectable;
022    import com.sun.jersey.spi.inject.InjectableProvider;
023    import org.slf4j.MDC;
024    
025    import javax.ws.rs.core.Context;
026    import javax.ws.rs.ext.Provider;
027    import java.lang.reflect.Type;
028    import java.security.Principal;
029    import java.util.regex.Pattern;
030    
031    @Provider
032    public class UserProvider extends AbstractHttpContextInjectable<Principal> implements
033      InjectableProvider<Context, Type> {
034    
035      public static final String USER_NAME_PARAM = "user.name";
036    
037      public static final Pattern USER_PATTERN = Pattern.compile("[_a-zA-Z0-9]+");
038    
039      private static class UserParam extends StringParam {
040    
041        public UserParam(String user) {
042          super(USER_NAME_PARAM, user, USER_PATTERN);
043        }
044      }
045    
046      @Override
047      public Principal getValue(HttpContext httpContext) {
048        Principal principal = httpContext.getRequest().getUserPrincipal();
049        if (principal == null) {
050          final String user = httpContext.getRequest().getQueryParameters().getFirst(USER_NAME_PARAM);
051          if (user != null) {
052            principal = new Principal() {
053              @Override
054              public String getName() {
055                return new UserParam(user).value();
056              }
057            };
058          }
059        }
060        if (principal != null) {
061          MDC.put("user", principal.getName());
062        }
063        return principal;
064      }
065    
066      @Override
067      public ComponentScope getScope() {
068        return ComponentScope.PerRequest;
069      }
070    
071      @Override
072      public Injectable getInjectable(ComponentContext componentContext, Context context, Type type) {
073        return (type.equals(Principal.class)) ? this : null;
074      }
075    }