Skip to content

Commit

Permalink
add Auth.GetUserData() method. trigger it on first OnChange() call. b…
Browse files Browse the repository at this point in the history
…ump version.
  • Loading branch information
endel committed Jan 16, 2024
1 parent 6358622 commit bc2d603
Show file tree
Hide file tree
Showing 5 changed files with 112 additions and 31 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/upmsemver.yml
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ jobs:
run: mkdir Release
- name: Generate Unity Package
id: build-package
uses: pCYSl5EDgo/create-unitypackage@v1.1.1
uses: pCYSl5EDgo/create-unitypackage@v1.2.3
with:
package-path: 'Colyseus_Plugin.unitypackage'
include-files: metaList
Expand Down
80 changes: 58 additions & 22 deletions Assets/Colyseus/Runtime/Colyseus/Models/Auth.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,26 +33,7 @@ public AuthData(string _token, IndexedDictionary<string, object> userData)
}
else if (userData != null)
{
Type targetType = typeof(T);
T instance = (T)Activator.CreateInstance(targetType);

for (var i = 0; i < rawUser.Keys.Count; i++)
{
var field = targetType.GetField(rawUser.Keys[i]);
if (field != null)
{
try
{
field.SetValue(instance, Convert.ChangeType(rawUser.Values[i], field.FieldType));
}
catch (Exception e)
{
Debug.LogWarning("Colyseus.Auth: cannot convert " + targetType.ToString() + " property '" + field.Name + "' from " + rawUser.Values[i].GetType() + " to " + field.FieldType + " (" + e.Message + ")");
}
}
}

user = instance;
user = ConvertType(userData);
}
}

Expand All @@ -79,6 +60,29 @@ public Type UserType
{
get => typeof(T);
}

public static T ConvertType(IndexedDictionary<string, object> rawUser)
{
Type targetType = typeof(T);
T instance = (T)Activator.CreateInstance(targetType);

for (var i = 0; i < rawUser.Keys.Count; i++)
{
var field = targetType.GetField(rawUser.Keys[i]);
if (field != null)
{
try
{
field.SetValue(instance, Convert.ChangeType(rawUser.Values[i], field.FieldType));
}
catch (Exception e)
{
Debug.LogWarning("Colyseus.Auth: cannot convert " + targetType.ToString() + " property '" + field.Name + "' from " + rawUser.Values[i].GetType() + " to " + field.FieldType + " (" + e.Message + ")");
}
}
}
return instance;
}
}

public interface IAuthChangeHandler
Expand Down Expand Up @@ -111,6 +115,7 @@ public class Auth

private ColyseusClient _client;
private List<IAuthChangeHandler> OnChangeHandlers = new List<IAuthChangeHandler>();
private bool initialized = false;

public Auth(ColyseusClient client)
{
Expand All @@ -124,7 +129,7 @@ public string Token
set => _client.Http.AuthToken = value;
}

public Action OnChange<T>(Action<AuthData<T>> callback)
public async Task<Action> OnChange<T>(Action<AuthData<T>> callback)
{
var handler = new AuthChangeHandler<AuthData<T>>
{
Expand All @@ -134,9 +139,36 @@ public Action OnChange<T>(Action<AuthData<T>> callback)

OnChangeHandlers.Add(handler);

if (!initialized)
{
initialized = true;
try
{
emitChange(new AuthData<T> {
token = Token,
user = await GetUserData<T>()
});
} catch (Exception _)
{
emitChange(new AuthData<object> { user = null, token = null });
}
}

return () => OnChangeHandlers.Remove(handler);
}

public async Task<T> GetUserData<T>()
{
if (string.IsNullOrEmpty(Token))
{
throw new Exception("missing Auth.Token");
}
else
{
return getAuthData<T>(await _client.Http.Request<AuthData<IndexedDictionary<string, object>>>("GET", $"{PATH}/userdata")).user;
}
}

public async Task<AuthData<T>> RegisterWithEmailAndPassword<T>(string email, string password, Dictionary<string, object> options = null)
{
var response = getAuthData<T>(await _client.Http.Request<AuthData<IndexedDictionary<string, object>>>("POST", $"{PATH}/register", new Dictionary<string, object>
Expand Down Expand Up @@ -213,7 +245,7 @@ public async Task<string> SendResetPasswordEmail(string email, string password)

public void SignOut()
{
emitChange(new AuthData<object> { token = null, user = null, });
emitChange(new AuthData<object> { token = null, user = null});
}

private void emitChange(IAuthData authData)
Expand Down Expand Up @@ -246,6 +278,10 @@ private void emitChange(IAuthData authData)
object instance = Activator.CreateInstance(handler.Type, authData.Token, null);
handler.Invoke(instance);
}
else
{
Debug.Log("Not triggering...");
}
});
}

Expand Down
58 changes: 51 additions & 7 deletions Assets/Colyseus/Tests/Editor/ColyseusTests/AuthTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,15 @@ class User
public bool anonymous;
}

private Colyseus.ColyseusClient client = new Colyseus.ColyseusClient("http://localhost:2567");
private Colyseus.ColyseusClient client;

[SetUp]
public void Init()
{
// Initialize without a token on each test
client = new Colyseus.ColyseusClient("http://localhost:2567");
client.Auth.Token = null;

// Make sure auth token is not cached
PlayerPrefs.DeleteAll();
}
Expand All @@ -29,6 +33,45 @@ public void Dispose()
{
}

[Test]
public async Task GetUserData()
{
var uniqueEmail = $"endel{Time.time.ToString().Replace(".", "")}@colyseus.io";

string tokenFromCallback = "OnChange was not called";
string emailFromCallback = "";
string nameFromCallback = "";

_ = client.Auth.OnChange((Colyseus.AuthData<User> authData) =>
{
tokenFromCallback = authData.token;
if (authData.user != null)
{
emailFromCallback = authData.user.email;
nameFromCallback = authData.user.name;
}
});

//
// Registering for the first time
//
Colyseus.IAuthData response = null;
try
{
response = await client.Auth.RegisterWithEmailAndPassword(uniqueEmail, "123456");
}
catch (Colyseus.HttpException e)
{
Assert.Fail(e.Message + $"({e.StatusCode})");
}

Assert.AreEqual(tokenFromCallback, client.Auth.Token);

var user = await client.Auth.GetUserData<User>();
Assert.AreEqual(user.email, emailFromCallback);
Assert.AreEqual(user.name, nameFromCallback);
}

[Test]
public async Task RegisterWithEmailAndPassword()
{
Expand All @@ -38,7 +81,7 @@ public async Task RegisterWithEmailAndPassword()
string emailFromCallback = "";
string nameFromCallback = "";

client.Auth.OnChange((Colyseus.AuthData<User> authData) =>
_ = client.Auth.OnChange((Colyseus.AuthData<User> authData) =>
{
tokenFromCallback = authData.token;
if (authData.user != null)
Expand Down Expand Up @@ -105,7 +148,7 @@ public async Task SignInAnonymously()
bool anonymousFromCallback = false;
int anonymousIdFromCallback = 0;

client.Auth.OnChange((Colyseus.AuthData<User> authData) =>
_ = client.Auth.OnChange((Colyseus.AuthData<User> authData) =>
{
tokenFromCallback = authData.token;
if (authData.user != null)
Expand Down Expand Up @@ -148,7 +191,7 @@ public async Task SignOut()
int onChangeCallCount = 0;
int onChangeCallWithNullUser = 0;

client.Auth.OnChange((Colyseus.AuthData<User> authData) =>
_ = client.Auth.OnChange((Colyseus.AuthData<User> authData) =>
{
onChangeCallCount++;
tokenFromCallback = authData.token;
Expand All @@ -165,12 +208,13 @@ public async Task SignOut()

await client.Auth.SignInAnonymously();
Assert.AreEqual(tokenFromCallback, client.Auth.Token);
Assert.AreEqual(1, onChangeCallCount);
Assert.AreEqual(1, onChangeCallWithNullUser);
Assert.AreEqual(2, onChangeCallCount);

client.Auth.SignOut();
Assert.AreEqual(null, client.Auth.Token);
Assert.AreEqual(2, onChangeCallCount);
Assert.AreEqual(1, onChangeCallWithNullUser);
Assert.AreEqual(3, onChangeCallCount);
Assert.AreEqual(2, onChangeCallWithNullUser);
}

}
2 changes: 1 addition & 1 deletion Assets/Colyseus/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "io.colyseus.sdk",
"version": "0.15.7",
"version": "0.15.8",
"displayName": "Colyseus SDK",
"description": "Colyseus Multiplayer SDK for Unity",
"unity": "2019.1",
Expand Down
1 change: 1 addition & 0 deletions Server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
"typescript": "^5.0.4"
},
"dependencies": {
"@colyseus/auth": "^0.15.8",
"@colyseus/core": "^0.15.0",
"@colyseus/monitor": "^0.15.0",
"@colyseus/redis-driver": "^0.15.0",
Expand Down

0 comments on commit bc2d603

Please sign in to comment.