/*
 * Copyright 2012-2016 the original author or authors.
 *
 * 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.springframework.boot.actuate.endpoint.mvc;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.HttpStatus;
import org.springframework.web.cors.CorsUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
 * Security interceptor for MvcEndpoints.
 *
 * @author Madhura Bhave
 * @since 1.5.0
 */
public class MvcEndpointSecurityInterceptor extends HandlerInterceptorAdapter {

	private final boolean secure;

	private final List<String> roles;

	public MvcEndpointSecurityInterceptor(boolean secure, List<String> roles) {
		this.secure = secure;
		this.roles = roles;
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
			Object handler) throws Exception {
		if (CorsUtils.isPreFlightRequest(request) || !this.secure) {
			return true;
		}
		HandlerMethod handlerMethod = (HandlerMethod) handler;
		MvcEndpoint mvcEndpoint = (MvcEndpoint) handlerMethod.getBean();
		if (!mvcEndpoint.isSensitive()) {
			return true;
		}
		for (String role : this.roles) {
			if (request.isUserInRole(role)) {
				return true;
			}
		}
		setFailureResponseStatus(request, response);
		return false;
	}

	private void setFailureResponseStatus(HttpServletRequest request,
			HttpServletResponse response) {
		if (request.getUserPrincipal() != null) {
			response.setStatus(HttpStatus.FORBIDDEN.value());
		}
		else {
			response.setStatus(HttpStatus.UNAUTHORIZED.value());
		}
	}

}
