-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFireBaseDB.cs
More file actions
executable file
·547 lines (485 loc) · 20.1 KB
/
Copy pathFireBaseDB.cs
File metadata and controls
executable file
·547 lines (485 loc) · 20.1 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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
using SharpFireStarter.Activity;
using SharpFireStarter.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace SharpFireStarter
{
public class FireBaseDB
{
//Stored Variables
public string databaseURL { get; set; }
public string webAPIKey { get; set; }
public string oAuthToken { get; set; }
public string refreshToken { get; set; }
public User currentUser { get; set; }
public FireBaseDB()
{
}
/// <summary>
/// Initialize FirebaseConnector with AppID and WebAPI Key (Found on your Firebase Console Online)
/// </summary>
/// <param name="appID"></param>
public FireBaseDB(string appID, string databaseURL, string webAPIKey)
{
if (!Uri.IsWellFormedUriString(appID, UriKind.RelativeOrAbsolute))
throw new UriFormatException("The given AppID URL Structure is not valid");
this.databaseURL = databaseURL;
this.webAPIKey = webAPIKey;
Logger.Log("Initialized with AppID " + appID);
}
/// <summary>
/// Authenticate user and Obtain oAuth Token
/// </summary>
/// <param name="email"></param>
/// <param name="password"></param>
/// <returns></returns>
public User Authenticate(string email, string password)
{
//Validate Request
if (email == string.Empty)
{
Logger.Log("Email for Auth not provided.");
return null;
}
else if (password == string.Empty)
{
Logger.Log("Password for Auth not provided.");
return null;
}
else if (webAPIKey == string.Empty)
{
Logger.Log("WebAPI Key for Auth not provided.");
return null;
}
User user = Activity.Auth.Authenticate(email.Trim(), password.Trim(), webAPIKey);
if (user != null)
{
currentUser = user;
oAuthToken = user.idToken;
Logger.Log("oAuth Token Received: " + oAuthToken);
return user;
}
else
{
Logger.Log("Failed to Authenticate. Check your Username and Password.");
return null;
}
}
public User AuthenticateOAuth(string OAuthCode)
{
//Validate Request
if (OAuthCode == null)
{
Logger.Log("OAuth Token for Auth not provided.");
return null;
}
User user = Activity.Auth.AuthenticateOAuth(OAuthCode, webAPIKey);
if (user != null)
{
currentUser = user;
oAuthToken = user.idToken;
Logger.Log("oAuth Token Received: " + oAuthToken);
return user;
}
else
{
Logger.Log("Failed to Authenticate. Check your Username and Password.");
return null;
}
}
public void SetoAuthToken(string token)
{
this.oAuthToken = token;
}
/// <summary>
/// Update the user's display name in Firebase Auth
/// </summary>
/// <param name="idToken">The user's current ID token</param>
/// <param name="displayName">The new display name to set</param>
/// <returns>True if successful, false otherwise</returns>
public bool UpdateDisplayName(string idToken, string displayName)
{
return Activity.Auth.UpdateDisplayName(idToken, displayName, webAPIKey);
}
/// <summary>
/// Update the user's display name in Firebase Auth (async version)
/// </summary>
/// <param name="idToken">The user's current ID token</param>
/// <param name="displayName">The new display name to set</param>
/// <returns>True if successful, false otherwise</returns>
public async Task<bool> UpdateDisplayNameAsync(string idToken, string displayName)
{
return await Activity.Auth.UpdateDisplayNameAsync(idToken, displayName, webAPIKey);
}
public User ChangePassword(string email, string oldpassword, string newpassword)
{
//Validate Request
if (email == string.Empty)
{
Logger.Log("Email for Auth not provided.");
return null;
}
else if (oldpassword == string.Empty)
{
Logger.Log("Old Password for Auth not provided.");
return null;
}
else if (newpassword == string.Empty)
{
Logger.Log("New Password for Auth not provided.");
return null;
}
User user = Activity.Auth.Authenticate(email.Trim(), oldpassword.Trim(), webAPIKey);
if (user != null)
{
User userChangedPassword = Activity.Auth.ChangePassword(ref user, email.Trim(), oldpassword.Trim(), newpassword.Trim(), webAPIKey);
Logger.Log("Password has been changed");
return user;
}
else
{
Logger.Log("Failed to Authenticate. Check your old Username and Password.");
return null;
}
}
public bool ChangePasswordWithOOBCode(string resetCode, string newPassword)
{
//Validate Request
if (resetCode == string.Empty)
{
Logger.Log("Reset code was not proved.");
return false;
}
if (newPassword == string.Empty)
{
Logger.Log("New password was not proved.");
return false;
}
string passwordResetWithCode = Activity.Auth.ChangePasswordWithOOBCode(resetCode, newPassword, webAPIKey);
if (passwordResetWithCode != null && passwordResetWithCode != "expired")
{
Logger.Log("Password was successfully changed");
return true;
}
else
{
Logger.Log("Password reset code was invalid or expired");
return false;
}
}
public bool SendPasswordResetEmail(string email)
{
//Validate Request
if (email == string.Empty)
{
Logger.Log("Email for Auth not provided.");
return false;
}
bool sendResetEamil = Activity.Auth.ResetPassword(email.Trim(), webAPIKey);
if (sendResetEamil == true)
{
Logger.Log("Password reset email has been sent");
return sendResetEamil;
}
else
{
Logger.Log("Failed to Send Email Reset Password. Check your email address.");
return sendResetEamil;
}
}
public string VerifyPasswordResetCode(string resetCode)
{
//Validate Request
if (resetCode == string.Empty)
{
Logger.Log("Reset code was not proved.");
return null;
}
string passwordResetCodeEmail = Activity.Auth.VerifyPasswordResetCode(resetCode, webAPIKey);
if (passwordResetCodeEmail != null && passwordResetCodeEmail != "expired")
{
Logger.Log("Password reset code was valid");
return passwordResetCodeEmail;
}
else
{
Logger.Log("Password reset code was invalid or expired");
return "expired";
}
}
public bool SendPasswordResetEmail(string email, string newPassword)
{
//Validate Request
if (email == string.Empty)
{
Logger.Log("Email for Auth not provided.");
return false;
}
bool sendResetEamil = Activity.Auth.ResetPassword(email.Trim(), webAPIKey);
if (sendResetEamil == true)
{
Logger.Log("Password reset email has been sent");
return sendResetEamil;
}
else
{
Logger.Log("Failed to Send Email Reset Password. Check your email address.");
return sendResetEamil;
}
}
/// <summary>
/// Sign up new user
/// </summary>
/// <param name="name"></param>
/// <param name="email"></param>
/// <param name="password"></param>
/// <returns></returns>
public User SignUp(string name, string email, string password)
{
var newUser = Auth.SignUp(name.Trim(), email.Trim(), password.Trim(), webAPIKey);
if (newUser != null)
{
currentUser = newUser;
oAuthToken = newUser.idToken;
return newUser;
}
else
return null;
}
/// <summary>
/// Sign Out Logged In Account
/// </summary>
/// <returns></returns>
public bool SignOut()
{
if(currentUser != null)
{
Auth.SignOut(currentUser, webAPIKey);
return true;
}
return false;
}
/// <summary>
/// Write to the Firebase DB
/// </summary>
/// <param name="data"></param>
public bool WriteToDB(string node, object data, bool runAuthenticated = true)
{
try
{
Activity.Set.WriteToDB(databaseURL, node, oAuthToken, data, runAuthenticated, true);
return true;
}
catch(Exception ex)
{
// Check if it's a token expiration error and retry with refresh
if (IsTokenExpiredError(ex) && !string.IsNullOrEmpty(refreshToken) && !string.IsNullOrEmpty(webAPIKey))
{
Logger.Log("Token expired during write, attempting refresh and retry...");
if (RefreshTokenInternal())
{
try
{
Logger.Log("Retrying write with refreshed token...");
Activity.Set.WriteToDB(databaseURL, node, oAuthToken, data, runAuthenticated, true);
return true;
}
catch (Exception retryEx)
{
Console.WriteLine("Write to DB retry after token refresh failed: " + retryEx.Message);
return false;
}
}
}
Console.WriteLine("Write to DB Failed: " + ex.Message);
return false;
}
}
public bool WriteToDB(string node, object data, bool runAuthenticated, bool silent = true)
{
try
{
Activity.Set.WriteToDB(databaseURL, node, oAuthToken, data, runAuthenticated, silent);
return true;
}
catch (Exception ex)
{
// Check if it's a token expiration error and retry with refresh
if (IsTokenExpiredError(ex) && !string.IsNullOrEmpty(refreshToken) && !string.IsNullOrEmpty(webAPIKey))
{
Logger.Log("Token expired during write, attempting refresh and retry...");
if (RefreshTokenInternal())
{
try
{
Logger.Log("Retrying write with refreshed token...");
Activity.Set.WriteToDB(databaseURL, node, oAuthToken, data, runAuthenticated, silent);
return true;
}
catch (Exception retryEx)
{
Console.WriteLine("Write to DB retry after token refresh failed: " + retryEx.Message);
return false;
}
}
}
Console.WriteLine("Write to DB Failed: " + ex.Message);
return false;
}
}
/// <summary>
/// Set (replace) a node in Firebase DB - uses PUT instead of PATCH
/// Use this when you want to completely replace a node rather than merge
/// </summary>
public bool SetToDB(string node, object data, bool runAuthenticated = true)
{
try
{
Activity.Set.SetToDB(databaseURL, node, oAuthToken, data, runAuthenticated, true);
return true;
}
catch (Exception ex)
{
// Check if it's a token expiration error and retry with refresh
if (IsTokenExpiredError(ex) && !string.IsNullOrEmpty(refreshToken) && !string.IsNullOrEmpty(webAPIKey))
{
Logger.Log("Token expired during set, attempting refresh and retry...");
if (RefreshTokenInternal())
{
try
{
Logger.Log("Retrying set with refreshed token...");
Activity.Set.SetToDB(databaseURL, node, oAuthToken, data, runAuthenticated, true);
return true;
}
catch (Exception retryEx)
{
Console.WriteLine("Set to DB retry after token refresh failed: " + retryEx.Message);
return false;
}
}
}
Console.WriteLine("Set to DB Failed: " + ex.Message);
return false;
}
}
//############################ GET DATA FROM DB ############################
public string GetFromDB(string data)
{
return runGetDataActivity(databaseURL, data, true, null, null, null, null, 0, 0, false);
}
public string GetFromDB(string data, bool runAuthenticated)
{
return runGetDataActivity(databaseURL, data, runAuthenticated, null, null, null, null, 0, 0, false);
}
public string GetFromDB(string data, bool runAuthenticated, bool shallow)
{
return runGetDataActivity(databaseURL, data, runAuthenticated, null, null, null, null, 0, 0, shallow);
}
public string GetFromDB(string data, bool runAuthenticated, string orderBy)
{
return runGetDataActivity(databaseURL, data, runAuthenticated, orderBy, null, null, null, 0, 0, false);
}
public string GetFromDB(string data, bool runAuthenticated, string orderBy, string startAt, string endAt = null, string equalTo = null, int limitToFirst = 0, int limitToLast = 0)
{
return runGetDataActivity(databaseURL, data, runAuthenticated, orderBy, startAt, endAt, equalTo, limitToFirst, limitToLast, false);
}
private string runGetDataActivity(string databaseURL, string data, bool runAuthenticated = true, string orderBy = null, string startAt = null, string endAt = null, string equalTo = null, int limitToFirst = 0, int limitToLast = 0, bool shallow = false)
{
try
{
string getData = Activity.Get.GetFromDB(databaseURL, data, oAuthToken, runAuthenticated, orderBy, startAt, endAt, equalTo, limitToFirst, limitToLast, shallow);
if (getData == "" || getData.ToLower() == "null")
return null;
return getData;
}
catch (Exception ex)
{
// Check if it's a token expiration error and retry with refresh
if (IsTokenExpiredError(ex) && !string.IsNullOrEmpty(refreshToken) && !string.IsNullOrEmpty(webAPIKey))
{
Logger.Log("Token expired, attempting refresh and retry...");
if (RefreshTokenInternal())
{
try
{
Logger.Log("Retrying request with refreshed token...");
string getData = Activity.Get.GetFromDB(databaseURL, data, oAuthToken, runAuthenticated, orderBy, startAt, endAt, equalTo, limitToFirst, limitToLast, shallow);
if (getData == "" || getData.ToLower() == "null")
return null;
return getData;
}
catch (Exception retryEx)
{
Logger.Log("Retry after token refresh failed: " + retryEx.Message);
return null;
}
}
}
Logger.Log(ex.Message);
return null;
}
}
/// <summary>
/// Check if the exception indicates a token expiration
/// </summary>
/// <param name="ex"></param>
/// <returns></returns>
private bool IsTokenExpiredError(Exception ex)
{
if (ex == null) return false;
string message = ex.Message.ToLower();
return message.Contains("401") ||
message.Contains("unauthorized") ||
message.Contains("token expired") ||
message.Contains("invalid token") ||
message.Contains("permission denied");
}
/// <summary>
/// Refresh the current token using the stored refresh token
/// </summary>
/// <returns></returns>
private bool RefreshTokenInternal()
{
try
{
if (string.IsNullOrEmpty(refreshToken) || string.IsNullOrEmpty(webAPIKey))
{
Logger.Log("Cannot refresh token: refresh token or webAPIKey missing");
return false;
}
// Create a temporary user object for the refresh operation
var tempUser = new User { refreshToken = this.refreshToken };
var refreshResult = Activity.Auth.RefreshAuthToken(ref tempUser, webAPIKey);
if (refreshResult != null && !string.IsNullOrEmpty(refreshResult.id_token))
{
// Update stored tokens
this.oAuthToken = refreshResult.id_token;
this.refreshToken = refreshResult.refresh_token;
// Update current user if exists
if (currentUser != null)
{
currentUser.idToken = refreshResult.id_token;
currentUser.refreshToken = refreshResult.refresh_token;
}
Logger.Log("Token refreshed successfully");
return true;
}
else
{
Logger.Log("Token refresh failed: no valid response");
return false;
}
}
catch (Exception ex)
{
Logger.Log("Token refresh failed: " + ex.Message);
return false;
}
}
}
}