// // Copyright (c) alveus.dev. All rights reserved. Licensed under the MIT License. // using System.Net; using System.Net.Sockets; using Astral.ApiServer.Models.Common; using Astral.Core.Constants; using Microsoft.AspNetCore.Mvc; namespace Astral.ApiServer.Controllers; /// /// Base API controller with common methods. /// [Produces("application/json")] [Consumes("application/x-www-form-urlencoded")] public class BaseApiController : ControllerBase { /// /// Return a failure status with no data. /// /// Instance of . protected IActionResult FailureResult() { Response.StatusCode = (int)HttpStatusCode.BadRequest; return new JsonResult(new ResultModel { Success = false, }); } /// /// Return a failure result with additional information. /// /// Api error code. /// Api error message. /// Instance of . protected IActionResult FailureResult(string errorCode, string message) { Response.StatusCode = (int)HttpStatusCode.BadRequest; return new JsonResult(new ErrorResultModel { Error = errorCode, Message = message, }); } /// /// Returns a failure result indicating the body is missing from the request. /// /// Instance of . protected IActionResult MissingBodyResult() { return FailureResult(CoreErrorCodes.NoDataProvided, "Missing request body"); } /// /// Return a success status with no data. /// /// Instance of . protected IActionResult SuccessResult() { Response.StatusCode = (int)HttpStatusCode.OK; return new JsonResult(new ResultModel { 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; } }