Login.cs 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.Networking;
  5. using UnityEngine.UI;
  6. using UnityEngine.EventSystems;
  7. using UnityEngine.SceneManagement;
  8. using System;
  9. using System.Security.Cryptography;
  10. using System.Text;
  11. using UnityEngine.Events;
  12. public class Login : MonoBehaviour {
  13. public GameObject username;
  14. public GameObject password;
  15. public Button loginButton;
  16. public Button SwedishButton;
  17. public Button EnglishButton;
  18. public Toggle keepSignedIn;
  19. public Text errorText;
  20. private string Username;
  21. private string Password;
  22. private string loginUrl = "http://nordh.xyz/narKampen/dbFiles/Login.php?";
  23. private Color errorColor;
  24. private EventSystem system;
  25. private Firebase.Auth.FirebaseAuth auth;
  26. [Serializable]
  27. public class User {
  28. public string userId;
  29. public string pass;
  30. public string salt;
  31. }
  32. private void CheckFirebaseGoogleDependencies() {
  33. Firebase.FirebaseApp.CheckAndFixDependenciesAsync().ContinueWith(task => {
  34. var dependencyStatus = task.Result;
  35. if (dependencyStatus == Firebase.DependencyStatus.Available) {
  36. // Create and hold a reference to your FirebaseApp,
  37. // where app is a Firebase.FirebaseApp property of your application class.
  38. // app = Firebase.FirebaseApp.DefaultInstance;
  39. // Set a flag here to indicate whether Firebase is ready to use by your app.
  40. } else {
  41. UnityEngine.Debug.LogError(System.String.Format(
  42. "Could not resolve all Firebase dependencies: {0}", dependencyStatus));
  43. // Firebase Unity SDK is not safe to use here.
  44. }
  45. });
  46. }
  47. private void Start() {
  48. // CheckFirebaseGoogleDependencies();
  49. if (Database.Instance.IsKeepSignedIn()) {
  50. SceneManager.LoadScene("MainMenu");
  51. }
  52. loginButton.onClick.AddListener(loginAction);
  53. errorColor = errorText.color;
  54. system = EventSystem.current;
  55. SwedishButton.onClick.AddListener(() => SwitchLanguage(0));
  56. EnglishButton.onClick.AddListener(() => SwitchLanguage(1));
  57. auth = Firebase.Auth.FirebaseAuth.DefaultInstance;
  58. }
  59. private void SwitchLanguage(int langId) {
  60. LocalizationManager.Instance.currentLanguageID = langId;
  61. TextLocalization[] texts = FindObjectsOfType(typeof(TextLocalization)) as TextLocalization[];
  62. foreach (TextLocalization tl in texts) {
  63. tl.UpdateText();
  64. }
  65. InputFieldLocalization[] inputFields = FindObjectsOfType(typeof(InputFieldLocalization)) as InputFieldLocalization[];
  66. foreach (InputFieldLocalization ifl in inputFields) {
  67. ifl.UpdateText();
  68. }
  69. ButtonLocalization[] buttonLocale = FindObjectsOfType(typeof(ButtonLocalization)) as ButtonLocalization[];
  70. foreach (ButtonLocalization bl in buttonLocale) {
  71. bl.UpdateText();
  72. }
  73. }
  74. private void Update() {
  75. Username = username.GetComponent<InputField>().text;
  76. Password = password.GetComponent<InputField>().text;
  77. if (Input.GetKeyDown(KeyCode.Tab)) {
  78. Selectable next = system.currentSelectedGameObject.GetComponent<Selectable>().FindSelectableOnDown();
  79. if (next != null) {
  80. InputField inputfield = next.GetComponent<InputField>();
  81. if (inputfield != null) inputfield.OnPointerClick(new PointerEventData(system));
  82. system.SetSelectedGameObject(next.gameObject, new BaseEventData(system));
  83. }
  84. }
  85. }
  86. void loginAction() {
  87. string errorMessage = "";
  88. if (Username == "") {
  89. errorMessage = LocalizationManager.Instance.GetText("REGISTER_ERROR_USERNAME_EMPTY");
  90. }
  91. if (Password == "") {
  92. if (errorMessage != "") {
  93. errorMessage += "\n";
  94. }
  95. errorMessage += LocalizationManager.Instance.GetText("REGISTER_ERROR_PASSWORD_EMPTY");
  96. }
  97. if (errorMessage == "") {
  98. errorColor.a = 0;
  99. firebaseLogin(Username, Password);
  100. StartCoroutine(loginCall());
  101. } else {
  102. errorText.text = errorMessage;
  103. errorColor.a = 1;
  104. }
  105. errorText.color = errorColor;
  106. }
  107. private void firebaseLogin(string email, string password) {
  108. auth.SignInWithEmailAndPasswordAsync(email, password).ContinueWith(task => {
  109. if (task.IsCanceled) {
  110. Debug.LogError("SignInWithEmailAndPasswordAsync was canceled.");
  111. return;
  112. }
  113. if (task.IsFaulted) {
  114. Debug.LogError("SignInWithEmailAndPasswordAsync encountered an error: " + task.Exception);
  115. return;
  116. }
  117. Firebase.Auth.FirebaseUser newUser = task.Result;
  118. Debug.LogFormat("User signed in successfully: {0} ({1})",
  119. newUser.DisplayName, newUser.UserId);
  120. });
  121. }
  122. IEnumerator loginCall() {
  123. string postUrl = loginUrl + "name=" + UnityWebRequest.EscapeURL(Username);
  124. UnityWebRequest www = UnityWebRequest.Get(postUrl);
  125. yield return www.SendWebRequest();
  126. if (www.error != null) {
  127. errorText.text = "There was an error logging in " + www.error;
  128. }
  129. string result = www.downloadHandler.text;
  130. User u = new User();
  131. if (!result.Equals("")) {
  132. JsonUtility.FromJsonOverwrite(result, u);
  133. }
  134. if (!u.userId.Equals("")) {
  135. byte[] pwd = Encoding.UTF8.GetBytes(u.salt + Password);
  136. SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();
  137. string pass = Convert.ToBase64String(sha1.ComputeHash(pwd));
  138. if (pass.Equals(u.pass)) {
  139. errorColor.a = 0;
  140. errorText.color = errorColor;
  141. Int32.TryParse(u.userId, out int userId);
  142. Database.Instance.KeepSignedIn(Username, userId, keepSignedIn.isOn);
  143. SceneManager.LoadScene("MainMenu");
  144. } else {
  145. errorText.text = LocalizationManager.Instance.GetText("LOGIN_WRONG_USERNAME_PASSWORD");
  146. errorColor.a = 1;
  147. errorText.color = errorColor;
  148. }
  149. } else {
  150. errorText.text = LocalizationManager.Instance.GetText("LOGIN_USER_NOT_FOUND");
  151. errorColor.a = 1;
  152. errorText.color = errorColor;
  153. }
  154. }
  155. }