1+ namespace Microsoft . eShopOnContainers . WebMVC . Services
2+ {
3+ using global ::WebMVC . Infrastructure ;
4+ using Microsoft . AspNetCore . Authentication ;
5+ using Microsoft . AspNetCore . Http ;
6+ using Microsoft . eShopOnContainers . BuildingBlocks . Resilience . Http ;
7+ using Microsoft . eShopOnContainers . WebMVC . Models ;
8+ using Microsoft . Extensions . Logging ;
9+ using Microsoft . Extensions . Options ;
10+ using Newtonsoft . Json ;
11+ using System ;
12+ using System . Collections . Generic ;
13+ using System . Threading . Tasks ;
14+
15+ public class CampaignService : ICampaignService
16+ {
17+ private readonly IOptionsSnapshot < AppSettings > _settings ;
18+ private readonly IHttpClient _apiClient ;
19+ private readonly ILogger < CampaignService > _logger ;
20+ private readonly string _remoteServiceBaseUrl ;
21+ private readonly IHttpContextAccessor _httpContextAccesor ;
22+
23+ public CampaignService ( IOptionsSnapshot < AppSettings > settings , IHttpClient httpClient ,
24+ ILogger < CampaignService > logger , IHttpContextAccessor httpContextAccesor )
25+ {
26+ _settings = settings ;
27+ _apiClient = httpClient ;
28+ _logger = logger ;
29+
30+ _remoteServiceBaseUrl = $ "{ _settings . Value . MarketingUrl } /api/v1/campaigns/";
31+ _httpContextAccesor = httpContextAccesor ?? throw new ArgumentNullException ( nameof ( httpContextAccesor ) ) ;
32+ }
33+
34+ public async Task < List < CampaignDTO > > GetCampaigns ( )
35+ {
36+ var userId = GetUserIdentity ( ) ;
37+ var allCampaignItemsUri = API . Marketing . GetAllCampaigns ( _remoteServiceBaseUrl , userId ) ;
38+
39+ var authorizationToken = await GetUserTokenAsync ( ) ;
40+ var dataString = await _apiClient . GetStringAsync ( allCampaignItemsUri , authorizationToken ) ;
41+
42+ var response = JsonConvert . DeserializeObject < List < CampaignDTO > > ( dataString ) ;
43+
44+ return response ;
45+ }
46+
47+ private string GetUserIdentity ( )
48+ {
49+ return _httpContextAccesor . HttpContext . User . FindFirst ( "sub" ) . Value ;
50+ }
51+
52+ private async Task < string > GetUserTokenAsync ( )
53+ {
54+ var context = _httpContextAccesor . HttpContext ;
55+ return await context . Authentication . GetTokenAsync ( "access_token" ) ;
56+ }
57+ }
58+ }
0 commit comments