SessionRetriever.cs 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. using System.Text.Json;
  2. using System;
  3. using System.Collections.Generic;
  4. namespace gameapi.Library
  5. {
  6. public class SessionRetriever
  7. {
  8. public SessionRetriever()
  9. {
  10. this.jsonFileReader = new JsonFileReader();
  11. }
  12. private JsonFileReader jsonFileReader;
  13. public dynamic GetValid(string token)
  14. {
  15. var sessionData = this.jsonFileReader.ReadGameData($"sessions/{token}.json");
  16. var dateProp = sessionData.GetProperty("validUntil").ToString();
  17. var date = DateTime.Parse(dateProp.ToString());
  18. if(DateTime.Now > date) {
  19. throw new Exception("Session expired.");
  20. }
  21. return sessionData;
  22. }
  23. private List<User> GetUsers()
  24. {
  25. JsonElement usersProp = this.jsonFileReader.ReadGameData("users.json");
  26. List<User> users = new List<User>();
  27. foreach (JsonElement userElem in usersProp.EnumerateArray())
  28. {
  29. var userToAdd = User.Parse(userElem);
  30. users.Add(userToAdd);
  31. }
  32. return users;
  33. }
  34. public User GetUserByToken(string token) {
  35. var sessionData = this.GetValid(token);
  36. List<User> users = this.GetUsers();
  37. User existingUser = users.Find(x => x.email == sessionData.GetProperty("email").ToString());
  38. if(existingUser == null) {
  39. throw new Exception("User not found.");
  40. }
  41. return existingUser;
  42. }
  43. }
  44. }