Skip to content

Commit d6078a8

Browse files
Merge pull request #15 from musab1234/master
WebGL Support
2 parents e330feb + 5726445 commit d6078a8

File tree

8 files changed

+224
-128
lines changed

8 files changed

+224
-128
lines changed
Lines changed: 27 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,14 @@
11
using System.Collections;
2-
using System.Collections.Generic;
3-
using UnityEngine;
4-
using System.Net.Http;
52
using System;
63
using Newtonsoft.Json.Linq;
74
using Newtonsoft.Json;
8-
using System.Text;
5+
using UnityEngine.Networking;
6+
using UnityEngine;
97

108
public class Web3AuthApi
119
{
1210
static Web3AuthApi instance;
13-
static Uri baseAddress = new Uri("https://broadcast-server.tor.us");
11+
static string baseAddress = "https://broadcast-server.tor.us";
1412

1513
public static Web3AuthApi getInstance()
1614
{
@@ -19,36 +17,37 @@ public static Web3AuthApi getInstance()
1917
return instance;
2018
}
2119

22-
public StoreApiResponse? authorizeSession(string key)
20+
public IEnumerator authorizeSession(string key, Action<StoreApiResponse> callback)
2321
{
24-
using (var client = new HttpClient())
25-
{
26-
client.BaseAddress = baseAddress;
27-
HttpResponseMessage response = client.GetAsync("/store/get?key=" + key).Result;
22+
var request = UnityWebRequest.Get($"{baseAddress}/store/get?key={key}");
23+
yield return request.SendWebRequest();
2824

29-
if (response.IsSuccessStatusCode)
30-
{
31-
string result = response.Content.ReadAsStringAsync().Result;
32-
return Newtonsoft.Json.JsonConvert.DeserializeObject<StoreApiResponse>(result);
33-
}
34-
return null;
25+
if (request.result == UnityWebRequest.Result.Success)
26+
{
27+
string result = request.downloadHandler.text;
28+
callback(Newtonsoft.Json.JsonConvert.DeserializeObject<StoreApiResponse>(result));
3529
}
30+
else
31+
callback(null);
3632
}
3733

38-
public JObject logout(LogoutApiRequest logoutApiRequest)
34+
public IEnumerator logout(LogoutApiRequest logoutApiRequest, Action<JObject> callback)
3935
{
40-
using (var client = new HttpClient())
41-
{
42-
client.BaseAddress = baseAddress;
43-
var content = new StringContent(JsonConvert.SerializeObject(logoutApiRequest), Encoding.UTF8, "application/json");
44-
HttpResponseMessage response = client.PostAsync("/store/set", content).Result;
36+
WWWForm data = new WWWForm();
37+
data.AddField("key", logoutApiRequest.key);
38+
data.AddField("data", logoutApiRequest.data);
39+
data.AddField("signature", logoutApiRequest.signature);
40+
data.AddField("timeout", logoutApiRequest.timeout.ToString());
41+
42+
var request = UnityWebRequest.Post($"{baseAddress}/store/set", data);
43+
yield return request.SendWebRequest();
4544

46-
if (response.IsSuccessStatusCode)
47-
{
48-
string result = response.Content.ReadAsStringAsync().Result;
49-
return Newtonsoft.Json.JsonConvert.DeserializeObject<JObject>(result);
50-
}
51-
return null;
45+
if (request.result == UnityWebRequest.Result.Success)
46+
{
47+
string result = request.downloadHandler.text;
48+
callback(Newtonsoft.Json.JsonConvert.DeserializeObject<JObject>(result));
5249
}
50+
else
51+
callback(null);
5352
}
5453
}

Assets/Plugins/Web3AuthSDK/Keystore/KeyStoreManagerUtils.cs

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -27,13 +27,20 @@ public class KeyStoreManagerUtils
2727

2828
public static string getPubKey(string sessionId)
2929
{
30-
var domain = SecNamedCurves.GetByName("secp256k1");
31-
var parameters = new ECDomainParameters(domain.Curve, domain.G, domain.H);
32-
33-
var key = new ECPrivateKeyParameters(new BigInteger(sessionId, 16), parameters);
34-
var q = new ECPublicKeyParameters("EC", domain.G.Multiply(key.D), parameters).Q;
35-
36-
return Hex.ToHexString(domain.Curve.CreatePoint(q.XCoord.ToBigInteger(), q.YCoord.ToBigInteger()).GetEncoded(false));
30+
try
31+
{
32+
var domain = SecNamedCurves.GetByName("secp256k1");
33+
var parameters = new ECDomainParameters(domain.Curve, domain.G, domain.H);
34+
35+
var key = new ECPrivateKeyParameters(new BigInteger(sessionId, 16), parameters);
36+
var q = new ECPublicKeyParameters("EC", domain.G.Multiply(key.D), parameters).Q;
37+
38+
return Hex.ToHexString(domain.Curve.CreatePoint(q.XCoord.ToBigInteger(), q.YCoord.ToBigInteger()).GetEncoded(false));
39+
} catch (System.Exception ex)
40+
{
41+
UnityEngine.Debug.Log(ex);
42+
return "";
43+
}
3744
}
3845

3946
static KeyStoreManagerUtils()

Assets/Plugins/Web3AuthSDK/Utils.cs

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,22 @@
88

99
public static class Utils
1010
{
11-
#if UNITY_IOS
11+
#if !UNITY_EDITOR && UNITY_IOS
1212
[DllImport("__Internal")]
1313
extern static void web3auth_launch(string url, string redirectUri, string objectName);
1414
#endif
1515

16+
#if !UNITY_EDITOR && UNITY_WEBGL
17+
[DllImport("__Internal")]
18+
public extern static string GetCurrentURL();
19+
20+
[DllImport("__Internal")]
21+
extern static void OpenURL(string url);
22+
23+
[DllImport("__Internal")]
24+
public extern static void RemoveAuthCodeFromURL();
25+
#endif
26+
1627

1728
public static void LaunchUrl(string url, string redirectUri = null, string objectName = null)
1829
{
@@ -29,6 +40,8 @@ public static void LaunchUrl(string url, string redirectUri = null, string objec
2940
#elif UNITY_IOS
3041
var uri = new Uri(redirectUri);
3142
web3auth_launch(url, uri.Scheme, objectName);
43+
#elif UNITY_WEBGL
44+
OpenURL(url);
3245
#endif
3346
}
3447

Assets/Plugins/Web3AuthSDK/Web3Auth.cs

Lines changed: 101 additions & 92 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,15 @@ public void Awake()
5454
{
5555
this.setResultUrl(url);
5656
};
57+
58+
//#elif UNITY_WEBGL
59+
// var code = Utils.GetAuthCode();
60+
// Debug.Log("code is " + code);
61+
// if (Utils.GetAuthCode() != "")
62+
// {
63+
// Debug.Log("I am here");
64+
// this.setResultUrl(new Uri($"http://localhost#{code}"));
65+
// }
5766
#endif
5867

5968
authorizeSession();
@@ -194,6 +203,8 @@ private void request(string path, LoginParams loginParams = null, Dictionary<st
194203
{
195204
#if UNITY_STANDALONE || UNITY_EDITOR
196205
this.initParams["redirectUrl"] = StartLocalWebserver();
206+
#elif UNITY_WEBGL
207+
this.initParams["redirectUrl"] = Utils.GetCurrentURL();
197208
#endif
198209
Dictionary<string, object> paramMap = new Dictionary<string, object>();
199210
paramMap["init"] = this.initParams;
@@ -221,9 +232,13 @@ private void request(string path, LoginParams loginParams = null, Dictionary<st
221232
public void setResultUrl(Uri uri)
222233
{
223234
string hash = uri.Fragment;
235+
#if !UNITY_EDITOR && UNITY_WEBGL
236+
if (hash == null || hash.Length == 0)
237+
return;
238+
#else
224239
if (hash == null)
225240
throw new UserCancelledException();
226-
241+
#endif
227242
hash = hash.Remove(0, 1);
228243

229244
Dictionary<string, string> queryParameters = Utils.ParseQuery(uri.Query);
@@ -249,6 +264,13 @@ public void setResultUrl(Uri uri)
249264
web3AuthResponse.userInfo?.verifier, web3AuthResponse.userInfo?.dappShare
250265
);
251266
}
267+
268+
#if !UNITY_EDITOR && UNITY_WEBGL
269+
if (this.web3AuthResponse != null)
270+
{
271+
Utils.RemoveAuthCodeFromURL();
272+
}
273+
#endif
252274
}
253275

254276
public void login(LoginParams loginParams)
@@ -270,7 +292,6 @@ public void login(LoginParams loginParams)
270292
public void logout(Dictionary<string, object> extraParams)
271293
{
272294
sessionTimeOutAPI();
273-
request("logout", extraParams: extraParams);
274295
}
275296

276297
public void logout(Uri redirectUrl = null, string appState = null)
@@ -291,54 +312,41 @@ private void authorizeSession()
291312
if (!string.IsNullOrEmpty(sessionId))
292313
{
293314
var pubKey = KeyStoreManagerUtils.getPubKey(sessionId);
294-
var response = Web3AuthApi.getInstance().authorizeSession(pubKey);
295-
296-
if (response != null)
315+
StartCoroutine(Web3AuthApi.getInstance().authorizeSession(pubKey, (response =>
297316
{
298-
var shareMetadata = Newtonsoft.Json.JsonConvert.DeserializeObject<ShareMetadata>(response.message);
299-
300-
KeyStoreManagerUtils.savePreferenceData(
301-
KeyStoreManagerUtils.EPHEM_PUBLIC_Key,
302-
shareMetadata.ephemPublicKey
303-
);
304-
305-
KeyStoreManagerUtils.savePreferenceData(
306-
KeyStoreManagerUtils.IV_KEY,
307-
shareMetadata.iv
308-
);
309-
310-
KeyStoreManagerUtils.savePreferenceData(
311-
KeyStoreManagerUtils.MAC,
312-
shareMetadata.mac
313-
);
314-
315-
var aes256cbc = new AES256CBC(
316-
sessionId,
317-
shareMetadata.ephemPublicKey,
318-
shareMetadata.iv
319-
);
320-
321-
var encryptedShareBytes = AES256CBC.toByteArray(new BigInteger(shareMetadata.ciphertext, 16));
322-
var share = aes256cbc.decrypt(encryptedShareBytes);
323-
var tempJson = JsonConvert.DeserializeObject<JObject>(share);
324-
tempJson.Add("userInfo", tempJson["store"]);
325-
tempJson.Remove("store");
326-
327-
this.web3AuthResponse = JsonConvert.DeserializeObject<Web3AuthResponse>(tempJson.ToString());
328-
329-
if (this.web3AuthResponse != null)
317+
if (response != null)
330318
{
331-
if (this.web3AuthResponse.error != null)
319+
var shareMetadata = Newtonsoft.Json.JsonConvert.DeserializeObject<ShareMetadata>(response.message);
320+
321+
var aes256cbc = new AES256CBC(
322+
sessionId,
323+
shareMetadata.ephemPublicKey,
324+
shareMetadata.iv
325+
);
326+
327+
var encryptedShareBytes = AES256CBC.toByteArray(new BigInteger(shareMetadata.ciphertext, 16));
328+
var share = aes256cbc.decrypt(encryptedShareBytes);
329+
var tempJson = JsonConvert.DeserializeObject<JObject>(share);
330+
tempJson.Add("userInfo", tempJson["store"]);
331+
tempJson.Remove("store");
332+
333+
this.web3AuthResponse = JsonConvert.DeserializeObject<Web3AuthResponse>(tempJson.ToString());
334+
335+
if (this.web3AuthResponse != null)
332336
{
333-
throw new UnKnownException(this.web3AuthResponse.error ?? "Something went wrong");
337+
if (this.web3AuthResponse.error != null)
338+
{
339+
throw new UnKnownException(this.web3AuthResponse.error ?? "Something went wrong");
340+
}
341+
342+
if (string.IsNullOrEmpty(this.web3AuthResponse.privKey) || string.IsNullOrEmpty(this.web3AuthResponse.privKey.Trim('0')))
343+
this.Enqueue(() => this.onLogout?.Invoke());
344+
else
345+
this.Enqueue(() => this.onLogin?.Invoke(this.web3AuthResponse));
334346
}
335-
336-
if (string.IsNullOrEmpty(this.web3AuthResponse.privKey) || string.IsNullOrEmpty(this.web3AuthResponse.privKey.Trim('0')))
337-
this.Enqueue(() => this.onLogout?.Invoke());
338-
else
339-
this.Enqueue(() => this.onLogin?.Invoke(this.web3AuthResponse));
340347
}
341-
}
348+
349+
})));
342350
}
343351
}
344352

@@ -347,58 +355,59 @@ private void sessionTimeOutAPI()
347355
string sessionId = KeyStoreManagerUtils.getPreferencesData(KeyStoreManagerUtils.SESSION_ID);
348356
if (!string.IsNullOrEmpty(sessionId))
349357
{
350-
var ephemKey = KeyStoreManagerUtils.getPreferencesData(KeyStoreManagerUtils.EPHEM_PUBLIC_Key);
351-
var ivKey = KeyStoreManagerUtils.getPreferencesData(KeyStoreManagerUtils.IV_KEY);
352-
var mac = KeyStoreManagerUtils.getPreferencesData(KeyStoreManagerUtils.MAC);
353-
354-
if (string.IsNullOrEmpty(ephemKey) == true && string.IsNullOrEmpty(ivKey) == true) return;
355-
356-
var aes256cbc = new AES256CBC(
357-
sessionId,
358-
ephemKey,
359-
ivKey
360-
);
361-
362-
363-
var encryptedData = aes256cbc.encrypt(System.Text.Encoding.UTF8.GetBytes(""));
364-
var encryptedMetadata = new ShareMetadata()
358+
var pubKey = KeyStoreManagerUtils.getPubKey(sessionId);
359+
StartCoroutine(Web3AuthApi.getInstance().authorizeSession(pubKey, (response =>
365360
{
366-
iv = ivKey,
367-
ephemPublicKey = ephemKey,
368-
ciphertext = encryptedData,
369-
mac = mac
370-
};
371-
var jsonData = JsonConvert.SerializeObject(encryptedMetadata);
372-
373-
var result = Web3AuthApi.getInstance().logout(
374-
new LogoutApiRequest()
361+
if (response != null)
375362
{
376-
key = KeyStoreManagerUtils.getPubKey(sessionId),
377-
data = jsonData,
378-
signature = KeyStoreManagerUtils.getECDSASignature(
379-
sessionId,
380-
jsonData
381-
),
382-
timeout = 1
383-
}
384-
);
363+
var shareMetadata = Newtonsoft.Json.JsonConvert.DeserializeObject<ShareMetadata>(response.message);
385364

365+
var aes256cbc = new AES256CBC(
366+
sessionId,
367+
shareMetadata.ephemPublicKey,
368+
shareMetadata.iv
369+
);
386370

387-
if (result != null)
388-
{
389-
try
390-
{
391-
KeyStoreManagerUtils.deletePreferencesData(KeyStoreManagerUtils.EPHEM_PUBLIC_Key);
392-
KeyStoreManagerUtils.deletePreferencesData(KeyStoreManagerUtils.IV_KEY);
393-
KeyStoreManagerUtils.deletePreferencesData(KeyStoreManagerUtils.MAC);
394-
KeyStoreManagerUtils.deletePreferencesData(KeyStoreManagerUtils.SESSION_ID);
395-
KeyStoreManagerUtils.deletePreferencesData(web3AuthOptions.loginConfig?.Values.First()?.verifier);
396-
}
397-
catch (Exception ex)
398-
{
399-
Debug.LogError(ex.Message);
371+
var encryptedData = aes256cbc.encrypt(System.Text.Encoding.UTF8.GetBytes(""));
372+
var encryptedMetadata = new ShareMetadata()
373+
{
374+
iv = shareMetadata.iv,
375+
ephemPublicKey = shareMetadata.ephemPublicKey,
376+
ciphertext = encryptedData,
377+
mac = shareMetadata.mac
378+
};
379+
var jsonData = JsonConvert.SerializeObject(encryptedMetadata);
380+
381+
StartCoroutine(Web3AuthApi.getInstance().logout(
382+
new LogoutApiRequest()
383+
{
384+
key = KeyStoreManagerUtils.getPubKey(sessionId),
385+
data = jsonData,
386+
signature = KeyStoreManagerUtils.getECDSASignature(
387+
sessionId,
388+
jsonData
389+
),
390+
timeout = 1
391+
}, result =>
392+
{
393+
if (result != null)
394+
{
395+
try
396+
{
397+
KeyStoreManagerUtils.deletePreferencesData(KeyStoreManagerUtils.SESSION_ID);
398+
KeyStoreManagerUtils.deletePreferencesData(web3AuthOptions.loginConfig?.Values.First()?.verifier);
399+
400+
this.Enqueue(() => this.onLogout?.Invoke());
401+
}
402+
catch (Exception ex)
403+
{
404+
Debug.LogError(ex.Message);
405+
}
406+
}
407+
}
408+
));
400409
}
401-
}
410+
})));
402411
}
403412
}
404413

0 commit comments

Comments
 (0)