FirebaseAuthentication.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. using UnityEngine;
  2. using UnityEngine.Networking;
  3. using System;
  4. using System.Collections;
  5. using System.Linq;
  6. using System.Collections.Generic;
  7. using System.Net;
  8. using System.Text;
  9. using System.ComponentModel;
  10. using System.Runtime.Serialization;
  11. using SimpleFirebaseUnity.MiniJSON;
  12. namespace SimpleFirebaseUnity
  13. {
  14. public enum FirebaseAuthenticationType
  15. {
  16. None,
  17. Email,
  18. Facebook,
  19. Google,
  20. Github,
  21. Twitter,
  22. Anonymous
  23. }
  24. [Serializable]
  25. public class FirebaseAuthentication
  26. {
  27. #if (UNITY_ANDROID || UNITY_EDITOR)
  28. public static string requestUri = "https://antm-mobile-game-full-edit-189.firebaseapp.com/__/auth/handler";
  29. #else
  30. public static string requestUri = "https://antm-5540150.firebaseapp.com/__/auth/handler";
  31. #endif
  32. public Action<FirebaseAuthentication, DataSnapshot> OnSignInWithPasswordSuccess;
  33. public Action<FirebaseAuthentication, FirebaseError> OnSignInWithPasswordFailed;
  34. public Action<FirebaseAuthentication, DataSnapshot> OnSignUpWithPasswordSuccess;
  35. public Action<FirebaseAuthentication, FirebaseError> OnSignUpWithPasswordFailed;
  36. public Action<FirebaseAuthentication, DataSnapshot> OnSignInOrUpWithCredentialSuccess;
  37. public Action<FirebaseAuthentication, FirebaseError> OnSignInOrUpWithCredentialFailed;
  38. public Action<FirebaseAuthentication, DataSnapshot> OnSignInOrUpAnonymousSuccess;
  39. public Action<FirebaseAuthentication, FirebaseError> OnSignInOrUpAnonymousFailed;
  40. public Action<FirebaseAuthentication, DataSnapshot> OnChangeDisplayNameSuccess;
  41. public Action<FirebaseAuthentication, FirebaseError> OnChangeDisplayNameFailed;
  42. public string apikey;
  43. public static FirebaseAuthenticationType currentAuthenticationType;
  44. private static string apikeyconfigs;
  45. public FirebaseAuthentication(string apikeyconfig)
  46. {
  47. apikeyconfigs = apikeyconfig;
  48. apikey = apikeyconfigs;
  49. }
  50. public static FirebaseAuthentication CreateNew(string apikeyconfig){
  51. apikeyconfigs = apikeyconfig;
  52. if (new FirebaseAuthentication(apikeyconfig) != null) {
  53. return new FirebaseAuthentication (apikeyconfig);
  54. } else {
  55. return null;
  56. }
  57. }
  58. public void SignInWithPassword(string email, string password,bool returnsecuretoken)
  59. {
  60. try
  61. {
  62. string json = "{\n email: \""+email+"\",\n password: \""+password+"\",\n returnSecureToken:"+ returnsecuretoken.ToString().ToLower()+"\n}";
  63. string url = "https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyPassword?key=" + apikeyconfigs;
  64. Dictionary<string,string> headers = new Dictionary<string,string>();
  65. headers.Add("Content-Type","application/json");
  66. byte [] bytes = Encoding.ASCII.GetBytes(json);
  67. StartCoroutine(RequestCoroutine(url, bytes, headers, OnSignInWithPasswordSuccess, OnSignInWithPasswordFailed));
  68. }
  69. catch (WebException webEx)
  70. {
  71. if (OnSignInWithPasswordFailed != null) OnSignInWithPasswordFailed(this, FirebaseError.Create(webEx));
  72. }
  73. catch (Exception ex)
  74. {
  75. if (OnSignInWithPasswordFailed != null) OnSignInWithPasswordFailed(this, new FirebaseError(ex.Message));
  76. }
  77. }
  78. public void SignUpWithPassword(string email, string password,bool returnsecuretoken)
  79. {
  80. try
  81. {
  82. string json = "{\n email: \""+email+"\",\n password: \""+password+"\",\n returnSecureToken:"+ returnsecuretoken.ToString().ToLower()+"\n}";
  83. string url = "https://www.googleapis.com/identitytoolkit/v3/relyingparty/signupNewUser?key=" + apikeyconfigs;
  84. Dictionary<string,string> headers = new Dictionary<string,string>();
  85. headers.Add("Content-Type","application/json");
  86. byte [] bytes = Encoding.ASCII.GetBytes(json);
  87. StartCoroutine(RequestCoroutine(url, bytes, headers, OnSignUpWithPasswordSuccess, OnSignUpWithPasswordFailed));
  88. }
  89. catch (WebException webEx)
  90. {
  91. if (OnSignUpWithPasswordFailed != null) OnSignUpWithPasswordFailed(this, FirebaseError.Create(webEx));
  92. }
  93. catch (Exception ex)
  94. {
  95. if (OnSignUpWithPasswordFailed != null) OnSignUpWithPasswordFailed(this, new FirebaseError(ex.Message));
  96. }
  97. }
  98. public void SignInOrUpAnonymous()
  99. {
  100. try
  101. {
  102. string url = "https://www.googleapis.com/identitytoolkit/v3/relyingparty/signupNewUser?key=" + apikeyconfigs;
  103. Dictionary<string, string> headers = new Dictionary<string, string>();
  104. headers.Add("Content-Type", "application/json");
  105. byte[] bytes = Encoding.ASCII.GetBytes("{}");
  106. StartCoroutine(RequestCoroutine(url, bytes, headers, OnSignInOrUpAnonymousSuccess, OnSignInOrUpAnonymousFailed));
  107. }
  108. catch (WebException webEx)
  109. {
  110. if (OnSignInOrUpAnonymousFailed != null) OnSignInOrUpAnonymousFailed(this, FirebaseError.Create(webEx));
  111. }
  112. catch (Exception ex)
  113. {
  114. if (OnSignInOrUpAnonymousFailed != null) OnSignInOrUpAnonymousFailed(this, new FirebaseError(ex.Message));
  115. }
  116. }
  117. public void SignInOrUpWithCredential(string accestoken, FirebaseAuthenticationType authenticationtype, string requestUri, bool returnIdpCredential, bool returnSecureToken, string apikey = null)
  118. {
  119. try
  120. {
  121. string json = "null";
  122. string url = "null";
  123. currentAuthenticationType = authenticationtype;
  124. if (currentAuthenticationType == FirebaseAuthenticationType.Facebook)
  125. {
  126. json = "{\"postBody\": \"access_token=" + accestoken + "&providerId=facebook.com" + "\",\"requestUri\": \"" + requestUri + "\",\n \" returnIdpCredential\":" + returnIdpCredential.ToString().ToLower() + ",\n \"returnSecureToken\": " + returnSecureToken.ToString().ToLower() + "}";
  127. }
  128. if (currentAuthenticationType == FirebaseAuthenticationType.Google)
  129. {
  130. json = "{\"postBody\": \"id_token=" + accestoken + "&providerId=google.com" + "\",\"requestUri\": \"" + requestUri + "\",\n \" returnIdpCredential\":" + returnIdpCredential.ToString().ToLower() + ",\n \"returnSecureToken\": " + returnSecureToken.ToString().ToLower() + "}";
  131. Debug.Log(json);
  132. }
  133. if (apikey != null)
  134. {
  135. url = "https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyAssertion?key=" + apikey;
  136. Debug.Log("url with apikey: " + url);
  137. }
  138. else
  139. {
  140. url = "https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyAssertion?key=" + apikeyconfigs;
  141. Debug.Log("url with apikeyconfigs: " + url);
  142. }
  143. Dictionary<string,string> headers = new Dictionary<string,string>();
  144. headers.Add("Content-Type","application/json");
  145. byte [] bytes = Encoding.ASCII.GetBytes(json);
  146. StartCoroutine(RequestCoroutine(url, bytes, headers, OnSignInOrUpWithCredentialSuccess, OnSignInOrUpWithCredentialFailed));
  147. }
  148. catch (WebException webEx)
  149. {
  150. if (OnSignInOrUpWithCredentialFailed != null) OnSignInOrUpWithCredentialFailed(this, FirebaseError.Create(webEx));
  151. }
  152. catch (Exception ex)
  153. {
  154. if (OnSignInOrUpWithCredentialFailed != null) OnSignInOrUpWithCredentialFailed(this, new FirebaseError(ex.Message));
  155. }
  156. }
  157. public void ChangeDisplayName(string displayname)
  158. {
  159. try
  160. {
  161. string json = "null";
  162. string url = "https://www.googleapis.com/identitytoolkit/v3/relyingparty/setAccountInfo?key=" + apikeyconfigs;
  163. Dictionary<string, string> headers = new Dictionary<string, string>();
  164. headers.Add("Content-Type", "application/json");
  165. json = "{\"idToken\":\"" + "DataTools.DataUser.Instance.ProfileData.IdToken" + "\",\"displayName\":\"" + displayname + "\",\"photoUrl\":\"\",\"returnSecureToken\":true}";
  166. byte[] bytes = Encoding.ASCII.GetBytes(json);
  167. StartCoroutine(RequestCoroutine(url, bytes, headers, OnChangeDisplayNameSuccess, OnChangeDisplayNameFailed));
  168. }
  169. catch (WebException webEx)
  170. {
  171. if (OnChangeDisplayNameFailed != null) OnChangeDisplayNameFailed(this, FirebaseError.Create(webEx));
  172. }
  173. catch (Exception ex)
  174. {
  175. if (OnChangeDisplayNameFailed != null) OnChangeDisplayNameFailed(this, new FirebaseError(ex.Message));
  176. }
  177. }
  178. public void StartCoroutine(IEnumerator routine)
  179. {
  180. FirebaseManager.Instance.StartCoroutine (routine);
  181. }
  182. public void StopCoroutine(IEnumerator routine)
  183. {
  184. FirebaseManager.Instance.StopCoroutine (routine);
  185. }
  186. protected IEnumerator RequestCoroutine(string url, byte[] postData, Dictionary<string, string> headers, Action<FirebaseAuthentication, DataSnapshot> OnSuccess, Action<FirebaseAuthentication, FirebaseError> OnFailed)
  187. {
  188. using (WWW www = (headers != null) ? new WWW(url, postData, headers) : (postData != null) ? new WWW(url, postData) : new WWW(url))
  189. {
  190. // Wait until load done
  191. yield return www;
  192. if (!string.IsNullOrEmpty(www.error))
  193. {
  194. HttpStatusCode status = 0;
  195. string errMessage = "";
  196. // Parse status code
  197. if (www.responseHeaders.ContainsKey("STATUS"))
  198. {
  199. string str = www.responseHeaders["STATUS"] as string;
  200. string[] components = str.Split(' ');
  201. int code = 0;
  202. if (components.Length >= 3 && int.TryParse(components[1], out code))
  203. status = (HttpStatusCode)code;
  204. }
  205. if (www.error.Contains("crossdomain.xml") || www.error.Contains("Couldn't resolve"))
  206. {
  207. errMessage = "No internet connection or crossdomain.xml policy problem";
  208. }
  209. else {
  210. // Parse error message
  211. try
  212. {
  213. if (!string.IsNullOrEmpty(www.text))
  214. {
  215. Dictionary<string, object> obj = Json.Deserialize(www.text) as Dictionary<string, object>;
  216. if (obj != null && obj.ContainsKey("error"))
  217. errMessage = obj["error"] as string;
  218. }
  219. }
  220. catch
  221. {
  222. }
  223. }
  224. if (OnFailed != null)
  225. {
  226. if (string.IsNullOrEmpty(errMessage))
  227. errMessage = www.text;
  228. if (errMessage.Contains("Failed downloading"))
  229. {
  230. errMessage = "Request failed with no info of error.";
  231. }
  232. OnFailed(this, new FirebaseError(status, errMessage));
  233. }
  234. #if UNITY_EDITOR
  235. Debug.LogWarning(www.error + " (" + (int)status + ")\nResponse Message: " + errMessage);
  236. #endif
  237. }
  238. else
  239. {
  240. DataSnapshot snapshot = new DataSnapshot(www.text);
  241. if (OnSuccess != null) OnSuccess(this, snapshot);
  242. }
  243. }
  244. }
  245. }
  246. }