Skip to content

Commit

Permalink
Merge pull request #15 from musab1234/master
Browse files Browse the repository at this point in the history
WebGL Support
  • Loading branch information
chaitanyapotti authored Feb 8, 2023
2 parents e330feb + 5726445 commit d6078a8
Show file tree
Hide file tree
Showing 8 changed files with 224 additions and 128 deletions.
55 changes: 27 additions & 28 deletions Assets/Plugins/Web3AuthSDK/Api/Web3AuthApi.cs
Original file line number Diff line number Diff line change
@@ -1,16 +1,14 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Net.Http;
using System;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Text;
using UnityEngine.Networking;
using UnityEngine;

public class Web3AuthApi
{
static Web3AuthApi instance;
static Uri baseAddress = new Uri("https://broadcast-server.tor.us");
static string baseAddress = "https://broadcast-server.tor.us";

public static Web3AuthApi getInstance()
{
Expand All @@ -19,36 +17,37 @@ public static Web3AuthApi getInstance()
return instance;
}

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

if (response.IsSuccessStatusCode)
{
string result = response.Content.ReadAsStringAsync().Result;
return Newtonsoft.Json.JsonConvert.DeserializeObject<StoreApiResponse>(result);
}
return null;
if (request.result == UnityWebRequest.Result.Success)
{
string result = request.downloadHandler.text;
callback(Newtonsoft.Json.JsonConvert.DeserializeObject<StoreApiResponse>(result));
}
else
callback(null);
}

public JObject logout(LogoutApiRequest logoutApiRequest)
public IEnumerator logout(LogoutApiRequest logoutApiRequest, Action<JObject> callback)
{
using (var client = new HttpClient())
{
client.BaseAddress = baseAddress;
var content = new StringContent(JsonConvert.SerializeObject(logoutApiRequest), Encoding.UTF8, "application/json");
HttpResponseMessage response = client.PostAsync("/store/set", content).Result;
WWWForm data = new WWWForm();
data.AddField("key", logoutApiRequest.key);
data.AddField("data", logoutApiRequest.data);
data.AddField("signature", logoutApiRequest.signature);
data.AddField("timeout", logoutApiRequest.timeout.ToString());

var request = UnityWebRequest.Post($"{baseAddress}/store/set", data);
yield return request.SendWebRequest();

if (response.IsSuccessStatusCode)
{
string result = response.Content.ReadAsStringAsync().Result;
return Newtonsoft.Json.JsonConvert.DeserializeObject<JObject>(result);
}
return null;
if (request.result == UnityWebRequest.Result.Success)
{
string result = request.downloadHandler.text;
callback(Newtonsoft.Json.JsonConvert.DeserializeObject<JObject>(result));
}
else
callback(null);
}
}
21 changes: 14 additions & 7 deletions Assets/Plugins/Web3AuthSDK/Keystore/KeyStoreManagerUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,20 @@ public class KeyStoreManagerUtils

public static string getPubKey(string sessionId)
{
var domain = SecNamedCurves.GetByName("secp256k1");
var parameters = new ECDomainParameters(domain.Curve, domain.G, domain.H);

var key = new ECPrivateKeyParameters(new BigInteger(sessionId, 16), parameters);
var q = new ECPublicKeyParameters("EC", domain.G.Multiply(key.D), parameters).Q;

return Hex.ToHexString(domain.Curve.CreatePoint(q.XCoord.ToBigInteger(), q.YCoord.ToBigInteger()).GetEncoded(false));
try
{
var domain = SecNamedCurves.GetByName("secp256k1");
var parameters = new ECDomainParameters(domain.Curve, domain.G, domain.H);

var key = new ECPrivateKeyParameters(new BigInteger(sessionId, 16), parameters);
var q = new ECPublicKeyParameters("EC", domain.G.Multiply(key.D), parameters).Q;

return Hex.ToHexString(domain.Curve.CreatePoint(q.XCoord.ToBigInteger(), q.YCoord.ToBigInteger()).GetEncoded(false));
} catch (System.Exception ex)
{
UnityEngine.Debug.Log(ex);
return "";
}
}

static KeyStoreManagerUtils()
Expand Down
15 changes: 14 additions & 1 deletion Assets/Plugins/Web3AuthSDK/Utils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,22 @@

public static class Utils
{
#if UNITY_IOS
#if !UNITY_EDITOR && UNITY_IOS
[DllImport("__Internal")]
extern static void web3auth_launch(string url, string redirectUri, string objectName);
#endif

#if !UNITY_EDITOR && UNITY_WEBGL
[DllImport("__Internal")]
public extern static string GetCurrentURL();

[DllImport("__Internal")]
extern static void OpenURL(string url);

[DllImport("__Internal")]
public extern static void RemoveAuthCodeFromURL();
#endif


public static void LaunchUrl(string url, string redirectUri = null, string objectName = null)
{
Expand All @@ -29,6 +40,8 @@ public static void LaunchUrl(string url, string redirectUri = null, string objec
#elif UNITY_IOS
var uri = new Uri(redirectUri);
web3auth_launch(url, uri.Scheme, objectName);
#elif UNITY_WEBGL
OpenURL(url);
#endif
}

Expand Down
193 changes: 101 additions & 92 deletions Assets/Plugins/Web3AuthSDK/Web3Auth.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,15 @@ public void Awake()
{
this.setResultUrl(url);
};

//#elif UNITY_WEBGL
// var code = Utils.GetAuthCode();
// Debug.Log("code is " + code);
// if (Utils.GetAuthCode() != "")
// {
// Debug.Log("I am here");
// this.setResultUrl(new Uri($"http://localhost#{code}"));
// }
#endif

authorizeSession();
Expand Down Expand Up @@ -194,6 +203,8 @@ private void request(string path, LoginParams loginParams = null, Dictionary<st
{
#if UNITY_STANDALONE || UNITY_EDITOR
this.initParams["redirectUrl"] = StartLocalWebserver();
#elif UNITY_WEBGL
this.initParams["redirectUrl"] = Utils.GetCurrentURL();
#endif
Dictionary<string, object> paramMap = new Dictionary<string, object>();
paramMap["init"] = this.initParams;
Expand Down Expand Up @@ -221,9 +232,13 @@ private void request(string path, LoginParams loginParams = null, Dictionary<st
public void setResultUrl(Uri uri)
{
string hash = uri.Fragment;
#if !UNITY_EDITOR && UNITY_WEBGL
if (hash == null || hash.Length == 0)
return;
#else
if (hash == null)
throw new UserCancelledException();

#endif
hash = hash.Remove(0, 1);

Dictionary<string, string> queryParameters = Utils.ParseQuery(uri.Query);
Expand All @@ -249,6 +264,13 @@ public void setResultUrl(Uri uri)
web3AuthResponse.userInfo?.verifier, web3AuthResponse.userInfo?.dappShare
);
}

#if !UNITY_EDITOR && UNITY_WEBGL
if (this.web3AuthResponse != null)
{
Utils.RemoveAuthCodeFromURL();
}
#endif
}

public void login(LoginParams loginParams)
Expand All @@ -270,7 +292,6 @@ public void login(LoginParams loginParams)
public void logout(Dictionary<string, object> extraParams)
{
sessionTimeOutAPI();
request("logout", extraParams: extraParams);
}

public void logout(Uri redirectUrl = null, string appState = null)
Expand All @@ -291,54 +312,41 @@ private void authorizeSession()
if (!string.IsNullOrEmpty(sessionId))
{
var pubKey = KeyStoreManagerUtils.getPubKey(sessionId);
var response = Web3AuthApi.getInstance().authorizeSession(pubKey);

if (response != null)
StartCoroutine(Web3AuthApi.getInstance().authorizeSession(pubKey, (response =>
{
var shareMetadata = Newtonsoft.Json.JsonConvert.DeserializeObject<ShareMetadata>(response.message);

KeyStoreManagerUtils.savePreferenceData(
KeyStoreManagerUtils.EPHEM_PUBLIC_Key,
shareMetadata.ephemPublicKey
);

KeyStoreManagerUtils.savePreferenceData(
KeyStoreManagerUtils.IV_KEY,
shareMetadata.iv
);

KeyStoreManagerUtils.savePreferenceData(
KeyStoreManagerUtils.MAC,
shareMetadata.mac
);

var aes256cbc = new AES256CBC(
sessionId,
shareMetadata.ephemPublicKey,
shareMetadata.iv
);

var encryptedShareBytes = AES256CBC.toByteArray(new BigInteger(shareMetadata.ciphertext, 16));
var share = aes256cbc.decrypt(encryptedShareBytes);
var tempJson = JsonConvert.DeserializeObject<JObject>(share);
tempJson.Add("userInfo", tempJson["store"]);
tempJson.Remove("store");

this.web3AuthResponse = JsonConvert.DeserializeObject<Web3AuthResponse>(tempJson.ToString());

if (this.web3AuthResponse != null)
if (response != null)
{
if (this.web3AuthResponse.error != null)
var shareMetadata = Newtonsoft.Json.JsonConvert.DeserializeObject<ShareMetadata>(response.message);

var aes256cbc = new AES256CBC(
sessionId,
shareMetadata.ephemPublicKey,
shareMetadata.iv
);

var encryptedShareBytes = AES256CBC.toByteArray(new BigInteger(shareMetadata.ciphertext, 16));
var share = aes256cbc.decrypt(encryptedShareBytes);
var tempJson = JsonConvert.DeserializeObject<JObject>(share);
tempJson.Add("userInfo", tempJson["store"]);
tempJson.Remove("store");

this.web3AuthResponse = JsonConvert.DeserializeObject<Web3AuthResponse>(tempJson.ToString());

if (this.web3AuthResponse != null)
{
throw new UnKnownException(this.web3AuthResponse.error ?? "Something went wrong");
if (this.web3AuthResponse.error != null)
{
throw new UnKnownException(this.web3AuthResponse.error ?? "Something went wrong");
}

if (string.IsNullOrEmpty(this.web3AuthResponse.privKey) || string.IsNullOrEmpty(this.web3AuthResponse.privKey.Trim('0')))
this.Enqueue(() => this.onLogout?.Invoke());
else
this.Enqueue(() => this.onLogin?.Invoke(this.web3AuthResponse));
}

if (string.IsNullOrEmpty(this.web3AuthResponse.privKey) || string.IsNullOrEmpty(this.web3AuthResponse.privKey.Trim('0')))
this.Enqueue(() => this.onLogout?.Invoke());
else
this.Enqueue(() => this.onLogin?.Invoke(this.web3AuthResponse));
}
}

})));
}
}

Expand All @@ -347,58 +355,59 @@ private void sessionTimeOutAPI()
string sessionId = KeyStoreManagerUtils.getPreferencesData(KeyStoreManagerUtils.SESSION_ID);
if (!string.IsNullOrEmpty(sessionId))
{
var ephemKey = KeyStoreManagerUtils.getPreferencesData(KeyStoreManagerUtils.EPHEM_PUBLIC_Key);
var ivKey = KeyStoreManagerUtils.getPreferencesData(KeyStoreManagerUtils.IV_KEY);
var mac = KeyStoreManagerUtils.getPreferencesData(KeyStoreManagerUtils.MAC);

if (string.IsNullOrEmpty(ephemKey) == true && string.IsNullOrEmpty(ivKey) == true) return;

var aes256cbc = new AES256CBC(
sessionId,
ephemKey,
ivKey
);


var encryptedData = aes256cbc.encrypt(System.Text.Encoding.UTF8.GetBytes(""));
var encryptedMetadata = new ShareMetadata()
var pubKey = KeyStoreManagerUtils.getPubKey(sessionId);
StartCoroutine(Web3AuthApi.getInstance().authorizeSession(pubKey, (response =>
{
iv = ivKey,
ephemPublicKey = ephemKey,
ciphertext = encryptedData,
mac = mac
};
var jsonData = JsonConvert.SerializeObject(encryptedMetadata);

var result = Web3AuthApi.getInstance().logout(
new LogoutApiRequest()
if (response != null)
{
key = KeyStoreManagerUtils.getPubKey(sessionId),
data = jsonData,
signature = KeyStoreManagerUtils.getECDSASignature(
sessionId,
jsonData
),
timeout = 1
}
);
var shareMetadata = Newtonsoft.Json.JsonConvert.DeserializeObject<ShareMetadata>(response.message);

var aes256cbc = new AES256CBC(
sessionId,
shareMetadata.ephemPublicKey,
shareMetadata.iv
);

if (result != null)
{
try
{
KeyStoreManagerUtils.deletePreferencesData(KeyStoreManagerUtils.EPHEM_PUBLIC_Key);
KeyStoreManagerUtils.deletePreferencesData(KeyStoreManagerUtils.IV_KEY);
KeyStoreManagerUtils.deletePreferencesData(KeyStoreManagerUtils.MAC);
KeyStoreManagerUtils.deletePreferencesData(KeyStoreManagerUtils.SESSION_ID);
KeyStoreManagerUtils.deletePreferencesData(web3AuthOptions.loginConfig?.Values.First()?.verifier);
}
catch (Exception ex)
{
Debug.LogError(ex.Message);
var encryptedData = aes256cbc.encrypt(System.Text.Encoding.UTF8.GetBytes(""));
var encryptedMetadata = new ShareMetadata()
{
iv = shareMetadata.iv,
ephemPublicKey = shareMetadata.ephemPublicKey,
ciphertext = encryptedData,
mac = shareMetadata.mac
};
var jsonData = JsonConvert.SerializeObject(encryptedMetadata);

StartCoroutine(Web3AuthApi.getInstance().logout(
new LogoutApiRequest()
{
key = KeyStoreManagerUtils.getPubKey(sessionId),
data = jsonData,
signature = KeyStoreManagerUtils.getECDSASignature(
sessionId,
jsonData
),
timeout = 1
}, result =>
{
if (result != null)
{
try
{
KeyStoreManagerUtils.deletePreferencesData(KeyStoreManagerUtils.SESSION_ID);
KeyStoreManagerUtils.deletePreferencesData(web3AuthOptions.loginConfig?.Values.First()?.verifier);

this.Enqueue(() => this.onLogout?.Invoke());
}
catch (Exception ex)
{
Debug.LogError(ex.Message);
}
}
}
));
}
}
})));
}
}

Expand Down
Loading

0 comments on commit d6078a8

Please sign in to comment.