MVCPostall/Postall.Infra/Services/FacebookTokenService.cs
2025-03-04 19:06:01 -03:00

50 lines
1.7 KiB
C#

using Microsoft.Extensions.Configuration;
using MongoDB.Driver;
using Postall.Domain.Dtos.Responses;
using Postall.Domain.Entities;
using Postall.Domain.Services.Contracts;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Json;
using System.Text;
using System.Threading.Tasks;
namespace Postall.Infra.Services
{
public class FacebookTokenService: IFacebookServices
{
private readonly IMongoCollection<UserSocialData> _tokens;
private readonly IConfiguration _config;
private readonly HttpClient _httpClient;
public async Task<string> GetLongLivedToken(string shortLivedToken)
{
var appId = _config["Authentication:Facebook:AppId"];
var appSecret = _config["Authentication:Facebook:AppSecret"];
var response = await _httpClient.GetFromJsonAsync<FacebookTokenResponse>(
$"https://graph.facebook.com/oauth/access_token?" +
$"grant_type=fb_exchange_token&" +
$"client_id={appId}&" +
$"client_secret={appSecret}&" +
$"fb_exchange_token={shortLivedToken}");
return response.AccessToken;
}
public async Task SaveFacebookToken(string userId, string token)
{
var update = Builders<UserSocialData>.Update
.Set(x => x.FacebookToken.AccessToken, token)
.Set(x => x.FacebookToken.ExpiresAt, DateTime.UtcNow.AddDays(60));
await _tokens.UpdateOneAsync(
x => x.UserId == userId,
update,
new UpdateOptions { IsUpsert = true }
);
}
}
}