Skip to content

Commit

Permalink
fix: create secret on startup
Browse files Browse the repository at this point in the history
On initial startup, before using the mobileadduiclient command, the
secret used to store client information does not exist. It is now
initialized if fixed touchpanel clients are added without the use of the
mobileadduiclient command.
  • Loading branch information
Andrew Welker committed Jul 26, 2024
1 parent 73763ec commit 0c229ae
Showing 1 changed file with 61 additions and 57 deletions.
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
using Crestron.SimplSharp;
using Crestron.SimplSharp.WebScripting;
using Crestron.SimplSharpPro;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using PepperDash.Core;
using PepperDash.Essentials.AppServer.Messengers;
using PepperDash.Essentials.Core;
using PepperDash.Essentials.Core.DeviceTypeInterfaces;
using PepperDash.Essentials.Core.Web;
using PepperDash.Essentials.Devices.Common.TouchPanel;
using PepperDash.Essentials.WebApiHandlers;
using System;
using System.Collections.Generic;
Expand Down Expand Up @@ -218,7 +216,7 @@ private string SecretProviderKey
{
get
{
return string.Format("{0}:{1}-tokens", Global.ControlSystem.ProgramNumber, this.Key);
return string.Format("{0}:{1}-tokens", Global.ControlSystem.ProgramNumber, Key);
}
}

Expand Down Expand Up @@ -331,35 +329,42 @@ private void AddConsoleCommands()

public override void Initialize()
{
base.Initialize();
try
{
base.Initialize();

_server = new HttpServer(Port, false);
_server = new HttpServer(Port, false);

_server.OnGet += Server_OnGet;
_server.OnGet += Server_OnGet;

_server.OnOptions += Server_OnOptions;
_server.OnOptions += Server_OnOptions;

if (_parent.Config.DirectServer.Logging.EnableRemoteLogging)
{
_server.OnPost += Server_OnPost;
}
if (_parent.Config.DirectServer.Logging.EnableRemoteLogging)
{
_server.OnPost += Server_OnPost;
}

CrestronEnvironment.ProgramStatusEventHandler += CrestronEnvironment_ProgramStatusEventHandler;
CrestronEnvironment.ProgramStatusEventHandler += CrestronEnvironment_ProgramStatusEventHandler;

_server.Start();
_server.Start();

if (_server.IsListening)
{
Debug.Console(0, this, "Mobile Control WebSocket Server lisening on port: {0}", _server.Port);
}
if (_server.IsListening)
{
Debug.LogMessage(Serilog.Events.LogEventLevel.Information, "Mobile Control WebSocket Server listening on port {port}", this, _server.Port);
}

CrestronEnvironment.ProgramStatusEventHandler += OnProgramStop;
CrestronEnvironment.ProgramStatusEventHandler += OnProgramStop;

RetrieveSecret();
RetrieveSecret();

CreateFolderStructure();
CreateFolderStructure();

AddClientsForTouchpanels();
AddClientsForTouchpanels();
}
catch (Exception ex)
{
Debug.LogMessage(ex, "Exception intializing websocket server", this);
}
}

private void AddClientsForTouchpanels()
Expand Down Expand Up @@ -528,10 +533,9 @@ private MobileControlApplicationConfig GetApplicationConfig()
}
catch (Exception ex)
{
Debug.Console(0, this, "Error getting application configuration: {0}", ex.Message);
Debug.Console(2, this, "Stack Trace: {0}", ex.StackTrace);
Debug.LogMessage(ex, "Error getting application configuration", this);

Debug.Console(2, "Config Object: {0} from config: {1}", config, _parent.Config);
Debug.LogMessage(Serilog.Events.LogEventLevel.Verbose, "Config Object: {config} from {parentConfig}", this, config, _parent.Config);
}

return config;
Expand All @@ -550,7 +554,7 @@ private void RetrieveSecret()

if (secret != null)
{
Debug.Console(2, this, "Secret successfully retrieved");
Debug.LogMessage(Serilog.Events.LogEventLevel.Information, "Secret successfully retrieved", this);

// populate the local secrets object
_secret = JsonConvert.DeserializeObject<ServerTokenSecrets>(secret.Value.ToString());
Expand All @@ -570,7 +574,8 @@ private void RetrieveSecret()
_server.AddWebSocketService(path, () =>
{
var c = new UiClient();
Debug.Console(2, this, "Constructing UiClient with id: {0}", key);
Debug.LogMessage(Serilog.Events.LogEventLevel.Debug, "Constructing UiClient with id: {key}", this, key);
c.Controller = _parent;
c.RoomKey = roomKey;
UiClients[key].SetClient(c);
Expand All @@ -589,27 +594,41 @@ private void RetrieveSecret()
}
else
{
Debug.Console(2, this, "No secret found");
Debug.LogMessage(Serilog.Events.LogEventLevel.Warning, "No secret found");
}

Debug.Console(2, this, "{0} UiClients restored from secrets data", UiClients.Count);
Debug.LogMessage(Serilog.Events.LogEventLevel.Debug, "{uiClientCount} UiClients restored from secrets data", this, UiClients.Count);
}

/// <summary>
/// Stores secrets to memory to persist through reboot
/// </summary>
public void UpdateSecret()
{
_secret.Tokens.Clear();

foreach (var uiClientContext in UiClients)
try
{
_secret.Tokens.Add(uiClientContext.Key, uiClientContext.Value.Token);
}
if (_secret == null)
{
Debug.LogMessage(Serilog.Events.LogEventLevel.Error, "Secret is null", this);

_secret = new ServerTokenSecrets(string.Empty);
}

var serializedSecret = JsonConvert.SerializeObject(_secret);
_secret.Tokens.Clear();

_secretProvider.SetSecret(SecretProviderKey, serializedSecret);
foreach (var uiClientContext in UiClients)
{
_secret.Tokens.Add(uiClientContext.Key, uiClientContext.Value.Token);
}

var serializedSecret = JsonConvert.SerializeObject(_secret);

_secretProvider.SetSecret(SecretProviderKey, serializedSecret);
}
catch (Exception ex)
{
Debug.LogMessage(ex, "Exception updating secret", this);
}
}

/// <summary>
Expand Down Expand Up @@ -695,17 +714,17 @@ private void GenerateClientTokenFromConsole(string s)
_server.AddWebSocketService(path, () =>
{
var c = new UiClient();
Debug.Console(2, this, "Constructing UiClient with id: {0}", key);
Debug.LogMessage(Serilog.Events.LogEventLevel.Verbose, "Constructing UiClient with id: {0}", this, key);
c.Controller = _parent;
c.RoomKey = bridge.RoomKey;
UiClients[key].SetClient(c);
return c;
});

Debug.Console(0, this, $"Added new WebSocket UiClient service at path: {path}");
Debug.Console(0, this, $"Token: {key}");
Debug.LogMessage(Serilog.Events.LogEventLevel.Information, "Added new WebSocket UiClient service at path: {path}", this, path);
Debug.LogMessage(Serilog.Events.LogEventLevel.Information, "Token: {@token}", this, token);

Debug.Console(2, this, "{0} websocket services present", _server.WebSocketServices.Count);
Debug.LogMessage(Serilog.Events.LogEventLevel.Verbose, "{serviceCount} websocket services present", this, _server.WebSocketServices.Count);

UpdateSecret();

Expand Down Expand Up @@ -829,7 +848,7 @@ private void Server_OnGet(object sender, HttpRequestEventArgs e)
}
catch (Exception ex)
{
Debug.Console(0, Debug.ErrorLogLevel.Error, "Caught an exception in the OnGet handler {0}\r{1}\r{2}", ex.Message, ex.InnerException, ex.StackTrace);
Debug.LogMessage(ex, "Caught an exception in the OnGet handler", this);
}
}

Expand Down Expand Up @@ -873,14 +892,7 @@ private async void Server_OnPost(object sender, HttpRequestEventArgs e)
}
catch (Exception ex)
{
Debug.Console(0, Debug.ErrorLogLevel.Error, "Caught an exception in the OnPost handler {0}", ex.Message);
Debug.Console(2, Debug.ErrorLogLevel.Error, "StackTrace: {0}", ex.StackTrace);

if (ex.InnerException != null)
{
Debug.Console(0, Debug.ErrorLogLevel.Error, "Caught an exception in the OnGet handler {0}", ex.InnerException.Message);
Debug.Console(2, Debug.ErrorLogLevel.Error, "StackTrace: {0}", ex.InnerException.StackTrace);
}
Debug.LogMessage(ex, "Caught an exception in the OnPost handler", this);
}
}

Expand All @@ -899,15 +911,7 @@ private void Server_OnOptions(object sender, HttpRequestEventArgs e)
}
catch (Exception ex)
{
Debug.Console(0, Debug.ErrorLogLevel.Error, "Caught an exception in the OnPost handler {0}", ex.Message);
Debug.Console(2, Debug.ErrorLogLevel.Error, "StackTrace: {0}", ex.StackTrace);

if (ex.InnerException != null)
{
Debug.Console(0, Debug.ErrorLogLevel.Error, "Caught an exception in the OnGet handler {0}", ex.InnerException.Message);
Debug.Console(2, Debug.ErrorLogLevel.Error, "StackTrace: {0}", ex.InnerException.StackTrace);
}

Debug.LogMessage(ex, "Caught an exception in the OnPost handler", this);
}
}

Expand Down

0 comments on commit 0c229ae

Please sign in to comment.