package hu.elte.alkfejl.restaurant.service.interceptor;

import hu.elte.alkfejl.restaurant.service.annotation.Role;
import hu.elte.alkfejl.restaurant.entity.User;
import hu.elte.alkfejl.restaurant.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

@Component
public class AuthInterceptor extends HandlerInterceptorAdapter {

    private UserService userService;

    @Autowired
    public AuthInterceptor(UserService userService) {
        this.userService = userService;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        List<User.Role> routeRoles = getRoles((HandlerMethod) handler);

        if (routeRoles.isEmpty() || routeRoles.contains(User.Role.GUEST)) {
            return true;
        }
        if (userService.isLoggedIn() && routeRoles.contains(userService.getRole())) {
            return true;
        }
        response.setStatus(401);
        return false;
    }

    private List<User.Role> getRoles(HandlerMethod handler) {
        Role role = handler.getMethodAnnotation(Role.class);
        return role == null ? Collections.emptyList() : Arrays.asList(role.value());
    }
}

@@ -1099,48 +1099,8 @@
 ty()
- %7C%7C routeRoles.contains(User.Role.GUEST)
 ) %7B%0A
@@ -1110,35 +1110,36 @@
          return 
-tru
+fals
 e;%0A        %7D%0A   
@@ -1175,12 +1175,28 @@
 In()
- && 
+) %7B%0A            if (
 rout
@@ -1233,24 +1233,126 @@
 tRole())) %7B%0A
+                return true;%0A            %7D%0A        %7D else if (routeRoles.contains(User.Role.GUEST)) %7B%0A
             
@@ -1366,32 +1366,33 @@
 true;%0A        %7D%0A
+%0A
         response

fix authorization of guest-only functions