// // Copyright (c) alveus.dev. All rights reserved. Licensed under the MIT License. // using Astral.ApiServer.Constants; using Astral.ApiServer.Models; using Astral.Core.Constants; using Astral.Services.Dtos; using Astral.Services.Interfaces; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; namespace Astral.ApiServer.Controllers; /// /// OAuth authentication controller. /// [Route("oauth")] public class OAuthApiController : BaseApiController { private readonly IAuthenticationService _authenticationService; /// /// Initializes a new instance of the class. /// /// Instance of . public OAuthApiController(IAuthenticationService authenticationService) { _authenticationService = authenticationService; } /// /// Grant token request. /// /// Instance of . [HttpPost("token")] [AllowAnonymous] public async Task GrantToken([FromForm] TokenGrantRequestModel tokenGrantRequest) { if (tokenGrantRequest is null) { return MissingBodyResult(); } if (!Enum.TryParse(tokenGrantRequest.GrantType, true, out OAuthGrantType grantType)) { return FailureResult(ApiErrorCodes.UnsupportedGrantType, "Unknown grant type"); } if (!Enum.TryParse(tokenGrantRequest.Scope, true, out TokenScope tokenScope)) { return FailureResult(ApiErrorCodes.UnsupportedTokenScope, "Unknown token scope"); } switch (grantType) { case OAuthGrantType.Password: var request = new PasswordAuthenticateDto { Username = tokenGrantRequest.Username, Password = tokenGrantRequest.Password, Scope = tokenScope, IpAddress = ClientIpAddress() }; var result = await _authenticationService.AuthenticateSession(request); return new JsonResult(new TokenGrantResultModel(result)); } return FailureResult(); } }