| | | 1 | | using Microsoft.AspNetCore.Identity; |
| | | 2 | | using Microsoft.Extensions.Caching.Memory; |
| | | 3 | | using OzonRepositories.Context.Identity; |
| | | 4 | | using System.Security.Claims; |
| | | 5 | | |
| | | 6 | | |
| | | 7 | | namespace Services.CacheServices.Cache.UserCacheService |
| | | 8 | | { |
| | | 9 | | public class UserCacheService : IUserCacheService |
| | | 10 | | { |
| | | 11 | | private readonly IMemoryCache _memoryCache; |
| | | 12 | | private readonly UserManager<CustomIdentityUser> _userManager; |
| | | 13 | | |
| | 0 | 14 | | public UserCacheService(IMemoryCache memoryCache, UserManager<CustomIdentityUser> userManager) |
| | | 15 | | { |
| | 0 | 16 | | _memoryCache = memoryCache; |
| | 0 | 17 | | _userManager = userManager; |
| | 0 | 18 | | } |
| | | 19 | | |
| | | 20 | | public async Task<CustomIdentityUser?> GetCachedUserAsync(ClaimsPrincipal user) |
| | | 21 | | { |
| | 0 | 22 | | var userId = _userManager.GetUserId(user); |
| | 0 | 23 | | if (string.IsNullOrEmpty(userId)) |
| | | 24 | | { |
| | 0 | 25 | | return null; |
| | | 26 | | } |
| | | 27 | | |
| | 0 | 28 | | if (!_memoryCache.TryGetValue(userId, out CustomIdentityUser? cachedUser)) |
| | | 29 | | { |
| | 0 | 30 | | cachedUser = await _userManager.GetUserAsync(user); |
| | | 31 | | |
| | 0 | 32 | | if (cachedUser != null) |
| | | 33 | | { |
| | 0 | 34 | | _memoryCache.Set(userId, cachedUser, TimeSpan.FromMinutes(10)); |
| | | 35 | | } |
| | | 36 | | } |
| | | 37 | | |
| | 0 | 38 | | return cachedUser; |
| | 0 | 39 | | } |
| | | 40 | | |
| | | 41 | | public void InvalidateUserCache(string userId) |
| | | 42 | | { |
| | 0 | 43 | | _memoryCache.Remove(userId); |
| | 0 | 44 | | } |
| | | 45 | | } |
| | | 46 | | |
| | | 47 | | } |