1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 package org.opencastproject.graphql.directive;
23
24 import org.opencastproject.graphql.exception.GraphQLUnauthorizedException;
25 import org.opencastproject.graphql.execution.context.OpencastContext;
26 import org.opencastproject.graphql.execution.context.OpencastContextManager;
27 import org.opencastproject.security.api.SecurityService;
28
29 import graphql.annotations.directives.AnnotationsDirectiveWiring;
30 import graphql.annotations.directives.AnnotationsWiringEnvironment;
31 import graphql.annotations.processor.util.CodeRegistryUtil;
32 import graphql.schema.GraphQLFieldDefinition;
33
34 public class RolesAllowedWiring implements AnnotationsDirectiveWiring {
35
36 @Override
37 public GraphQLFieldDefinition onField(AnnotationsWiringEnvironment environment) {
38 GraphQLFieldDefinition field = (GraphQLFieldDefinition) environment.getElement();
39 String[] hasRole = environment.getDirective().toAppliedDirective().getArgument("roles").getValue();
40 CodeRegistryUtil.wrapDataFetcher(field, environment, (((dataFetchingEnvironment, value) -> {
41 OpencastContext context = OpencastContextManager.getCurrentContext();
42 SecurityService securityService = context.getService(SecurityService.class);
43 for (String role : hasRole) {
44 if (securityService != null && securityService.getUser().hasRole(role)) {
45 break;
46 }
47 throw new GraphQLUnauthorizedException("The current user is not authorized to access this resource.");
48 }
49
50 return value;
51 })));
52 return field;
53 }
54
55 }