using System.Net;
using System.Net.Sockets;
using Galaeth.ApiServer.Models.Common;
using Galaeth.Core.Constants;
using Microsoft.AspNetCore.Mvc;
namespace Galaeth.ApiServer.Controllers;
///
/// Base Api Controller.
///
[Consumes("application/json")]
[Produces("application/json")]
public class ApiController : ControllerBase
{
///
/// Return a failure status with no data.
///
/// Instance of .
protected static IActionResult FailureResult()
{
return new JsonResult(new ResultModel
{
Success = false,
});
}
///
/// Return a failure result with additional information.
///
/// Api error code.
/// Api error message.
/// Instance of .
protected static IActionResult FailureResult(string errorCode, string message)
{
return new JsonResult(new ErrorResultModel
{
Error = errorCode,
Message = message,
});
}
///
/// Returns a failure result indicating the body is missing from the request.
///
/// Instance of .
protected static IActionResult MissingBodyResult()
{
return FailureResult(CoreErrorCodes.NoDataProvided, "Missing request body");
}
///
/// Return a success status with no data.
///
/// Instance of .
protected static IActionResult SuccessResult()
{
return new JsonResult(new ResultModel
{
Success = true,
});
}
///
/// Return a success status with data.
///
/// Instance of .
/// The primary key type.
/// The data to return in the result.
protected static IActionResult SuccessResult(TDataType data)
where TDataType : class
{
return new JsonResult(new DataResultModel
{
Data = data,
Success = true,
});
}
///
/// Fetch IP address of requesting agent.
///
/// Request origin's IP address.
protected IPAddress ClientIpAddress()
{
IPAddress remoteIpAddress = null;
if (Request.Headers.TryGetValue("X-Forwarded-For", out var value))
{
foreach (var ip in value)
{
if (IPAddress.TryParse(ip, out var address) &&
(address.AddressFamily is AddressFamily.InterNetwork
or AddressFamily.InterNetworkV6))
{
remoteIpAddress = address;
break;
}
}
}
else
{
remoteIpAddress = HttpContext.Connection.RemoteIpAddress?.MapToIPv4();
}
return remoteIpAddress;
}
}