/*
* Copyright 2013 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.artificer.devsvr;
import org.artificer.common.ArtificerConfig;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.IOException;
import java.security.Principal;
import java.util.HashSet;
import java.util.Set;
public class BasicAuthFilter implements Filter {
@Override
public void init(FilterConfig config) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
ServletException {
SimplePrincipal principal = new SimplePrincipal(ArtificerConfig.getMavenReadOnlyUsername());
principal.addRole("artificer");
chain.doFilter(wrapRequest(request, principal), response);
}
private HttpServletRequest wrapRequest(final ServletRequest request, final SimplePrincipal principal) {
HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper((HttpServletRequest) request) {
@Override
public Principal getUserPrincipal() {
return principal;
}
@Override
public String getRemoteUser() {
return principal.getName();
}
/**
* @see javax.servlet.http.HttpServletRequestWrapper#isUserInRole(java.lang.String)
*/
@Override
public boolean isUserInRole(String role) {
return principal.getRoles().contains(role);
}
};
return wrapper;
}
@Override
public void destroy() {
}
// TODO: Duplicates MavenRepositoryAuthFilter
private static class SimplePrincipal implements Principal {
private String username;
private Set<String> roles = new HashSet();
public SimplePrincipal(String username) {
this.username = username;
}
public String getName() {
return this.username;
}
public void addRole(String role) {
this.roles.add(role);
}
public Set<String> getRoles() {
return this.roles;
}
}
}