/*
 * $Id: UnauthorisedException.java 10489 2008-01-23 17:53:38Z dfeist $
 * --------------------------------------------------------------------------------------
 * Copyright (c) MuleSource, Inc.  All rights reserved.  http://www.mulesource.com
 *
 * The software in this package is published under the terms of the CPAL v1.0
 * license, a copy of which has been included with this distribution in the
 * LICENSE.txt file.
 */

package org.mule.api.security;

import org.mule.RequestContext;
import org.mule.api.MuleMessage;
import org.mule.api.endpoint.ImmutableEndpoint;
import org.mule.config.i18n.CoreMessages;
import org.mule.config.i18n.Message;

/**
 * <code>UnauthorisedException</code> is thrown if authentication fails
 */

public class UnauthorisedException extends SecurityException
{
    /**
     * Serial version
     */
    private static final long serialVersionUID = -6664384216189042672L;

    public UnauthorisedException(Message message)
    {
        super(message, RequestContext.getEventContext().getMessage());
    }

    public UnauthorisedException(Message message, Throwable cause)
    {
        super(message, RequestContext.getEventContext().getMessage(), cause);
    }

    public UnauthorisedException(Message message, MuleMessage umoMessage)
    {
        super(message, umoMessage);
    }

    public UnauthorisedException(Message message, MuleMessage umoMessage, Throwable cause)
    {
        super(message, umoMessage, cause);
    }

    public UnauthorisedException(MuleMessage umoMessage,
                                 SecurityContext context,
                                 ImmutableEndpoint endpoint,
                                 EndpointSecurityFilter filter)
    {
        super(constructMessage(context, endpoint, filter), umoMessage);
    }

    private static Message constructMessage(SecurityContext context,
                                            ImmutableEndpoint endpoint,
                                            EndpointSecurityFilter filter)
    {

        Message m = null;
        if (context == null)
        {
            m = CoreMessages.authSetButNoContext(filter.getClass().getName());
        }
        else
        {
            m = CoreMessages.authFailedForUser(context.getAuthentication().getPrincipal());
        }
        m.setNextMessage(CoreMessages.authDeniedOnEndpoint(endpoint.getEndpointURI()));
        return m;
    }
}
