using Newtonsoft.Json.Linq;
using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
namespace Citi.QSDB.WebApi.Client
{
public class QSDBAPIAgent
{
private readonly string userName;
private readonly string password;
private readonly string baseUrl;
private string tokenString;
private string tokenExpiry;
static QSDBAPIAgent()
{
// for ignoring DEV/UAT server cert alert, not required in PROD
var trustAllCerts = new X509Certificate2Collection();
ServicePointManager.ServerCertificateValidationCallback = (sender, cert, chain, sslPolicyErrors) => true;
}
public QSDBAPIAgent(string baseUrl, string userName, string password)
{
if (string.IsNullOrEmpty(userName))
throw new ArgumentException("userName is null");
if (string.IsNullOrEmpty(password))
throw new ArgumentException("password is null");
this.userName = userName;
this.password = password;
this.baseUrl = baseUrl;
}
public async Task<string> LoadData(string requestUrl)
{
if (!IsTokenExpiryValid())
await ApplyNewToken();
using (var client = new HttpClient())
{
var requestUri = new Uri(baseUrl + requestUrl);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenString);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await client.GetAsync(requestUri);
if (!response.IsSuccessStatusCode)
throw new Exception("Load data failed with url " + baseUrl + requestUrl);
return await response.Content.ReadAsStringAsync();
}
}
public bool IsTokenExpiryValid()
{
if (string.IsNullOrEmpty(tokenString))
return false;
var instant = Instant.Parse(tokenExpiry);
var compareResult = instant.Minus(Duration.OfMinutes(30)).CompareTo(Instant.Now);
return compareResult < 0;
}
private async Task ApplyNewToken()
{
using (var client = new HttpClient())
{
var requestUri = new Uri(baseUrl + "/qsdb/api/rest/auth/v1/token");
var requestBody = "{\"Username\":\"" + userName + "\",\"Password\":\"" + password + "\"}";
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await client.PostAsync(requestUri, new StringContent(requestBody, Encoding.UTF8, "application/json"));
if (!response.IsSuccessStatusCode)
throw new AuthenticationException("Authenticate failed");
var responseString = await response.Content.ReadAsStringAsync();
var jsonObject = JObject.Parse(responseString);
tokenString = jsonObject.GetValue("TokenString").ToString();
tokenExpiry = jsonObject.GetValue("TokenExpiry").ToString();
if (string.IsNullOrEmpty(tokenString) || string.IsNullOrEmpty(tokenExpiry))
throw new AuthenticationException("Authenticate failed");
}
}
public class AuthenticationException : Exception
{
public AuthenticationException() { }
public AuthenticationException(string message) : base(message) { }
public AuthenticationException(string message, Exception innerException) : base(message, innerException) { }
}
}
}