View Javadoc
1   /*
2    * Licensed to The Apereo Foundation under one or more contributor license
3    * agreements. See the NOTICE file distributed with this work for additional
4    * information regarding copyright ownership.
5    *
6    *
7    * The Apereo Foundation licenses this file to you under the Educational
8    * Community License, Version 2.0 (the "License"); you may not use this file
9    * except in compliance with the License. You may obtain a copy of the License
10   * at:
11   *
12   *   http://opensource.org/licenses/ecl2.txt
13   *
14   * Unless required by applicable law or agreed to in writing, software
15   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
16   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
17   * License for the specific language governing permissions and limitations under
18   * the License.
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  }