PluralKit/PluralKit.API/Controllers/MemberController.cs

98 lines
2.9 KiB
C#
Raw Normal View History

using System.Linq;
2019-07-09 22:19:18 +00:00
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
2019-07-09 22:19:18 +00:00
using PluralKit.Core;
namespace PluralKit.API.Controllers
{
[ApiController]
[Route("m")]
2019-07-09 22:23:41 +00:00
[Route("v1/m")]
2019-07-09 22:19:18 +00:00
public class MemberController: ControllerBase
{
private IDataStore _data;
2019-07-09 22:19:18 +00:00
private TokenAuthService _auth;
public MemberController(IDataStore data, TokenAuthService auth)
2019-07-09 22:19:18 +00:00
{
_data = data;
2019-07-09 22:19:18 +00:00
_auth = auth;
}
[HttpGet("{hid}")]
public async Task<ActionResult<JObject>> GetMember(string hid)
2019-07-09 22:19:18 +00:00
{
var member = await _data.GetMemberByHid(hid);
2019-07-09 22:19:18 +00:00
if (member == null) return NotFound("Member not found.");
return Ok(member.ToJson());
2019-07-09 22:19:18 +00:00
}
[HttpPost]
[RequiresSystem]
public async Task<ActionResult<JObject>> PostMember([FromBody] JObject properties)
{
var system = _auth.CurrentSystem;
if (!properties.ContainsKey("name"))
return BadRequest("Member name must be specified.");
// Enforce per-system member limit
var memberCount = await _data.GetSystemMemberCount(system);
if (memberCount >= Limits.MaxMemberCount)
return BadRequest($"Member limit reached ({memberCount} / {Limits.MaxMemberCount}).");
var member = await _data.CreateMember(system, properties.Value<string>("name"));
try
{
member.Apply(properties);
}
catch (PKParseError e)
{
return BadRequest(e.Message);
}
await _data.SaveMember(member);
return Ok(member.ToJson());
}
2019-07-09 22:19:18 +00:00
[HttpPatch("{hid}")]
[RequiresSystem]
public async Task<ActionResult<JObject>> PatchMember(string hid, [FromBody] JObject changes)
2019-07-09 22:19:18 +00:00
{
var member = await _data.GetMemberByHid(hid);
2019-07-09 22:19:18 +00:00
if (member == null) return NotFound("Member not found.");
if (member.System != _auth.CurrentSystem.Id) return Unauthorized($"Member '{hid}' is not part of your system.");
try
{
member.Apply(changes);
}
catch (PKParseError e)
{
return BadRequest(e.Message);
}
await _data.SaveMember(member);
return Ok(member.ToJson());
2019-07-09 22:19:18 +00:00
}
[HttpDelete("{hid}")]
[RequiresSystem]
public async Task<ActionResult> DeleteMember(string hid)
{
var member = await _data.GetMemberByHid(hid);
if (member == null) return NotFound("Member not found.");
if (member.System != _auth.CurrentSystem.Id) return Unauthorized($"Member '{hid}' is not part of your system.");
await _data.DeleteMember(member);
return Ok();
}
2019-07-09 22:19:18 +00:00
}
}