Skip to content

Commit 9385c45

Browse files
committed
Upgrade all OAuthFlows to V2 Lambda + Redirect
1 parent 8c7118c commit 9385c45

File tree

3 files changed

+67
-63
lines changed

3 files changed

+67
-63
lines changed

Assets/Thirdweb/Examples/Scripts/PlaygroundManager.cs

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,11 @@ private async void ConnectWallet(WalletOptions options)
8484
{
8585
// Connect the wallet
8686

87+
var internalWalletProvider = options.Provider == WalletProvider.MetaMaskWallet ? WalletProvider.WalletConnectWallet : options.Provider;
88+
var currentPanel = WalletPanels.Find(panel => panel.Identifier == internalWalletProvider.ToString());
89+
90+
Log(currentPanel.LogText, $"Connecting...");
91+
8792
var wallet = await ThirdwebManager.Instance.ConnectWallet(options);
8893

8994
// Initialize the wallet panel
@@ -92,8 +97,6 @@ private async void ConnectWallet(WalletOptions options)
9297

9398
// Setup actions
9499

95-
var internalWalletProvider = options.Provider == WalletProvider.MetaMaskWallet ? WalletProvider.WalletConnectWallet : options.Provider;
96-
var currentPanel = WalletPanels.Find(panel => panel.Identifier == internalWalletProvider.ToString());
97100
ClearLog(currentPanel.LogText);
98101
currentPanel.Panel.SetActive(true);
99102

@@ -121,6 +124,7 @@ private async void ConnectWallet(WalletOptions options)
121124
currentPanel.Action3Button.onClick.RemoveAllListeners();
122125
currentPanel.Action3Button.onClick.AddListener(async () =>
123126
{
127+
LoadingLog(currentPanel.LogText);
124128
var balance = await wallet.GetBalance(chainId: ActiveChainId);
125129
var balanceEth = Utils.ToEth(wei: balance.ToString(), decimalsToDisplay: 4, addCommas: true);
126130
Log(currentPanel.LogText, $"Balance: {balanceEth} {_chainDetails.NativeCurrency.Symbol}");
@@ -171,7 +175,7 @@ private void InitializeInAppWalletPanel()
171175
InitializeInAppWalletPanel_Phone();
172176
});
173177

174-
// Socials (Using Google Here)
178+
// Socials
175179
panel.Action3Button.onClick.RemoveAllListeners();
176180
panel.Action3Button.onClick.AddListener(() =>
177181
{
@@ -256,6 +260,7 @@ private void InitializeInAppWalletPanel_Socials()
256260
{
257261
try
258262
{
263+
Log(panel.LogText, "Authenticating...");
259264
var inAppWalletOptions = new InAppWalletOptions(authprovider: AuthProvider.Google);
260265
var options = new WalletOptions(provider: WalletProvider.InAppWallet, chainId: ActiveChainId, inAppWalletOptions: inAppWalletOptions);
261266
ConnectWallet(options);
@@ -271,6 +276,7 @@ private void InitializeInAppWalletPanel_Socials()
271276
{
272277
try
273278
{
279+
Log(panel.LogText, "Authenticating...");
274280
var inAppWalletOptions = new InAppWalletOptions(authprovider: AuthProvider.Apple);
275281
var options = new WalletOptions(provider: WalletProvider.InAppWallet, chainId: ActiveChainId, inAppWalletOptions: inAppWalletOptions);
276282
ConnectWallet(options);
@@ -286,6 +292,7 @@ private void InitializeInAppWalletPanel_Socials()
286292
{
287293
try
288294
{
295+
Log(panel.LogText, "Authenticating...");
289296
var inAppWalletOptions = new InAppWalletOptions(authprovider: AuthProvider.Discord);
290297
var options = new WalletOptions(provider: WalletProvider.InAppWallet, chainId: ActiveChainId, inAppWalletOptions: inAppWalletOptions);
291298
ConnectWallet(options);
@@ -318,6 +325,7 @@ private void InitializeContractsPanel()
318325
{
319326
try
320327
{
328+
LoadingLog(panel.LogText);
321329
var dropErc1155Contract = await ThirdwebManager.Instance.GetContract(address: "0x6A7a26c9a595E6893C255C9dF0b593e77518e0c3", chainId: ActiveChainId);
322330
var nft = await dropErc1155Contract.ERC1155_GetNFT(tokenId: 1);
323331
Log(panel.LogText, $"NFT: {JsonConvert.SerializeObject(nft.Metadata)}");
@@ -334,6 +342,7 @@ private void InitializeContractsPanel()
334342
{
335343
try
336344
{
345+
LoadingLog(panel.LogText);
337346
var contract = await ThirdwebManager.Instance.GetContract(address: "0x6A7a26c9a595E6893C255C9dF0b593e77518e0c3", chainId: ActiveChainId);
338347
var result = await contract.ERC1155_URI(tokenId: 1);
339348
Log(panel.LogText, $"Result (uri): {result}");
@@ -350,6 +359,7 @@ private void InitializeContractsPanel()
350359
{
351360
try
352361
{
362+
LoadingLog(panel.LogText);
353363
var dropErc20Contract = await ThirdwebManager.Instance.GetContract(address: "0xEBB8a39D865465F289fa349A67B3391d8f910da9", chainId: ActiveChainId);
354364
var symbol = await dropErc20Contract.ERC20_Symbol();
355365
var balance = await dropErc20Contract.ERC20_BalanceOf(ownerAddress: await ThirdwebManager.Instance.GetActiveWallet().GetAddress());
@@ -431,6 +441,7 @@ private async void InitializeAccountAbstractionPanel()
431441
{
432442
try
433443
{
444+
LoadingLog(panel.LogText);
434445
var activeSigners = await smartWallet.GetAllActiveSigners();
435446
Log(panel.LogText, $"Active Signers: {JsonConvert.SerializeObject(activeSigners)}");
436447
}
@@ -460,5 +471,10 @@ private void Log(TMP_Text logText, string message)
460471
logText.text = message;
461472
ThirdwebDebug.Log(message);
462473
}
474+
475+
private void LoadingLog(TMP_Text logText)
476+
{
477+
logText.text = "Loading...";
478+
}
463479
}
464480
}

Assets/Thirdweb/Runtime/Unity/Browser/WebGLInAppWalletBrowser.cs

Lines changed: 7 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ public class WebGLInAppWalletBrowser : MonoBehaviour, IThirdwebBrowser
1717
private bool _isCallbackInvoked;
1818

1919
[DllImport("__Internal")]
20-
private static extern void openPopup(string url, string developerClientId, string authOption, string unityObjectName, string unityCallbackMethod);
20+
private static extern void openPopup(string url, string unityObjectName, string unityCallbackMethod);
2121

2222
private void Awake()
2323
{
@@ -34,6 +34,8 @@ private void Awake()
3434

3535
public async Task<BrowserResult> Login(ThirdwebClient client, string loginUrl, string redirectUrl, Action<string> browserOpenAction, CancellationToken cancellationToken = default)
3636
{
37+
ThirdwebDebug.Log($"WebGLInAppWalletBrowser.Login: {loginUrl}");
38+
3739
_taskCompletionSource = new TaskCompletionSource<BrowserResult>();
3840

3941
_isCallbackInvoked = false;
@@ -48,18 +50,9 @@ public async Task<BrowserResult> Login(ThirdwebClient client, string loginUrl, s
4850

4951
Uri uri = new(loginUrl);
5052

51-
string developerClientId = client.ClientId;
52-
53-
var queryParts = uri.Query.TrimStart('?').Split('&');
54-
string logoutUriEncoded = queryParts.FirstOrDefault(q => q.StartsWith("logout_uri="))?.Split('=')[1];
55-
string logoutUriDecoded = Uri.UnescapeDataString(logoutUriEncoded ?? string.Empty);
56-
Uri logoutUri = new(logoutUriDecoded);
57-
var logoutQueryParts = logoutUri.Query.TrimStart('?').Split('&');
58-
string authOption = logoutQueryParts.FirstOrDefault(q => q.StartsWith("identity_provider="))?.Split('=')[1];
59-
60-
openPopup(loginUrl, developerClientId, authOption, unityObjectName, unityCallbackMethod);
53+
openPopup(loginUrl, unityObjectName, unityCallbackMethod);
6154

62-
var completedTask = await Task.WhenAny(_taskCompletionSource.Task, Task.Delay(TimeSpan.FromSeconds(90), cancellationToken));
55+
var completedTask = await Task.WhenAny(_taskCompletionSource.Task, Task.Delay(TimeSpan.FromSeconds(120), cancellationToken));
6356
return completedTask == _taskCompletionSource.Task ? await _taskCompletionSource.Task : new BrowserResult(BrowserStatus.Timeout, null, "The operation timed out.");
6457
}
6558

@@ -80,12 +73,12 @@ public void OnRedirect(string message)
8073
{
8174
var data = JsonConvert.DeserializeObject<JObject>(message);
8275

83-
if (data["eventType"].ToString() == "userLoginSuccess")
76+
if (data["eventType"].ToString() == "oauthSuccessResult")
8477
{
8578
_isCallbackInvoked = true;
8679
_taskCompletionSource.SetResult(new BrowserResult(BrowserStatus.Success, data["authResult"].ToString()));
8780
}
88-
else if (data["eventType"].ToString() == "userLoginFailed")
81+
else if (data["eventType"].ToString() == "oauthFailureResult")
8982
{
9083
_isCallbackInvoked = true;
9184
_taskCompletionSource.SetResult(new BrowserResult(BrowserStatus.UnknownError, null, data["error"].ToString()));
Lines changed: 41 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,12 @@
11
mergeInto(LibraryManager.library, {
2-
openPopup: function (
3-
urlPtr,
4-
developerClientIdPtr,
5-
authOptionPtr,
6-
unityObjectNamePtr,
7-
unityCallbackMethodPtr
8-
) {
2+
openPopup: function (urlPtr, unityObjectNamePtr, unityCallbackMethodPtr) {
93
var initialUrl = UTF8ToString(urlPtr);
10-
var developerClientId = UTF8ToString(developerClientIdPtr);
11-
var authOption = UTF8ToString(authOptionPtr);
124
var unityObjectName = UTF8ToString(unityObjectNamePtr);
135
var unityCallbackMethod = UTF8ToString(unityCallbackMethodPtr);
146

157
// Calculate dimensions and position for the popup
16-
var width = 350;
17-
var height = 500;
8+
var width = 600;
9+
var height = 750;
1810
var top = (window.innerHeight - height) / 2;
1911
var left = (window.innerWidth - width) / 2;
2012

@@ -35,49 +27,52 @@ mergeInto(LibraryManager.library, {
3527
SendMessage(unityObjectName, unityCallbackMethod, message);
3628
}
3729

38-
// Listen for messages from the popup
39-
window.addEventListener("message", function (event) {
40-
var data = event.data;
41-
42-
// console.log("Received message from popup: ", data);
43-
44-
switch (data.eventType) {
45-
case "injectDeveloperClientId":
46-
// send message back with developer client id
47-
popupWindow.postMessage({
48-
eventType: "injectDeveloperClientIdResult",
49-
developerClientId: developerClientId,
50-
authOption: authOption,
51-
}, "*");
52-
break;
53-
case "userLoginSuccess":
54-
clearInterval(pollTimer);
55-
sendMessageToUnity(JSON.stringify(data));
56-
popupWindow.close();
57-
break;
58-
case "userLoginFailed":
59-
clearInterval(pollTimer);
60-
sendMessageToUnity(JSON.stringify(data));
61-
popupWindow.close();
62-
break;
63-
default:
64-
break;
65-
}
66-
});
67-
68-
// Poll to check if the popup is closed
69-
var pollTimer = setInterval(function () {
30+
// Detect when the popup is closed
31+
var pollTimer = window.setInterval(function () {
7032
if (popupWindow.closed) {
7133
clearInterval(pollTimer);
72-
sendMessageToUnity("PopupClosedWithoutAction");
34+
window.removeEventListener("message", messageListener);
35+
sendMessageToUnity(
36+
JSON.stringify({
37+
eventType: "PopupClosedWithoutAction",
38+
})
39+
);
7340
}
74-
}, 500);
41+
}, 1000);
42+
43+
// Listen for messages from the popup window
44+
function messageListener(event) {
45+
// Ensure the message is from the expected origin
46+
if (event.origin !== new URL(initialUrl).origin) {
47+
return;
48+
}
49+
50+
// Ensure the event data is an object
51+
if (typeof event.data !== "object") {
52+
return;
53+
}
54+
55+
switch (event.data.eventType) {
56+
case "oauthSuccessResult":
57+
case "oauthFailureResult":
58+
window.removeEventListener("message", messageListener);
59+
clearInterval(pollTimer);
60+
popupWindow.close();
61+
sendMessageToUnity(JSON.stringify(event.data));
62+
break;
63+
default:
64+
// no-op, do not throw here
65+
break;
66+
}
67+
}
68+
69+
window.addEventListener("message", messageListener);
7570

7671
// Close the popup when the main window is closed or refreshed
7772
window.addEventListener("beforeunload", function () {
7873
if (popupWindow) {
7974
popupWindow.close();
8075
}
8176
});
82-
}
77+
},
8378
});

0 commit comments

Comments
 (0)