1 package usecase.auth;
2
3 import common.http.interceptor.HttpServletBiConsumer;
4 import common.http.interceptor.ServletInterceptor;
5
6 import javax.servlet.ServletException;
7 import javax.servlet.http.HttpServletRequest;
8 import javax.servlet.http.HttpServletResponse;
9 import java.io.IOException;
10 import java.util.Arrays;
11 import java.util.EnumSet;
12 import java.util.Set;
13
14 import static usecase.auth.AuthorizationConstraints.Types.*;
15
16 public class AuthorizationConstraintsInterceptor extends ServletInterceptor<AuthorizationConstraints> {
17
18 private Set<AuthorizationConstraints.Types> authorizationConstraintTypes;
19
20 @Override
21 protected void init(AuthorizationConstraints annotation) {
22 authorizationConstraintTypes = EnumSet.noneOf(AuthorizationConstraints.Types.class);
23 authorizationConstraintTypes.addAll(Arrays.asList(annotation.value()));
24 }
25
26 @Override
27 public void handle(HttpServletRequest req, HttpServletResponse resp, HttpServletBiConsumer next) throws ServletException, IOException {
28 CurrentUser currentUser = (CurrentUser) req.getAttribute("currentUser");
29 if(authorizationConstraintTypes.contains(ADMINS_ONLY)
30 || authorizationConstraintTypes.contains(REQUIRE_AUTHENTICATION)){
31
32 if(!currentUser.isLoggedIn()){
33 throw new AuthenticationRequiredException();
34 }
35 }
36
37 if(authorizationConstraintTypes.contains(ADMINS_ONLY)){
38 if(!currentUser.isAdmin()){
39 throw new AuthorizationException();
40 }
41 }
42
43 if(authorizationConstraintTypes.contains(DENY_BANNED_USERS)){
44 if(currentUser.getBanDuration() != null){
45 throw new BannedUserException();
46 }
47 }
48
49 next.handle(req,resp);
50 }
51
52 @Override
53 public int priority() {
54 return super.priority();
55 }
56 }