ApiTokenCore.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. using Microsoft.AspNetCore.Http;
  2. using Microsoft.AspNetCore.Mvc.Controllers;
  3. using Microsoft.AspNetCore.Mvc.Filters;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Text;
  8. using dodohold.core;
  9. using Dataoke;
  10. namespace molilian.core
  11. {
  12. public class ApiTokenDTO
  13. {
  14. public int id { get; set; }
  15. public string name { get; set; } = string.Empty;
  16. public string token { get; set; } = string.Empty;
  17. public string description { get; set; } = string.Empty;
  18. public DateTime create_time { get; set; }
  19. public DateTime last_time { get; set; }
  20. public bool status { get; set; }
  21. public int interval { get; set; }
  22. }
  23. public partial class ApiTokenCore
  24. {
  25. private static readonly object _lockObj = new();
  26. private static IEnumerable<ApiTokenDTO> _cached;
  27. public static ApiTokenDTO? GetOne(string token)
  28. {
  29. var list = List();
  30. if (!list.Any()) return null;
  31. return list.Where(e => e.token == token).FirstOrDefault();
  32. // var token = new DBContext.Table("api_token").Get<dynamic>("token=@token", new { token = tokenString });
  33. }
  34. public static IEnumerable<ApiTokenDTO> List(bool force = false)
  35. {
  36. if (!force && _cached != null) return _cached;
  37. string cache_key = $"cache:api_token";
  38. var list = RedisHelper.Get<IEnumerable<ApiTokenDTO>>(cache_key);
  39. if (force || list == null)
  40. {
  41. lock (_lockObj)
  42. {
  43. list = new DBContext.Table("api_token").Select<ApiTokenDTO>();
  44. if (list == null) return default;
  45. RedisHelper.Set(cache_key, list, 1 * 86400);
  46. }
  47. }
  48. _cached = list;
  49. return list;
  50. }
  51. public static void Refresh()
  52. {
  53. _cached = null;
  54. _ = List(true);
  55. }
  56. public static void Disabled(string name)
  57. {
  58. string cache_key = $"cache:api_token:{name}:disabled";
  59. long count = RedisHelper.IncrBy(cache_key);
  60. RedisHelper.Expire(cache_key, 10);
  61. if (count > 1) return;
  62. new DBContext.Table("api_token")
  63. .Add("status", 0)
  64. .Where("name=@name", new { name })
  65. .Update();
  66. _ = List(true);
  67. }
  68. }
  69. }