Support ability to scope how global behaviors are applied to clients and services...
[castle.git] / Facilities / Security / Castle.Facilities.SecurityManagement / SecurityComponentInspector.cs
blob10eaf10d43900077f9dfb718e40650a61e63191f
1 // Copyright 2004-2008 Castle Project - http://www.castleproject.org/
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
15 namespace Castle.Facilities.SecurityManagement
17 using System;
18 using System.Collections;
19 using System.Reflection;
20 using Castle.MicroKernel;
21 using Castle.MicroKernel.Facilities;
22 using Castle.MicroKernel.ModelBuilder;
23 using Castle.Core;
24 using Castle.Services.Security;
26 /// <summary>
27 /// Summary description for SecurityComponentInspector.
28 /// </summary>
29 public class SecurityComponentInspector : IContributeComponentModelConstruction
31 public SecurityComponentInspector()
35 public void ProcessModel(IKernel kernel, ComponentModel model)
37 if (model.Implementation.IsDefined( typeof(SecureAttribute), true ))
39 EnsureRelevantMethodsAreVirtual( model.Service, model.Implementation );
41 model.Dependencies.Add(
42 new DependencyModel( DependencyType.Service, null, typeof(SecurityInterceptor), false ) );
44 model.Interceptors.Add(
45 new InterceptorReference( typeof(SecurityInterceptor) ) );
49 private void EnsureRelevantMethodsAreVirtual(Type service, Type implementation)
51 if (service.IsInterface) return;
53 MethodInfo[] methods = implementation.GetMethods(
54 BindingFlags.Instance|BindingFlags.Public|BindingFlags.DeclaredOnly );
56 ArrayList problematicMethods = new ArrayList();
58 foreach( MethodInfo method in methods )
60 if (!method.IsVirtual && method.IsDefined( typeof(PermissionAttribute), true ))
62 problematicMethods.Add( method.Name );
66 if (problematicMethods.Count != 0)
68 String[] methodNames = (String[]) problematicMethods.ToArray( typeof(String) );
70 String message = String.Format( "The class {0} wants to use security interception, " +
71 "however the methods must be marked as virtual in order to do so. Please correct " +
72 "the following methods: {1}", implementation.FullName, String.Join(", ", methodNames) );
74 throw new FacilityException(message);