Esempio n. 1
0
        public static void Start(SchemaBuilder sb)
        {
            if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
            {
                AuthLogic.AssertStarted(sb);
                OperationLogic.AssertStarted(sb);

                OperationLogic.AllowOperation += OperationLogic_AllowOperation;

                cache = new AuthCache <RuleOperationEntity, OperationAllowedRule, OperationSymbol, OperationSymbol, OperationAllowed>(sb,
                                                                                                                                      s => s,
                                                                                                                                      s => s,
                                                                                                                                      merger: new OperationMerger(),
                                                                                                                                      invalidateWithTypes: true,
                                                                                                                                      coercer:  OperationCoercer.Instance);

                AuthLogic.ExportToXml += exportAll => cache.ExportXml("Operations", "Operation", s => s.Key, b => b.ToString(),
                                                                      exportAll ? OperationLogic.RegisteredOperations.ToList() : null);
                AuthLogic.ImportFromXml += (x, roles, replacements) =>
                {
                    string replacementKey = "AuthRules:" + typeof(OperationSymbol).Name;

                    replacements.AskForReplacements(
                        x.Element("Operations").Elements("Role").SelectMany(r => r.Elements("Operation")).Select(p => p.Attribute("Resource").Value).ToHashSet(),
                        SymbolLogic <OperationSymbol> .AllUniqueKeys(),
                        replacementKey);

                    return(cache.ImportXml(x, "Operations", "Operation", roles,
                                           s => SymbolLogic <OperationSymbol> .TryToSymbol(replacements.Apply(replacementKey, s)), EnumExtensions.ToEnum <OperationAllowed>));
                };
            }
        }
        public virtual void AuthSucceeded(HttpHost authhost, AuthScheme authScheme, HttpContext
                                          context)
        {
            Args.NotNull(authhost, "Host");
            Args.NotNull(authScheme, "Auth scheme");
            Args.NotNull(context, "HTTP context");
            HttpClientContext clientContext = ((HttpClientContext)HttpClientContext.Adapt(context
                                                                                          ));

            if (IsCachable(authScheme))
            {
                AuthCache authCache = clientContext.GetAuthCache();
                if (authCache == null)
                {
                    authCache = new BasicAuthCache();
                    clientContext.SetAuthCache(authCache);
                }
                if (this.log.IsDebugEnabled())
                {
                    this.log.Debug("Caching '" + authScheme.GetSchemeName() + "' auth scheme for " +
                                   authhost);
                }
                authCache.Put(authhost, authScheme);
            }
        }
Esempio n. 3
0
        private void Login()
        {
            var auth    = new AuthCache();
            var account = new AccountModel();

            AddCacheObject("auth", auth);
            AddCacheObject("user", account);

            NavigateWindow(new NewPostViewModel(), new MainWindow());
        }
Esempio n. 4
0
        public AuthInfo GetAuthInfoFromCache(Uri uri)
        {
            AuthInfo val;

            if (AuthCache.TryGetValue(GetAuthInfoKey(uri), out val))
            {
                return(val);
            }

            return(null);
        }
Esempio n. 5
0
        private async Task Login()
        {
            var auth    = new AuthCache();
            var account = new AccountModel();
            await Task.Delay(2000);

            AddCacheObject("auth", auth);
            AddCacheObject("user", account);

            NavigateWindow(new NewPostViewModel(), new MainWindow());
        }
Esempio n. 6
0
        /// <exception cref="Apache.Http.HttpException"></exception>
        /// <exception cref="System.IO.IOException"></exception>
        public virtual void Process(IHttpRequest request, HttpContext context)
        {
            Args.NotNull(request, "HTTP request");
            Args.NotNull(context, "HTTP context");
            HttpClientContext clientContext = ((HttpClientContext)HttpClientContext.Adapt(context
                                                                                          ));
            AuthCache authCache = clientContext.GetAuthCache();

            if (authCache == null)
            {
                this.log.Debug("Auth cache not set in the context");
                return;
            }
            CredentialsProvider credsProvider = clientContext.GetCredentialsProvider();

            if (credsProvider == null)
            {
                this.log.Debug("Credentials provider not set in the context");
                return;
            }
            RouteInfo route  = clientContext.GetHttpRoute();
            HttpHost  target = clientContext.GetTargetHost();

            if (target.GetPort() < 0)
            {
                target = new HttpHost(target.GetHostName(), route.GetTargetHost().GetPort(), target
                                      .GetSchemeName());
            }
            AuthState targetState = clientContext.GetTargetAuthState();

            if (targetState != null && targetState.GetState() == AuthProtocolState.Unchallenged)
            {
                AuthScheme authScheme = authCache.Get(target);
                if (authScheme != null)
                {
                    DoPreemptiveAuth(target, authScheme, targetState, credsProvider);
                }
            }
            HttpHost  proxy      = route.GetProxyHost();
            AuthState proxyState = clientContext.GetProxyAuthState();

            if (proxy != null && proxyState != null && proxyState.GetState() == AuthProtocolState
                .Unchallenged)
            {
                AuthScheme authScheme = authCache.Get(proxy);
                if (authScheme != null)
                {
                    DoPreemptiveAuth(proxy, authScheme, proxyState, credsProvider);
                }
            }
        }
Esempio n. 7
0
        public static void Start(SchemaBuilder sb, DynamicQueryManager dqm)
        {
            if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
            {
                AuthLogic.AssertStarted(sb);
                QueryLogic.Start(sb, dqm);

                dqm.AllowQuery += new Func <object, bool, bool>(dqm_AllowQuery);

                cache = new AuthCache <RuleQueryEntity, QueryAllowedRule, QueryEntity, object, QueryAllowed>(sb,
                                                                                                             qn => QueryLogic.ToQueryName(qn.Key),
                                                                                                             QueryLogic.GetQueryEntity,
                                                                                                             merger: new QueryMerger(),
                                                                                                             invalidateWithTypes: true,
                                                                                                             coercer: QueryCoercer.Instance);

                AuthLogic.ExportToXml += exportAll => cache.ExportXml("Queries", "Query", QueryUtils.GetKey, b => b.ToString(),
                                                                      exportAll ? QueryLogic.QueryNames.Values.ToList(): null);
                AuthLogic.ImportFromXml += (x, roles, replacements) =>
                {
                    string replacementKey = "AuthRules:" + typeof(QueryEntity).Name;

                    replacements.AskForReplacements(
                        x.Element("Queries").Elements("Role").SelectMany(r => r.Elements("Query")).Select(p => p.Attribute("Resource").Value).ToHashSet(),
                        QueryLogic.QueryNames.Keys.ToHashSet(),
                        replacementKey);

                    return(cache.ImportXml(x, "Queries", "Query", roles, s =>
                    {
                        var qn = QueryLogic.TryToQueryName(replacements.Apply(replacementKey, s));

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

                        return QueryLogic.GetQueryEntity(qn);
                    }, str =>
                    {
                        if (Enum.TryParse <QueryAllowed>(str, out var result))
                        {
                            return result;
                        }

                        var bResult = bool.Parse(str); //For backwards compatibilityS
                        return bResult ? QueryAllowed.Allow : QueryAllowed.None;
                    }));
                };
            }
        }
Esempio n. 8
0
        public static void Start(SchemaBuilder sb)
        {
            if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
            {
                AuthLogic.AssertStarted(sb);

                sb.Include <PermissionSymbol>();

                SymbolLogic <PermissionSymbol> .Start(sb, () => RegisteredPermission.ToHashSet());

                sb.Include <RulePermissionEntity>()
                .WithUniqueIndex(rt => new { rt.Resource, rt.Role });

                cache = new AuthCache <RulePermissionEntity, PermissionAllowedRule, PermissionSymbol, PermissionSymbol, bool>(sb,
                                                                                                                              toKey: p => p,
                                                                                                                              toEntity: p => p,
                                                                                                                              isEquals: (p1, p2) => p1 == p2,
                                                                                                                              merger: new PermissionMerger(),
                                                                                                                              invalidateWithTypes: false);

                sb.Schema.EntityEvents <RoleEntity>().PreUnsafeDelete += query =>
                {
                    Database.Query <RulePermissionEntity>().Where(r => query.Contains(r.Role.Entity)).UnsafeDelete();
                    return(null);
                };

                RegisterPermissions(BasicPermission.AdminRules,
                                    BasicPermission.AutomaticUpgradeOfProperties,
                                    BasicPermission.AutomaticUpgradeOfOperations,
                                    BasicPermission.AutomaticUpgradeOfQueries);

                AuthLogic.ExportToXml += exportAll => cache.ExportXml("Permissions", "Permission", a => a.Key, b => b.ToString(),
                                                                      exportAll ? PermissionAuthLogic.RegisteredPermission.ToList() : null);
                AuthLogic.ImportFromXml += (x, roles, replacements) =>
                {
                    string replacementKey = "AuthRules:" + typeof(PermissionSymbol).Name;

                    replacements.AskForReplacements(
                        x.Element("Permissions").Elements("Role").SelectMany(r => r.Elements("Permission")).Select(p => p.Attribute("Resource").Value).ToHashSet(),
                        SymbolLogic <PermissionSymbol> .Symbols.Select(s => s.Key).ToHashSet(),
                        replacementKey);

                    return(cache.ImportXml(x, "Permissions", "Permission", roles,
                                           s => SymbolLogic <PermissionSymbol> .TryToSymbol(replacements.Apply(replacementKey, s)), bool.Parse));
                };

                sb.Schema.Table <PermissionSymbol>().PreDeleteSqlSync += new Func <Entity, SqlPreCommand>(AuthCache_PreDeleteSqlSync);
            }
        }
Esempio n. 9
0
        public void SetAuthInfo(Uri uri, AuthInfo authInfo)
        {
            var key = $"{uri.Scheme}://{uri.Host}:{uri.Port}";

            if (authInfo == null ||
                authInfo.Username == null && authInfo.Password == null && authInfo.Domain == null)
            {
                AuthInfo val;
                AuthCache.TryRemove(key, out val);
            }
            else
            {
                AuthCache.AddOrUpdate(key, authInfo, (s, info) => authInfo);
            }
        }
        public virtual void AuthFailed(HttpHost authhost, AuthScheme authScheme, HttpContext
                                       context)
        {
            Args.NotNull(authhost, "Host");
            Args.NotNull(context, "HTTP context");
            HttpClientContext clientContext = ((HttpClientContext)HttpClientContext.Adapt(context
                                                                                          ));
            AuthCache authCache = clientContext.GetAuthCache();

            if (authCache != null)
            {
                if (this.log.IsDebugEnabled())
                {
                    this.log.Debug("Clearing cached auth scheme for " + authhost);
                }
                authCache.Remove(authhost);
            }
        }
Esempio n. 11
0
        public static void Start(SchemaBuilder sb, DynamicQueryManager dqm)
        {
            if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
            {
                AuthLogic.AssertStarted(sb);

                sb.Include <PermissionSymbol>();

                SymbolLogic <PermissionSymbol> .Start(sb, dqm, () => RegisteredPermission.ToHashSet());

                cache = new AuthCache <RulePermissionEntity, PermissionAllowedRule, PermissionSymbol, PermissionSymbol, bool>(sb,
                                                                                                                              s => s,
                                                                                                                              s => s,
                                                                                                                              merger: new PermissionMerger(),
                                                                                                                              invalidateWithTypes: false);

                RegisterPermissions(BasicPermission.AdminRules,
                                    BasicPermission.AutomaticUpgradeOfProperties,
                                    BasicPermission.AutomaticUpgradeOfOperations,
                                    BasicPermission.AutomaticUpgradeOfQueries);

                AuthLogic.ExportToXml += exportAll => cache.ExportXml("Permissions", "Permission", a => a.Key, b => b.ToString(),
                                                                      exportAll ? PermissionAuthLogic.RegisteredPermission.ToList() : null);
                AuthLogic.ImportFromXml += (x, roles, replacements) =>
                {
                    string replacementKey = "AuthRules:" + typeof(PermissionSymbol).Name;

                    replacements.AskForReplacements(
                        x.Element("Permissions").Elements("Role").SelectMany(r => r.Elements("Permission")).Select(p => p.Attribute("Resource").Value).ToHashSet(),
                        SymbolLogic <PermissionSymbol> .Symbols.Select(s => s.Key).ToHashSet(),
                        replacementKey);

                    return(cache.ImportXml(x, "Permissions", "Permission", roles,
                                           s => SymbolLogic <PermissionSymbol> .TryToSymbol(replacements.Apply(replacementKey, s)), bool.Parse));
                };
            }
        }
Esempio n. 12
0
        public static void Start(SchemaBuilder sb)
        {
            if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
            {
                AuthLogic.AssertStarted(sb);
                PropertyRouteLogic.Start(sb);

                sb.Include <RulePropertyEntity>()
                .WithUniqueIndex(rt => new { rt.Resource, rt.Role });

                cache = new AuthCache <RulePropertyEntity, PropertyAllowedRule, PropertyRouteEntity, PropertyRoute, PropertyAllowed>(sb,
                                                                                                                                     toKey: PropertyRouteEntity.ToPropertyRouteFunc,
                                                                                                                                     toEntity: PropertyRouteLogic.ToPropertyRouteEntity,
                                                                                                                                     isEquals: (p1, p2) => p1 == p2,
                                                                                                                                     merger: new PropertyMerger(),
                                                                                                                                     invalidateWithTypes: true,
                                                                                                                                     coercer: PropertyCoercer.Instance);

                sb.Schema.EntityEvents <RoleEntity>().PreUnsafeDelete += query =>
                {
                    Database.Query <RulePropertyEntity>().Where(r => query.Contains(r.Role.Entity)).UnsafeDelete();
                    return(null);
                };

                PropertyRoute.SetIsAllowedCallback(pp => pp.GetAllowedFor(PropertyAllowed.Read));

                AuthLogic.ExportToXml += exportAll => cache.ExportXml("Properties", "Property", p => TypeLogic.GetCleanName(p.RootType) + "|" + p.PropertyString(), pa => pa.ToString(),
                                                                      exportAll ? TypeLogic.TypeToEntity.Keys.SelectMany(t => PropertyRoute.GenerateRoutes(t)).ToList() : null);
                AuthLogic.ImportFromXml += (x, roles, replacements) =>
                {
                    Dictionary <Type, Dictionary <string, PropertyRoute> > routesDicCache = new Dictionary <Type, Dictionary <string, PropertyRoute> >();

                    var groups = x.Element("Properties").Elements("Role").SelectMany(r => r.Elements("Property")).Select(p => new PropertyPair(p.Attribute("Resource").Value))
                                 .AgGroupToDictionary(a => a.Type, gr => gr.Select(pp => pp.Property).ToHashSet());

                    foreach (var item in groups)
                    {
                        Type?type = TypeLogic.NameToType.TryGetC(replacements.Apply(TypeAuthCache.typeReplacementKey, item.Key));

                        if (type == null)
                        {
                            continue;
                        }

                        var dic = PropertyRoute.GenerateRoutes(type).ToDictionary(a => a.PropertyString());

                        replacements.AskForReplacements(
                            item.Value,
                            dic.Keys.ToHashSet(),
                            AuthPropertiesReplacementKey(type));

                        routesDicCache[type] = dic;
                    }

                    var routes = Database.Query <PropertyRouteEntity>().ToDictionary(a => a.ToPropertyRoute());

                    return(cache.ImportXml(x, "Properties", "Property", roles, s =>
                    {
                        var pp = new PropertyPair(s);

                        Type?type = TypeLogic.NameToType.TryGetC(replacements.Apply(TypeAuthCache.typeReplacementKey, pp.Type));
                        if (type == null)
                        {
                            return null;
                        }

                        PropertyRoute?route = routesDicCache[type].TryGetC(replacements.Apply(AuthPropertiesReplacementKey(type), pp.Property));
                        if (route == null)
                        {
                            return null;
                        }

                        var property = routes.GetOrCreate(route, () => new PropertyRouteEntity
                        {
                            RootType = TypeLogic.TypeToEntity[route.RootType],
                            Path = route.PropertyString()
                        }.Save());

                        return property;
                    }, EnumExtensions.ToEnum <PropertyAllowed>));
                };

                sb.Schema.Table <PropertyRouteEntity>().PreDeleteSqlSync += new Func <Entity, SqlPreCommand>(AuthCache_PreDeleteSqlSync);
            }
        }
Esempio n. 13
0
        public static void Start(SchemaBuilder sb)
        {
            if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
            {
                AuthLogic.AssertStarted(sb);
                QueryLogic.Start(sb);

                QueryLogic.Queries.AllowQuery += new Func <object, bool, bool>(dqm_AllowQuery);

                sb.Include <RuleQueryEntity>()
                .WithUniqueIndex(rt => new { rt.Resource, rt.Role });

                cache = new AuthCache <RuleQueryEntity, QueryAllowedRule, QueryEntity, object, QueryAllowed>(sb,
                                                                                                             toKey: qn => QueryLogic.ToQueryName(qn.Key),
                                                                                                             toEntity: QueryLogic.GetQueryEntity,
                                                                                                             isEquals: (q1, q2) => q1 == q2,
                                                                                                             merger: new QueryMerger(),
                                                                                                             invalidateWithTypes: true,
                                                                                                             coercer: QueryCoercer.Instance);

                sb.Schema.EntityEvents <RoleEntity>().PreUnsafeDelete += query =>
                {
                    Database.Query <RuleQueryEntity>().Where(r => query.Contains(r.Role.Entity)).UnsafeDelete();
                    return(null);
                };

                AuthLogic.ExportToXml += exportAll => cache.ExportXml("Queries", "Query", QueryUtils.GetKey, b => b.ToString(),
                                                                      exportAll ? QueryLogic.QueryNames.Values.ToList(): null);
                AuthLogic.ImportFromXml += (x, roles, replacements) =>
                {
                    string replacementKey = "AuthRules:" + typeof(QueryEntity).Name;

                    replacements.AskForReplacements(
                        x.Element("Queries") !.Elements("Role").SelectMany(r => r.Elements("Query")).Select(p => p.Attribute("Resource") !.Value).ToHashSet(),
                        QueryLogic.QueryNames.Keys.ToHashSet(),
                        replacementKey);

                    return(cache.ImportXml(x, "Queries", "Query", roles, s =>
                    {
                        var qn = QueryLogic.TryToQueryName(replacements.Apply(replacementKey, s));

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

                        return QueryLogic.GetQueryEntity(qn);
                    }, str =>
                    {
                        if (Enum.TryParse <QueryAllowed>(str, out var result))
                        {
                            return result;
                        }

                        var bResult = bool.Parse(str); //For backwards compatibilityS
                        return bResult ? QueryAllowed.Allow : QueryAllowed.None;
                    }));
                };

                sb.Schema.Table <QueryEntity>().PreDeleteSqlSync += new Func <Entity, SqlPreCommand>(AuthCache_PreDeleteSqlSync);
            }
        }
 public virtual void SetAuthCache(AuthCache authCache)
 {
     SetAttribute(AuthCache, authCache);
 }
Esempio n. 15
0
 //校验票据(内存数据匹配)
 private bool ValidateTicket(string token)
 {
     return(AuthCache.ContainsToken(token));
 }