Ejemplo n.º 1
0
        internal static ConfigurationSet GetConfiguration(string id, string env, string localFile, bool skipSave = false)
        {
            ConfigurationSet configData;
            var req = WebRequest.Create(CreateRequestUriString(id, env)) as HttpWebRequest;

            req.Method      = "GET";
            req.Accept      = "application/json";
            req.ContentType = "application/json";
            req.Headers.Add("Accept-Language", "en-us");
            req.UserAgent   = "StardustProxy/1.0";
            req.Credentials = new NetworkCredential(
                ConfigurationManagerHelper.GetValueOnKey("stardust.configUser"),
                ConfigurationManagerHelper.GetValueOnKey("stardust.configPassword"),
                ConfigurationManagerHelper.GetValueOnKey("stardust.configDomain"));
            req.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
            var resp = req.GetResponse();

            using (var reader = new StreamReader(resp.GetResponseStream()))
            {
                configData = JsonConvert.DeserializeObject <ConfigurationSet>(reader.ReadToEnd());
                if (!skipSave)
                {
                    ConfigCacheHelper.UpdateCache(localFile, configData, new ConfigWrapper {
                        Set = configData, Environment = env, Id = id
                    });
                }
            }
            return(configData);
        }
Ejemplo n.º 2
0
        private ConfigurationSet GetAndWriteLocal(string id, string env, string localFile)
        {
            ConfigurationSet configData;

            configData = ConfigCacheHelper.GetConfiguration(id, env, localFile);
            ValidateAccess(configData, env);
            return(configData);
        }
Ejemplo n.º 3
0
        public HttpResponseMessage TryAddService([FromBody] ServiceRegistrationServer.ServiceRegistrationMessage data)
        {
            var localFile = ConfigCacheHelper.GetLocalFileName(data.ConfigSetId, data.Environment);

            if (File.Exists(localFile))
            {
                var configData = ConfigCacheHelper.GetConfigFromCache(data.ConfigSetId, data.Environment, localFile).Set;
                ValidateAccess(configData, data.Environment);
            }
            return(Request.CreateResponse(HttpStatusCode.OK));
        }
Ejemplo n.º 4
0
        public static void UpdateConfigSets()
        {
            Logging.DebugMessage("Updating files");
            var configSets = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory + "\\App_Data");

            foreach (var configSet in configSets)
            {
                var cs           = JsonConvert.DeserializeObject <ConfigWrapper>(File.ReadAllText(configSet));
                var newConfigSet = ConfigCacheHelper.GetConfiguration(cs.Id, cs.Environment, configSet, true);
                ConfigCacheHelper.UpdateCache(configSet, newConfigSet, cs);
            }
        }
Ejemplo n.º 5
0
        private static void UpdateEnvironmet(string id, string name)
        {
            Logging.DebugMessage("Config set updated: {0}-{1}", id, name);
            var fileName = ConfigCacheHelper.GetLocalFileName(id, name);

            ConfigCacheHelper.GetConfiguration(id, name, fileName);
            try
            {
                var hubSender = GlobalHost.ConnectionManager.GetHubContext("notificationHub");
                var groupName = string.Format("{0}-{1}", id, name).ToLower();
                hubSender.Clients.Group(groupName).notify(id, name);
            }
            catch (Exception ex)
            {
                ex.Log("failure sending message");
            }
        }
Ejemplo n.º 6
0
 private static void Timer_Elapsed(object sender, ElapsedEventArgs e)
 {
     if (hubConnection.State == ConnectionState.Disconnected)
     {
         try
         {
             hubConnection.Stop();
         }
         catch (Exception ex)
         {
             ex.Log();
         }
         ConfigCacheHelper.SetCredentials(hubConnection);
         hubConnection.Start();
     }
     hub.Invoke("ping", Environment.MachineName);
 }
Ejemplo n.º 7
0
        public HttpResponseMessage GetHostParameter(string configSet, string environment, string host, string key)
        {
            var localFile = ConfigCacheHelper.GetLocalFileName(configSet, environment);
            ConfigurationSet configData = null;

            try
            {
                if (!File.Exists(localFile))
                {
                    configData = ConfigCacheHelper.GetConfiguration(configSet, environment, localFile);
                }
                else
                {
                    configData = ConfigCacheHelper.GetConfigFromCache(configSet, environment, localFile).Set;
                }
                ValidateAccess(configData, environment);
            }
            catch (UnauthorizedAccessException ex)
            {
                return(CreateUnauthenticatedMessage(ex));
            }
            catch (Exception ex)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadGateway, new HttpError(ex.Message)));
            }
            if (configData == null)
            {
                return(Request.CreateResponse(HttpStatusCode.NotFound, new { Message = "Invalid config set" }));
            }
            var env = configData.Environments.SingleOrDefault(e => e.EnvironmentName.Equals(environment, StringComparison.OrdinalIgnoreCase));

            if (env == null)
            {
                return(Request.CreateResponse(HttpStatusCode.NotFound, new { Message = "Environment not defined" }));
            }
            var hostData = configData.Services.SingleOrDefault(h => h.ServiceName.Equals(host, StringComparison.OrdinalIgnoreCase));

            if (hostData == null)
            {
                return(Request.CreateResponse(HttpStatusCode.NotFound, new { Message = "Service host not defined" }));
            }
            var param = hostData.GetConfigParameter(key);

            return(Request.CreateResponse(param.ContainsCharacters() ? HttpStatusCode.OK : HttpStatusCode.NoContent, param.ContainsCharacters() ? new { Name = key, Value = param } : null));
        }
Ejemplo n.º 8
0
        public HttpResponseMessage Get(string id, string env, string updKey)
        {
            var localFile = string.Format(GetPathFormat(), id, env);

            if (File.Exists(localFile))
            {
                try
                {
                    var configData = ConfigCacheHelper.GetConfigFromCache(localFile).Set;
                    ValidateAccess(configData);
                    return(Request.CreateResponse(HttpStatusCode.OK, configData));
                }
                catch (Exception ex)
                {
                    ex.Log();
                }
            }
            return(GetAndWriteLocal(id, env, localFile));
        }
Ejemplo n.º 9
0
 static void hubConnection_Error(Exception obj)
 {
     obj.Log("Signalr connection issue");
     if (obj is UnauthorizedAccessException || obj.InnerException is UnauthorizedAccessException)
     {
         Logging.DebugMessage("Token expiry... refreshing oauth token");
         try
         {
             hubConnection.Stop();
         }
         catch (Exception)
         {
             // ignored
         }
         hubConnection.Dispose();
         ConfigCacheHelper.SetCredentials(hubConnection);
         hubConnection.Start();
     }
 }
Ejemplo n.º 10
0
 private static void RegisterForNotifications()
 {
     try
     {
         var userName = GetConfigServiceUser();
         var password = GetConfigServicePassword();
         GlobalHost.HubPipeline.RequireAuthentication();
         hubConnection = new HubConnection(GetConfigLocation());
         if (hubConnection.CookieContainer == null)
         {
             hubConnection.CookieContainer = new CookieContainer();
         }
         //hubConnection.Credentials = new NetworkCredential(userName, password, GetConfigServiceDomain());
         ConfigCacheHelper.SetCredentials(hubConnection);
         hub = hubConnection.CreateHubProxy("configSetHub");
         hub.On("changed",
                (string id, string name) =>
         {
             if (string.Equals(id, "user", StringComparison.OrdinalIgnoreCase))
             {
                 UpdateUser(name);
             }
             else
             {
                 UpdateEnvironmet(id, name);
             }
         });
         hubConnection.EnsureReconnecting();
         hubConnection.Reconnecting += hubConnection_Reconnecting;
         hubConnection.Closed       += hubConnection_Closed;
         hubConnection.Error        += hubConnection_Error;
         hubConnection.StateChanged += hubConnection_StateChanged;
         hubConnection.Start();
         CreatePingService();
     }
     catch (Exception ex)
     {
         ex.Log();
     }
 }
Ejemplo n.º 11
0
        public HttpResponseMessage Get(string id, string env = null, string updKey = null)
        {
            var localFile = ConfigCacheHelper.GetLocalFileName(id, env);

            if (File.Exists(localFile))
            {
                try
                {
                    var configData = ConfigCacheHelper.GetConfigFromCache(id, env, localFile).Set;
                    ValidateAccess(configData, env);
                    return(CreateResponse(configData));
                }
                catch (UnauthorizedAccessException ex)
                {
                    return(CreateUnauthenticatedMessage(ex));
                }
                catch (Exception ex)
                {
                    ex.Log();
                }
            }
            try
            {
                return(CreateResponse(GetAndWriteLocal(id, env, localFile)));
            }
            catch (UnauthorizedAccessException ex)
            {
                return(CreateUnauthenticatedMessage(ex));
            }
            catch (WebException webEx)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadGateway, webEx));
            }
            catch (Exception ex)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex));
            }
        }
Ejemplo n.º 12
0
        ///// <summary>
        ///// Wraps a function that is called when a client connects to the <see cref="T:Microsoft.AspNet.SignalR.Hubs.HubDispatcher"/> for each
        /////             <see cref="T:Microsoft.AspNet.SignalR.Hubs.IHub"/> the client connects to. By default, this results in the <see cref="T:Microsoft.AspNet.SignalR.Hubs.IHub"/>'s
        /////             OnConnected method being invoked.
        ///// </summary>
        ///// <param name="connect">A function to be called when a client connects to a hub.</param>
        ///// <returns>
        ///// A wrapped function to be called when a client connects to a hub.
        ///// </returns>
        //public override Func<IHub, Task> BuildConnect(Func<IHub, Task> connect)
        //{
        //    connect = hub =>
        //        {
        //            try
        //            {
        //                var set = hub.Context.Headers["set"];
        //                var env = hub.Context.Headers["env"];
        //                Logging.DebugMessage("Connecting to: {0}", string.Format("{0}-{1}", set, env));
        //                hub.Groups.Add(hub.Context.ConnectionId, string.Format("{0}-{1}", set, env));
        //            }
        //            catch (Exception ex)
        //            {
        //                ex.Log();
        //            }
        //            return Task.FromResult(1);
        //        };
        //    return connect;
        //}

        /// <summary>
        /// Wraps a function that determines which of the groups belonging to the hub described by the <see cref="T:Microsoft.AspNet.SignalR.Hubs.HubDescriptor"/>
        ///             the client should be allowed to rejoin.
        ///             By default, clients will rejoin all the groups they were in prior to reconnecting.
        /// </summary>
        /// <param name="rejoiningGroups">A function that determines which groups the client should be allowed to rejoin.</param>
        /// <returns>
        /// A wrapped function that determines which groups the client should be allowed to rejoin.
        /// </returns>
        //public override Func<HubDescriptor, IRequest, IList<string>, IList<string>> BuildRejoiningGroups(Func<HubDescriptor, IRequest, IList<string>, IList<string>> rejoiningGroups)
        //{
        //    rejoiningGroups = (descriptor, request, arg3) =>
        //        {
        //            try
        //            {
        //                var set = request.Headers["set"];
        //                var env = request.Headers["env"];
        //                Logging.DebugMessage("reconnecting to: {0}", string.Format("{0}-{1}", set, env));
        //                return new List<string> { string.Format("{0}-{1}", set, env) };
        //            }
        //            catch (Exception ex)
        //            {
        //                ex.Log();
        //                return new List<string>();
        //            }
        //        };
        //    return rejoiningGroups;
        //}

        /// <summary>
        /// Wraps a function to be called before a client subscribes to signals belonging to the hub described by the
        ///             <see cref="T:Microsoft.AspNet.SignalR.Hubs.HubDescriptor"/>. By default, the <see cref="T:Microsoft.AspNet.SignalR.Hubs.AuthorizeModule"/> will look for attributes on the
        ///             <see cref="T:Microsoft.AspNet.SignalR.Hubs.IHub"/> to help determine if the client is authorized to subscribe to method invocations for the
        ///             described hub.
        ///             The function returns true if the client is authorized to subscribe to client-side hub method
        ///             invocations; false, otherwise.
        /// </summary>
        /// <param name="authorizeConnect">A function that dictates whether or not the client is authorized to connect to the described Hub.
        ///             </param>
        /// <returns>
        /// A wrapped function that dictates whether or not the client is authorized to connect to the described Hub.
        /// </returns>
        public override Func <HubDescriptor, IRequest, bool> BuildAuthorizeConnect(Func <HubDescriptor, IRequest, bool> authorizeConnect)
        {
            authorizeConnect = (descriptor, request) =>
            {
                try
                {
                    Logging.DebugMessage("Authorizing hub connection..");
                    var set       = request.Headers["set"];
                    var env       = request.Headers["env"];
                    var key       = request.Headers["key"];
                    var localFile = ConfigCacheHelper.GetLocalFileName(set, env);
                    var token     = ExtractToken(request);
                    var config    = ConfigCacheHelper.GetConfigFromCache(set, env, localFile);
                    if (config == null)
                    {
                        ConfigCacheHelper.GetConfiguration(set, env, localFile);
                        config = ConfigCacheHelper.GetConfigFromCache(set, env, localFile);
                    }
                    var auth = config.TryValidateToken(env, token, key);
                    if (!auth)
                    {
                        Logging.DebugMessage("Unauthorized access");
                    }

                    else
                    {
                        Logging.DebugMessage("Authorized '{0}'", request.User.Identity.Name);
                    }
                    return(auth);
                }
                catch (Exception ex)
                {
                    ex.Log();
                    return(false);
                }
            };
            return(authorizeConnect);
        }
Ejemplo n.º 13
0
 // GET: Auth
 public ActionResult Index()
 {
     try
     {
         var env        = Request.Headers["env"];
         var set        = Request.Headers["set"];
         var localfile  = ConfigCacheHelper.GetLocalFileName(set, env);
         var configData = ConfigCacheHelper.GetConfigFromCache(set, env, localfile);
         if (configData == null)
         {
             ConfigCacheHelper.GetConfiguration(set, env, localfile);
             configData = ConfigCacheHelper.GetConfigFromCache(set, env, localfile);
         }
         ValidateAccess(configData.Set, env);
         return(new ContentResult {
             Content = "OK", ContentEncoding = Encoding.UTF8, ContentType = ""
         });
     }
     catch (Exception ex)
     {
         ex.Log();
         return(new HttpStatusCodeResult(HttpStatusCode.Forbidden, "Invalid credentials"));
     }
 }