public object DeleteOperation(string OperationID)
        {
            List <object> results = new List <object>();

            using (AuthEntityModelContainer context = new AuthEntityModelContainer())
            {
                var obsoleteRoleOps = context.RoleOperations.Where(ro => ro.OperationId.ToLower() == OperationID.ToLower());

                if (obsoleteRoleOps != null)
                {
                    results.Add(context.RoleOperations.RemoveRange(obsoleteRoleOps.ToArray()));
                }

                var obsoleteObjectAuthItems = context.ObjectOperationAuthItems.Where(oo => oo.OperationId.ToLower() == OperationID.ToLower());

                if (obsoleteObjectAuthItems != null)
                {
                    results.Add(context.ObjectOperationAuthItems.RemoveRange(obsoleteObjectAuthItems.ToArray()));
                }

                var obsoleteOps = context.Operations.Where(o => o.Id.ToLower() == OperationID.ToLower());

                if (obsoleteOps != null)
                {
                    results.Add(context.Operations.RemoveRange(obsoleteOps.ToArray()));
                }

                context.SaveChanges();
            }

            return(results);
        }
        public object DeleteDataScope(string DataScopeID)
        {
            List <object> results = new List <object>();

            using (AuthEntityModelContainer context = new AuthEntityModelContainer())
            {
                var obsoleteRoleDataScopes = context.RoleDataScopes.Where(rd => rd.DataScopeId.ToLower() == DataScopeID.ToLower());

                if (obsoleteRoleDataScopes != null)
                {
                    results.Add(context.RoleDataScopes.RemoveRange(obsoleteRoleDataScopes.ToArray()));
                }

                var obsoleteDataScopes = context.DataScopes.Where(ds => ds.Id.ToLower() == DataScopeID.ToLower());

                if (obsoleteDataScopes != null)
                {
                    results.Add(context.DataScopes.RemoveRange(obsoleteDataScopes.ToArray()));
                }

                context.SaveChanges();
            }

            return(results);
        }
        public object SetRoleDataScope(string RoleID, string DataScopeID, string DataScopeValue)
        {
            string result = "";

            using (AuthEntityModelContainer context = new AuthEntityModelContainer())
            {
                var dataScope = context.DataScopes.FirstOrDefault(s => s.Id == DataScopeID);

                if (dataScope != null)
                {
                    var roleDataScope = context.RoleDataScopes.Add(new RoleDataScope()
                    {
                        Id          = Guid.NewGuid().ToString(),
                        DataScopeId = DataScopeID,
                        ScopeValue  = DataScopeValue,
                        RoleId      = RoleID
                    });

                    context.SaveChanges();

                    result = roleDataScope.Id;
                }
            }

            return(result);
        }
        public object SetRoleOperation(string RoleID, string OperationID)
        {
            string result = "";

            using (AuthEntityModelContainer context = new AuthEntityModelContainer())
            {
                var op = context.Operations.FirstOrDefault(o => o.Id == OperationID);

                if (op != null)
                {
                    var roleOps = context.RoleOperations.Add(new RoleOperation()
                    {
                        Id          = Guid.NewGuid().ToString(),
                        OperationId = OperationID,
                        RoleId      = RoleID
                    });

                    context.SaveChanges();

                    result = roleOps.Id;
                }
            }

            return(result);
        }
        public string[] GetDataScopes(string DataTypeName)
        {
            List <string> scopeIds = null;

            using (AuthEntityModelContainer context = new AuthEntityModelContainer())
            {
                var scopes = context.DataScopes.Where(s => true);

                if (!String.IsNullOrEmpty(DataTypeName))
                {
                    scopes = scopes.Where(o => o.DataType.ToLower() == DataTypeName.ToLower());
                }

                if (scopes != null)
                {
                    var scopeArray = scopes.ToArray();

                    scopeIds = new List <string>();

                    foreach (var scope in scopes)
                    {
                        scopeIds.Add(scope.Id.ToLower());
                    }
                }
            }

            return(scopeIds != null?scopeIds.ToArray() : null);
        }
        public object SetActorObjectOperation(string ActorID, string ObjectID, string OperationID)
        {
            string result = "";

            using (AuthEntityModelContainer context = new AuthEntityModelContainer())
            {
                var op = context.Operations.FirstOrDefault(o => o.Id == OperationID);

                if (op != null)
                {
                    var authItem = context.ObjectOperationAuthItems.Add(new ObjectOperationAuthItem()
                    {
                        Id          = Guid.NewGuid().ToString(),
                        ActorId     = ActorID,
                        ObjectId    = ObjectID,
                        OperationId = OperationID
                    });

                    context.SaveChanges();

                    result = authItem.Id;
                }
            }

            return(result);
        }
        public string[] GetDataTypeOperations(string DataTypeName)
        {
            List <string> opIds = null;

            using (AuthEntityModelContainer context = new AuthEntityModelContainer())
            {
                var ops = context.Operations.Where(o => true);

                if (!String.IsNullOrEmpty(DataTypeName))
                {
                    ops = ops.Where(o => o.DataType.ToLower() == DataTypeName.ToLower());
                }

                if (ops != null)
                {
                    var opArray = ops.ToArray();

                    opIds = new List <string>();

                    foreach (var op in ops)
                    {
                        opIds.Add(op.Id.ToLower());
                    }
                }
            }

            return(opIds != null?opIds.ToArray() : null);
        }
        public object[] GetAuthorizedObjects(string Actor, string DataTypeName, Func <string, object, IDictionary <string, string>, IDictionary <string, IList <object> >, object[]> ComputingFunction)
        {
            IDictionary <string, IList <object> > dataScopeValues = new Dictionary <string, List <object> >() as IDictionary <string, IList <object> >;
            IDictionary <string, string>          dataScopeTypes  = new Dictionary <string, string>();
            string dataIndetifier = null;

            var userManager = new UserManager <IdentityUser>(new UserStore <IdentityUser>());

            var identity = userManager.FindByName(Actor);

            if (identity == null)
            {
                return(null);
            }

            var roles = userManager.GetRoles(identity.Id);

            if (roles == null)
            {
                return(null);
            }

            using (AuthEntityModelContainer context = new AuthEntityModelContainer())
            {
                var roleDataScopes = context.RoleDataScopes.Where(s => s.DataScope.DataType.ToLower() == DataTypeName.ToLower()).ToArray();

                roleDataScopes = roleDataScopes.Where(s => roles.Contains(s.RoleId)).ToArray();

                foreach (var roleDataScope in roleDataScopes)
                {
                    if (String.IsNullOrEmpty(dataIndetifier))
                    {
                        dataIndetifier = roleDataScope.DataScope.DataIdentifier;
                    }

                    if (!dataScopeTypes.ContainsKey(roleDataScope.DataScope.ScopeName))
                    {
                        dataScopeTypes.Add(roleDataScope.DataScope.ScopeName, roleDataScope.DataScope.ScopeType);
                    }

                    if (!dataScopeValues.ContainsKey(roleDataScope.DataScope.ScopeName))
                    {
                        dataScopeValues.Add(roleDataScope.DataScope.ScopeName, new List <object>());
                    }

                    dataScopeValues[roleDataScope.DataScope.ScopeName].Add(roleDataScope.ScopeValue);
                }
            }

            if (ComputingFunction != null)
            {
                return(ComputingFunction(DataTypeName, dataIndetifier, dataScopeTypes, dataScopeValues));
            }

            return(null);
        }
        public bool IsAuthorized(string Actor, string ObjectID, string OperationID)
        {
            bool result = false;

            var userManager = new UserManager <IdentityUser>(new UserStore <IdentityUser>(new IdentityDbContext(ModuleConfiguration.DefaultIdentityStoreConnectionName)));

            var identity = userManager.FindByName(Actor);

            if (identity == null)
            {
                return(false);
            }

            //var roleNames = userManager.GetRoles(identity.Id);

            //if (roleNames == null)
            //{
            //    return false;
            //}

            //var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new MySQLDatabase(ModuleConfiguration.DefaultIdentityStoreConnectionName)));

            //var roleIDs = new List<string>();

            //var role = new IdentityRole();

            //foreach (var roleName in roleNames)
            //{
            //    role = roleManager.FindByName(roleName);

            //    if (role != null)
            //    {
            //        roleIDs.Add(role.Id);
            //    }
            //}

            //if (roleIDs.Count <= 0)
            //{
            //    return false;
            //}

            using (AuthEntityModelContainer context = new AuthEntityModelContainer())
            {
                //var roleOps = context.RoleOperations.Where(o => o.OperationId.ToLower() == OperationID.ToLower() && roleIDs.Contains(o.RoleId));

                //result = (roleOps != null) && (roleOps.ToArray().Length > 0);

                var authItems = context.ObjectOperationAuthItems.Where(a => (a.ActorId.ToLower() == identity.Id.ToLower()) && (a.ObjectId.ToLower() == ObjectID.ToLower()) && (a.OperationId.ToLower() == OperationID.ToLower()));

                result = (authItems != null) && (authItems.ToArray().Length > 0);
            }

            return(result);
        }
        public object DeleteRole(string RoleID)
        {
            List <object> results = new List <object>();

            using (AuthEntityModelContainer context = new AuthEntityModelContainer())
            {
                var obsoleteRoleOps = context.RoleOperations.Where(ro => ro.RoleId.ToLower() == RoleID.ToLower());

                if (obsoleteRoleOps != null)
                {
                    results.Add(context.RoleOperations.RemoveRange(obsoleteRoleOps.ToArray()));
                }

                var obsoleteRoleDataScopes = context.RoleDataScopes.Where(rd => rd.RoleId.ToLower() == RoleID.ToLower());

                if (obsoleteRoleDataScopes != null)
                {
                    results.Add(context.RoleDataScopes.RemoveRange(obsoleteRoleDataScopes.ToArray()));
                }

                context.SaveChanges();
            }

            var roleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(new IdentityDbContext(ModuleConfiguration.DefaultIdentityStoreConnectionName)));

            var obsoleteRoles = roleManager.Roles.Where(r => r.Id.ToLower() == RoleID.ToLower());

            if (obsoleteRoles != null)
            {
                var userManager = new UserManager <IdentityUser>(new UserStore <IdentityUser>(new IdentityDbContext(ModuleConfiguration.DefaultIdentityStoreConnectionName)));

                var users = userManager.Users;

                foreach (var role in obsoleteRoles.ToArray())
                {
                    if (users != null)
                    {
                        foreach (var user in users.ToArray())
                        {
                            results.Add(userManager.RemoveFromRole(user.Id, role.Name));
                        }
                    }

                    results.Add(roleManager.Delete(role));
                }
            }

            return(results);
        }
        public object DeleteActor(string ActorID)
        {
            List <object> results = new List <object>();

            using (AuthEntityModelContainer context = new AuthEntityModelContainer())
            {
                var obsoleteObjectAuthItems = context.ObjectOperationAuthItems.Where(oo => oo.ActorId.ToLower() == ActorID.ToLower());

                if (obsoleteObjectAuthItems != null)
                {
                    results.Add(context.ObjectOperationAuthItems.RemoveRange(obsoleteObjectAuthItems.ToArray()));
                }

                context.SaveChanges();
            }

            var userManager = new UserManager <IdentityUser>(new UserStore <IdentityUser>(new IdentityDbContext(ModuleConfiguration.DefaultIdentityStoreConnectionName)));

            var obsoleteUsers = userManager.Users.Where(u => u.Id.ToLower() == ActorID.ToLower());

            if (obsoleteUsers != null)
            {
                var roleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(new IdentityDbContext(ModuleConfiguration.DefaultIdentityStoreConnectionName)));

                var obsoleteRoles = roleManager.Roles;

                if (obsoleteRoles != null)
                {
                    foreach (var role in obsoleteRoles.ToArray())
                    {
                        results.Add(userManager.RemoveFromRole(ActorID, role.Name));
                    }
                }

                foreach (var user in obsoleteUsers.ToArray())
                {
                    results.Add(userManager.Delete(user));
                }
            }

            return(results);
        }
        public object RegisterOperation(string DataTypeName, string OperationID, string OperationName)
        {
            string result = "";

            using (AuthEntityModelContainer context = new AuthEntityModelContainer())
            {
                var op = context.Operations.Add(new Operation()
                {
                    Id       = OperationID.ToLower(),
                    Name     = OperationName,
                    DataType = DataTypeName
                });

                context.SaveChanges();

                result = op.Id;
            }

            return(result);
        }
        public object RegisterDataScope(string DataTypeName, string DataScopeID, string DataScopeName, string DataScopeType, string DataIndentifier)
        {
            string result = "";

            using (AuthEntityModelContainer context = new AuthEntityModelContainer())
            {
                var ds = context.DataScopes.Add(new DataScope()
                {
                    Id             = DataScopeID.ToLower(),
                    ScopeName      = DataScopeName,
                    ScopeType      = DataScopeType,
                    DataType       = DataTypeName,
                    DataIdentifier = DataIndentifier
                });

                context.SaveChanges();

                result = ds.Id;
            }

            return(result);
        }
        //public static ILogger Logger = null;

        //public static IExHandler ExceptionHandler = null;

        //public static ITracer Tracer = null;

        public static object Regiser()
        {
            string configXmlPath = DefaultResourceACConfigurationFilePath;
            string configXml     = "";

            using (FileStream stream = new System.IO.FileStream(configXmlPath, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                using (StreamReader reader = new StreamReader(stream))
                {
                    configXml = reader.ReadToEnd();
                }
            }

            ResourceAuthConfiguration authConf = XmlUtility.XmlDeserialize(configXml, typeof(ResourceAuthConfiguration), new Type[] { typeof(Resource), typeof(Subject), typeof(Scope), typeof(Action) }, "utf-8") as ResourceAuthConfiguration;

            ISecurityManager securityManager = new SecurityManager();

            string regiseredOpId = null, registeredScopeId = null;

            string[] ops = securityManager.GetDataTypeOperations(null), scopes = securityManager.GetDataScopes(null);

            List <string> opsRegistered = null, scopesRegistered = null, rolesRegistered = null, allRoles = new List <string>();

            List <object> identityResults = null;

            if (authConf != null)
            {
                opsRegistered    = new List <string>();
                scopesRegistered = new List <string>();
                //rolesRegistered = new List<string>();

                foreach (var resource in authConf.Resources)
                {
                    if (resource != null)
                    {
                        if ((resource.Actions != null) && (resource.Actions.Length > 0))
                        {
                            //ops = securityManager.GetDataTypeOperations(resource.Name);

                            foreach (var action in resource.Actions)
                            {
                                if ((action != null) && (!ops.Contains(action.ID.ToLower())) && (!opsRegistered.Contains(action.ID.ToLower())))
                                {
                                    regiseredOpId = (string)securityManager.RegisterOperation(resource.Name, action.ID, action.Name);

                                    if (!String.IsNullOrEmpty(regiseredOpId))
                                    {
                                        opsRegistered.Add(regiseredOpId.ToLower());
                                    }
                                }
                            }

                            if (ShouldDeleteObsoleteOperationsOnRegistration)
                            {
                                using (AuthEntityModelContainer context = new AuthEntityModelContainer())
                                {
                                    var obsoleteRoleOps = context.RoleOperations.Where(ro => !opsRegistered.Contains(ro.OperationId) && !ops.Contains(ro.OperationId));
                                    context.RoleOperations.RemoveRange(obsoleteRoleOps.ToArray());

                                    var obsoleteObjectAuthItems = context.ObjectOperationAuthItems.Where(oo => !opsRegistered.Contains(oo.OperationId) && !ops.Contains(oo.OperationId));
                                    context.ObjectOperationAuthItems.RemoveRange(obsoleteObjectAuthItems.ToArray());

                                    var obsoleteOps = context.Operations.Where(o => !opsRegistered.Contains(o.Id) && !ops.Contains(o.Id));
                                    context.Operations.RemoveRange(obsoleteOps.ToArray());

                                    context.SaveChanges();
                                }
                            }
                        }

                        if ((resource.Scopes != null) && (resource.Scopes.Length > 0))
                        {
                            //scopes = securityManager.GetDataScopes(resource.Name);

                            foreach (var scope in resource.Scopes)
                            {
                                if ((scope != null) && (!scopes.Contains(scope.ID.ToLower())) && (!scopesRegistered.Contains(scope.ID.ToLower())))
                                {
                                    registeredScopeId = (string)securityManager.RegisterDataScope(resource.Name, scope.ID, scope.Name, scope.Type, resource.Key);

                                    if (!String.IsNullOrEmpty(registeredScopeId))
                                    {
                                        scopesRegistered.Add(registeredScopeId.ToLower());
                                    }
                                }
                            }

                            if (ShouldDeleteObsoleteDataScopesOnRegistration)
                            {
                                using (AuthEntityModelContainer context = new AuthEntityModelContainer())
                                {
                                    var obsoleteRoleDataScopes = context.RoleDataScopes.Where(rd => !scopesRegistered.Contains(rd.DataScopeId) && !scopes.Contains(rd.DataScopeId));
                                    context.RoleDataScopes.RemoveRange(obsoleteRoleDataScopes.ToArray());

                                    var obsoleteDataScopes = context.DataScopes.Where(ds => !scopesRegistered.Contains(ds.Id) && !scopes.Contains(ds.Id));
                                    context.DataScopes.RemoveRange(obsoleteDataScopes.ToArray());

                                    context.SaveChanges();
                                }
                            }
                        }

                        if ((resource.Subjects != null) && (resource.Subjects.Length > 0))
                        {
                            //var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new MySQLDatabase(ModuleConfiguration.DefaultIdentityStoreConnectionName)));
                            //var userManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(new MySQLDatabase(ModuleConfiguration.DefaultIdentityStoreConnectionName)));

                            var roleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(new IdentityDbContext(ModuleConfiguration.DefaultIdentityStoreConnectionName)));
                            var userManager = new UserManager <IdentityUser>(new UserStore <IdentityUser>(new IdentityDbContext(ModuleConfiguration.DefaultIdentityStoreConnectionName)));

                            IDictionary <string, string> rolesToRegister  = new Dictionary <string, string>();
                            IDictionary <string, string> roleDescriptions = new Dictionary <string, string>();

                            IdentityUser identityUser = null;

                            IdentityResult identityResult = null;

                            identityResults = new List <object>();

                            foreach (var subject in resource.Subjects)
                            {
                                if (subject.Type.ToLower() == "fixedrole")
                                {
                                    allRoles.Add(subject.ID);

                                    if (!roleManager.RoleExists(subject.Name))
                                    {
                                        rolesToRegister.Add(subject.ID, subject.Name);
                                        roleDescriptions.Add(subject.ID, subject.Description);
                                    }
                                }
                                else if (subject.Type.ToLower() == "fixeduser")
                                {
                                    identityUser = userManager.FindById(subject.ID);

                                    if (identityUser == null)
                                    {
                                        identityUser = userManager.FindByName(subject.Name);
                                    }

                                    if ((identityUser != null) && ShouldDeleteObsoleteUsersOnRegistration)
                                    {
                                        foreach (var role in roleManager.Roles)
                                        {
                                            identityResult = userManager.RemoveFromRole(identityUser.Id, role.Name);
                                            identityResults.Add(identityResult);
                                        }

                                        identityResult = userManager.Delete(identityUser);
                                        identityResults.Add(identityResult);

                                        if (identityResult.Succeeded)
                                        {
                                            identityUser = null;
                                        }
                                    }

                                    if (identityUser == null)
                                    {
                                        identityUser = new IdentityUser()
                                        {
                                            Id       = subject.ID,
                                            UserName = subject.Name,
                                            Email    = String.Format(DefaultFixedUserEmailTemplate, subject.Name),
                                            //Description = subject.Description,
                                            //UserType = 1
                                        };

                                        identityResult = userManager.Create(identityUser, DefaultFixedUserPassword);

                                        identityResults.Add(identityResult);
                                    }
                                }
                            }

                            rolesRegistered = securityManager.AddRoles(rolesToRegister, roleDescriptions) as List <string>;

                            if (rolesRegistered == null)
                            {
                                rolesRegistered = new List <string>();
                            }

                            if (ShouldDeleteObsoleteRolesOnRegistration)
                            {
                                using (AuthEntityModelContainer context = new AuthEntityModelContainer())
                                {
                                    var obsoleteRoleDataScopes = context.RoleDataScopes.Where(rd => !rolesRegistered.Contains(rd.RoleId) && !scopes.Contains(rd.RoleId));
                                    context.RoleDataScopes.RemoveRange(obsoleteRoleDataScopes.ToArray());

                                    var obsoleteRoleOps = context.RoleOperations.Where(ro => !rolesRegistered.Contains(ro.RoleId) && !ops.Contains(ro.RoleId));
                                    context.RoleOperations.RemoveRange(obsoleteRoleOps.ToArray());

                                    context.SaveChanges();
                                }

                                var obsoleteRoles = roleManager.Roles.Where(r => !rolesRegistered.Contains(r.Id) && !allRoles.Contains(r.Id));

                                if (obsoleteRoles != null)
                                {
                                    var users = userManager.Users;

                                    foreach (var role in obsoleteRoles.ToArray())
                                    {
                                        foreach (var user in users)
                                        {
                                            identityResult = userManager.RemoveFromRole(user.Id, role.Name);
                                            identityResults.Add(identityResult);
                                        }

                                        identityResult = roleManager.Delete(role);
                                        identityResults.Add(identityResult);
                                    }
                                }
                            }
                        }
                    }
                }
            }

            return(((opsRegistered != null) || (scopesRegistered != null) || (rolesRegistered != null) || (identityResults != null)) ? new object[] { opsRegistered, scopesRegistered, rolesRegistered, identityResults } : null);
        }