package org.luxons.sevenwonders.config;

import java.security.Principal;

import org.luxons.sevenwonders.validation.DestinationAccessValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptorAdapter;
import org.springframework.stereotype.Component;

@Component
public class TopicSubscriptionInterceptor extends ChannelInterceptorAdapter {

    private final DestinationAccessValidator destinationAccessValidator;

    @Autowired
    public TopicSubscriptionInterceptor(DestinationAccessValidator destinationAccessValidator) {
        this.destinationAccessValidator = destinationAccessValidator;
    }

    @Override
    public Message<?> preSend(Message<?> message, MessageChannel channel) {
        StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(message);
        if (StompCommand.SUBSCRIBE.equals(headerAccessor.getCommand())) {
            Principal userPrincipal = headerAccessor.getUser();
            if (!destinationAccessValidator.hasAccess(userPrincipal.getName(), headerAccessor.getDestination())) {
                throw new ForbiddenSubscriptionException();
            }
        }
        return message;
    }

    private static class ForbiddenSubscriptionException extends RuntimeException {
    }
}

@@ -45,33 +45,58 @@
 ort 
-java.security.Principal;%0A
+org.luxons.sevenwonders.errors.ApiMisuseException;
 %0Aimp
@@ -1190,31 +1190,23 @@
     
-Principal userPrincipal
+String username
  = h
@@ -1228,16 +1228,92 @@
 etUser()
+.getName();%0A            String destination = headerAccessor.getDestination()
 ;%0A      
@@ -1368,48 +1368,15 @@
 user
-Principal.getName(), headerAccessor.getD
+name, d
 esti
@@ -1381,18 +1381,16 @@
 tination
-()
 )) %7B%0A   
@@ -1439,24 +1439,45 @@
 onException(
+username, destination
 );%0A         
@@ -1590,26 +1590,217 @@
 nds 
-RuntimeException %7B
+ApiMisuseException %7B%0A%0A        ForbiddenSubscriptionException(String username, String destination) %7B%0A            super(String.format(%22Player '%25s' is not allowed to access %25s%22, username, destination));%0A        %7D
 %0A   

Improve forbidden subscription exception message