Skip to content

Commit bc2d603

Browse files
committed
add Auth.GetUserData() method. trigger it on first OnChange() call. bump version.
1 parent 6358622 commit bc2d603

File tree

5 files changed

+112
-31
lines changed

5 files changed

+112
-31
lines changed

.github/workflows/upmsemver.yml

+1-1
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ jobs:
6363
run: mkdir Release
6464
- name: Generate Unity Package
6565
id: build-package
66-
uses: pCYSl5EDgo/create-unitypackage@v1.1.1
66+
uses: pCYSl5EDgo/create-unitypackage@v1.2.3
6767
with:
6868
package-path: 'Colyseus_Plugin.unitypackage'
6969
include-files: metaList

Assets/Colyseus/Runtime/Colyseus/Models/Auth.cs

+58-22
Original file line numberDiff line numberDiff line change
@@ -33,26 +33,7 @@ public AuthData(string _token, IndexedDictionary<string, object> userData)
3333
}
3434
else if (userData != null)
3535
{
36-
Type targetType = typeof(T);
37-
T instance = (T)Activator.CreateInstance(targetType);
38-
39-
for (var i = 0; i < rawUser.Keys.Count; i++)
40-
{
41-
var field = targetType.GetField(rawUser.Keys[i]);
42-
if (field != null)
43-
{
44-
try
45-
{
46-
field.SetValue(instance, Convert.ChangeType(rawUser.Values[i], field.FieldType));
47-
}
48-
catch (Exception e)
49-
{
50-
Debug.LogWarning("Colyseus.Auth: cannot convert " + targetType.ToString() + " property '" + field.Name + "' from " + rawUser.Values[i].GetType() + " to " + field.FieldType + " (" + e.Message + ")");
51-
}
52-
}
53-
}
54-
55-
user = instance;
36+
user = ConvertType(userData);
5637
}
5738
}
5839

@@ -79,6 +60,29 @@ public Type UserType
7960
{
8061
get => typeof(T);
8162
}
63+
64+
public static T ConvertType(IndexedDictionary<string, object> rawUser)
65+
{
66+
Type targetType = typeof(T);
67+
T instance = (T)Activator.CreateInstance(targetType);
68+
69+
for (var i = 0; i < rawUser.Keys.Count; i++)
70+
{
71+
var field = targetType.GetField(rawUser.Keys[i]);
72+
if (field != null)
73+
{
74+
try
75+
{
76+
field.SetValue(instance, Convert.ChangeType(rawUser.Values[i], field.FieldType));
77+
}
78+
catch (Exception e)
79+
{
80+
Debug.LogWarning("Colyseus.Auth: cannot convert " + targetType.ToString() + " property '" + field.Name + "' from " + rawUser.Values[i].GetType() + " to " + field.FieldType + " (" + e.Message + ")");
81+
}
82+
}
83+
}
84+
return instance;
85+
}
8286
}
8387

8488
public interface IAuthChangeHandler
@@ -111,6 +115,7 @@ public class Auth
111115

112116
private ColyseusClient _client;
113117
private List<IAuthChangeHandler> OnChangeHandlers = new List<IAuthChangeHandler>();
118+
private bool initialized = false;
114119

115120
public Auth(ColyseusClient client)
116121
{
@@ -124,7 +129,7 @@ public string Token
124129
set => _client.Http.AuthToken = value;
125130
}
126131

127-
public Action OnChange<T>(Action<AuthData<T>> callback)
132+
public async Task<Action> OnChange<T>(Action<AuthData<T>> callback)
128133
{
129134
var handler = new AuthChangeHandler<AuthData<T>>
130135
{
@@ -134,9 +139,36 @@ public Action OnChange<T>(Action<AuthData<T>> callback)
134139

135140
OnChangeHandlers.Add(handler);
136141

142+
if (!initialized)
143+
{
144+
initialized = true;
145+
try
146+
{
147+
emitChange(new AuthData<T> {
148+
token = Token,
149+
user = await GetUserData<T>()
150+
});
151+
} catch (Exception _)
152+
{
153+
emitChange(new AuthData<object> { user = null, token = null });
154+
}
155+
}
156+
137157
return () => OnChangeHandlers.Remove(handler);
138158
}
139159

160+
public async Task<T> GetUserData<T>()
161+
{
162+
if (string.IsNullOrEmpty(Token))
163+
{
164+
throw new Exception("missing Auth.Token");
165+
}
166+
else
167+
{
168+
return getAuthData<T>(await _client.Http.Request<AuthData<IndexedDictionary<string, object>>>("GET", $"{PATH}/userdata")).user;
169+
}
170+
}
171+
140172
public async Task<AuthData<T>> RegisterWithEmailAndPassword<T>(string email, string password, Dictionary<string, object> options = null)
141173
{
142174
var response = getAuthData<T>(await _client.Http.Request<AuthData<IndexedDictionary<string, object>>>("POST", $"{PATH}/register", new Dictionary<string, object>
@@ -213,7 +245,7 @@ public async Task<string> SendResetPasswordEmail(string email, string password)
213245

214246
public void SignOut()
215247
{
216-
emitChange(new AuthData<object> { token = null, user = null, });
248+
emitChange(new AuthData<object> { token = null, user = null});
217249
}
218250

219251
private void emitChange(IAuthData authData)
@@ -246,6 +278,10 @@ private void emitChange(IAuthData authData)
246278
object instance = Activator.CreateInstance(handler.Type, authData.Token, null);
247279
handler.Invoke(instance);
248280
}
281+
else
282+
{
283+
Debug.Log("Not triggering...");
284+
}
249285
});
250286
}
251287

Assets/Colyseus/Tests/Editor/ColyseusTests/AuthTest.cs

+51-7
Original file line numberDiff line numberDiff line change
@@ -15,11 +15,15 @@ class User
1515
public bool anonymous;
1616
}
1717

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

2020
[SetUp]
2121
public void Init()
2222
{
23+
// Initialize without a token on each test
24+
client = new Colyseus.ColyseusClient("http://localhost:2567");
25+
client.Auth.Token = null;
26+
2327
// Make sure auth token is not cached
2428
PlayerPrefs.DeleteAll();
2529
}
@@ -29,6 +33,45 @@ public void Dispose()
2933
{
3034
}
3135

36+
[Test]
37+
public async Task GetUserData()
38+
{
39+
var uniqueEmail = $"endel{Time.time.ToString().Replace(".", "")}@colyseus.io";
40+
41+
string tokenFromCallback = "OnChange was not called";
42+
string emailFromCallback = "";
43+
string nameFromCallback = "";
44+
45+
_ = client.Auth.OnChange((Colyseus.AuthData<User> authData) =>
46+
{
47+
tokenFromCallback = authData.token;
48+
if (authData.user != null)
49+
{
50+
emailFromCallback = authData.user.email;
51+
nameFromCallback = authData.user.name;
52+
}
53+
});
54+
55+
//
56+
// Registering for the first time
57+
//
58+
Colyseus.IAuthData response = null;
59+
try
60+
{
61+
response = await client.Auth.RegisterWithEmailAndPassword(uniqueEmail, "123456");
62+
}
63+
catch (Colyseus.HttpException e)
64+
{
65+
Assert.Fail(e.Message + $"({e.StatusCode})");
66+
}
67+
68+
Assert.AreEqual(tokenFromCallback, client.Auth.Token);
69+
70+
var user = await client.Auth.GetUserData<User>();
71+
Assert.AreEqual(user.email, emailFromCallback);
72+
Assert.AreEqual(user.name, nameFromCallback);
73+
}
74+
3275
[Test]
3376
public async Task RegisterWithEmailAndPassword()
3477
{
@@ -38,7 +81,7 @@ public async Task RegisterWithEmailAndPassword()
3881
string emailFromCallback = "";
3982
string nameFromCallback = "";
4083

41-
client.Auth.OnChange((Colyseus.AuthData<User> authData) =>
84+
_ = client.Auth.OnChange((Colyseus.AuthData<User> authData) =>
4285
{
4386
tokenFromCallback = authData.token;
4487
if (authData.user != null)
@@ -105,7 +148,7 @@ public async Task SignInAnonymously()
105148
bool anonymousFromCallback = false;
106149
int anonymousIdFromCallback = 0;
107150

108-
client.Auth.OnChange((Colyseus.AuthData<User> authData) =>
151+
_ = client.Auth.OnChange((Colyseus.AuthData<User> authData) =>
109152
{
110153
tokenFromCallback = authData.token;
111154
if (authData.user != null)
@@ -148,7 +191,7 @@ public async Task SignOut()
148191
int onChangeCallCount = 0;
149192
int onChangeCallWithNullUser = 0;
150193

151-
client.Auth.OnChange((Colyseus.AuthData<User> authData) =>
194+
_ = client.Auth.OnChange((Colyseus.AuthData<User> authData) =>
152195
{
153196
onChangeCallCount++;
154197
tokenFromCallback = authData.token;
@@ -165,12 +208,13 @@ public async Task SignOut()
165208

166209
await client.Auth.SignInAnonymously();
167210
Assert.AreEqual(tokenFromCallback, client.Auth.Token);
168-
Assert.AreEqual(1, onChangeCallCount);
211+
Assert.AreEqual(1, onChangeCallWithNullUser);
212+
Assert.AreEqual(2, onChangeCallCount);
169213

170214
client.Auth.SignOut();
171215
Assert.AreEqual(null, client.Auth.Token);
172-
Assert.AreEqual(2, onChangeCallCount);
173-
Assert.AreEqual(1, onChangeCallWithNullUser);
216+
Assert.AreEqual(3, onChangeCallCount);
217+
Assert.AreEqual(2, onChangeCallWithNullUser);
174218
}
175219

176220
}

Assets/Colyseus/package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "io.colyseus.sdk",
3-
"version": "0.15.7",
3+
"version": "0.15.8",
44
"displayName": "Colyseus SDK",
55
"description": "Colyseus Multiplayer SDK for Unity",
66
"unity": "2019.1",

Server/package.json

+1
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
"typescript": "^5.0.4"
3030
},
3131
"dependencies": {
32+
"@colyseus/auth": "^0.15.8",
3233
"@colyseus/core": "^0.15.0",
3334
"@colyseus/monitor": "^0.15.0",
3435
"@colyseus/redis-driver": "^0.15.0",

0 commit comments

Comments
 (0)