75 lines
2.5 KiB
C#
75 lines
2.5 KiB
C#
// <copyright file="OAuthApiController.cs" company="alveus.dev">
|
|
// Copyright (c) alveus.dev. All rights reserved. Licensed under the MIT License.
|
|
// </copyright>
|
|
|
|
using Astral.ApiServer.Constants;
|
|
using Astral.ApiServer.Models.Requests;
|
|
using Astral.ApiServer.Models.Responses;
|
|
using Astral.Core.Constants;
|
|
using Astral.Services.Dtos;
|
|
using Astral.Services.Interfaces;
|
|
using Microsoft.AspNetCore.Authorization;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
|
|
namespace Astral.ApiServer.Controllers;
|
|
|
|
/// <summary>
|
|
/// OAuth authentication controller.
|
|
/// </summary>
|
|
[Route("oauth")]
|
|
public class OAuthApiController : BaseApiController
|
|
{
|
|
private readonly IAuthenticationService _authenticationService;
|
|
|
|
/// <summary>
|
|
/// Initializes a new instance of the <see cref="OAuthApiController"/> class.
|
|
/// </summary>
|
|
/// <param name="authenticationService">Instance of <see cref="IAuthenticationService"/>.</param>
|
|
public OAuthApiController(IAuthenticationService authenticationService)
|
|
{
|
|
_authenticationService = authenticationService;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Grant token request.
|
|
/// </summary>
|
|
/// <param name="tokenGrantRequest">Instance of <see cref="TokenGrantRequestModel"/>.</param>
|
|
[HttpPost("token")]
|
|
[Consumes("application/x-www-form-urlencoded")]
|
|
[AllowAnonymous]
|
|
public async Task<IActionResult> 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 TokenGrantResponseModel(result));
|
|
}
|
|
|
|
return FailureResult();
|
|
}
|
|
}
|