-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAuthManager.cs
More file actions
199 lines (174 loc) · 6.29 KB
/
AuthManager.cs
File metadata and controls
199 lines (174 loc) · 6.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
using UnityEngine;
using UnityEngine.UI;
using Firebase;
using Firebase.Auth;
using Firebase.Firestore;
using System.Threading.Tasks;
using TMPro;
using Firebase.Storage;
using System.IO;
using UnityEngine.Networking;
using System.Collections;
using Firebase.Extensions;
public class AuthManager : MonoBehaviour
{
private FirebaseAuth auth;
private FirebaseFirestore db;
private FirebaseStorage storage;
private StorageReference storageRef;
public Image avatarImage;
public Button selectAvatarButton, uploadAvatarButton;
private string localAvatarPath;
public InputField emailInput, passwordInput;
public TMP_Text profileEmailText, profileNameText;
public TMP_Text statusText;
public GameObject loginPanel;
public TMP_InputField updateNameInput;
private void Awake()
{
auth = FirebaseAuth.DefaultInstance;
db = FirebaseFirestore.DefaultInstance;
storage = FirebaseStorage.DefaultInstance;
storageRef = storage.GetReferenceFromUrl("gs://your-firebase-project.appspot.com");
}
public async void RegisterUser()
{
string email = emailInput.text;
string password = passwordInput.text;
try
{
FirebaseUser newUser = (await auth.CreateUserWithEmailAndPasswordAsync(email, password)).User;
statusText.text = "Registration Successful!";
await StoreUserData(newUser.UserId, email);
}
catch (System.Exception e)
{
statusText.text = "Registration Failed: " + e.Message;
}
}
public async void LoginUser()
{
string email = emailInput.text;
string password = passwordInput.text;
if (string.IsNullOrEmpty(email) || string.IsNullOrEmpty(password))
{
statusText.text = "Please enter email and password!";
return;
}
try
{
FirebaseUser loggedInUser = (await auth.SignInWithEmailAndPasswordAsync(email, password)).User;
statusText.text = "Login Successful!";
await RetrieveUserData(loggedInUser.UserId);
}
catch (System.Exception e)
{
statusText.text = "Login Failed: " + e.Message;
}
}
public void LogoutUser()
{
auth.SignOut();
statusText.text = "Logged out.";
Invoke(nameof(UpdateLogoutUI), 0);
}
private void UpdateLogoutUI()
{
profileEmailText.text = "Email: Loading...";
profileNameText.text = "Name: Loading...";
avatarImage.sprite = null;
loginPanel.SetActive(true);
statusText.text = "Please log in.";
}
private async Task StoreUserData(string userId, string email)
{
DocumentReference docRef = db.Collection("users").Document(userId);
var user = new { email = email, displayName = "Guest", avatarUrl = "" };
await docRef.SetAsync(user);
}
private async Task RetrieveUserData(string userId)
{
DocumentReference docRef = db.Collection("users").Document(userId);
try
{
DocumentSnapshot snapshot = await docRef.GetSnapshotAsync();
if (snapshot.Exists)
{
string email = snapshot.GetValue<string>("email");
string displayName = snapshot.GetValue<string>("displayName");
string avatarUrl = snapshot.ContainsField("avatarUrl") ? snapshot.GetValue<string>("avatarUrl") : "";
profileEmailText.text = "Email: " + email;
profileNameText.text = "Name: " + displayName;
if (!string.IsNullOrEmpty(avatarUrl))
{
StartCoroutine(LoadAvatar(avatarUrl));
}
loginPanel.SetActive(false);
}
else
{
Debug.LogWarning("No user data found!");
}
}
catch (System.Exception e)
{
Debug.LogError("Error retrieving user data: " + e.Message);
}
}
public void UploadAvatar(string filePath)
{
if (string.IsNullOrEmpty(filePath))
{
Debug.LogError("No image selected for upload.");
return;
}
FirebaseUser user = FirebaseAuth.DefaultInstance.CurrentUser;
if (user == null)
{
Debug.LogError("User not logged in.");
return;
}
string fileName = user.UserId + "_avatar.png";
StorageReference avatarRef = storageRef.Child("avatars/" + fileName);
byte[] fileBytes = File.ReadAllBytes(filePath);
avatarRef.PutBytesAsync(fileBytes).ContinueWithOnMainThread(task =>
{
if (task.IsFaulted || task.IsCanceled)
{
Debug.LogError("Upload failed: " + task.Exception);
}
else
{
avatarRef.GetDownloadUrlAsync().ContinueWithOnMainThread(urlTask =>
{
if (urlTask.IsCompleted)
{
string downloadUrl = urlTask.Result.ToString();
Debug.Log("Avatar uploaded successfully: " + downloadUrl);
SaveAvatarUrlToFirestore(user.UserId, downloadUrl);
}
});
}
});
}
private async void SaveAvatarUrlToFirestore(string userId, string url)
{
DocumentReference docRef = db.Collection("users").Document(userId);
await docRef.UpdateAsync("avatarUrl", url);
Debug.Log("Avatar URL updated in Firestore.");
}
private IEnumerator LoadAvatar(string url)
{
UnityWebRequest request = UnityWebRequestTexture.GetTexture(url);
yield return request.SendWebRequest();
if (request.result == UnityWebRequest.Result.Success)
{
Texture2D texture = DownloadHandlerTexture.GetContent(request);
avatarImage.sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
}
else
{
Debug.LogError("Error loading avatar: " + request.error);
}
}
}