Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Jc/0 0 15 updates #43

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ public static string CheckForExistingCachedTokenAsync()

if (!File.Exists(refreshTokenPath))
return null;

Debug.Log("[Hathora.Auth0Login.CheckForExistingCachedTokenAsync] " +
$"Found already-present auth token file at: `{refreshTokenPath}`");
return File.ReadAllText(refreshTokenPath); // (!) The Async variant is bugged, freezing Unity
Expand All @@ -52,7 +52,7 @@ public async Task<string> GetTokenAsync(CancellationToken cancelToken)
Auth0DeviceResponse deviceAuthorizationResponse = await requestDeviceAuthorizationAsync();
if (deviceAuthorizationResponse == null)
{
Debug.Log("Error: Failed to get device authorizatio");
Debug.Log("Error: Failed to get device authorization");
return null;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,20 @@ private void insertDeployLogsScrollLbl()

// Content within the scroller >>
base.BeginPaddedBox();
InsertLabel(ServerConfig.HathoraDeployOpts.LastDeployLogsStrb.ToString());

//Need to delete hidden symbols for Unity format
string str = ServerConfig.HathoraDeployOpts.LastDeployLogsStrb.ToString();
string cleanedStr = "";
foreach (var c in str)
{
if (!char.IsControl(c) || c == '\n')
{
cleanedStr += c;
}
}

InsertLabel(cleanedStr);

base.EndPaddedBox();

GUILayout.EndScrollView();
Expand Down
17 changes: 11 additions & 6 deletions src/Assets/Hathora/Core/Scripts/Editor/Server/HathoraServerAuth.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using System.Threading.Tasks;
using Hathora.Core.Scripts.Editor.Server.Auth0;
using Hathora.Core.Scripts.Runtime.Server;
using Hathora.Core.Scripts.Runtime.Server.ApiWrapper;
using UnityEngine;

namespace Hathora.Core.Scripts.Editor.Server
Expand Down Expand Up @@ -42,27 +43,31 @@ static HathoraServerAuth()
/// <returns>isSuccess</returns>
public static async Task<bool> DevAuthLogin(HathoraServerConfig _hathoraServerConfig)
{
Debug.Log("DevAuthLogin - test");
createNewAuthCancelToken();
Auth0Login auth = new();
string refreshToken = await auth.GetTokenAsync(cancelToken: AuthCancelTokenSrc.Token);

HathoraServerOrgApiWrapper orgApiWrapper = new();
string createdOrgToken = await orgApiWrapper.CreateOrgTokenAsync(refreshToken);
Copy link

Choose a reason for hiding this comment

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

as discussed - you should use the bearer token instead of the refresh token


bool isSuccess = onGetTokenDone(
_hathoraServerConfig,
refreshToken);
createdOrgToken);

return isSuccess;
}

/// <summary>
/// </summary>
/// <param name="_hathoraServerConfig"></param>
/// <param name="_refreshToken"></param>
/// <param name="_authToken"></param>
/// <returns>isSuccess</returns>
private static bool onGetTokenDone(
HathoraServerConfig _hathoraServerConfig,
string _refreshToken)
string _authToken)
{
if (string.IsNullOrEmpty(_refreshToken))
if (string.IsNullOrEmpty(_authToken))
{
// Fail >>
if (AuthCancelTokenSrc != null && HasCancellableAuthToken)
Expand All @@ -71,7 +76,7 @@ private static bool onGetTokenDone(
return false; // !isSuccess
}

SetAuthToken(_hathoraServerConfig, _refreshToken);
SetAuthToken(_hathoraServerConfig, _authToken);
return true; // isSuccess
}

Expand All @@ -90,7 +95,7 @@ private static void createNewAuthCancelToken()

/// <summary>Shortcut to set dev auth token with log</summary>
/// <param name="_hathoraServerConfig"></param>
/// <param name="_token">You probably want the refreshToken</param>
/// <param name="_token">You probably want the authToken</param>
public static void SetAuthToken(HathoraServerConfig _hathoraServerConfig, string _token)
{
_hathoraServerConfig.HathoraCoreOpts.DevAuthOpts.HathoraDevToken = _token;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,30 @@ public async Task<BuildV3> GetBuildInfoAsync(

#region Utils

/// <summary>
/// Wrapper for UnityWebRequest to Task
/// </summary>
/// <param name="webRequest"></param>
/// <returns>Task</returns>
private static Task AwaitWebRequest(UnityWebRequest webRequest)
{
var tcs = new TaskCompletionSource<object>();

webRequest.SendWebRequest().completed += (asyncOperation) =>
{
if (webRequest.result != UnityWebRequest.Result.Success)
{
tcs.SetException(new Exception(webRequest.error));
}
else
{
tcs.SetResult(null);
}
};

return tcs.Task;
}

public async Task UploadToMultipartUrl(List<BuildPart> multipartUploadParts, double maxChunkSize, string completeUploadPostRequestUrl, string filePath)
{
Debug.Log($"~~~~~~{multipartUploadParts.Count} parts, maxChunkSize: {maxChunkSize}");
Expand Down Expand Up @@ -303,7 +327,7 @@ public async Task UploadToMultipartUrl(List<BuildPart> multipartUploadParts, dou
postRequest.downloadHandler = new DownloadHandlerBuffer();
postRequest.SetRequestHeader("Content-Type", "application/xml");

await postRequest.SendWebRequest();
await AwaitWebRequest(postRequest); //postRequest.SendWebRequest();

if (postRequest.result == UnityWebRequest.Result.Success)
{
Expand Down Expand Up @@ -349,7 +373,7 @@ private async Task<PartResult> UploadPart(BuildPart part, string filePath, doubl
putRequest.uploadHandler = new UploadHandlerRaw(fileChunk);
putRequest.SetRequestHeader("Content-Type", "application/octet-stream");

await putRequest.SendWebRequest();
await AwaitWebRequest(putRequest);

if (putRequest.result != UnityWebRequest.Result.Success)
{
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using HathoraCloud;
using HathoraCloud.Models.Operations;
using HathoraCloud.Models.Shared;
using Debug = UnityEngine.Debug;

namespace Hathora.Core.Scripts.Runtime.Server.ApiWrapper
{
/// <summary>
/// Operations that allow you manage your org tokens.
/// Apps Concept | https://hathora.dev/docs/concepts/hathora-entities#application
/// API Docs | https://hathora.dev/api#tag/AppV1
/// </summary>
public class HathoraServerOrgApiWrapper
{

// protected IOrganizationsV1 OrgApi { get; }
// protected ITokensV1 TokenApi { get; }

public HathoraServerOrgApiWrapper()
{
Debug.Log($"[{nameof(HathoraServerOrgApiWrapper)}.Constructor] " +
"Initializing Server API...");

// this.OrgApi = _hathoraSdk.OrganizationsV1;
// this.TokenApi = _hathoraSdk.TokensV1;
}


#region Server App Async Hathora SDK Calls
/// <summary>
/// Wrapper for `CreateAppAsync` to upload and app a cloud app to Hathora.
/// </summary>
/// <param name="_cancelToken">TODO: This may be implemented in the future</param>
/// <returns>Returns App on success</returns>
public async Task<string> CreateOrgTokenAsync(
string bearerToken,
CancellationToken _cancelToken = default)
{
Debug.Log("CreateOrgTokenAsync - test");
var sdk = new HathoraCloudSDK(
security: new Security()
{
HathoraDevToken = bearerToken,
});
IOrganizationsV1 OrgApi = sdk.OrganizationsV1;
ITokensV1 TokenApi = sdk.TokensV1;

string logPrefix = $"[{nameof(HathoraServerAppApiWrapper)}.{nameof(CreateOrgTokenAsync)}]";
Debug.Log($"{logPrefix} making GetAppsAsync request");

// Get response async =>
GetOrgsResponse getOrgsResponse = null;

try
{
getOrgsResponse = await OrgApi.GetOrgsAsync();
}
catch (Exception e)
{
Debug.LogError($"{logPrefix} {nameof(OrgApi.GetOrgsAsync)} => Error: {e.Message}");
return null; // fail
}

// Get inner response to return -> Log/Validate
// TODO: this assumes one org per user
List<Scope> userScopes =
getOrgsResponse.OrgsPage != null && getOrgsResponse.OrgsPage.Orgs[0] != null ?
getOrgsResponse.OrgsPage.Orgs[0].Scopes : new List<Scope>();
Debug.Log($"{logPrefix} num: '{userScopes?.Count ?? 0}'");

getOrgsResponse.RawResponse?.Dispose(); // Prevent mem leaks

// Create org tokenw ith same user scopes
// Get response async =>
CreateOrgTokenResponse createOrgTokenResponse = null;

string currentDateTime = DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss");
CreateOrgTokenRequest createTokenRequest = new CreateOrgTokenRequest() {
CreateOrgToken = new CreateOrgToken() {
Name = "unity-plugin-token_" + currentDateTime,
Scopes = Scopes.CreateArrayOfScope(userScopes)
},
// TODO: this assumes one org per user
OrgId = getOrgsResponse.OrgsPage.Orgs[0].OrgId,
};

try
{
createOrgTokenResponse = await TokenApi.CreateOrgTokenAsync(createTokenRequest);
}
catch (Exception e)
{
Debug.LogError($"{logPrefix} {nameof(TokenApi.CreateOrgTokenAsync)} => Error: {e.Message}");
return null; // fail
}

string createdOrgToken =
createOrgTokenResponse.CreatedOrgToken != null && createOrgTokenResponse.CreatedOrgToken.PlainTextToken.Length > 0 ?
createOrgTokenResponse.CreatedOrgToken.PlainTextToken : "";
Copy link

Choose a reason for hiding this comment

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

should you do something more than just assign it "" if it is null or empty?

Debug.Log($"{logPrefix} num: 'orgToken created, named: " + "unity-plugin-token_" + currentDateTime);

createOrgTokenResponse.RawResponse?.Dispose(); // Prevent mem leaks

return createdOrgToken;
}
#endregion // Server Org Async Hathora SDK Calls
}
}

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

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 @@ -12,7 +12,7 @@ MonoBehaviour:
m_Script: {fileID: 11500000, guid: d0353a89b1f911e48b9e16bdc9f2e058, type: 3}
m_Name:
m_EditorClassIdentifier:
version: 7
version: 9
--- !u!21 &2100000
Material:
serializedVersion: 8
Expand All @@ -35,7 +35,8 @@ Material:
m_CustomRenderQueue: -1
stringTagMap:
RenderType: Opaque
disabledShaderPasses: []
disabledShaderPasses:
- MOTIONVECTORS
m_LockedProperties:
m_SavedProperties:
serializedVersion: 3
Expand Down Expand Up @@ -136,3 +137,4 @@ Material:
- _EmissionColor: {r: 0, g: 0, b: 0, a: 1}
- _SpecColor: {r: 0.2, g: 0.2, b: 0.2, a: 1}
m_BuildTextureStacks: []
m_AllowLocking: 1
Loading