Skip to content
This repository has been archived by the owner on Jan 18, 2022. It is now read-only.

Move runtime IP to EditorPref / DevAuthToken to PlayerPref #961

Merged
merged 11 commits into from
Jun 3, 2019
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@
### Changed

- Upgraded the project to be compatible with `2019.1.3f1`.
- Moved Runtime IP from the `GdkToolsConfiguration.json` to an Editor Preference.
paulbalaji marked this conversation as resolved.
Show resolved Hide resolved
- Moved Dev Auth Token to a PlayerPref.
paulbalaji marked this conversation as resolved.
Show resolved Hide resolved
- Added a setting in `GdkToolsConfiguration` to let users configure whether a DevAuthToken.txt should be generated or not.
paulbalaji marked this conversation as resolved.
Show resolved Hide resolved
- When launching Android cloud clients from the Editor, the DevAuthToken is now passed in as a command line argument.

### Fixed

Expand Down
4 changes: 2 additions & 2 deletions workers/unity/Assets/Config/GdkToolsConfiguration.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
],
"CodegenOutputDir": "Assets/Generated/Source",
"DescriptorOutputDir": "../../build/assembly/schema",
"RuntimeIp": "",
"DevAuthTokenDir": "Resources",
"DevAuthTokenLifetimeDays": 30
"DevAuthTokenLifetimeDays": 30,
"SaveDevAuthTokenToFile": false
}
2 changes: 1 addition & 1 deletion workers/unity/Assets/Plugins.meta

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ public static class RuntimeConfigNames
public const string LinkProtocol = "linkProtocol";
public const string LocatorHost = "locatorHost";
public const string LoginToken = "loginToken";
public const string DevAuthTokenKey = "devAuthTokenSecret";
public const string PlayerIdentityToken = "playerIdentityToken";
public const string ProjectName = "projectName";
public const string ReceptionistHost = "receptionistHost";
Expand All @@ -36,7 +37,7 @@ public static class RuntimeConfigNames
}

/// <summary>
/// Stores the configuration needed to connect via the Lcoator.
/// Stores the configuration needed to connect via the Locator.
/// </summary>
public struct LocatorConfig
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -254,16 +254,23 @@ protected virtual string SelectDeploymentName(DeploymentList deployments)
/// </summary>
protected virtual string GetDevAuthToken()
{
if (PlayerPrefs.HasKey(RuntimeConfigNames.DevAuthTokenKey))
{
return PlayerPrefs.GetString(RuntimeConfigNames.DevAuthTokenKey);
}

var textAsset = Resources.Load<TextAsset>("DevAuthToken");
if (textAsset != null)
{
return textAsset.text.Trim();
PlayerPrefs.SetString(RuntimeConfigNames.DevAuthTokenKey, textAsset.text.Trim());
}
else
{
throw new MissingReferenceException("Unable to find DevAuthToken.txt in the Resources folder. " +
"You can generate one via SpatialOS > Generate Dev Authentication Token.");
}

return PlayerPrefs.GetString(RuntimeConfigNames.DevAuthTokenKey);
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ public static class LaunchMenu
private const string MenuLaunchAndroidLocal = "/Android for local";
private const string MenuLaunchAndroidCloud = "/Android for cloud";


[MenuItem(MenuLaunchMobile + MenuLaunchAndroidLocal, false, 73)]
private static void LaunchAndroidLocal()
{
Expand Down Expand Up @@ -90,6 +89,24 @@ private static void LaunchAndroid(bool shouldConnectLocally)
else
{
arguments.Append($"+{RuntimeConfigNames.Environment} {RuntimeConfigDefaults.CloudEnvironment} ");

var gdkToolsConfig = GdkToolsConfiguration.GetOrCreateInstance();

// Return error if no DevAuthToken is set AND fails to generate new DevAuthToken.
if (!PlayerPrefs.HasKey(RuntimeConfigNames.DevAuthTokenKey) && !DevAuthTokenUtils.TryGenerate())
{
Debug.LogError("Failed to generate a Dev Auth Token to launch mobile client.");
return;
}

// Prints a warning if DevAuthToken.txt does not exist, if GdkToolsConfiguration is configured
// to save a DAT to file.
if (gdkToolsConfig.SaveDevAuthTokenToFile && !File.Exists(gdkToolsConfig.DevAuthTokenFilepath))
{
Debug.LogWarning("Launching Android client without a DevAuthToken.txt asset.");
paulbalaji marked this conversation as resolved.
Show resolved Hide resolved
}

arguments.Append($"+{RuntimeConfigNames.DevAuthTokenKey} {DevAuthTokenUtils.DevAuthToken} ");
}

// Get chosen android package id and launch
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,10 @@
"optionalUnityReferences": [],
"includePlatforms": [],
"excludePlatforms": [],
"allowUnsafeCode": false
}
"allowUnsafeCode": false,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": [],
"versionDefines": []
}
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,12 @@ protected virtual void InitializeClient()
PlayerPrefs.DeleteKey(HostIpPlayerPrefsKey);
}

var devAuthToken = CommandLineUtility.GetCommandLineValue(arguments, RuntimeConfigNames.DevAuthTokenKey, string.Empty);
if (!string.IsNullOrEmpty(devAuthToken))
{
PlayerPrefs.SetString(RuntimeConfigNames.DevAuthTokenKey, devAuthToken);
}

PlayerPrefs.Save();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,26 @@ namespace Improbable.Gdk.Tools
{
public static class DevAuthTokenUtils
{
public static string DevAuthToken => PlayerPrefs.GetString(PlayerPrefDevAuthTokenKey);

private static string DevAuthTokenAssetPath =>
Path.Combine("Assets", GdkToolsConfiguration.GetOrCreateInstance().DevAuthTokenDir, "DevAuthToken.txt");
paulbalaji marked this conversation as resolved.
Show resolved Hide resolved

private static readonly string JsonDataKey = "json_data";
private static readonly string TokenSecretKey = "token_secret";
private static readonly string JsonErrorKey = "error";
private static readonly string JsonTokenSecretKey = "token_secret";
private static readonly string PlayerPrefDevAuthTokenKey = "devAuthTokenSecret";

[MenuItem("SpatialOS/Generate Dev Authentication Token", false, MenuPriorities.GenerateDevAuthToken)]
private static void Generate()
private const string DevAuthMenuPrefix = "SpatialOS/Dev Authentication Token";
private const string DevAuthMenuGenerateToken = "/Generate Token";
private const string DevAuthMenuClearToken = "/Clear Token";

[MenuItem(DevAuthMenuPrefix + DevAuthMenuGenerateToken, false, MenuPriorities.GenerateDevAuthToken)]
public static bool TryGenerate()
{
var devAuthToken = string.Empty;
var gdkToolsConfiguration = GdkToolsConfiguration.GetOrCreateInstance();
var devAuthTokenFullDir = gdkToolsConfiguration.DevAuthTokenFullDir;
var devAuthTokenFilePath = gdkToolsConfiguration.DevAuthTokenFilepath;

var devAuthTokenLifetimeHours = $"{gdkToolsConfiguration.DevAuthTokenLifetimeHours}h";

var receivedMessage = string.Empty;
Expand All @@ -33,18 +43,53 @@ private static void Generate()

try
{
if (Json.Deserialize(receivedMessage).TryGetValue(JsonDataKey, out var jsonData) &&
((Dictionary<string, object>) jsonData).TryGetValue(TokenSecretKey, out var tokenSecret))
var deserializedMessage = Json.Deserialize(receivedMessage);
if (deserializedMessage.TryGetValue(JsonDataKey, out var jsonData) &&
((Dictionary<string, object>) jsonData).TryGetValue(JsonTokenSecretKey, out var tokenSecret))
{
devAuthToken = (string) tokenSecret;
}
else
{
throw new Exception(
$@"{(deserializedMessage.TryGetValue(JsonErrorKey, out var errorMessage)
paulbalaji marked this conversation as resolved.
Show resolved Hide resolved
? errorMessage
: string.Empty)}");
}
}
catch (Exception e)
{
Debug.LogError($"Unable to generate Dev Auth Token. {e.Message}");
return;
return false;
}

Debug.Log($"Saving token to Player Preferences.");
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is the log needed?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

given there's a couple ways of saving out a token (player prefs / .txt), I'd prefer to log where it's being saved

this way we'll be able to see if a user's actually created DAT.txt before complaining it doesn't exist

PlayerPrefs.SetString(PlayerPrefDevAuthTokenKey, devAuthToken);

if (gdkToolsConfiguration.SaveDevAuthTokenToFile)
{
return SaveTokenToFile();
}

return true;
}

private static bool SaveTokenToFile()
{
var gdkToolsConfiguration = GdkToolsConfiguration.GetOrCreateInstance();
var devAuthTokenFullDir = gdkToolsConfiguration.DevAuthTokenFullDir;
var devAuthTokenFilePath = gdkToolsConfiguration.DevAuthTokenFilepath;

if (!PlayerPrefs.HasKey(PlayerPrefDevAuthTokenKey))
{
// Given we call SaveTokenToFile after successfully generating a Dev Auth Token,
// we should never see the following warning.
Debug.LogWarning("Cannot save Development Authentication Token, as it has not been generated.");
paulbalaji marked this conversation as resolved.
Show resolved Hide resolved
return false;
}

var devAuthToken = PlayerPrefs.GetString(PlayerPrefDevAuthTokenKey);

if (!Directory.Exists(devAuthTokenFullDir))
{
Directory.CreateDirectory(devAuthTokenFullDir);
Expand All @@ -57,13 +102,21 @@ private static void Generate()
catch (Exception e)
{
Debug.LogError($"Unable to save Dev Auth Token asset. {e.Message}");
return;
return false;
}

Debug.Log($"Saving token {devAuthToken} to {devAuthTokenFilePath}.");
AssetDatabase.ImportAsset(
Path.Combine("Assets", gdkToolsConfiguration.DevAuthTokenDir, "DevAuthToken.txt"),
ImportAssetOptions.ForceUpdate);
Debug.Log($"Saving token to {devAuthTokenFilePath}.");
AssetDatabase.ImportAsset(DevAuthTokenAssetPath, ImportAssetOptions.ForceUpdate);
paulbalaji marked this conversation as resolved.
Show resolved Hide resolved
AssetDatabase.Refresh();

return true;
}

[MenuItem(DevAuthMenuPrefix + DevAuthMenuClearToken, false, MenuPriorities.ClearDevAuthToken)]
private static void ClearToken()
{
PlayerPrefs.DeleteKey(PlayerPrefDevAuthTokenKey);
AssetDatabase.DeleteAsset(DevAuthTokenAssetPath);
AssetDatabase.Refresh();
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System.Collections.Generic;
using System.IO;
using System.Net;
using UnityEditor;
using UnityEngine;

namespace Improbable.Gdk.Tools
Expand All @@ -13,9 +14,12 @@ public class GdkToolsConfiguration
public List<string> SchemaSourceDirs = new List<string>();
public string CodegenOutputDir;
public string DescriptorOutputDir;
public string RuntimeIp;
public string DevAuthTokenDir;
public int DevAuthTokenLifetimeDays;
public bool SaveDevAuthTokenToFile;

internal string RuntimeIpEditorPrefKey = "RuntimeIp";
public string RuntimeIp => EditorPrefs.GetString(RuntimeIpEditorPrefKey);
paulbalaji marked this conversation as resolved.
Show resolved Hide resolved

public string DevAuthTokenFullDir => Path.Combine(Application.dataPath, DevAuthTokenDir);
public string DevAuthTokenFilepath => Path.Combine(DevAuthTokenFullDir, "DevAuthToken.txt");
Expand Down Expand Up @@ -83,6 +87,11 @@ internal List<string> Validate()
errors.Add($"Runtime IP \"{RuntimeIp}\" is not a valid IP address.");
}

if (!SaveDevAuthTokenToFile)
{
return errors;
}

if (string.IsNullOrEmpty(DevAuthTokenDir))
{
errors.Add($"{GdkToolsConfigurationWindow.DevAuthTokenDirLabel} cannot be empty.");
Expand All @@ -101,7 +110,6 @@ internal void ResetToDefault()
SchemaStdLibDir = DefaultValues.SchemaStdLibDir;
CodegenOutputDir = DefaultValues.CodegenOutputDir;
DescriptorOutputDir = DefaultValues.DescriptorOutputDir;
RuntimeIp = DefaultValues.RuntimeIp;
DevAuthTokenDir = DefaultValues.DevAuthTokenDir;
DevAuthTokenLifetimeDays = DefaultValues.DevAuthTokenLifetimeDays;

Expand Down Expand Up @@ -134,7 +142,6 @@ private static class DefaultValues
public const string CodegenOutputDir = "Assets/Generated/Source";
public const string DescriptorOutputDir = "../../build/assembly/schema";
public const string SchemaSourceDir = "../../schema";
public const string RuntimeIp = null;
public const string DevAuthTokenDir = "Resources";
public const int DevAuthTokenLifetimeDays = 30;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,9 @@ private void DrawCodeGenerationOptions()
GUILayout.Label(MobileSectionLabel, EditorStyles.boldLabel);
using (new EditorGUI.IndentLevelScope())
{
toolsConfig.RuntimeIp = EditorGUILayout.TextField(RuntimeIpLabel, toolsConfig.RuntimeIp);
EditorPrefs.SetString(
toolsConfig.RuntimeIpEditorPrefKey,
EditorGUILayout.TextField(RuntimeIpLabel, toolsConfig.RuntimeIp));
}

GUILayout.Label(DevAuthTokenSectionLabel, EditorStyles.boldLabel);
Expand All @@ -163,9 +165,12 @@ private void DrawCodeGenerationOptions()
toolsConfig.DevAuthTokenLifetimeDays =
EditorGUILayout.IntSlider(DevAuthTokenLifetimeLabel, toolsConfig.DevAuthTokenLifetimeDays, 1, 90);

toolsConfig.DevAuthTokenDir = EditorGUILayout.TextField(DevAuthTokenDirLabel, toolsConfig.DevAuthTokenDir);

GUILayout.Label($"Token filepath: {toolsConfig.DevAuthTokenFilepath}", EditorStyles.helpBox);
toolsConfig.SaveDevAuthTokenToFile = EditorGUILayout.Toggle("Save token to file", toolsConfig.SaveDevAuthTokenToFile);
using (new EditorGUI.DisabledScope(!toolsConfig.SaveDevAuthTokenToFile))
{
toolsConfig.DevAuthTokenDir = EditorGUILayout.TextField(DevAuthTokenDirLabel, toolsConfig.DevAuthTokenDir);
GUILayout.Label($"Token filepath: {toolsConfig.DevAuthTokenFilepath}", EditorStyles.helpBox);
}
}

EditorGUIUtility.labelWidth = previousWidth;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,6 @@ internal static class MenuPriorities

internal const int GdkToolsConfiguration = 201;
internal const int GenerateDevAuthToken = 202;
internal const int ClearDevAuthToken = 203;
}
}
1 change: 1 addition & 0 deletions workers/unity/ProjectSettings/GraphicsSettings.asset
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ GraphicsSettings:
- {fileID: 10770, guid: 0000000000000000f000000000000000, type: 0}
- {fileID: 17000, guid: 0000000000000000f000000000000000, type: 0}
- {fileID: 16000, guid: 0000000000000000f000000000000000, type: 0}
- {fileID: 16001, guid: 0000000000000000f000000000000000, type: 0}
m_PreloadedShaders: []
m_SpritesDefaultMaterial: {fileID: 10754, guid: 0000000000000000f000000000000000,
type: 0}
Expand Down
Loading