1
0
mirror of https://github.com/RaidMax/IW4M-Admin.git synced 2025-06-07 21:58:06 -05:00

Add /api/client/{clientId} Endpoint

This endpoint returns general information about the client ID provided.
This commit is contained in:
Ayymoss 2024-08-22 19:03:58 +01:00 committed by RaidMax
parent 0a8bbf2997
commit 5c9cfbd2c2
2 changed files with 91 additions and 51 deletions

View File

@ -0,0 +1,17 @@
using System;
using Data.Models.Client;
namespace SharedLibraryCore.Dtos;
public class ClientInfoResult
{
public int ClientId { get; set; }
public string Name { get; set; }
public string Level { get; set; }
public long NetworkId { get; set; }
public string? Tag { get; set; }
public DateTime FirstConnection { get; set; }
public DateTime LastConnection { get; set; }
public int TotalConnectionTime { get; set; }
public int Connections { get; set; }
}

View File

@ -3,10 +3,12 @@ using Microsoft.AspNetCore.Mvc;
using SharedLibraryCore.Dtos; using SharedLibraryCore.Dtos;
using SharedLibraryCore.Interfaces; using SharedLibraryCore.Interfaces;
using System; using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.Linq; using System.Linq;
using System.Security.Claims; using System.Security.Claims;
using System.Threading.Tasks; using System.Threading.Tasks;
using Data.Models;
using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
@ -24,20 +26,15 @@ namespace WebfrontCore.Controllers.API
/// </summary> /// </summary>
[ApiController] [ApiController]
[Route("api/[controller]")] [Route("api/[controller]")]
public class ClientController : BaseController public class ClientController(
{ ILogger<ClientController> logger,
private readonly IResourceQueryHelper<FindClientRequest, FindClientResult> _clientQueryHelper;
private readonly ILogger _logger;
private readonly ClientService _clientService;
public ClientController(ILogger<ClientController> logger,
IResourceQueryHelper<FindClientRequest, FindClientResult> clientQueryHelper, IResourceQueryHelper<FindClientRequest, FindClientResult> clientQueryHelper,
ClientService clientService, IManager manager) : base(manager) ClientService clientService,
IManager manager,
IMetaServiceV2 metaService)
: BaseController(manager)
{ {
_logger = logger; private readonly ILogger _logger = logger;
_clientQueryHelper = clientQueryHelper;
_clientService = clientService;
}
[HttpGet("find")] [HttpGet("find")]
[ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status200OK)]
@ -47,16 +44,16 @@ namespace WebfrontCore.Controllers.API
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return BadRequest(new ErrorResponse() return BadRequest(new ErrorResponse
{ {
Messages = ModelState.Values Messages = ModelState.Values
.SelectMany(_value => _value.Errors.Select(_error => _error.ErrorMessage)).ToArray() .SelectMany(value => value.Errors.Select(error => error.ErrorMessage)).ToArray()
}); });
} }
try try
{ {
var results = await _clientQueryHelper.QueryResource(request); var results = await clientQueryHelper.QueryResource(request);
return Ok(new FindClientResponse return Ok(new FindClientResponse
{ {
@ -64,28 +61,57 @@ namespace WebfrontCore.Controllers.API
Clients = results.Results Clients = results.Results
}); });
} }
catch (Exception e) catch (Exception e)
{ {
_logger.LogWarning(e, "Failed to retrieve clients with query - {@request}", request); _logger.LogWarning(e, "Failed to retrieve clients with query - {@Request}", request);
return StatusCode(StatusCodes.Status500InternalServerError, new ErrorResponse { Messages = [e.Message] });
}
}
return StatusCode(StatusCodes.Status500InternalServerError, new ErrorResponse() [HttpGet("{clientId:int}")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<IActionResult> GetPlayerInfoAsync([FromRoute] int clientId)
{ {
Messages = new[] {e.Message} try
{
var clientInfo = await clientService.Get(clientId);
if (clientInfo is null)
{
return BadRequest("Could not find client");
}
var metaResult = await metaService
.GetPersistentMetaByLookup(EFMeta.ClientTagV2, EFMeta.ClientTagNameV2, clientInfo.ClientId);
return Ok(new ClientInfoResult
{
ClientId = clientInfo.ClientId,
Name = clientInfo.CleanedName,
Level = clientInfo.Level.ToLocalizedLevelName(),
NetworkId = clientInfo.NetworkId,
Tag = metaResult?.Value,
FirstConnection = clientInfo.FirstConnection,
LastConnection = clientInfo.LastConnection,
TotalConnectionTime = clientInfo.TotalConnectionTime,
Connections = clientInfo.Connections,
}); });
} }
catch (Exception e)
{
_logger.LogWarning(e, "Failed to retrieve information for Client - {ClientId}", clientId);
return StatusCode(StatusCodes.Status500InternalServerError, new ErrorResponse { Messages = [e.Message] });
}
} }
[HttpPost("{clientId:int}/login")] [HttpPost("{clientId:int}/login")]
[ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)] [ProducesResponseType(StatusCodes.Status401Unauthorized)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)] [ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> Login([FromRoute] int clientId, public async Task<IActionResult> Login([FromRoute] int clientId, [FromBody, Required] PasswordRequest request)
[FromBody, Required] PasswordRequest request)
{ {
if (clientId == 0) if (clientId is 0)
{ {
return Unauthorized(); return Unauthorized();
} }
@ -97,7 +123,7 @@ namespace WebfrontCore.Controllers.API
try try
{ {
var privilegedClient = await _clientService.GetClientForLogin(clientId); var privilegedClient = await clientService.GetClientForLogin(clientId);
var loginSuccess = false; var loginSuccess = false;
if (!Authorized) if (!Authorized)
@ -108,21 +134,20 @@ namespace WebfrontCore.Controllers.API
Token = request.Password Token = request.Password
}; };
loginSuccess = loginSuccess = Manager.TokenAuthenticator.AuthorizeToken(tokenData) ||
Manager.TokenAuthenticator.AuthorizeToken(tokenData) || (await Task.FromResult(Hashing.Hash(request.Password, privilegedClient.PasswordSalt)))[0] ==
(await Task.FromResult(Hashing.Hash(request.Password, privilegedClient.Password;
privilegedClient.PasswordSalt)))[0] == privilegedClient.Password;
} }
if (loginSuccess) if (loginSuccess)
{ {
var claims = new[] List<Claim> claims =
{ [
new Claim(ClaimTypes.NameIdentifier, privilegedClient.Name), new Claim(ClaimTypes.NameIdentifier, privilegedClient.Name),
new Claim(ClaimTypes.Role, privilegedClient.Level.ToString()), new Claim(ClaimTypes.Role, privilegedClient.Level.ToString()),
new Claim(ClaimTypes.Sid, privilegedClient.ClientId.ToString()), new Claim(ClaimTypes.Sid, privilegedClient.ClientId.ToString()),
new Claim(ClaimTypes.PrimarySid, privilegedClient.NetworkId.ToString("X")) new Claim(ClaimTypes.PrimarySid, privilegedClient.NetworkId.ToString("X"))
}; ];
var claimsIdentity = new ClaimsIdentity(claims, "login"); var claimsIdentity = new ClaimsIdentity(claims, "login");
var claimsPrinciple = new ClaimsPrincipal(claimsIdentity); var claimsPrinciple = new ClaimsPrincipal(claimsIdentity);
@ -133,9 +158,9 @@ namespace WebfrontCore.Controllers.API
Origin = privilegedClient, Origin = privilegedClient,
Type = GameEvent.EventType.Login, Type = GameEvent.EventType.Login,
Owner = Manager.GetServers().First(), Owner = Manager.GetServers().First(),
Data = HttpContext.Request.Headers.ContainsKey("X-Forwarded-For") Data = HttpContext.Request.Headers.TryGetValue("X-Forwarded-For", out var gameStringValues)
? HttpContext.Request.Headers["X-Forwarded-For"].ToString() ? gameStringValues.ToString()
: HttpContext.Connection.RemoteIpAddress.ToString() : HttpContext.Connection.RemoteIpAddress?.ToString()
}); });
Manager.QueueEvent(new LoginEvent Manager.QueueEvent(new LoginEvent
@ -143,15 +168,14 @@ namespace WebfrontCore.Controllers.API
Source = this, Source = this,
LoginSource = LoginEvent.LoginSourceType.Webfront, LoginSource = LoginEvent.LoginSourceType.Webfront,
EntityId = Client.ClientId.ToString(), EntityId = Client.ClientId.ToString(),
Identifier = HttpContext.Request.Headers.ContainsKey("X-Forwarded-For") Identifier = HttpContext.Request.Headers.TryGetValue("X-Forwarded-For", out var loginStringValues)
? HttpContext.Request.Headers["X-Forwarded-For"].ToString() ? loginStringValues.ToString()
: HttpContext.Connection.RemoteIpAddress?.ToString() : HttpContext.Connection.RemoteIpAddress?.ToString()
}); });
return Ok(); return Ok();
} }
} }
catch (Exception) catch (Exception)
{ {
return Unauthorized(); return Unauthorized();
@ -172,9 +196,9 @@ namespace WebfrontCore.Controllers.API
Origin = Client, Origin = Client,
Type = GameEvent.EventType.Logout, Type = GameEvent.EventType.Logout,
Owner = Manager.GetServers().First(), Owner = Manager.GetServers().First(),
Data = HttpContext.Request.Headers.ContainsKey("X-Forwarded-For") Data = HttpContext.Request.Headers.TryGetValue("X-Forwarded-For", out var gameStringValues)
? HttpContext.Request.Headers["X-Forwarded-For"].ToString() ? gameStringValues.ToString()
: HttpContext.Connection.RemoteIpAddress.ToString() : HttpContext.Connection.RemoteIpAddress?.ToString()
}); });
Manager.QueueEvent(new LogoutEvent Manager.QueueEvent(new LogoutEvent
@ -182,14 +206,13 @@ namespace WebfrontCore.Controllers.API
Source = this, Source = this,
LoginSource = LoginEvent.LoginSourceType.Webfront, LoginSource = LoginEvent.LoginSourceType.Webfront,
EntityId = Client.ClientId.ToString(), EntityId = Client.ClientId.ToString(),
Identifier = HttpContext.Request.Headers.ContainsKey("X-Forwarded-For") Identifier = HttpContext.Request.Headers.TryGetValue("X-Forwarded-For", out var logoutStringValues)
? HttpContext.Request.Headers["X-Forwarded-For"].ToString() ? logoutStringValues.ToString()
: HttpContext.Connection.RemoteIpAddress?.ToString() : HttpContext.Connection.RemoteIpAddress?.ToString()
}); });
} }
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return Ok(); return Ok();
} }