using Microsoft.AspNetCore.Mvc;
using ServiceInside.Filter;
using ServiceShared;
using ServiceShared.Crypto;
using ServiceShared.Models.Response;
using System.Text.Json;
namespace ServiceInside.Controllers
{
[TrustedHeader]
[ServiceOutsideRequest]
public class BaseController : ControllerBase
{
///
/// Current LogType from the configuration
///
private static Log.Types _LogType = Log.Types.INFO;
///
/// Configuration from appsettings.json
///
private readonly IConfiguration _configuration = null;
///
/// Server asymetric KeyPair(PrivateKey, PublicKey)
/// It changes evrytime when the server is restarting
///
protected readonly KeyPair _KeyPair = null;
///
/// Constructor of BaseController, that getting instance of configuration and KeyPair
///
/// Configuration from appsettings.json
/// Server Curve25519 KeyPair
public BaseController(IConfiguration _configuration, KeyPair keyPair)
{
this._configuration = _configuration;
this._KeyPair = keyPair;
}
///
/// Sets the log type
///
/// Log.Types
public static void SetLog(Log.Types logType)
{
_LogType = logType;
}
///
/// Signature public key of server for the trusted response
///
/// Returns server signature public key
public string GetServerSignatureKey()
{
return this._KeyPair.SigningPublicKey;
}
///
/// Signature of server for the trusted response
/// Response text, that sould be signied by server
///
/// Returns signature of response
public string GetServerSignature(String response)
{
return this._KeyPair.GetSignature(response);
}
///
/// Client public key
///
/// Returns client public key from the header (base64)
protected string GetClientPublicKey()
{
return this.HttpContext.Request.Headers["Client-Key"].ToString();
}
///
/// Client signature of trusted request
///
/// Returns client signature of request from the header (base64)
protected string GetClientSignature()
{
return this.HttpContext.Request.Headers["Client-Signature"].ToString();
}
///
/// Client public signature key for the trusted request
///
/// Returns client signature public key of trusted request from the header (base64), that was used in the signature
protected string GetClientSignatureKey()
{
return this.HttpContext.Request.Headers["Client-Signature-Key"].ToString();
}
///
/// Server public key for shared key(Encryption)
///
/// Returns server public key for shared key
public string GetServerPublicKey()
{
return this._KeyPair.PublicKey;
}
///
/// Returns client shared key
///
/// HKDF.DeriveKey(SHA512)
protected byte[] GetClientSharedKey()
{
return this._KeyPair.GetSharedKey(this.GetClientPublicKey());
}
///
/// Debugs object in debug mode
///
///
protected void Debug(object obj, string type)
{
if (_LogType == Log.Types.DEBUG)
{
if (obj != null)
{
try
{
Log.Debug("[" + type + "]" + JsonSerializer.Serialize(obj));
}
catch (Exception ex)
{
Log.Critical(ex, "ServiceInside.Controllers.BaseController", "Debug");
}
}
}
}
}
}