001package usecase.auth; 002 003import common.http.interceptor.HttpServletBiConsumer; 004import common.http.interceptor.ServletInterceptor; 005 006import javax.servlet.ServletException; 007import javax.servlet.http.HttpServletRequest; 008import javax.servlet.http.HttpServletResponse; 009import java.io.IOException; 010import java.util.Arrays; 011import java.util.EnumSet; 012import java.util.Set; 013 014import static usecase.auth.AuthorizationConstraints.Types.*; 015 016public class AuthorizationConstraintsInterceptor extends ServletInterceptor<AuthorizationConstraints> { 017 018 private Set<AuthorizationConstraints.Types> authorizationConstraintTypes; 019 020 @Override 021 protected void init(AuthorizationConstraints annotation) { 022 authorizationConstraintTypes = EnumSet.noneOf(AuthorizationConstraints.Types.class); 023 authorizationConstraintTypes.addAll(Arrays.asList(annotation.value())); 024 } 025 026 @Override 027 public void handle(HttpServletRequest req, HttpServletResponse resp, HttpServletBiConsumer next) throws ServletException, IOException { 028 CurrentUser currentUser = (CurrentUser) req.getAttribute("currentUser"); 029 if(authorizationConstraintTypes.contains(ADMINS_ONLY) 030 || authorizationConstraintTypes.contains(REQUIRE_AUTHENTICATION)){ 031 //controlla se l'utente รจ autenticato 032 if(!currentUser.isLoggedIn()){ 033 throw new AuthenticationRequiredException(); 034 } 035 } 036 037 if(authorizationConstraintTypes.contains(ADMINS_ONLY)){ 038 if(!currentUser.isAdmin()){ 039 throw new AuthorizationException(); 040 } 041 } 042 043 if(authorizationConstraintTypes.contains(DENY_BANNED_USERS)){ 044 if(currentUser.getBanDuration() != null){ 045 throw new BannedUserException(); 046 } 047 } 048 049 next.handle(req,resp); 050 } 051 052 @Override 053 public int priority() { 054 return super.priority(); 055 } 056}