/*
 * Copyright 2002-2011 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.security.oauth2.provider.error;

import java.io.IOException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.DefaultThrowableAnalyzer;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.web.util.ThrowableAnalyzer;

/**
 * @author Dave Syer
 * 
 */
public class DefaultWebResponseExceptionTranslator implements WebResponseExceptionTranslator {

	/** Logger available to subclasses */
	private static final Log logger = LogFactory.getLog(DefaultWebResponseExceptionTranslator.class);

	private ThrowableAnalyzer throwableAnalyzer = new DefaultThrowableAnalyzer();

	public ResponseEntity<OAuth2Exception> translate(Exception e) throws Exception {

		// Try to extract a SpringSecurityException from the stacktrace
		Throwable[] causeChain = throwableAnalyzer.determineCauseChain(e);
		RuntimeException ase = (AuthenticationException) throwableAnalyzer.getFirstThrowableOfType(
				AuthenticationException.class, causeChain);

		if (ase instanceof OAuth2Exception) {
			return handleOAuth2Exception((OAuth2Exception) ase);
		}
		
		if (ase instanceof AuthenticationException) {
			return handleOAuth2Exception(new InvalidTokenException(e.getMessage(), e));
		}
		
		if (ase == null) {
			ase = (AccessDeniedException) throwableAnalyzer.getFirstThrowableOfType(AccessDeniedException.class,
					causeChain);
			if (ase instanceof AccessDeniedException) {
				return handleOAuth2Exception(new WrappedException(ase.getMessage(), ase));
			}
		}

		throw e;

	}

	private ResponseEntity<OAuth2Exception> handleOAuth2Exception(OAuth2Exception e) throws IOException {

		if (logger.isDebugEnabled()) {
			logger.debug("OAuth error.", e);
		}

		int status = e.getHttpErrorCode();
		HttpHeaders headers = new HttpHeaders();
		headers.set("Cache-Control", "no-store");
		if (status==HttpStatus.UNAUTHORIZED.value()) {
			headers.set("WWW-Authenticate", String.format("%s %s", OAuth2AccessToken.BEARER_TYPE, e.getSummary()));
		}

		ResponseEntity<OAuth2Exception> response = new ResponseEntity<OAuth2Exception>(e, headers,
				HttpStatus.valueOf(status));

		return response;

	}

	public void setThrowableAnalyzer(ThrowableAnalyzer throwableAnalyzer) {
		this.throwableAnalyzer = throwableAnalyzer;
	}

	private static class WrappedException extends OAuth2Exception {

		public WrappedException(String msg, Throwable t) {
			super(msg, t);
		}

		public String getOAuth2ErrorCode() {
			return "access_denied";
		}

		public int getHttpErrorCode() {
			return 403;
		}

	}
}

@@ -1207,92 +1207,8 @@
 en;%0A
-import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;%0A
 impo
@@ -2246,20 +2246,20 @@
 new 
-InvalidToken
+Unauthorized
 Exce
@@ -2519,23 +2519,25 @@
 ion(new 
-Wrapped
+Forbidden
 Exceptio
@@ -3348,23 +3348,25 @@
 c class 
-Wrapped
+Forbidden
 Exceptio
@@ -3407,15 +3407,17 @@
 lic 
-Wrapped
+Forbidden
 Exce
@@ -3597,13 +3597,293 @@
 3;%0A%09%09%7D%0A%0A
+%09%7D%0A%0A%09private static class UnauthorizedException extends OAuth2Exception %7B%0A%0A%09%09public UnauthorizedException(String msg, Throwable t) %7B%0A%09%09%09super(msg, t);%0A%09%09%7D%0A%0A%09%09public String getOAuth2ErrorCode() %7B%0A%09%09%09return %22unauthorized%22;%0A%09%09%7D%0A%0A%09%09public int getHttpErrorCode() %7B%0A%09%09%09return 401;%0A%09%09%7D%0A%0A
 %09%7D%0A%7D%0A

send clear 401 message on auth failure