SecurityInterceptor.java 2.52 KB
package etunicorn;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

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

/**
 * etunicorn-server
 * Copyright © 2017 Le Club Info Polytech Lille
 * Tous droits réservés
 */
public class SecurityInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    SessionService sessionService;
    @Autowired
    PermissionRepository permissionRepository;

    public SecurityInterceptor() {
        super();
    }

    @Override
    @Transactional
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Session session = sessionService.getSession(request);

        HandlerMethod method = (HandlerMethod) handler;
        RestrictedTo annotation = method.getMethodAnnotation(RestrictedTo.class);

        Permission requiredPermission = permissionRepository.findByNom(annotation.value());
        if (requiredPermission == null) {
            response.setStatus(HttpStatus.NOT_IMPLEMENTED.value());
            return false;
        }

        if (annotation.authentifie()) {
            if (session == null) {
                response.setStatus(HttpStatus.UNAUTHORIZED.value());
                return false;
            } else {
                if (!session.hasPermission(requiredPermission)) {
                    response.setStatus(HttpStatus.FORBIDDEN.value());
                    return false;
                }
            }
        }
        return super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        super.afterCompletion(request, response, handler, ex);
    }

    @Override
    public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        super.afterConcurrentHandlingStarted(request, response, handler);
    }
}