changes
This commit is contained in:
55
Assets/Web3Unity/Scripts/Scenes/WalletLogin.cs
Normal file
55
Assets/Web3Unity/Scripts/Scenes/WalletLogin.cs
Normal file
@@ -0,0 +1,55 @@
|
||||
using System.Text;
|
||||
using Nethereum.Signer;
|
||||
using Nethereum.Util;
|
||||
using UnityEngine;
|
||||
using UnityEngine.SceneManagement;
|
||||
using UnityEngine.UI;
|
||||
using Web3Unity.Scripts.Library.Web3Wallet;
|
||||
|
||||
public class WalletLogin : MonoBehaviour
|
||||
{
|
||||
public Toggle rememberMe;
|
||||
private void Start()
|
||||
{
|
||||
// if remember me is checked, set the account to the saved account
|
||||
if (PlayerPrefs.HasKey("RememberMe") && PlayerPrefs.HasKey("Account"))
|
||||
if (PlayerPrefs.GetInt("RememberMe") == 1 && PlayerPrefs.GetString("Account") != "")
|
||||
// move to next scene
|
||||
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
|
||||
}
|
||||
public async void OnLogin()
|
||||
{
|
||||
// get current timestamp
|
||||
var timestamp = (int)System.DateTime.UtcNow.Subtract(new System.DateTime(1970, 1, 1)).TotalSeconds;
|
||||
// set expiration time
|
||||
var expirationTime = timestamp + 60;
|
||||
// set message
|
||||
var message = expirationTime.ToString();
|
||||
// sign message
|
||||
var signature = await Web3Wallet.Sign(message);
|
||||
// verify account
|
||||
var account = SignVerifySignature(signature, message);
|
||||
var now = (int)System.DateTime.UtcNow.Subtract(new System.DateTime(1970, 1, 1)).TotalSeconds;
|
||||
// validate
|
||||
if (account.Length == 42 && expirationTime >= now)
|
||||
{
|
||||
// save account
|
||||
PlayerPrefs.SetString("Account", account);
|
||||
if (rememberMe.isOn)
|
||||
PlayerPrefs.SetInt("RememberMe", 1);
|
||||
else
|
||||
PlayerPrefs.SetInt("RememberMe", 0);
|
||||
print("Account: " + account);
|
||||
// load next scene
|
||||
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
|
||||
}
|
||||
}
|
||||
public string SignVerifySignature(string signatureString, string originalMessage)
|
||||
{
|
||||
var msg = "\x19" + "Ethereum Signed Message:\n" + originalMessage.Length + originalMessage;
|
||||
var msgHash = new Sha3Keccack().CalculateHash(Encoding.UTF8.GetBytes(msg));
|
||||
var signature = MessageSigner.ExtractEcdsaSignature(signatureString);
|
||||
var key = EthECKey.RecoverFromSignature(signature, msgHash);
|
||||
return key.GetPublicAddress();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user